Skip to main content

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                    has_updates: None,
105                }),
106                None => Err(StatsigErr::UnstartedAdapter("Listener not set".to_string())),
107            },
108            None => Err(StatsigErr::LockFailure(
109                "Failed to acquire read lock on listener".to_string(),
110            )),
111        }
112    }
113
114    fn read_specs_from_file(&self) -> Result<Option<SpecsResponseFull>, StatsigErr> {
115        if !std::path::Path::new(&self.file_path).exists() {
116            return Ok(None);
117        }
118
119        let data = match std::fs::read_to_string(&self.file_path) {
120            Ok(data) => data,
121            Err(e) => {
122                return Err(StatsigErr::FileError(e.to_string()));
123            }
124        };
125
126        Ok(self.parse_specs_data_to_full_response(&data))
127    }
128
129    fn parse_specs_data_to_full_response(&self, data: &str) -> Option<SpecsResponseFull> {
130        match serde_json::from_slice::<SpecsResponseFull>(data.as_bytes()) {
131            Ok(response) => Some(response),
132            Err(e) => {
133                log_w!(TAG, "Failed to parse specs data: {}", e);
134                None
135            }
136        }
137    }
138
139    fn write_specs_to_file(&self, data: &str) {
140        match std::fs::write(&self.file_path, data) {
141            Ok(()) => (),
142            Err(e) => log_w!(TAG, "Failed to write specs to file: {}", e),
143        }
144    }
145}
146
147#[async_trait]
148impl SpecsAdapter for StatsigLocalFileSpecsAdapter {
149    async fn start(
150        self: Arc<Self>,
151        _statsig_runtime: &Arc<StatsigRuntime>,
152    ) -> Result<(), StatsigErr> {
153        self.resync_from_file()
154    }
155
156    fn initialize(&self, listener: Arc<dyn SpecsUpdateListener>) {
157        match self
158            .listener
159            .try_write_for(std::time::Duration::from_secs(5))
160        {
161            Some(mut lock) => *lock = Some(listener),
162            None => {
163                log_e!(TAG, "Failed to acquire write lock on listener");
164            }
165        }
166    }
167
168    async fn shutdown(
169        &self,
170        _timeout: Duration,
171        _statsig_runtime: &Arc<StatsigRuntime>,
172    ) -> Result<(), StatsigErr> {
173        Ok(())
174    }
175
176    async fn schedule_background_sync(
177        self: Arc<Self>,
178        _statsig_runtime: &Arc<StatsigRuntime>,
179    ) -> Result<(), StatsigErr> {
180        Ok(())
181    }
182
183    fn get_type_name(&self) -> String {
184        stringify!(StatsigLocalFileSpecsAdapter).to_string()
185    }
186}