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, log_w, 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 SpecsUpdate {
335 data,
336 source,
337 source_api,
338 ..
339 } = specs_update;
340
341 let current_lcut = {
342 let read_lock = read_lock_or_else!(self.data, {
343 let msg = "Failed to acquire read lock for set_values";
344 log_e!(TAG, "{}", msg);
345 return Err(StatsigErr::LockFailure(msg.to_string()));
346 });
347
348 self.emit_specs_updated_sdk_event(
349 &read_lock.source,
350 &read_lock.source_api,
351 &read_lock.values,
352 );
353
354 read_lock.values.time
355 };
356
357 self.try_update_data_store(&source, data, apply_result.time_received_at);
359
360 self.ops_stats_log_config_propagation_diff(
361 current_lcut,
362 apply_result.prev_lcut,
363 &source,
364 &apply_result.prev_source,
365 source_api,
366 response_format,
367 );
368
369 Ok(())
370 }
371
372 fn deserialize_specs_data(
373 &self,
374 current_values: &SpecsResponseFull,
375 response_format: &SpecsFormat,
376 response_data: &mut ResponseData,
377 ) -> Result<SpecsResponseFull, StatsigErr> {
378 let mut next_values = SpecsResponseFull::default();
379
380 let parse_result = match response_format {
381 SpecsFormat::Protobuf => deserialize_protobuf(
382 &self.ops_stats,
383 current_values,
384 &mut next_values,
385 response_data,
386 ),
387 SpecsFormat::Json => response_data.deserialize_in_place(&mut next_values),
388 };
389
390 match parse_result {
391 Ok(()) => Ok(next_values),
392 Err(e) => Err(e),
393 }
394 }
395
396 fn emit_specs_updated_sdk_event(
397 &self,
398 source: &SpecsSource,
399 source_api: &Option<String>,
400 values: &SpecsResponseFull,
401 ) {
402 self.event_emitter.emit(SdkEvent::SpecsUpdated {
403 source,
404 source_api,
405 values,
406 });
407 }
408
409 fn get_spec_response_format(&self, update: &SpecsUpdate) -> SpecsFormat {
410 let content_type = update.data.get_header_ref("content-type");
411 if content_type.map(|s| s.as_str().contains("application/octet-stream")) != Some(true) {
412 return SpecsFormat::Json;
413 }
414
415 let content_encoding = update.data.get_header_ref("content-encoding");
416 if content_encoding.map(|s| s.as_str().contains("statsig-br")) != Some(true) {
417 return SpecsFormat::Json;
418 }
419
420 SpecsFormat::Protobuf
421 }
422
423 fn try_update_global_configs(&self, dcs: &SpecsResponseFull) {
424 if let Some(diagnostics) = &dcs.diagnostics {
425 self.global_configs
426 .set_diagnostics_sampling_rates(diagnostics.clone());
427 }
428
429 if let Some(sdk_configs) = &dcs.sdk_configs {
430 self.global_configs.set_sdk_configs(sdk_configs.clone());
431 }
432
433 if let Some(sdk_flags) = &dcs.sdk_flags {
434 self.global_configs.set_sdk_flags(sdk_flags.clone());
435 }
436 }
437
438 fn try_update_data_store(&self, source: &SpecsSource, mut data: ResponseData, now: u64) {
439 if source != &SpecsSource::Network {
440 return;
441 }
442
443 let data_store = match &self.data_store {
444 Some(data_store) => data_store.clone(),
445 None => return,
446 };
447
448 let data_store_key = self.data_store_key.clone();
449 let supports_bytes = data_store.supports_bytes();
450
451 let spawn_result = self.statsig_runtime.spawn(
452 "spec_store_update_data_store",
453 move |_shutdown_notif| async move {
454 if supports_bytes {
455 let data_bytes = match data.read_to_bytes() {
456 Ok(bytes) => bytes,
457 Err(e) => {
458 log_e!(TAG, "Failed to read data as bytes: {}", e);
459 return;
460 }
461 };
462
463 let _ = data_store
464 .set_bytes(&data_store_key, &data_bytes, Some(now))
465 .await;
466 return;
467 }
468
469 let data_string = match data.read_to_string() {
470 Ok(s) => s,
471 Err(e) => {
472 log_w!(
473 TAG,
474 "Skipping data store write because payload is not valid UTF-8 and data store does not support bytes: {}",
475 e
476 );
477 return;
478 }
479 };
480
481 let _ = data_store
482 .set(&data_store_key, &data_string, Some(now))
483 .await;
484 },
485 );
486
487 if let Err(e) = spawn_result {
488 log_e!(
489 TAG,
490 "Failed to spawn spec store update data store task: {e}"
491 );
492 }
493 }
494
495 fn are_current_values_newer(
496 &self,
497 data: &SpecStoreData,
498 next_values: &SpecsResponseFull,
499 ) -> bool {
500 let curr_values = &data.values;
501 let curr_checksum = curr_values.checksum.as_deref().unwrap_or_default();
502 let new_checksum = next_values.checksum.as_deref().unwrap_or_default();
503
504 let cached_time_is_newer = curr_values.time > 0 && curr_values.time > next_values.time;
505 let checksums_match = !curr_checksum.is_empty() && curr_checksum == new_checksum;
506
507 if cached_time_is_newer || checksums_match {
508 log_d!(
509 TAG,
510 "Received values for [time: {}, checksum: {}], but currently has values for [time: {}, checksum: {}]. Ignoring values.",
511 next_values.time,
512 new_checksum,
513 curr_values.time,
514 curr_checksum,
515 );
516 return true;
517 }
518
519 false
520 }
521}
522
523impl SpecStore {
526 fn ops_stats_log_no_update(&self, source: SpecsSource, source_api: Option<String>) {
527 log_d!(TAG, "No Updates");
528 self.ops_stats.log(ObservabilityEvent::new_event(
529 MetricType::Increment,
530 "config_no_update".to_string(),
531 1.0,
532 Some(HashMap::from([
533 ("source".to_string(), source.to_string()),
534 ("source_api".to_string(), source_api.unwrap_or_default()),
535 ])),
536 ));
537 }
538
539 #[allow(clippy::too_many_arguments)]
540 fn ops_stats_log_config_propagation_diff(
541 &self,
542 lcut: u64,
543 prev_lcut: u64,
544 source: &SpecsSource,
545 prev_source: &SpecsSource,
546 source_api: Option<String>,
547 response_format: SpecsFormat,
548 ) {
549 let delay = (Utc::now().timestamp_millis() as u64).saturating_sub(lcut);
550 log_d!(TAG, "Updated ({:?})", source);
551
552 if *prev_source == SpecsSource::Uninitialized || *prev_source == SpecsSource::Loading {
553 return;
554 }
555
556 self.ops_stats.log(ObservabilityEvent::new_event(
557 MetricType::Dist,
558 "config_propagation_diff".to_string(),
559 delay as f64,
560 Some(HashMap::from([
561 ("source".to_string(), source.to_string()),
562 ("lcut".to_string(), lcut.to_string()),
563 ("prev_lcut".to_string(), prev_lcut.to_string()),
564 ("source_api".to_string(), source_api.unwrap_or_default()),
565 (
566 "response_format".to_string(),
567 Into::<&str>::into(&response_format).to_string(),
568 ),
569 ])),
570 ));
571 }
572}
573
574impl SpecsUpdateListener for SpecStore {
577 fn did_receive_specs_update(&self, update: SpecsUpdate) -> Result<(), StatsigErr> {
578 self.set_values(update)
579 }
580
581 fn get_current_specs_info(&self) -> SpecsInfo {
582 let data = read_lock_or_else!(self.data, {
583 log_e!(
584 TAG,
585 "Failed to acquire read lock for get_current_specs_info"
586 );
587 return SpecsInfo {
588 lcut: None,
589 checksum: None,
590 source: SpecsSource::Error,
591 source_api: None,
592 };
593 });
594
595 SpecsInfo {
596 lcut: Some(data.values.time),
597 checksum: data.values.checksum.clone(),
598 source: data.source.clone(),
599 source_api: data.source_api.clone(),
600 }
601 }
602}
603
604impl IdListsUpdateListener for SpecStore {
607 fn get_current_id_list_metadata(
608 &self,
609 ) -> HashMap<String, crate::id_lists_adapter::IdListMetadata> {
610 let data = read_lock_or_else!(self.data, {
611 let err = StatsigErr::LockFailure(
612 "Failed to acquire read lock for id list metadata".to_string(),
613 );
614 log_error_to_statsig_and_console!(self.ops_stats, TAG, err);
615 return HashMap::new();
616 });
617
618 data.id_lists
619 .iter()
620 .map(|(key, list)| (key.clone(), list.metadata.clone()))
621 .collect()
622 }
623
624 fn did_receive_id_list_updates(
625 &self,
626 updates: HashMap<String, crate::id_lists_adapter::IdListUpdate>,
627 ) {
628 let mut data = write_lock_or_else!(self.data, {
629 let err = StatsigErr::LockFailure(
630 "Failed to acquire write lock for did_receive_id_list_updates".to_string(),
631 );
632 log_error_to_statsig_and_console!(self.ops_stats, TAG, err);
633
634 return;
635 });
636
637 data.id_lists.retain(|name, _| updates.contains_key(name));
639
640 for (list_name, update) in updates {
641 if let Some(entry) = data.id_lists.get_mut(&list_name) {
642 entry.apply_update(update);
644 } else {
645 let mut list = IdList::new(update.new_metadata.clone());
647 list.apply_update(update);
648 data.id_lists.insert(list_name, list);
649 }
650 }
651 }
652}