Skip to main content

worklane_core/
id.rs

1use std::fmt;
2use std::str::FromStr;
3
4use serde::{Deserialize, Serialize};
5use uuid::Uuid;
6
7/// A unique identifier for an enqueued job.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
9pub struct JobId(Uuid);
10
11impl JobId {
12    /// Generate a new random (v4) job id.
13    pub fn new() -> Self {
14        JobId(Uuid::new_v4())
15    }
16}
17
18impl Default for JobId {
19    fn default() -> Self {
20        Self::new()
21    }
22}
23
24impl fmt::Display for JobId {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        write!(f, "{}", self.0)
27    }
28}
29
30/// The error returned when [`JobId`] fails to parse from a string.
31///
32/// Wraps the underlying parse failure as text so the `uuid` crate does not leak
33/// into worklane's public API (a `uuid` major bump would otherwise be a breaking
34/// change here).
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct JobIdParseError(String);
37
38impl fmt::Display for JobIdParseError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        write!(f, "invalid job id: {}", self.0)
41    }
42}
43
44impl std::error::Error for JobIdParseError {}
45
46impl FromStr for JobId {
47    type Err = JobIdParseError;
48
49    fn from_str(s: &str) -> Result<Self, Self::Err> {
50        Uuid::parse_str(s)
51            .map(JobId)
52            .map_err(|e| JobIdParseError(e.to_string()))
53    }
54}