statsig_rust/specs_adapter/
statsig_local_file_specs_adapter.rs

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