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