apalis_core/task/
task_id.rs

1//! Defines the `TaskId` type and related functionality.
2//!
3//! `TaskId` is a wrapper around a generic identifier type, providing type safety and utility methods for task identification.
4//!
5use std::{
6    fmt::{Debug, Display},
7    hash::Hash,
8    str::FromStr,
9};
10
11use crate::{
12    task::{Task, data::MissingDataError},
13    task_fn::FromRequest,
14};
15
16pub use random_id::RandomId;
17
18/// A wrapper type that defines a task id.
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq, PartialOrd, Ord)]
21pub struct TaskId<IdType = RandomId>(IdType);
22
23impl<IdType> TaskId<IdType> {
24    /// Generate a new [`TaskId`]
25    pub fn new(id: IdType) -> Self {
26        Self(id)
27    }
28    /// Get the inner value
29    pub fn inner(&self) -> &IdType {
30        &self.0
31    }
32}
33
34/// Errors that can occur when parsing a `TaskId` from a string
35#[derive(Debug, thiserror::Error)]
36pub enum TaskIdError<E> {
37    /// Decoding error
38    #[error("could not decode task_id: `{0}`")]
39    Decode(E),
40}
41
42impl<IdType: FromStr> FromStr for TaskId<IdType> {
43    type Err = TaskIdError<IdType::Err>;
44    fn from_str(s: &str) -> Result<Self, Self::Err> {
45        Ok(Self::new(IdType::from_str(s).map_err(TaskIdError::Decode)?))
46    }
47}
48
49impl<IdType: FromStr> TryFrom<&'_ str> for TaskId<IdType> {
50    type Error = TaskIdError<IdType::Err>;
51
52    fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
53        Self::from_str(value)
54    }
55}
56
57impl<IdType: Display> Display for TaskId<IdType> {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        Display::fmt(&self.0, f)
60    }
61}
62
63impl<Args: Sync, Ctx: Sync, IdType: Sync + Send + Clone> FromRequest<Task<Args, Ctx, IdType>>
64    for TaskId<IdType>
65{
66    type Error = MissingDataError;
67    async fn from_request(task: &Task<Args, Ctx, IdType>) -> Result<Self, Self::Error> {
68        task.parts.task_id.clone().ok_or(MissingDataError::NotFound(
69            std::any::type_name::<Self>().to_owned(),
70        ))
71    }
72}
73
74mod random_id {
75    use super::*;
76    use std::convert::Infallible;
77    use std::sync::atomic::{AtomicU64, Ordering};
78    use std::time::{SystemTime, UNIX_EPOCH};
79
80    const ALPHABET: &[u8] = b"abcdefghijkmnopqrstuvwxyz23456789-";
81    const BASE: u64 = 34;
82    const TIME_LEN: usize = 6;
83    const RANDOM_LEN: usize = 5;
84
85    /// A simple, unique, time-ordered ID (zero-deps).
86    ///
87    /// Consider using a ulid/uuid/nanoid in backend implementation
88    /// This is a placeholder and does not guarantee/tested as the other implementations
89    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
90    #[derive(Debug, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
91    pub struct RandomId(String);
92
93    impl FromStr for RandomId {
94        type Err = Infallible;
95        fn from_str(s: &str) -> Result<Self, Self::Err> {
96            Ok(Self(s.to_owned()))
97        }
98    }
99
100    #[allow(clippy::infallible_try_from)]
101    impl TryFrom<&'_ str> for RandomId {
102        type Error = Infallible;
103
104        fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
105            Self::from_str(value)
106        }
107    }
108
109    impl Display for RandomId {
110        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111            Display::fmt(&self.0, f)
112        }
113    }
114
115    impl Default for RandomId {
116        fn default() -> Self {
117            Self(unique_id())
118        }
119    }
120
121    // Atomic counter to ensure uniqueness within same millisecond
122    static COUNTER: AtomicU64 = AtomicU64::new(0);
123
124    /// Converts a number to base-64 using the NanoID alphabet.
125    fn encode_base64(mut value: u64, length: usize) -> String {
126        let mut buf = vec![b'A'; length];
127        for i in (0..length).rev() {
128            buf[i] = ALPHABET[(value % BASE) as usize];
129            value /= BASE;
130        }
131        String::from_utf8(buf).unwrap()
132    }
133
134    /// Generates a unique, time-ordered NanoID-style string (zero-deps).
135    pub(super) fn unique_id() -> String {
136        let timestamp = current_time_millis();
137        let time_str = encode_base64(timestamp, TIME_LEN);
138
139        // Counter ensures uniqueness across fast calls
140        let count = COUNTER.fetch_add(1, Ordering::Relaxed);
141        let rand_part = encode_base64(xorshift64(timestamp ^ count), RANDOM_LEN);
142
143        format!("{time_str}{rand_part}")
144    }
145
146    /// Returns current time in milliseconds since UNIX epoch.
147    fn current_time_millis() -> u64 {
148        SystemTime::now()
149            .duration_since(UNIX_EPOCH)
150            .unwrap_or_default()
151            .as_millis() as u64
152    }
153
154    /// Simple xorshift PRNG
155    fn xorshift64(mut x: u64) -> u64 {
156        x ^= x << 13;
157        x ^= x >> 7;
158        x ^= x << 17;
159        x
160    }
161}