1use 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
20pub const DEFAULT_FLUSH_INTERVAL: Duration = Duration::from_secs(5);
22
23pub const DEFAULT_BATCH_SIZE: usize = 20;
25
26pub const DEFAULT_MAX_QUEUE_SIZE: usize = 500;
28
29pub const DEFAULT_SESSION_TIMEOUT: Duration = Duration::from_secs(30 * 60);
31
32const SERVER_BATCH_MAX: usize = 50;
34
35const MAX_BACKOFF: Duration = Duration::from_secs(60);
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
40pub enum AnalyticsPersistence {
41 #[default]
43 Device,
44 Session,
46 None,
48}
49
50#[derive(Debug, Clone)]
52pub struct AnalyticsOptions {
53 pub enabled: bool,
55 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 pub state_path: Option<PathBuf>,
65 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#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct QueuedEvent {
90 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#[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
107pub 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 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
151pub 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 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
186pub 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
198pub 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
212fn 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
227fn 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#[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 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#[derive(Debug)]
351pub struct EventQueue {
352 options: AnalyticsOptions,
353 storage: Storage,
354 prefix: String,
355 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 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 last_flush_at: Some(Instant::now()),
413 failures: 0,
414 opted_out,
415 consented,
416 }),
417 }
418 }
419
420 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 pub fn has_opted_out(&self) -> bool {
431 self.state.lock().map(|s| s.opted_out).unwrap_or(false)
432 }
433
434 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 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 pub fn grant_consent(&self) {
459 if let Ok(mut state) = self.state.lock() {
460 state.consented = true;
461 }
462 }
463
464 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 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 pub fn current_distinct_id(&self) -> Option<String> {
483 if !self.active() {
484 return None;
485 }
486 Some(self.identity())
487 }
488
489 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 let now = Instant::now();
516 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 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 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 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 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 pub fn namespace(&self) -> &str {
582 &self.namespace
583 }
584
585 pub fn pending(&self) -> usize {
587 self.state.lock().map(|s| s.queue.len()).unwrap_or(0)
588 }
589
590 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 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 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 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 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 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 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 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}