1use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::OnceLock;
7use std::time::{Duration, SystemTime};
8
9#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11pub struct JobId(pub String);
12
13impl JobId {
14 pub fn generate() -> Self {
22 static PREFIX: OnceLock<String> = OnceLock::new();
23 static COUNTER: AtomicU64 = AtomicU64::new(0);
24
25 let prefix = PREFIX.get_or_init(|| {
26 let nanos = SystemTime::now()
27 .duration_since(SystemTime::UNIX_EPOCH)
28 .unwrap_or_default()
29 .as_nanos();
30 format!("{nanos:x}{:x}", std::process::id())
31 });
32 let sequence = COUNTER.fetch_add(1, Ordering::Relaxed);
33 Self(format!("{prefix}-{sequence:x}"))
34 }
35}
36
37impl std::fmt::Display for JobId {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 write!(f, "{}", self.0)
40 }
41}
42
43#[derive(Debug, Clone)]
45pub struct Job {
46 pub id: JobId,
48 pub topic: String,
50 pub payload: Vec<u8>,
52 pub attempt: u32,
54 pub enqueued_at: SystemTime,
56 pub delivered_at: Option<SystemTime>,
58 pub visibility_timeout: Option<Duration>,
60}
61
62impl Job {
63 pub fn new(id: JobId, topic: &str, payload: Vec<u8>) -> Self {
64 let now = SystemTime::now();
67 Self {
68 id,
69 topic: topic.to_string(),
70 payload,
71 attempt: 0,
72 enqueued_at: now,
73 delivered_at: Some(now),
74 visibility_timeout: None,
75 }
76 }
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82
83 #[test]
84 fn generated_ids_are_unique() {
85 let a = JobId::generate();
86 let b = JobId::generate();
87 assert_ne!(a, b);
88 }
89
90 #[test]
91 fn generated_ids_share_the_process_prefix() {
92 let a = JobId::generate().0;
93 let b = JobId::generate().0;
94 let prefix = |s: &str| s.rsplit_once('-').unwrap().0.to_owned();
95 assert_eq!(prefix(&a), prefix(&b));
96 }
97}