Skip to main content

verhub_sdk/
analytics.rs

1//! 事件采集的本地状态:匿名标识、退出标记与待发送队列。
2//!
3//! 这是整个 SDK 里唯一会在设备上写入数据的部分;改动这里要同步更新
4//! 《SDK 合规性文档》。
5//!
6//! 与其余三个语言的 SDK 的唯一差异是定时发送:Rust 版不自己起后台任务,改成在
7//! `track` 时顺带检查「距上次发送是否已超过 flush_interval」。攒着的最后一批靠
8//! [`crate::PublicApi::flush`] 发出去。这条差异同样记在合规文档的
9//! 「各语言版本的差异」一节里。
10
11use std::collections::HashMap;
12use std::hash::{BuildHasher, Hasher, RandomState};
13use std::path::PathBuf;
14use std::sync::Mutex;
15use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
16
17use serde::{Deserialize, Serialize};
18use serde_json::{Map, Value};
19
20/// 攒批的时间上限。
21pub const DEFAULT_FLUSH_INTERVAL: Duration = Duration::from_secs(5);
22
23/// 攒够这么多条立即发送。
24pub const DEFAULT_BATCH_SIZE: usize = 20;
25
26/// 队列上限,超出丢最旧的。
27pub const DEFAULT_MAX_QUEUE_SIZE: usize = 500;
28
29/// 会话空闲多久换新。
30pub const DEFAULT_SESSION_TIMEOUT: Duration = Duration::from_secs(30 * 60);
31
32/// 服务端单批上限,与 `VERHUB_EVENT_BATCH_MAX` 的默认值一致。
33const SERVER_BATCH_MAX: usize = 50;
34
35/// 重试退避的上限,避免服务端长时间不可用时把间隔拖到几小时。
36const MAX_BACKOFF: Duration = Duration::from_secs(60);
37
38/// 匿名标识的持久化程度。
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40pub enum AnalyticsPersistence {
41    /// 写入本地,重启后仍是同一个标识,可算跨天留存。
42    #[default]
43    Device,
44    /// 只在进程内存里,重启即换新,无法算跨天留存。
45    Session,
46    /// 不生成持久标识,也不落盘。
47    None,
48}
49
50/// 事件采集配置。
51#[derive(Debug, Clone)]
52pub struct AnalyticsOptions {
53    /// 关掉后 `track` 直接返回,不生成标识、不落盘、不发请求。
54    pub enabled: bool,
55    /// 开启后,在 `grant_consent` 被调用前不采集、不写盘(含匿名标识的生成),
56    /// 事件直接丢弃。面向欧盟用户的接入方应当开启。
57    pub require_consent: bool,
58    pub persistence: AnalyticsPersistence,
59    pub flush_interval: Duration,
60    pub batch_size: usize,
61    pub max_queue_size: usize,
62    pub session_timeout: Duration,
63    /// 自定义状态文件位置;省略则用各平台的常规用户状态目录。
64    pub state_path: Option<PathBuf>,
65    /// 覆盖本地状态的命名空间。默认由 `base_url` 的 origin 与 `project_key` 算出。
66    ///
67    /// 同一实例同一项目下的两个应用要各自独立的匿名标识时显式指定。
68    pub namespace: Option<String>,
69}
70
71impl Default for AnalyticsOptions {
72    fn default() -> Self {
73        Self {
74            enabled: true,
75            require_consent: false,
76            persistence: AnalyticsPersistence::default(),
77            flush_interval: DEFAULT_FLUSH_INTERVAL,
78            batch_size: DEFAULT_BATCH_SIZE,
79            max_queue_size: DEFAULT_MAX_QUEUE_SIZE,
80            session_timeout: DEFAULT_SESSION_TIMEOUT,
81            state_path: None,
82            namespace: None,
83        }
84    }
85}
86
87/// 队列里的一条事件。
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct QueuedEvent {
90    /// 客户端生成的幂等键,服务端据此去重。
91    pub event_id: String,
92    pub name: String,
93    pub occurred_at: i64,
94    #[serde(skip_serializing_if = "Option::is_none")]
95    pub properties: Option<Map<String, Value>>,
96}
97
98/// 一次上报的载荷。
99#[derive(Debug, Clone, Serialize)]
100pub struct EventBatch {
101    pub distinct_id: String,
102    #[serde(skip_serializing_if = "Option::is_none")]
103    pub session_id: Option<String>,
104    pub events: Vec<QueuedEvent>,
105}
106
107/// 随机 UUIDv4。不读取任何设备特征。
108///
109/// 自己拼而不引 `uuid` / `getrandom`:`RandomState` 每次构造都由操作系统播种,
110/// 两次取样即得 128 位,足够区分不同使用者。不承担安全职责。
111pub fn random_id() -> String {
112    let hi = random_u64();
113    let lo = random_u64();
114    let mut bytes = [0u8; 16];
115    bytes[..8].copy_from_slice(&hi.to_be_bytes());
116    bytes[8..].copy_from_slice(&lo.to_be_bytes());
117
118    // 打上 v4 与 RFC 4122 变体标记,让它是一个格式合法的 UUID。
119    bytes[6] = (bytes[6] & 0x0f) | 0x40;
120    bytes[8] = (bytes[8] & 0x3f) | 0x80;
121
122    let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
123    format!(
124        "{}-{}-{}-{}-{}",
125        &hex[0..8],
126        &hex[8..12],
127        &hex[12..16],
128        &hex[16..20],
129        &hex[20..32]
130    )
131}
132
133fn random_u64() -> u64 {
134    let mut hasher = RandomState::new().build_hasher();
135    hasher.write_u128(
136        SystemTime::now()
137            .duration_since(UNIX_EPOCH)
138            .map(|d| d.as_nanos())
139            .unwrap_or_default(),
140    );
141    hasher.finish()
142}
143
144fn now_seconds() -> i64 {
145    SystemTime::now()
146        .duration_since(UNIX_EPOCH)
147        .map(|d| d.as_secs() as i64)
148        .unwrap_or_default()
149}
150
151/// 取 base_url 的 origin(协议 + 主机 + 端口),路径一律忽略。
152///
153/// 主机名与协议转小写,剥掉 userinfo,`http` 的 80 与 `https` 的 443 会被省略。
154/// 不含 `://` 的输入原样转小写返回。四个语言的 SDK 规则相同。
155pub fn origin_of(base_url: &str) -> String {
156    let trimmed = base_url.trim();
157    let Some(scheme_end) = trimmed.find("://") else {
158        return trimmed.to_lowercase();
159    };
160
161    let scheme = trimmed[..scheme_end].to_lowercase();
162    let rest = &trimmed[scheme_end + 3..];
163    let authority = match rest.find('/') {
164        Some(slash) => &rest[..slash],
165        None => rest,
166    };
167    let mut authority = authority.to_lowercase();
168
169    if let Some(at) = authority.rfind('@') {
170        authority = authority[at + 1..].to_string();
171    }
172
173    // IPv6 的冒号在方括号里,端口只可能在 `]` 之后。
174    let host_end = authority.rfind(']').map(|i| i + 1).unwrap_or(0);
175    if let Some(offset) = authority[host_end..].find(':') {
176        let colon = host_end + offset;
177        let port = &authority[colon + 1..];
178        if (scheme == "http" && port == "80") || (scheme == "https" && port == "443") {
179            authority.truncate(colon);
180        }
181    }
182
183    format!("{scheme}://{authority}")
184}
185
186/// FNV-1a 32 位,按 UTF-8 字节计算,输出 8 位小写 hex。
187///
188/// 四个语言的 SDK 对同一输入给出同一结果。
189pub fn fnv1a32_hex(value: &str) -> String {
190    let mut hash: u32 = 0x811c_9dc5;
191    for byte in value.as_bytes() {
192        hash ^= u32::from(*byte);
193        hash = hash.wrapping_mul(0x0100_0193);
194    }
195    format!("{hash:08x}")
196}
197
198/// 本地状态的命名空间:`<origin 哈希>-<小写 project_key>`。
199///
200/// `project_key` 去首尾空白后转小写;为空或只有空白时用 `default`。
201/// 四个语言的 SDK 对同一组入参给出同一结果。
202pub fn analytics_namespace(base_url: &str, project_key: Option<&str>) -> String {
203    let key = project_key.unwrap_or("default").trim().to_lowercase();
204    let key = if key.is_empty() {
205        "default".to_string()
206    } else {
207        key
208    };
209    format!("{}-{}", fnv1a32_hex(&origin_of(base_url)), key)
210}
211
212/// 把命名空间洗成安全的文件名:非 `[A-Za-z0-9._-]` 换成下划线,截到 96 字符。
213fn file_safe(namespace: &str) -> String {
214    namespace
215        .chars()
216        .map(|c| {
217            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
218                c
219            } else {
220                '_'
221            }
222        })
223        .take(96)
224        .collect()
225}
226
227/// 各平台的常规用户状态目录,每个命名空间一个文件。
228fn default_state_path(namespace: &str) -> PathBuf {
229    let base = if cfg!(windows) {
230        std::env::var_os("LOCALAPPDATA")
231            .map(PathBuf::from)
232            .or_else(|| home_dir().map(|h| h.join("AppData").join("Local")))
233    } else if cfg!(target_os = "macos") {
234        home_dir().map(|h| h.join("Library").join("Application Support"))
235    } else {
236        std::env::var_os("XDG_STATE_HOME")
237            .map(PathBuf::from)
238            .or_else(|| home_dir().map(|h| h.join(".local").join("state")))
239    };
240
241    base.unwrap_or_else(std::env::temp_dir)
242        .join("verhub-sdk")
243        .join(format!("{}.json", file_safe(namespace)))
244}
245
246fn home_dir() -> Option<PathBuf> {
247    std::env::var_os("HOME")
248        .or_else(|| std::env::var_os("USERPROFILE"))
249        .map(PathBuf::from)
250}
251
252/// 本地状态的读写。目录不可写时退化成不持久化。
253#[derive(Debug)]
254enum Storage {
255    File(PathBuf),
256    Memory(Mutex<HashMap<String, String>>),
257    Null,
258}
259
260impl Storage {
261    fn read(&self, key: &str) -> Option<String> {
262        match self {
263            Storage::File(path) => Self::read_file(path).get(key).cloned(),
264            Storage::Memory(map) => map.lock().ok()?.get(key).cloned(),
265            Storage::Null => None,
266        }
267    }
268
269    fn write(&self, key: &str, value: &str) {
270        match self {
271            Storage::File(path) => {
272                let mut data = Self::read_file(path);
273                data.insert(key.to_string(), value.to_string());
274                Self::write_file(path, &data);
275            }
276            Storage::Memory(map) => {
277                if let Ok(mut guard) = map.lock() {
278                    guard.insert(key.to_string(), value.to_string());
279                }
280            }
281            Storage::Null => {}
282        }
283    }
284
285    fn remove(&self, key: &str) {
286        match self {
287            Storage::File(path) => {
288                let mut data = Self::read_file(path);
289                data.remove(key);
290                Self::write_file(path, &data);
291            }
292            Storage::Memory(map) => {
293                if let Ok(mut guard) = map.lock() {
294                    guard.remove(key);
295                }
296            }
297            Storage::Null => {}
298        }
299    }
300
301    fn read_file(path: &PathBuf) -> HashMap<String, String> {
302        std::fs::read_to_string(path)
303            .ok()
304            .and_then(|raw| serde_json::from_str(&raw).ok())
305            .unwrap_or_default()
306    }
307
308    fn write_file(path: &PathBuf, data: &HashMap<String, String>) {
309        if let Some(parent) = path.parent() {
310            if std::fs::create_dir_all(parent).is_err() {
311                log::debug!("verhub: 事件采集状态目录不可写,本次不持久化");
312                return;
313            }
314        }
315        let Ok(raw) = serde_json::to_string(data) else {
316            log::debug!("verhub: 事件采集状态序列化失败");
317            return;
318        };
319
320        // 先写临时文件再 rename,写入过程中崩溃不会留下半个 JSON。
321        let tmp = path.with_extension(format!("{}.tmp", std::process::id()));
322        if std::fs::write(&tmp, raw).is_err() {
323            log::debug!("verhub: 事件采集状态写入失败,本次不持久化");
324            let _ = std::fs::remove_file(&tmp);
325            return;
326        }
327        if std::fs::rename(&tmp, path).is_err() {
328            log::debug!("verhub: 事件采集状态替换失败,本次不持久化");
329            let _ = std::fs::remove_file(&tmp);
330        }
331    }
332}
333
334#[derive(Debug)]
335struct QueueState {
336    queue: Vec<QueuedEvent>,
337    distinct_id: Option<String>,
338    session_id: Option<String>,
339    last_event_at: Option<Instant>,
340    last_flush_at: Option<Instant>,
341    failures: u32,
342    opted_out: bool,
343    consented: bool,
344}
345
346/// 事件队列:攒批入队,满一批或距上次发送超过 `flush_interval` 时要求发送。
347///
348/// 每条事件带 `event_id` 幂等键,重发不会在服务端产生重复。队列本身不发请求,
349/// 取批与提交由 [`crate::PublicApi`] 驱动。
350#[derive(Debug)]
351pub struct EventQueue {
352    options: AnalyticsOptions,
353    storage: Storage,
354    prefix: String,
355    /// 本地状态的命名空间。调用方据此判断绑定项目变化后要不要重建队列。
356    namespace: String,
357    state: Mutex<QueueState>,
358}
359
360impl EventQueue {
361    pub(crate) fn new(namespace: &str, mut options: AnalyticsOptions) -> Self {
362        options.batch_size = options.batch_size.clamp(1, SERVER_BATCH_MAX);
363
364        // 显式的 namespace 选项优先于调用方算出来的那个。
365        let resolved = options
366            .namespace
367            .clone()
368            .unwrap_or_else(|| namespace.to_string());
369
370        let storage = match options.persistence {
371            AnalyticsPersistence::Device => Storage::File(
372                options
373                    .state_path
374                    .clone()
375                    .unwrap_or_else(|| default_state_path(&resolved)),
376            ),
377            AnalyticsPersistence::Session => Storage::Memory(Mutex::new(HashMap::new())),
378            AnalyticsPersistence::None => Storage::Null,
379        };
380
381        let prefix = format!("verhub.analytics.{resolved}.");
382
383        let opted_out = storage.read(&format!("{prefix}opt_out")).as_deref() == Some("1");
384        let consented = !options.require_consent;
385
386        let mut queue = Vec::new();
387        if options.enabled && !opted_out && consented {
388            if let Some(raw) = storage.read(&format!("{prefix}queue")) {
389                match serde_json::from_str::<Vec<QueuedEvent>>(&raw) {
390                    Ok(mut restored) => {
391                        if restored.len() > options.max_queue_size {
392                            restored.drain(..restored.len() - options.max_queue_size);
393                        }
394                        queue = restored;
395                    }
396                    Err(_) => storage.remove(&format!("{prefix}queue")),
397                }
398            }
399        }
400
401        Self {
402            options,
403            storage,
404            prefix,
405            namespace: resolved,
406            state: Mutex::new(QueueState {
407                queue,
408                distinct_id: None,
409                session_id: None,
410                last_event_at: None,
411                // 以构造时刻起算,第一条事件不会立刻触发一次单条发送。
412                last_flush_at: Some(Instant::now()),
413                failures: 0,
414                opted_out,
415                consented,
416            }),
417        }
418    }
419
420    /// 当前是否会采集。为 false 时不生成标识、不落盘、不发请求。
421    pub fn active(&self) -> bool {
422        let state = match self.state.lock() {
423            Ok(state) => state,
424            Err(_) => return false,
425        };
426        self.options.enabled && !state.opted_out && state.consented
427    }
428
429    /// 当前是否处于退出状态。
430    pub fn has_opted_out(&self) -> bool {
431        self.state.lock().map(|s| s.opted_out).unwrap_or(false)
432    }
433
434    /// 停止采集、丢弃待发队列、删除本地匿名标识,并把退出标记写入本地。
435    pub fn opt_out(&self) {
436        if let Ok(mut state) = self.state.lock() {
437            state.opted_out = true;
438            state.consented = !self.options.require_consent;
439            state.queue.clear();
440            state.distinct_id = None;
441            state.session_id = None;
442        }
443        self.storage.remove(&format!("{}distinct_id", self.prefix));
444        self.storage.remove(&format!("{}queue", self.prefix));
445        self.storage.write(&format!("{}opt_out", self.prefix), "1");
446    }
447
448    /// 撤销退出,并生成一个新的匿名标识。
449    pub fn opt_in(&self) {
450        if let Ok(mut state) = self.state.lock() {
451            state.opted_out = false;
452        }
453        self.storage.remove(&format!("{}opt_out", self.prefix));
454        self.reset_identity();
455    }
456
457    /// `require_consent` 模式下开闸。在此之前不会有任何字节写入设备。
458    pub fn grant_consent(&self) {
459        if let Ok(mut state) = self.state.lock() {
460            state.consented = true;
461        }
462    }
463
464    /// 撤回同意,等价于 [`EventQueue::opt_out`] 并回到未同意状态。
465    pub fn revoke_consent(&self) {
466        self.opt_out();
467        if let Ok(mut state) = self.state.lock() {
468            state.consented = false;
469        }
470    }
471
472    /// 换一个新的匿名标识,切断与既往事件序列的关联。
473    pub fn reset_identity(&self) {
474        if let Ok(mut state) = self.state.lock() {
475            state.distinct_id = None;
476            state.session_id = None;
477        }
478        self.storage.remove(&format!("{}distinct_id", self.prefix));
479    }
480
481    /// 当前的匿名标识;未采集状态下返回 `None`,且不会顺带生成一个。
482    pub fn current_distinct_id(&self) -> Option<String> {
483        if !self.active() {
484            return None;
485        }
486        Some(self.identity())
487    }
488
489    /// 入队一条事件,返回是否该立即发送(攒够一批,或距上次发送已超过间隔)。
490    pub(crate) fn enqueue(&self, name: &str, properties: Option<Map<String, Value>>) -> bool {
491        if !self.active() {
492            return false;
493        }
494
495        let event = QueuedEvent {
496            event_id: random_id(),
497            name: name.to_string(),
498            occurred_at: now_seconds(),
499            properties,
500        };
501
502        let should_flush = {
503            let mut state = match self.state.lock() {
504                Ok(state) => state,
505                Err(_) => return false,
506            };
507
508            state.queue.push(event);
509            if state.queue.len() > self.options.max_queue_size {
510                let excess = state.queue.len() - self.options.max_queue_size;
511                state.queue.drain(..excess);
512            }
513
514            // 空闲超过 session_timeout 就换一个会话号。会话号从不落盘。
515            let now = Instant::now();
516            // map_or 而不是 is_none_or:后者要 Rust 1.82,本 crate 的 MSRV 是 1.75。
517            let stale = state.last_event_at.map_or(true, |at| {
518                now.duration_since(at) > self.options.session_timeout
519            });
520            if state.session_id.is_none() || stale {
521                state.session_id = Some(random_id());
522            }
523            state.last_event_at = Some(now);
524
525            let due = state.last_flush_at.map_or(true, |at| {
526                now.duration_since(at) >= self.options.flush_interval
527            });
528            state.queue.len() >= self.options.batch_size || due
529        };
530
531        self.persist_queue();
532        should_flush
533    }
534
535    /// 取出下一批待发送的载荷;没有可发的返回 `None`。
536    pub(crate) fn take_batch(&self) -> Option<EventBatch> {
537        let distinct_id = self.current_distinct_id()?;
538        let state = self.state.lock().ok()?;
539        if state.queue.is_empty() {
540            return None;
541        }
542
543        let size = state.queue.len().min(self.options.batch_size);
544        Some(EventBatch {
545            distinct_id,
546            session_id: state.session_id.clone(),
547            events: state.queue[..size].to_vec(),
548        })
549    }
550
551    /// 一批发送成功后从队列里摘掉。
552    pub(crate) fn commit(&self, sent: usize) {
553        if let Ok(mut state) = self.state.lock() {
554            let sent = sent.min(state.queue.len());
555            state.queue.drain(..sent);
556            state.failures = 0;
557            state.last_flush_at = Some(Instant::now());
558        }
559        self.persist_queue();
560    }
561
562    /// 记一次失败并返回下次重试前应等待的时长(指数退避,封顶 [`MAX_BACKOFF`])。
563    pub(crate) fn record_failure(&self) -> Duration {
564        let failures = {
565            let mut state = match self.state.lock() {
566                Ok(state) => state,
567                Err(_) => return self.options.flush_interval,
568            };
569            state.failures = state.failures.saturating_add(1);
570            // 失败也算「试过了」,否则每次 track 都会立刻重试同一批。
571            state.last_flush_at = Some(Instant::now());
572            state.failures
573        };
574        self.options
575            .flush_interval
576            .saturating_mul(2u32.saturating_pow(failures.saturating_sub(1).min(16)))
577            .min(MAX_BACKOFF)
578    }
579
580    /// 本地状态的命名空间。绑定项目变了就该按新命名空间重建队列。
581    pub fn namespace(&self) -> &str {
582        &self.namespace
583    }
584
585    /// 队列里还剩多少条。
586    pub fn pending(&self) -> usize {
587        self.state.lock().map(|s| s.queue.len()).unwrap_or(0)
588    }
589
590    /// 匿名标识。`persistence` 为 `None` 时每次返回一个不落盘的临时标识。
591    fn identity(&self) -> String {
592        if let Ok(state) = self.state.lock() {
593            if let Some(id) = state.distinct_id.clone() {
594                return id;
595            }
596        }
597
598        let key = format!("{}distinct_id", self.prefix);
599        if let Some(stored) = self.storage.read(&key) {
600            if let Ok(mut state) = self.state.lock() {
601                state.distinct_id = Some(stored.clone());
602            }
603            return stored;
604        }
605
606        let created = random_id();
607        if let Ok(mut state) = self.state.lock() {
608            state.distinct_id = Some(created.clone());
609        }
610        self.storage.write(&key, &created);
611        created
612    }
613
614    fn persist_queue(&self) {
615        if self.options.persistence != AnalyticsPersistence::Device {
616            return;
617        }
618        let snapshot = match self.state.lock() {
619            Ok(state) => serde_json::to_string(&state.queue).ok(),
620            Err(_) => None,
621        };
622        if let Some(raw) = snapshot {
623            self.storage.write(&format!("{}queue", self.prefix), &raw);
624        }
625    }
626}
627
628#[cfg(test)]
629mod tests {
630    use super::*;
631
632    fn memory_queue(options: AnalyticsOptions) -> EventQueue {
633        let mut queue = EventQueue::new("test", options);
634        // 测试一律用内存存储,不碰真实用户目录。
635        queue.storage = Storage::Memory(Mutex::new(HashMap::new()));
636        queue
637    }
638
639    fn session_options() -> AnalyticsOptions {
640        AnalyticsOptions {
641            persistence: AnalyticsPersistence::Session,
642            ..Default::default()
643        }
644    }
645
646    #[test]
647    fn random_id_is_a_well_formed_uuid_v4() {
648        let id = random_id();
649        assert_eq!(id.len(), 36);
650        assert_eq!(id.as_bytes()[14], b'4');
651        assert!(matches!(id.as_bytes()[19], b'8' | b'9' | b'a' | b'b'));
652        assert_ne!(random_id(), random_id());
653    }
654
655    #[test]
656    fn full_batch_asks_for_a_flush() {
657        let queue = memory_queue(AnalyticsOptions {
658            batch_size: 2,
659            flush_interval: Duration::from_secs(3600),
660            ..session_options()
661        });
662
663        // 第一条:既没满也没到间隔,不该要求发送。
664        assert!(!queue.enqueue("a", None));
665        assert!(queue.enqueue("b", None));
666    }
667
668    #[test]
669    fn every_event_carries_a_unique_idempotency_key() {
670        let queue = memory_queue(session_options());
671        queue.enqueue("a", None);
672        queue.enqueue("b", None);
673
674        let batch = queue.take_batch().expect("batch");
675        assert_eq!(batch.events.len(), 2);
676        assert_ne!(batch.events[0].event_id, batch.events[1].event_id);
677    }
678
679    #[test]
680    fn a_batch_shares_one_distinct_and_session_id() {
681        let queue = memory_queue(session_options());
682        queue.enqueue("a", None);
683
684        let batch = queue.take_batch().expect("batch");
685        assert!(!batch.distinct_id.is_empty());
686        assert!(batch.session_id.is_some());
687    }
688
689    #[test]
690    fn a_failed_batch_stays_queued_with_the_same_ids() {
691        let queue = memory_queue(session_options());
692        queue.enqueue("a", None);
693
694        let first = queue.take_batch().expect("batch");
695        queue.record_failure();
696
697        // 没有 commit,事件仍在队列里,幂等键不变。
698        let retry = queue.take_batch().expect("batch");
699        assert_eq!(first.events[0].event_id, retry.events[0].event_id);
700    }
701
702    #[test]
703    fn commit_removes_only_what_was_sent() {
704        let queue = memory_queue(AnalyticsOptions {
705            batch_size: 1,
706            ..session_options()
707        });
708        queue.enqueue("a", None);
709        queue.enqueue("b", None);
710        assert_eq!(queue.pending(), 2);
711
712        queue.commit(1);
713        assert_eq!(queue.pending(), 1);
714        assert_eq!(queue.take_batch().expect("batch").events[0].name, "b");
715    }
716
717    #[test]
718    fn opt_out_drops_the_queue_and_survives_a_restart() {
719        let path = std::env::temp_dir().join(format!("verhub-test-{}.json", random_id()));
720        let options = AnalyticsOptions {
721            state_path: Some(path.clone()),
722            ..Default::default()
723        };
724
725        let queue = EventQueue::new("test", options.clone());
726        queue.enqueue("a", None);
727        queue.opt_out();
728
729        assert_eq!(queue.pending(), 0);
730        assert!(queue.take_batch().is_none());
731        assert!(queue.current_distinct_id().is_none());
732
733        // 退出标记落了盘,重启后仍然生效。
734        let restarted = EventQueue::new("test", options);
735        assert!(restarted.has_opted_out());
736        assert!(!restarted.active());
737
738        let _ = std::fs::remove_file(&path);
739    }
740
741    #[test]
742    fn opt_in_mints_a_new_identity_instead_of_reusing_the_old_one() {
743        let queue = memory_queue(session_options());
744        let before = queue.current_distinct_id().expect("id");
745
746        queue.opt_out();
747        queue.opt_in();
748
749        let after = queue.current_distinct_id().expect("id");
750        assert_ne!(before, after);
751    }
752
753    #[test]
754    fn require_consent_collects_nothing_before_consent() {
755        let queue = memory_queue(AnalyticsOptions {
756            require_consent: true,
757            ..session_options()
758        });
759
760        assert!(!queue.active());
761        assert!(!queue.enqueue("a", None));
762        assert_eq!(queue.pending(), 0);
763        assert!(queue.current_distinct_id().is_none());
764
765        queue.grant_consent();
766        assert!(queue.active());
767        queue.enqueue("b", None);
768        assert_eq!(queue.pending(), 1);
769    }
770
771    #[test]
772    fn disabled_queue_is_a_no_op() {
773        let queue = memory_queue(AnalyticsOptions {
774            enabled: false,
775            ..session_options()
776        });
777        assert!(!queue.enqueue("a", None));
778        assert_eq!(queue.pending(), 0);
779    }
780
781    #[test]
782    fn oversized_queue_drops_the_oldest() {
783        let queue = memory_queue(AnalyticsOptions {
784            max_queue_size: 2,
785            batch_size: 10,
786            ..session_options()
787        });
788        queue.enqueue("a", None);
789        queue.enqueue("b", None);
790        queue.enqueue("c", None);
791
792        let batch = queue.take_batch().expect("batch");
793        let names: Vec<_> = batch.events.iter().map(|e| e.name.as_str()).collect();
794        assert_eq!(names, ["b", "c"]);
795    }
796
797    #[test]
798    fn restart_replays_what_was_never_sent() {
799        let path = std::env::temp_dir().join(format!("verhub-test-{}.json", random_id()));
800        let options = AnalyticsOptions {
801            state_path: Some(path.clone()),
802            ..Default::default()
803        };
804
805        let first = EventQueue::new("test", options.clone());
806        first.enqueue("a", None);
807        let queued = first.take_batch().expect("batch");
808
809        let restarted = EventQueue::new("test", options);
810        let replayed = restarted.take_batch().expect("batch");
811        assert_eq!(replayed.events[0].event_id, queued.events[0].event_id);
812
813        let _ = std::fs::remove_file(&path);
814    }
815
816    #[test]
817    fn persistence_none_writes_nothing_locally() {
818        let queue = EventQueue::new(
819            "test",
820            AnalyticsOptions {
821                persistence: AnalyticsPersistence::None,
822                ..Default::default()
823            },
824        );
825        queue.enqueue("a", None);
826
827        assert!(matches!(queue.storage, Storage::Null));
828        assert!(queue.storage.read("anything").is_none());
829    }
830
831    #[test]
832    fn backoff_grows_and_stays_capped() {
833        let queue = memory_queue(AnalyticsOptions {
834            flush_interval: Duration::from_secs(5),
835            ..session_options()
836        });
837
838        assert_eq!(queue.record_failure(), Duration::from_secs(5));
839        assert_eq!(queue.record_failure(), Duration::from_secs(10));
840        assert_eq!(queue.record_failure(), Duration::from_secs(20));
841        for _ in 0..20 {
842            queue.record_failure();
843        }
844        assert_eq!(queue.record_failure(), MAX_BACKOFF);
845    }
846}
847
848#[cfg(test)]
849mod namespace_tests {
850    use super::*;
851
852    /// 这组固定向量在 TypeScript / Python / 纯 JS 版里逐字相同。
853    const ORIGIN_CASES: &[(&str, &str)] = &[
854        (
855            "https://verhub.example.com/api/v1",
856            "https://verhub.example.com",
857        ),
858        (
859            "https://verhub.example.com/v2/api/v1",
860            "https://verhub.example.com",
861        ),
862        ("https://verhub.example.com", "https://verhub.example.com"),
863        (
864            "HTTPS://Verhub.Example.COM/api/v1",
865            "https://verhub.example.com",
866        ),
867        (
868            "https://verhub.example.com:443/api/v1",
869            "https://verhub.example.com",
870        ),
871        (
872            "http://verhub.example.com:80/api/v1",
873            "http://verhub.example.com",
874        ),
875        (
876            "http://verhub.example.com:3080/api/v1",
877            "http://verhub.example.com:3080",
878        ),
879        (
880            "https://user:pass@verhub.example.com/api/v1",
881            "https://verhub.example.com",
882        ),
883        ("http://[::1]:3080/api/v1", "http://[::1]:3080"),
884        ("https://[::1]:443/api/v1", "https://[::1]"),
885    ];
886
887    #[test]
888    fn origin_只取协议主机端口() {
889        for (raw, expected) in ORIGIN_CASES {
890            assert_eq!(&origin_of(raw), expected, "{raw}");
891        }
892    }
893
894    #[test]
895    fn fnv1a_与其余三个语言逐位一致() {
896        assert_eq!(fnv1a32_hex(""), "811c9dc5");
897        assert_eq!(fnv1a32_hex("a"), "e40c292c");
898        assert_eq!(fnv1a32_hex("foobar"), "bf9cf968");
899        assert_eq!(fnv1a32_hex("https://verhub.example.com"), "8e08b085");
900        // 非 ASCII 按 UTF-8 字节算。
901        assert_eq!(fnv1a32_hex("héllo"), "4aa48540");
902    }
903
904    #[test]
905    fn 命名空间带实例哈希且project_key小写化() {
906        let ns = analytics_namespace("https://verhub.example.com/api/v1", Some("Demo"));
907        assert_eq!(ns, "8e08b085-demo");
908        assert_eq!(
909            analytics_namespace("https://verhub.example.com/v2/api/v1", Some("demo")),
910            ns
911        );
912    }
913
914    #[test]
915    fn 同project_key的两个实例互不相同() {
916        assert_ne!(
917            analytics_namespace("https://a.example.com/api/v1", Some("demo")),
918            analytics_namespace("https://b.example.com/api/v1", Some("demo"))
919        );
920    }
921
922    #[test]
923    fn 没绑定项目时回落到default() {
924        // 空串与纯空白也回落到 default,四个语言的 SDK 一致。
925        for key in [None, Some(""), Some("  ")] {
926            assert!(
927                analytics_namespace("https://a.example.com/api/v1", key).ends_with("-default"),
928                "{key:?}"
929            );
930        }
931    }
932
933    #[test]
934    fn 状态文件按命名空间分开() {
935        let a = default_state_path("8e08b085-demo");
936        let b = default_state_path("8e08b085-other");
937        assert_eq!(a.file_name().unwrap(), "8e08b085-demo.json");
938        assert_eq!(a.parent(), b.parent());
939        assert_ne!(a, b);
940    }
941
942    #[test]
943    fn 文件名清洗掉路径分隔符() {
944        assert_eq!(file_safe("abc-a/b"), "abc-a_b");
945        assert_eq!(file_safe(r"abc-a\b"), "abc-a_b");
946        assert!(!file_safe("abc-../x").contains('/'));
947    }
948}