Skip to main content

mytheclipse_queue/
job.rs

1//! The `Job` type and its metadata.
2//!
3//! A minimal, dependency-free in-process job queue using `tokio::sync::mpsc`.
4
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::OnceLock;
7use std::time::{Duration, SystemTime};
8
9/// A unique identifier for a queued job.
10#[derive(Debug, Clone, PartialEq, Eq, Hash)]
11pub struct JobId(pub String);
12
13impl JobId {
14    /// Generates an id that is unique within this process and across restarts.
15    ///
16    /// The prefix is fixed once per process from the start instant and the pid,
17    /// so two runs never overlap; the suffix is a monotonic counter, so two jobs
18    /// in one run never collide. This replaces a random UUID: uniqueness is the
19    /// only property callers need, and a counter gets it without a random
20    /// source or a 36-byte string.
21    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/// A unit of queued work.
44#[derive(Debug, Clone)]
45pub struct Job {
46    /// The unique ID of this job.
47    pub id: JobId,
48    /// The topic/queue name the job was delivered from.
49    pub topic: String,
50    /// The raw payload bytes.
51    pub payload: Vec<u8>,
52    /// How many times this job has been attempted (0 = first attempt).
53    pub attempt: u32,
54    /// When the job was first enqueued.
55    pub enqueued_at: SystemTime,
56    /// When the job was delivered to the worker (None if not yet delivered).
57    pub delivered_at: Option<SystemTime>,
58    /// Optional visibility timeout - after this the job becomes visible again.
59    pub visibility_timeout: Option<Duration>,
60}
61
62impl Job {
63    pub fn new(id: JobId, topic: &str, payload: Vec<u8>) -> Self {
64        // One clock read for both timestamps: they describe the same instant,
65        // and `SystemTime::now()` is not free.
66        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}