1use chrono::Utc;
2use parking_lot::RwLock;
3use std::collections::HashMap;
4use std::sync::Arc;
5
6use crate::data_store_interface::DataStoreTrait;
7use crate::evaluation::evaluator::SpecType;
8use crate::global_configs::GlobalConfigs;
9use crate::id_lists_adapter::{IdList, IdListsUpdateListener};
10use crate::interned_string::InternedString;
11use crate::networking::ResponseData;
12use crate::observability::observability_client_adapter::{MetricType, ObservabilityEvent};
13use crate::observability::ops_stats::{OpsStatsForInstance, OPS_STATS};
14use crate::observability::sdk_errors_observer::ErrorBoundaryEvent;
15use crate::sdk_event_emitter::{SdkEvent, SdkEventEmitter};
16use crate::specs_response::proto_specs::deserialize_protobuf;
17use crate::specs_response::spec_types::{SpecsResponseFull, SpecsResponseNoUpdates};
18use crate::utils::try_release_unused_heap_memory;
19use crate::{
20 log_d, log_e, log_error_to_statsig_and_console, read_lock_or_else, write_lock_or_else,
21 SpecsFormat, SpecsInfo, SpecsSource, SpecsUpdate, SpecsUpdateListener, StatsigErr,
22 StatsigOptions, StatsigRuntime,
23};
24
25pub struct SpecStoreData {
26 pub source: SpecsSource,
27 pub source_api: Option<String>,
28 pub time_received_at: Option<u64>,
29 pub values: SpecsResponseFull,
30 pub id_lists: HashMap<String, IdList>,
31}
32
33const TAG: &str = stringify!(SpecStore);
34
35pub struct SpecStore {
36 pub data: Arc<RwLock<SpecStoreData>>,
37
38 data_store_key: String,
39 data_store: Option<Arc<dyn DataStoreTrait>>,
40 statsig_runtime: Arc<StatsigRuntime>,
41 ops_stats: Arc<OpsStatsForInstance>,
42 global_configs: Arc<GlobalConfigs>,
43 event_emitter: Arc<SdkEventEmitter>,
44}
45
46impl SpecStore {
47 #[must_use]
48 pub fn new(
49 sdk_key: &str,
50 data_store_key: String,
51 statsig_runtime: Arc<StatsigRuntime>,
52 event_emitter: Arc<SdkEventEmitter>,
53 options: Option<&StatsigOptions>,
54 ) -> SpecStore {
55 let mut data_store = None;
56 if let Some(options) = options {
57 data_store = options.data_store.clone();
58 }
59
60 SpecStore {
61 data_store_key,
62 data: Arc::new(RwLock::new(SpecStoreData {
63 values: SpecsResponseFull::default(),
64 time_received_at: None,
65 source: SpecsSource::Uninitialized,
66 source_api: None,
67 id_lists: HashMap::new(),
68 })),
69 event_emitter,
70 data_store,
71 statsig_runtime,
72 ops_stats: OPS_STATS.get_for_instance(sdk_key),
73 global_configs: GlobalConfigs::get_instance(sdk_key),
74 }
75 }
76
77 pub fn set_source(&self, source: SpecsSource) {
78 let mut locked_data = write_lock_or_else!(self.data, {
79 log_e!(TAG, "Failed to acquire write lock: Failed to lock data");
80 return;
81 });
82
83 locked_data.source = source;
84 log_d!(TAG, "Source Changed ({:?})", locked_data.source);
85 }
86
87 pub fn get_current_values(&self) -> Option<SpecsResponseFull> {
88 let data = read_lock_or_else!(self.data, {
89 log_e!(TAG, "Failed to acquire read lock: Failed to lock data");
90 return None;
91 });
92
93 let json = serde_json::to_string(&data.values).ok()?;
94 serde_json::from_str::<SpecsResponseFull>(&json).ok()
95 }
96
97 pub fn get_fields_used_for_entity(
98 &self,
99 entity_name: &str,
100 entity_type: SpecType,
101 ) -> Vec<String> {
102 let data = read_lock_or_else!(self.data, {
103 log_error_to_statsig_and_console!(
104 &self.ops_stats,
105 TAG,
106 StatsigErr::LockFailure(
107 "Failed to acquire read lock for spec store data".to_string()
108 )
109 );
110 return vec![];
111 });
112
113 let entities = match entity_type {
114 SpecType::Gate => &data.values.feature_gates,
115 SpecType::DynamicConfig | SpecType::Experiment => &data.values.dynamic_configs,
116 SpecType::Layer => &data.values.layer_configs,
117 SpecType::ParameterStore => return vec![],
118 };
119
120 let entity_name = InternedString::from_str_ref(entity_name);
121 let entity = entities.get(&entity_name);
122
123 match entity {
124 Some(entity) => match &entity.as_spec_ref().fields_used {
125 Some(fields) => fields.iter().map(|f| f.unperformant_to_string()).collect(),
126 None => vec![],
127 },
128 None => vec![],
129 }
130 }
131
132 pub fn unperformant_keys_entity_filter(
133 &self,
134 top_level_key: &str,
135 entity_type: &str,
136 ) -> Vec<String> {
137 let data = read_lock_or_else!(self.data, {
138 log_error_to_statsig_and_console!(
139 &self.ops_stats,
140 TAG,
141 StatsigErr::LockFailure(
142 "Failed to acquire read lock for spec store data".to_string()
143 )
144 );
145 return vec![];
146 });
147
148 if top_level_key == "param_stores" {
149 match &data.values.param_stores {
150 Some(param_stores) => {
151 return param_stores
152 .keys()
153 .map(|k| k.unperformant_to_string())
154 .collect()
155 }
156 None => return vec![],
157 }
158 }
159
160 let values = match top_level_key {
161 "feature_gates" => &data.values.feature_gates,
162 "dynamic_configs" => &data.values.dynamic_configs,
163 "layer_configs" => &data.values.layer_configs,
164 _ => {
165 log_e!(TAG, "Invalid top level key: {}", top_level_key);
166 return vec![];
167 }
168 };
169
170 if entity_type == "*" {
171 return values.keys().map(|k| k.unperformant_to_string()).collect();
172 }
173
174 values
175 .iter()
176 .filter(|(_, v)| v.as_spec_ref().entity == entity_type)
177 .map(|(k, _)| k.unperformant_to_string())
178 .collect()
179 }
180
181 pub fn set_values(&self, mut specs_update: SpecsUpdate) -> Result<(), StatsigErr> {
182 let prep_result = self.specs_update_prep(&mut specs_update).map_err(|e| {
190 log_error_to_statsig_and_console!(self.ops_stats, TAG, e);
191 e
192 })?;
193
194 let (next_values, response_format) = match prep_result {
195 PrepResult::HasUpdates(next_values, response_format) => (next_values, response_format),
196 PrepResult::CurrentValuesNewer => return Ok(()),
197 PrepResult::NoUpdates => {
198 self.ops_stats_log_no_update(specs_update.source, specs_update.source_api);
199 return Ok(());
200 }
201 };
202
203 let apply_result = self
206 .specs_update_apply(next_values, &specs_update)
207 .map_err(|e| {
208 log_error_to_statsig_and_console!(self.ops_stats, TAG, e);
209 e
210 })?;
211
212 try_release_unused_heap_memory();
213
214 self.specs_update_notify(response_format, specs_update, apply_result)
217 .map_err(|e| {
218 log_error_to_statsig_and_console!(self.ops_stats, TAG, e);
219 e
220 })?;
221
222 Ok(())
223 }
224}
225
226enum PrepResult {
229 HasUpdates(Box<SpecsResponseFull>, SpecsFormat),
230 NoUpdates,
231 CurrentValuesNewer,
232}
233
234struct ApplyResult {
235 prev_source: SpecsSource,
236 prev_lcut: u64,
237 time_received_at: u64,
238}
239
240impl SpecStore {
241 fn specs_update_prep(&self, specs_update: &mut SpecsUpdate) -> Result<PrepResult, StatsigErr> {
242 let response_format = self.get_spec_response_format(specs_update);
243
244 let read_data = read_lock_or_else!(self.data, {
245 let msg = "Failed to acquire read lock for extract_response_from_update";
246 log_e!(TAG, "{}", msg);
247 return Err(StatsigErr::LockFailure(msg.to_string()));
248 });
249
250 let current_values = &read_data.values;
251
252 let first_deserialize_result =
254 self.deserialize_specs_data(current_values, &response_format, &mut specs_update.data);
255
256 let first_deserialize_error = match first_deserialize_result {
257 Ok(next_values) => {
258 if self.are_current_values_newer(&read_data, &next_values) {
259 return Ok(PrepResult::CurrentValuesNewer);
260 }
261
262 if next_values.has_updates {
263 return Ok(PrepResult::HasUpdates(
264 Box::new(next_values),
265 response_format,
266 ));
267 }
268
269 None
270 }
271 Err(e) => Some(e),
272 };
273
274 let second_deserialize_result = specs_update
276 .data
277 .deserialize_into::<SpecsResponseNoUpdates>();
278
279 let second_deserialize_error = match second_deserialize_result {
280 Ok(result) => {
281 if !result.has_updates {
282 return Ok(PrepResult::NoUpdates);
283 }
284
285 None
286 }
287 Err(e) => Some(e),
288 };
289
290 let error = first_deserialize_error
291 .or(second_deserialize_error)
292 .unwrap_or_else(|| {
293 StatsigErr::JsonParseError("SpecsResponse".to_string(), "Unknown error".to_string())
294 });
295
296 Err(error)
297 }
298
299 fn specs_update_apply(
300 &self,
301 next_values: Box<SpecsResponseFull>,
302 specs_update: &SpecsUpdate,
303 ) -> Result<ApplyResult, StatsigErr> {
304 self.try_update_global_configs(&next_values);
306
307 let mut data = write_lock_or_else!(self.data, {
308 let msg = "Failed to acquire write lock for swap_current_with_next";
309 log_e!(TAG, "{}", msg);
310 return Err(StatsigErr::LockFailure(msg.to_string()));
311 });
312
313 let prev_source = std::mem::replace(&mut data.source, specs_update.source.clone());
314 let prev_lcut = data.values.time;
315 let time_received_at = Utc::now().timestamp_millis() as u64;
316
317 data.values = *next_values;
318 data.time_received_at = Some(time_received_at);
319 data.source_api = specs_update.source_api.clone();
320
321 Ok(ApplyResult {
322 prev_source,
323 prev_lcut,
324 time_received_at,
325 })
326 }
327
328 fn specs_update_notify(
329 &self,
330 response_format: SpecsFormat,
331 specs_update: SpecsUpdate,
332 apply_result: ApplyResult,
333 ) -> Result<(), StatsigErr> {
334 let current_lcut = {
335 let read_lock = read_lock_or_else!(self.data, {
336 let msg = "Failed to acquire read lock for set_values";
337 log_e!(TAG, "{}", msg);
338 return Err(StatsigErr::LockFailure(msg.to_string()));
339 });
340
341 self.emit_specs_updated_sdk_event(
342 &read_lock.source,
343 &read_lock.source_api,
344 &read_lock.values,
345 );
346
347 read_lock.values.time
348 };
349
350 if let SpecsFormat::Json = response_format {
351 self.try_update_data_store(
353 &specs_update.source,
354 specs_update.data,
355 apply_result.time_received_at,
356 );
357 }
358
359 self.ops_stats_log_config_propagation_diff(
360 current_lcut,
361 apply_result.prev_lcut,
362 &specs_update.source,
363 &apply_result.prev_source,
364 specs_update.source_api,
365 response_format,
366 );
367
368 Ok(())
369 }
370
371 fn deserialize_specs_data(
372 &self,
373 current_values: &SpecsResponseFull,
374 response_format: &SpecsFormat,
375 response_data: &mut ResponseData,
376 ) -> Result<SpecsResponseFull, StatsigErr> {
377 let mut next_values = SpecsResponseFull::default();
378
379 let parse_result = match response_format {
380 SpecsFormat::Protobuf => deserialize_protobuf(
381 &self.ops_stats,
382 current_values,
383 &mut next_values,
384 response_data,
385 ),
386 SpecsFormat::Json => response_data.deserialize_in_place(&mut next_values),
387 };
388
389 match parse_result {
390 Ok(()) => Ok(next_values),
391 Err(e) => Err(e),
392 }
393 }
394
395 fn emit_specs_updated_sdk_event(
396 &self,
397 source: &SpecsSource,
398 source_api: &Option<String>,
399 values: &SpecsResponseFull,
400 ) {
401 self.event_emitter.emit(SdkEvent::SpecsUpdated {
402 source,
403 source_api,
404 values,
405 });
406 }
407
408 fn get_spec_response_format(&self, update: &SpecsUpdate) -> SpecsFormat {
409 let content_type = update.data.get_header_ref("content-type");
410 if content_type.map(|s| s.as_str().contains("application/octet-stream")) != Some(true) {
411 return SpecsFormat::Json;
412 }
413
414 let content_encoding = update.data.get_header_ref("content-encoding");
415 if content_encoding.map(|s| s.as_str().contains("statsig-br")) != Some(true) {
416 return SpecsFormat::Json;
417 }
418
419 SpecsFormat::Protobuf
420 }
421
422 fn try_update_global_configs(&self, dcs: &SpecsResponseFull) {
423 if let Some(diagnostics) = &dcs.diagnostics {
424 self.global_configs
425 .set_diagnostics_sampling_rates(diagnostics.clone());
426 }
427
428 if let Some(sdk_configs) = &dcs.sdk_configs {
429 self.global_configs.set_sdk_configs(sdk_configs.clone());
430 }
431
432 if let Some(sdk_flags) = &dcs.sdk_flags {
433 self.global_configs.set_sdk_flags(sdk_flags.clone());
434 }
435 }
436
437 fn try_update_data_store(&self, source: &SpecsSource, mut data: ResponseData, now: u64) {
438 if source != &SpecsSource::Network {
439 return;
440 }
441
442 let data_store = match &self.data_store {
443 Some(data_store) => data_store.clone(),
444 None => return,
445 };
446
447 let data_store_key = self.data_store_key.clone();
448
449 let spawn_result = self.statsig_runtime.spawn(
450 "spec_store_update_data_store",
451 move |_shutdown_notif| async move {
452 let data_string = match data.read_to_string() {
453 Ok(s) => s,
454 Err(e) => {
455 log_e!(TAG, "Failed to convert data to string: {}", e);
456 return;
457 }
458 };
459
460 let _ = data_store
461 .set(&data_store_key, &data_string, Some(now))
462 .await;
463 },
464 );
465
466 if let Err(e) = spawn_result {
467 log_e!(
468 TAG,
469 "Failed to spawn spec store update data store task: {e}"
470 );
471 }
472 }
473
474 fn are_current_values_newer(
475 &self,
476 data: &SpecStoreData,
477 next_values: &SpecsResponseFull,
478 ) -> bool {
479 let curr_values = &data.values;
480 let curr_checksum = curr_values.checksum.as_deref().unwrap_or_default();
481 let new_checksum = next_values.checksum.as_deref().unwrap_or_default();
482
483 let cached_time_is_newer = curr_values.time > 0 && curr_values.time > next_values.time;
484 let checksums_match = !curr_checksum.is_empty() && curr_checksum == new_checksum;
485
486 if cached_time_is_newer || checksums_match {
487 log_d!(
488 TAG,
489 "Received values for [time: {}, checksum: {}], but currently has values for [time: {}, checksum: {}]. Ignoring values.",
490 next_values.time,
491 new_checksum,
492 curr_values.time,
493 curr_checksum,
494 );
495 return true;
496 }
497
498 false
499 }
500}
501
502impl SpecStore {
505 fn ops_stats_log_no_update(&self, source: SpecsSource, source_api: Option<String>) {
506 log_d!(TAG, "No Updates");
507 self.ops_stats.log(ObservabilityEvent::new_event(
508 MetricType::Increment,
509 "config_no_update".to_string(),
510 1.0,
511 Some(HashMap::from([
512 ("source".to_string(), source.to_string()),
513 ("source_api".to_string(), source_api.unwrap_or_default()),
514 ])),
515 ));
516 }
517
518 #[allow(clippy::too_many_arguments)]
519 fn ops_stats_log_config_propagation_diff(
520 &self,
521 lcut: u64,
522 prev_lcut: u64,
523 source: &SpecsSource,
524 prev_source: &SpecsSource,
525 source_api: Option<String>,
526 response_format: SpecsFormat,
527 ) {
528 let delay = (Utc::now().timestamp_millis() as u64).saturating_sub(lcut);
529 log_d!(TAG, "Updated ({:?})", source);
530
531 if *prev_source == SpecsSource::Uninitialized || *prev_source == SpecsSource::Loading {
532 return;
533 }
534
535 self.ops_stats.log(ObservabilityEvent::new_event(
536 MetricType::Dist,
537 "config_propagation_diff".to_string(),
538 delay as f64,
539 Some(HashMap::from([
540 ("source".to_string(), source.to_string()),
541 ("lcut".to_string(), lcut.to_string()),
542 ("prev_lcut".to_string(), prev_lcut.to_string()),
543 ("source_api".to_string(), source_api.unwrap_or_default()),
544 (
545 "response_format".to_string(),
546 Into::<&str>::into(&response_format).to_string(),
547 ),
548 ])),
549 ));
550 }
551}
552
553impl SpecsUpdateListener for SpecStore {
556 fn did_receive_specs_update(&self, update: SpecsUpdate) -> Result<(), StatsigErr> {
557 self.set_values(update)
558 }
559
560 fn get_current_specs_info(&self) -> SpecsInfo {
561 let data = read_lock_or_else!(self.data, {
562 log_e!(
563 TAG,
564 "Failed to acquire read lock for get_current_specs_info"
565 );
566 return SpecsInfo {
567 lcut: None,
568 checksum: None,
569 source: SpecsSource::Error,
570 source_api: None,
571 };
572 });
573
574 SpecsInfo {
575 lcut: Some(data.values.time),
576 checksum: data.values.checksum.clone(),
577 source: data.source.clone(),
578 source_api: data.source_api.clone(),
579 }
580 }
581}
582
583impl IdListsUpdateListener for SpecStore {
586 fn get_current_id_list_metadata(
587 &self,
588 ) -> HashMap<String, crate::id_lists_adapter::IdListMetadata> {
589 let data = read_lock_or_else!(self.data, {
590 let err = StatsigErr::LockFailure(
591 "Failed to acquire read lock for id list metadata".to_string(),
592 );
593 log_error_to_statsig_and_console!(self.ops_stats, TAG, err);
594 return HashMap::new();
595 });
596
597 data.id_lists
598 .iter()
599 .map(|(key, list)| (key.clone(), list.metadata.clone()))
600 .collect()
601 }
602
603 fn did_receive_id_list_updates(
604 &self,
605 updates: HashMap<String, crate::id_lists_adapter::IdListUpdate>,
606 ) {
607 let mut data = write_lock_or_else!(self.data, {
608 let err = StatsigErr::LockFailure(
609 "Failed to acquire write lock for did_receive_id_list_updates".to_string(),
610 );
611 log_error_to_statsig_and_console!(self.ops_stats, TAG, err);
612
613 return;
614 });
615
616 data.id_lists.retain(|name, _| updates.contains_key(name));
618
619 for (list_name, update) in updates {
620 if let Some(entry) = data.id_lists.get_mut(&list_name) {
621 entry.apply_update(update);
623 } else {
624 let mut list = IdList::new(update.new_metadata.clone());
626 list.apply_update(update);
627 data.id_lists.insert(list_name, list);
628 }
629 }
630 }
631}