use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::OnceLock;
use std::time::{Duration, SystemTime};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct JobId(pub String);
impl JobId {
pub fn generate() -> Self {
static PREFIX: OnceLock<String> = OnceLock::new();
static COUNTER: AtomicU64 = AtomicU64::new(0);
let prefix = PREFIX.get_or_init(|| {
let nanos = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_nanos() as u64;
let mut prefix = String::with_capacity(32);
push_hex(&mut prefix, nanos);
push_hex(&mut prefix, u64::from(std::process::id()));
prefix
});
let sequence = COUNTER.fetch_add(1, Ordering::Relaxed);
let mut id = String::with_capacity(prefix.len() + 17);
id.push_str(prefix);
id.push('-');
push_hex(&mut id, sequence);
Self(id)
}
}
fn push_hex(out: &mut String, value: u64) {
const DIGITS: &[u8; 16] = b"0123456789abcdef";
let mut buf = [0u8; 16];
let mut cursor = buf.len();
let mut rest = value;
loop {
cursor -= 1;
buf[cursor] = DIGITS[(rest & 0xf) as usize];
rest >>= 4;
if rest == 0 {
break;
}
}
out.push_str(std::str::from_utf8(&buf[cursor..]).expect("hex digits are ASCII"));
}
impl std::fmt::Display for JobId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
#[derive(Debug, Clone)]
pub struct Job {
pub id: JobId,
pub topic: String,
pub payload: Vec<u8>,
pub attempt: u32,
pub enqueued_at: SystemTime,
pub delivered_at: Option<SystemTime>,
pub visibility_timeout: Option<Duration>,
}
impl Job {
pub fn new(id: JobId, topic: &str, payload: Vec<u8>) -> Self {
let now = SystemTime::now();
Self {
id,
topic: topic.to_string(),
payload,
attempt: 0,
enqueued_at: now,
delivered_at: Some(now),
visibility_timeout: None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn generated_ids_are_unique() {
let a = JobId::generate();
let b = JobId::generate();
assert_ne!(a, b);
}
#[test]
fn generated_ids_share_the_process_prefix() {
let a = JobId::generate().0;
let b = JobId::generate().0;
let prefix = |s: &str| s.rsplit_once('-').unwrap().0.to_owned();
assert_eq!(prefix(&a), prefix(&b));
}
}