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_e, log_w, StatsigOptions, StatsigRuntime};
7use async_trait::async_trait;
8use chrono::Utc;
9use parking_lot::RwLock;
10use std::sync::Arc;
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), None),
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(e));
70 }
71 };
72
73 if let Some(response) = self.parse_specs_data_to_full_response(&data) {
74 if response.has_updates {
75 self.write_specs_to_file(&data);
76 }
77 }
78
79 Ok(())
80 }
81
82 pub fn resync_from_file(&self) -> Result<(), StatsigErr> {
83 let data = match std::fs::read_to_string(&self.file_path) {
84 Ok(data) => data,
85 Err(e) => {
86 return Err(StatsigErr::FileError(e.to_string()));
87 }
88 };
89
90 match &self
91 .listener
92 .try_read_for(std::time::Duration::from_secs(5))
93 {
94 Some(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 None => Err(StatsigErr::LockFailure(
104 "Failed to acquire read lock on listener".to_string(),
105 )),
106 }
107 }
108
109 fn read_specs_from_file(&self) -> Result<Option<SpecsResponseFull>, StatsigErr> {
110 if !std::path::Path::new(&self.file_path).exists() {
111 return Ok(None);
112 }
113
114 let data = match std::fs::read_to_string(&self.file_path) {
115 Ok(data) => data,
116 Err(e) => {
117 return Err(StatsigErr::FileError(e.to_string()));
118 }
119 };
120
121 Ok(self.parse_specs_data_to_full_response(&data))
122 }
123
124 fn parse_specs_data_to_full_response(&self, data: &str) -> Option<SpecsResponseFull> {
125 let mut place = SpecsResponseFull::default();
126 match DecodedSpecsResponse::from_slice(data.as_bytes(), &mut place, None) {
127 Ok(_) => Some(place),
128 Err(e) => {
129 log_w!(TAG, "Failed to parse specs data: {}", e);
130 None
131 }
132 }
133 }
134
135 fn write_specs_to_file(&self, data: &str) {
136 match std::fs::write(&self.file_path, data) {
137 Ok(()) => (),
138 Err(e) => log_w!(TAG, "Failed to write specs to file: {}", e),
139 }
140 }
141}
142
143#[async_trait]
144impl SpecsAdapter for StatsigLocalFileSpecsAdapter {
145 async fn start(
146 self: Arc<Self>,
147 _statsig_runtime: &Arc<StatsigRuntime>,
148 ) -> Result<(), StatsigErr> {
149 self.resync_from_file()
150 }
151
152 fn initialize(&self, listener: Arc<dyn SpecsUpdateListener>) {
153 match self
154 .listener
155 .try_write_for(std::time::Duration::from_secs(5))
156 {
157 Some(mut lock) => *lock = Some(listener),
158 None => {
159 log_e!(TAG, "Failed to acquire write lock on listener");
160 }
161 }
162 }
163
164 async fn shutdown(
165 &self,
166 _timeout: Duration,
167 _statsig_runtime: &Arc<StatsigRuntime>,
168 ) -> Result<(), StatsigErr> {
169 Ok(())
170 }
171
172 async fn schedule_background_sync(
173 self: Arc<Self>,
174 _statsig_runtime: &Arc<StatsigRuntime>,
175 ) -> Result<(), StatsigErr> {
176 Ok(())
177 }
178
179 fn get_type_name(&self) -> String {
180 stringify!(StatsigLocalFileSpecsAdapter).to_string()
181 }
182}