statsig_rust/
spec_store.rs

1use crate::compression::zstd_decompression_dict::DictionaryDecoder;
2use crate::data_store_interface::{get_data_adapter_dcs_key, DataStoreTrait};
3use crate::global_configs::GlobalConfigs;
4use crate::id_lists_adapter::{IdList, IdListsUpdateListener};
5use crate::observability::observability_client_adapter::{MetricType, ObservabilityEvent};
6use crate::observability::ops_stats::{OpsStatsForInstance, OPS_STATS};
7use crate::observability::sdk_errors_observer::ErrorBoundaryEvent;
8use crate::specs_response::spec_types::{SpecsResponseFull, SpecsResponseNoUpdates};
9use crate::specs_response::spec_types_encoded::DecodedSpecsResponse;
10use crate::utils::maybe_trim_malloc;
11use crate::{
12    log_d, log_e, log_error_to_statsig_and_console, SpecsInfo, SpecsSource, SpecsUpdate,
13    SpecsUpdateListener, StatsigErr, StatsigRuntime,
14};
15use chrono::Utc;
16use parking_lot::RwLock;
17use std::collections::HashMap;
18use std::sync::Arc;
19use std::time::Duration;
20
21pub struct SpecStoreData {
22    pub source: SpecsSource,
23    pub source_api: Option<String>,
24    pub time_received_at: Option<u64>,
25    pub values: SpecsResponseFull,
26    pub next_values: Option<SpecsResponseFull>,
27    pub decompression_dict: Option<DictionaryDecoder>,
28    pub id_lists: HashMap<String, IdList>,
29}
30
31const TAG: &str = stringify!(SpecStore);
32
33pub struct SpecStore {
34    pub data: Arc<RwLock<SpecStoreData>>,
35
36    hashed_sdk_key: String,
37    data_store: Option<Arc<dyn DataStoreTrait>>,
38    statsig_runtime: Arc<StatsigRuntime>,
39    ops_stats: Arc<OpsStatsForInstance>,
40    global_configs: Arc<GlobalConfigs>,
41}
42
43impl SpecStore {
44    #[must_use]
45    pub fn new(
46        sdk_key: &str,
47        hashed_sdk_key: String,
48        statsig_runtime: Arc<StatsigRuntime>,
49        data_store: Option<Arc<dyn DataStoreTrait>>,
50    ) -> SpecStore {
51        SpecStore {
52            hashed_sdk_key,
53            data: Arc::new(RwLock::new(SpecStoreData {
54                values: SpecsResponseFull::default(),
55                next_values: Some(SpecsResponseFull::default()),
56                time_received_at: None,
57                source: SpecsSource::Uninitialized,
58                source_api: None,
59                decompression_dict: None,
60                id_lists: HashMap::new(),
61            })),
62            data_store,
63            statsig_runtime,
64            ops_stats: OPS_STATS.get_for_instance(sdk_key),
65            global_configs: GlobalConfigs::get_instance(sdk_key),
66        }
67    }
68
69    pub fn set_source(&self, source: SpecsSource) {
70        match self.data.try_write_for(Duration::from_secs(5)) {
71            Some(mut data) => {
72                data.source = source;
73                log_d!(TAG, "Source Changed ({:?})", data.source);
74            }
75            None => {
76                log_e!(TAG, "Failed to acquire write lock: Failed to lock data");
77            }
78        }
79    }
80
81    pub fn get_current_values(&self) -> Option<SpecsResponseFull> {
82        let data = match self.data.try_read_for(Duration::from_secs(5)) {
83            Some(data) => data,
84            None => {
85                log_e!(TAG, "Failed to acquire read lock: Failed to lock data");
86                return None;
87            }
88        };
89        let json = serde_json::to_string(&data.values).ok()?;
90        serde_json::from_str::<SpecsResponseFull>(&json).ok()
91    }
92
93    pub fn set_values(&self, specs_update: SpecsUpdate) -> Result<(), StatsigErr> {
94        let (mut next_values, decompression_dict) =
95            match self.data.try_write_for(Duration::from_secs(5)) {
96                Some(mut data) => (
97                    data.next_values.take().unwrap_or_default(),
98                    data.decompression_dict.clone(),
99                ),
100                None => {
101                    log_e!(TAG, "Failed to acquire write lock: Failed to lock data");
102                    return Err(StatsigErr::LockFailure(
103                        "Failed to acquire write lock: Failed to lock data".to_string(),
104                    ));
105                }
106            };
107
108        let decompression_dict =
109            match self.parse_specs_response(&specs_update, &mut next_values, decompression_dict) {
110                Ok(Some(full)) => full,
111                Ok(None) => {
112                    self.ops_stats_log_no_update(specs_update.source, specs_update.source_api);
113                    return Ok(());
114                }
115                Err(e) => {
116                    return Err(e);
117                }
118            };
119
120        if self.are_current_values_newer(&next_values) {
121            return Ok(());
122        }
123
124        self.try_update_global_configs(&next_values);
125
126        let now = Utc::now().timestamp_millis() as u64;
127        let (prev_source, prev_lcut, curr_values_time) = self.swap_current_with_next(
128            next_values,
129            &specs_update,
130            decompression_dict,
131            now,
132            specs_update.source_api.clone(),
133        )?;
134
135        self.try_update_data_store(&specs_update.source, specs_update.data, now);
136        self.ops_stats_log_config_propagation_diff(
137            curr_values_time,
138            prev_lcut,
139            &specs_update.source,
140            &prev_source,
141            specs_update.source_api,
142        );
143
144        // Glibc requested more memory than needed when deserializing a big json blob
145        // And memory allocator fails to return it.
146        // To prevent service from OOMing, manually unused heap memory.
147        maybe_trim_malloc();
148
149        Ok(())
150    }
151}
152
153// -------------------------------------------------------------------------------------------- [Private Functions]
154
155impl SpecStore {
156    fn parse_specs_response(
157        &self,
158        values: &SpecsUpdate,
159        next_values: &mut SpecsResponseFull,
160        decompression_dict: Option<DictionaryDecoder>,
161    ) -> Result<Option<Option<DictionaryDecoder>>, StatsigErr> {
162        let full_update_decoder_result = DecodedSpecsResponse::from_slice(
163            &values.data,
164            next_values,
165            decompression_dict.as_ref(),
166        );
167
168        if let Ok(result) = full_update_decoder_result {
169            if next_values.has_updates {
170                return Ok(Some(result));
171            }
172
173            return Ok(None);
174        }
175
176        let mut next_no_updates = SpecsResponseNoUpdates { has_updates: false };
177        let no_updates_decoder_result = DecodedSpecsResponse::from_slice(
178            &values.data,
179            &mut next_no_updates,
180            decompression_dict.as_ref(),
181        );
182
183        if no_updates_decoder_result.is_ok() && !next_no_updates.has_updates {
184            return Ok(None);
185        }
186
187        let error = full_update_decoder_result.err().map_or_else(
188            || StatsigErr::JsonParseError("SpecsResponse".to_string(), "Unknown error".to_string()),
189            |e| StatsigErr::JsonParseError("SpecsResponse".to_string(), e.to_string()),
190        );
191
192        log_error_to_statsig_and_console!(self.ops_stats, TAG, error);
193        Err(error)
194    }
195
196    fn swap_current_with_next(
197        &self,
198        next_values: SpecsResponseFull,
199        specs_update: &SpecsUpdate,
200        decompression_dict: Option<DictionaryDecoder>,
201        now: u64,
202        source_api: Option<String>,
203    ) -> Result<(SpecsSource, u64, u64), StatsigErr> {
204        match self.data.try_write_for(Duration::from_secs(5)) {
205            Some(mut data) => {
206                let prev_source = std::mem::replace(&mut data.source, specs_update.source.clone());
207                let prev_lcut = data.values.time;
208
209                let mut temp = next_values;
210                std::mem::swap(&mut data.values, &mut temp);
211                data.next_values = Some(temp);
212
213                data.time_received_at = Some(now);
214                data.decompression_dict = decompression_dict;
215                data.source_api = source_api;
216                Ok((prev_source, prev_lcut, data.values.time))
217            }
218            None => {
219                log_e!(TAG, "Failed to acquire write lock: Failed to lock data");
220                Err(StatsigErr::LockFailure(
221                    "Failed to acquire write lock: Failed to lock data".to_string(),
222                ))
223            }
224        }
225    }
226
227    fn ops_stats_log_no_update(&self, source: SpecsSource, source_api: Option<String>) {
228        log_d!(TAG, "No Updates");
229        self.ops_stats.log(ObservabilityEvent::new_event(
230            MetricType::Increment,
231            "config_no_update".to_string(),
232            1.0,
233            Some(HashMap::from([
234                ("source".to_string(), source.to_string()),
235                (
236                    "spec_source_api".to_string(),
237                    source_api.unwrap_or_default(),
238                ),
239            ])),
240        ));
241    }
242
243    fn ops_stats_log_config_propagation_diff(
244        &self,
245        lcut: u64,
246        prev_lcut: u64,
247        source: &SpecsSource,
248        prev_source: &SpecsSource,
249        source_api: Option<String>,
250    ) {
251        let delay = Utc::now().timestamp_millis() as u64 - lcut;
252        log_d!(TAG, "Updated ({:?})", source);
253
254        if *prev_source == SpecsSource::Uninitialized || *prev_source == SpecsSource::Loading {
255            return;
256        }
257
258        self.ops_stats.log(ObservabilityEvent::new_event(
259            MetricType::Dist,
260            "config_propagation_diff".to_string(),
261            delay as f64,
262            Some(HashMap::from([
263                ("source".to_string(), source.to_string()),
264                ("lcut".to_string(), lcut.to_string()),
265                ("prev_lcut".to_string(), prev_lcut.to_string()),
266                (
267                    "spec_source_api".to_string(),
268                    source_api.unwrap_or_default(),
269                ),
270            ])),
271        ));
272    }
273
274    fn try_update_global_configs(&self, dcs: &SpecsResponseFull) {
275        if let Some(diagnostics) = &dcs.diagnostics {
276            self.global_configs
277                .set_diagnostics_sampling_rates(diagnostics.clone());
278        }
279
280        if let Some(sdk_configs) = &dcs.sdk_configs {
281            self.global_configs.set_sdk_configs(sdk_configs.clone());
282        }
283    }
284
285    fn try_update_data_store(&self, source: &SpecsSource, data: Vec<u8>, now: u64) {
286        if source != &SpecsSource::Network {
287            return;
288        }
289
290        let data_store = match &self.data_store {
291            Some(data_store) => data_store.clone(),
292            None => return,
293        };
294
295        let hashed_key = self.hashed_sdk_key.clone();
296
297        let spawn_result = self.statsig_runtime.spawn(
298            "spec_store_update_data_store",
299            move |_shutdown_notif| async move {
300                let data_string = match String::from_utf8(data) {
301                    Ok(s) => s,
302                    Err(e) => {
303                        log_e!(TAG, "Failed to convert data to string: {}", e);
304                        return;
305                    }
306                };
307
308                let _ = data_store
309                    .set(
310                        &get_data_adapter_dcs_key(&hashed_key),
311                        &data_string,
312                        Some(now),
313                    )
314                    .await;
315            },
316        );
317
318        if let Err(e) = spawn_result {
319            log_e!(
320                TAG,
321                "Failed to spawn spec store update data store task: {e}"
322            );
323        }
324    }
325
326    fn are_current_values_newer(&self, next_values: &SpecsResponseFull) -> bool {
327        let data = match self.data.try_read_for(Duration::from_secs(5)) {
328            Some(data) => data,
329            None => {
330                log_e!(TAG, "Failed to acquire read lock: Failed to lock data");
331                return false;
332            }
333        };
334
335        let curr_values = &data.values;
336        let curr_checksum = curr_values.checksum.as_deref().unwrap_or_default();
337        let new_checksum = next_values.checksum.as_deref().unwrap_or_default();
338
339        let cached_time_is_newer = curr_values.time > 0 && curr_values.time > next_values.time;
340        let checksums_match = !curr_checksum.is_empty() && curr_checksum == new_checksum;
341
342        if cached_time_is_newer || checksums_match {
343            log_d!(
344                TAG,
345                "Received values for [time: {}, checksum: {}], but currently has values for [time: {}, checksum: {}]. Ignoring values.",
346                next_values.time,
347                new_checksum,
348                curr_values.time,
349                curr_checksum,
350                );
351            return true;
352        }
353
354        false
355    }
356}
357
358// -------------------------------------------------------------------------------------------- [Impl SpecsUpdateListener]
359
360impl SpecsUpdateListener for SpecStore {
361    fn did_receive_specs_update(&self, update: SpecsUpdate) -> Result<(), StatsigErr> {
362        self.set_values(update)
363    }
364
365    fn get_current_specs_info(&self) -> SpecsInfo {
366        match self.data.try_read_for(Duration::from_secs(5)) {
367            Some(data) => SpecsInfo {
368                lcut: Some(data.values.time),
369                checksum: data.values.checksum.clone(),
370                zstd_dict_id: data
371                    .decompression_dict
372                    .as_ref()
373                    .map(|d| d.get_dict_id().to_string()),
374                source: data.source.clone(),
375                source_api: data.source_api.clone(),
376            },
377            None => {
378                log_e!(TAG, "Failed to acquire read lock: Failed to lock data");
379                SpecsInfo {
380                    lcut: None,
381                    checksum: None,
382                    zstd_dict_id: None,
383                    source: SpecsSource::Error,
384                    source_api: None,
385                }
386            }
387        }
388    }
389}
390
391// -------------------------------------------------------------------------------------------- [Impl IdListsUpdateListener]
392
393impl IdListsUpdateListener for SpecStore {
394    fn get_current_id_list_metadata(
395        &self,
396    ) -> HashMap<String, crate::id_lists_adapter::IdListMetadata> {
397        match self.data.try_read_for(Duration::from_secs(5)) {
398            Some(data) => data
399                .id_lists
400                .iter()
401                .map(|(key, list)| (key.clone(), list.metadata.clone()))
402                .collect(),
403            None => {
404                log_e!(TAG, "Failed to acquire read lock: Failed to lock data");
405                HashMap::new()
406            }
407        }
408    }
409
410    fn did_receive_id_list_updates(
411        &self,
412        updates: HashMap<String, crate::id_lists_adapter::IdListUpdate>,
413    ) {
414        let mut data = match self.data.try_write_for(Duration::from_secs(5)) {
415            Some(data) => data,
416            None => {
417                log_e!(TAG, "Failed to acquire write lock: Failed to lock data");
418                return;
419            }
420        };
421
422        // delete any id_lists that are not in the updates
423        data.id_lists.retain(|name, _| updates.contains_key(name));
424
425        for (list_name, update) in updates {
426            if let Some(entry) = data.id_lists.get_mut(&list_name) {
427                // update existing
428                entry.apply_update(&update);
429            } else {
430                // add new
431                let mut list = IdList::new(update.new_metadata.clone());
432                list.apply_update(&update);
433                data.id_lists.insert(list_name, list);
434            }
435        }
436    }
437}