Skip to main content

statsig_rust/id_lists_adapter/
id_lists_adapter_trait.rs

1use crate::{StatsigErr, StatsigRuntime};
2use async_trait::async_trait;
3use std::sync::Arc;
4use std::time::Duration;
5use std::{collections::HashMap, fmt};
6
7use serde::{Deserialize, Serialize};
8
9#[derive(Serialize, Deserialize, Debug, Clone)]
10#[serde(rename_all = "camelCase")]
11pub struct IdListMetadata {
12    #[serde(alias = "key")]
13    pub name: String,
14    pub url: String,
15
16    #[serde(rename = "fileID")]
17    pub file_id: Option<String>,
18
19    pub size: u64,
20    pub creation_time: i64,
21}
22
23pub struct IdListUpdate {
24    pub raw_changeset: Option<String>,
25    pub new_metadata: IdListMetadata,
26}
27
28#[async_trait]
29pub trait IdListsAdapter: Send + Sync {
30    /// Called during Statsig::initialize. Mostly to attach the listener.
31    /// Scheduling background threads should be done in the IdListsAdapter::schedule_background_sync function.
32    ///
33    /// # Arguments
34    ///
35    /// * `statsig_runtime` - The Statsig runtime instance.
36    /// * `listener` - The listener to push updates to.
37    async fn start(
38        self: Arc<Self>,
39        statsig_runtime: &Arc<StatsigRuntime>,
40        listener: Arc<dyn IdListsUpdateListener + Send + Sync>,
41    ) -> Result<(), StatsigErr>;
42
43    /// Called during Statsig::shutdown or Statsig::shutdown_with_timeout.
44    /// This function gives some grace period to the adapter to finish its work.
45    ///
46    /// # Arguments
47    ///
48    /// * `timeout` - The timeout for the shutdown.
49    async fn shutdown(&self, timeout: Duration) -> Result<(), StatsigErr>;
50
51    /// Called during Statsig::initialize.
52    /// This function is used to schedule the background sync thread and is called just after IdListsAdapter::start
53    ///
54    /// # Arguments
55    ///
56    /// * `statsig_runtime` - The Statsig runtime instance.
57    async fn schedule_background_sync(
58        self: Arc<Self>,
59        statsig_runtime: &Arc<StatsigRuntime>,
60    ) -> Result<(), StatsigErr>;
61
62    /// Returns the type name of the adapter. Used for logging and error messages.
63    fn get_type_name(&self) -> String;
64}
65
66pub trait IdListsUpdateListener: Send + Sync {
67    fn get_current_id_list_metadata(&self) -> HashMap<String, IdListMetadata>;
68
69    fn did_receive_id_list_updates(&self, updates: HashMap<String, IdListUpdate>);
70}
71
72impl fmt::Debug for dyn IdListsAdapter {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        write!(f, "{}", self.get_type_name())
75    }
76}