1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use std::time::Duration;

use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;
use std::collections::HashMap;

#[derive(Serialize, Deserialize)]
pub struct StatsigConfig<T> {
    pub value: Option<T>,
    pub name: String,
    pub group_name: String,
    pub rule_id: String,
    pub group: String,
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StatsigPost {
    pub events: Vec<StatsigEvent>,
}

#[derive(Debug, PartialEq, Clone, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StatsigEvent {
    pub event_name: String,
    pub value: String,
    pub time: String, // unix timestamp
    pub user: StatsigUser,
    pub metadata: HashMap<String, String>,
    // secondary_exposures
}

#[skip_serializing_none]
#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StatsigUser {
    #[serde(rename = "userID")]
    pub user_id: String,
    pub email: Option<String>,
    pub ip: Option<String>,
    pub user_agent: Option<String>,
    pub country: Option<String>,
    pub locale: Option<String>,
    pub app_version: Option<String>,
    pub custom: Option<HashMap<String, String>>,
    pub private_atributes: Option<HashMap<String, String>>,
    #[serde(rename = "customIDs")]
    pub custom_ids: Option<HashMap<String, String>>,
    pub statsig_environment: StatsigEnvironment,
}

/// Options to use when creating the client, they will override default values, if they exist.
///
/// The default value for api_url is https://api.statsig.com/v1
/// The default value for config_sync_interval is 15s
pub struct StatsigOptions {
    pub api_url: Option<String>,
    pub events_url: Option<String>,
    pub disable_cache: bool,
    pub config_sync_interval: Option<Duration>,
}

impl StatsigOptions {
    pub fn default() -> Self {
        Self {
            api_url: None,
            disable_cache: false,
            config_sync_interval: None,
            events_url: None,
        }
    }

    pub fn cache_disabled() -> Self {
        Self {
            api_url: None,
            disable_cache: true,
            config_sync_interval: None,
            events_url: None,
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StatsigEnvironment {
    pub tier: String,
}

impl StatsigEnvironment {
    pub fn get_field(&self, field: &str) -> String {
        let empty = "".to_string();
        match field.to_ascii_lowercase().as_str() {
            "tier" => self.tier.clone(),
            _ => empty,
        }
    }
}

impl StatsigUser {
    pub fn new(user_id: String, tier: String) -> Self {
        StatsigUser {
            user_id,
            email: None,
            ip: None,
            user_agent: None,
            country: None,
            locale: None,
            app_version: None,
            custom: None,
            private_atributes: None,
            custom_ids: None,
            statsig_environment: StatsigEnvironment { tier },
        }
    }

    /// Fetch the id of id_type for the user, defaults to user_id.
    pub fn get_unit_id(&self, id_type: &String) -> String {
        if id_type.to_ascii_lowercase() == *"userid" {
            return self.user_id.clone();
        }
        if let Some(custom_ids) = &self.custom_ids {
            if custom_ids.contains_key(id_type) {
                return custom_ids.get(id_type).unwrap_or(&self.user_id).clone();
            }
            let lower = id_type.to_ascii_lowercase();
            if custom_ids.contains_key(&lower) {
                return custom_ids.get(&lower).unwrap_or(&self.user_id).clone();
            }
        }
        self.user_id.clone()
    }

    pub fn get_field(&self, field: &String) -> String {
        let empty = "".to_string();
        match field.to_ascii_lowercase().as_str() {
            "userid" | "user_id" => self.user_id.clone(),
            "email" => self.email.as_ref().unwrap_or(&empty).clone(),
            "ip" | "ipaddress" | "ip_address" => self.ip.as_ref().unwrap_or(&empty).clone(),
            "useragent" | "user_agent" => self.user_agent.as_ref().unwrap_or(&empty).clone(),
            "country" => self.country.as_ref().unwrap_or(&empty).clone(),
            "locale" => self.locale.as_ref().unwrap_or(&empty).clone(),
            "appversion" | "app_version" => self.app_version.as_ref().unwrap_or(&empty).clone(),
            _ => {
                let mut ret = "".to_string();
                if let Some(custom) = &self.custom {
                    if let Some(v) = custom.get(field) {
                        ret = v.clone();
                    } else if let Some(v) = custom.get(&field.to_ascii_lowercase()) {
                        ret = v.clone();
                    }
                } else if let Some(private) = &self.private_atributes {
                    if let Some(v) = private.get(field) {
                        ret = v.clone();
                    } else if let Some(v) = private.get(&field.to_ascii_lowercase()) {
                        ret = v.clone();
                    }
                }
                ret
            }
        }
    }
}

#[cfg(test)]
mod test {
    use std::collections::HashMap;

    use crate::models::StatsigEnvironment;

    use super::StatsigUser;

    #[test]
    fn test_get_unit_id_default_user() {
        let user = StatsigUser::new("user_id".to_string(), "prod".to_string());
        assert_eq!(
            user.get_unit_id(&"userid".to_string()),
            "user_id".to_string()
        );
        assert_eq!(
            user.get_unit_id(&"not_userid".to_string()),
            "user_id".to_string()
        );
    }

    #[test]
    fn test_get_unit_id_custom_ids() {
        let mut user = StatsigUser::new("user_id".to_string(), "prod".to_string());
        let mut custom_ids = HashMap::new();
        custom_ids.insert("not_userid".to_string(), "not_userid".to_string());
        custom_ids.insert("ALL_CAPS".to_string(), "ALL_CAPS".to_string());
        user.custom_ids = Some(custom_ids);
        assert_eq!(
            user.get_unit_id(&"userid".to_string()),
            "user_id".to_string()
        );
        assert_eq!(
            user.get_unit_id(&"Not_userid".to_string()),
            "not_userid".to_string()
        );
        assert_eq!(
            user.get_unit_id(&"ALL_CAPS".to_string()),
            "ALL_CAPS".to_string()
        );
        assert_eq!(
            user.get_unit_id(&"non_existing".to_string()),
            "user_id".to_string()
        );
    }

    #[test]
    fn test_get_field() {
        let user = StatsigUser {
            user_id: "userid".to_string(),
            email: Some("abc@email.com".to_string()),
            ip: Some("192.168.0.1".to_string()),
            user_agent: None,
            country: None,
            locale: None,
            app_version: None,
            custom: Some(HashMap::from([("custom1".to_string(), "val1".to_string())])),
            private_atributes: None,
            custom_ids: None,
            statsig_environment: StatsigEnvironment {
                tier: "prod".to_string(),
            },
        };
        assert_eq!("userid".to_string(), user.get_field(&"userID".to_string()));
        assert_eq!(
            "abc@email.com".to_string(),
            user.get_field(&"email".to_string())
        );
        assert_eq!("192.168.0.1".to_string(), user.get_field(&"ip".to_string()));
        assert_eq!("val1".to_string(), user.get_field(&"custom1".to_string()));
    }
}