statsig_rust/specs_adapter/
statsig_local_file_specs_adapter.rs1use crate::hashing::djb2;
2use crate::specs_adapter::{SpecsAdapter, SpecsSource, SpecsUpdate, SpecsUpdateListener};
3use crate::specs_response::spec_types::SpecsResponseFull;
4use crate::specs_response::spec_types_encoded::DecodedSpecsResponse;
5use crate::statsig_err::StatsigErr;
6use crate::{log_w, StatsigOptions, StatsigRuntime};
7use async_trait::async_trait;
8use chrono::Utc;
9
10use std::sync::{Arc, RwLock};
11use std::time::Duration;
12
13use super::{SpecsInfo, StatsigHttpSpecsAdapter};
14
15const TAG: &str = stringify!(StatsigLocalFileSpecsAdapter);
16
17pub struct StatsigLocalFileSpecsAdapter {
18 file_path: String,
19 listener: RwLock<Option<Arc<dyn SpecsUpdateListener>>>,
20 http_adapter: StatsigHttpSpecsAdapter,
21}
22
23impl StatsigLocalFileSpecsAdapter {
24 #[must_use]
25 pub fn new(
26 sdk_key: &str,
27 output_directory: &str,
28 specs_url: Option<String>,
29 fallback_to_statsig_api: bool,
30 disable_network: bool,
31 ) -> Self {
32 let hashed_key = djb2(sdk_key);
33 let file_path = format!("{output_directory}/{hashed_key}_specs.json");
34
35 let options = StatsigOptions {
36 specs_url,
37 disable_network: Some(disable_network),
38 fallback_to_statsig_api: Some(fallback_to_statsig_api),
39 ..Default::default()
40 };
41
42 Self {
43 file_path,
44 listener: RwLock::new(None),
45 http_adapter: StatsigHttpSpecsAdapter::new(sdk_key, Some(&options)),
46 }
47 }
48
49 pub async fn fetch_and_write_to_file(&self) -> Result<(), StatsigErr> {
50 let specs_info = match self.read_specs_from_file() {
51 Ok(Some(specs)) => SpecsInfo {
52 lcut: Some(specs.time),
53 checksum: specs.checksum,
54 zstd_dict_id: None, source: SpecsSource::Adapter("FileBased".to_owned()),
56 source_api: None,
57 },
58 _ => SpecsInfo::empty(),
59 };
60
61 let data = match self.http_adapter.fetch_specs_from_network(specs_info).await {
62 Ok(response) => match String::from_utf8(response.data) {
63 Ok(data) => data,
64 Err(e) => {
65 return Err(StatsigErr::SerializationError(e.to_string()));
66 }
67 },
68 Err(e) => {
69 return Err(StatsigErr::NetworkError(
70 e,
71 Some("No data received".to_string()),
72 ));
73 }
74 };
75
76 if let Some(response) = self.parse_specs_data_to_full_response(&data) {
77 if response.has_updates {
78 self.write_specs_to_file(&data);
79 }
80 }
81
82 Ok(())
83 }
84
85 pub fn resync_from_file(&self) -> Result<(), StatsigErr> {
86 let data = match std::fs::read_to_string(&self.file_path) {
87 Ok(data) => data,
88 Err(e) => {
89 return Err(StatsigErr::FileError(e.to_string()));
90 }
91 };
92
93 match &self.listener.read() {
94 Ok(lock) => match lock.as_ref() {
95 Some(listener) => listener.did_receive_specs_update(SpecsUpdate {
96 data: data.into_bytes(),
97 source: SpecsSource::Adapter("FileBased".to_owned()),
98 received_at: Utc::now().timestamp_millis() as u64,
99 source_api: None,
100 }),
101 None => Err(StatsigErr::UnstartedAdapter("Listener not set".to_string())),
102 },
103 Err(e) => Err(StatsigErr::LockFailure(e.to_string())),
104 }
105 }
106
107 fn read_specs_from_file(&self) -> Result<Option<SpecsResponseFull>, StatsigErr> {
108 if !std::path::Path::new(&self.file_path).exists() {
109 return Ok(None);
110 }
111
112 let data = match std::fs::read_to_string(&self.file_path) {
113 Ok(data) => data,
114 Err(e) => {
115 return Err(StatsigErr::FileError(e.to_string()));
116 }
117 };
118
119 Ok(self.parse_specs_data_to_full_response(&data))
120 }
121
122 fn parse_specs_data_to_full_response(&self, data: &str) -> Option<SpecsResponseFull> {
123 let mut place = SpecsResponseFull::default();
124 match DecodedSpecsResponse::from_slice(data.as_bytes(), &mut place, None) {
125 Ok(_) => Some(place),
126 Err(e) => {
127 log_w!(TAG, "Failed to parse specs data: {}", e);
128 None
129 }
130 }
131 }
132
133 fn write_specs_to_file(&self, data: &str) {
134 match std::fs::write(&self.file_path, data) {
135 Ok(()) => (),
136 Err(e) => log_w!(TAG, "Failed to write specs to file: {}", e),
137 }
138 }
139}
140
141#[async_trait]
142impl SpecsAdapter for StatsigLocalFileSpecsAdapter {
143 async fn start(
144 self: Arc<Self>,
145 _statsig_runtime: &Arc<StatsigRuntime>,
146 ) -> Result<(), StatsigErr> {
147 self.resync_from_file()
148 }
149
150 fn initialize(&self, listener: Arc<dyn SpecsUpdateListener>) {
151 if let Ok(mut mut_listener) = self.listener.write() {
152 *mut_listener = Some(listener);
153 }
154 }
155
156 async fn shutdown(
157 &self,
158 _timeout: Duration,
159 _statsig_runtime: &Arc<StatsigRuntime>,
160 ) -> Result<(), StatsigErr> {
161 Ok(())
162 }
163
164 async fn schedule_background_sync(
165 self: Arc<Self>,
166 _statsig_runtime: &Arc<StatsigRuntime>,
167 ) -> Result<(), StatsigErr> {
168 Ok(())
169 }
170
171 fn get_type_name(&self) -> String {
172 stringify!(StatsigLocalFileSpecsAdapter).to_string()
173 }
174}