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