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(TaskId::new(
46            IdType::from_str(s).map_err(TaskIdError::Decode)?,
47        ))
48    }
49}
50
51impl<IdType: FromStr> TryFrom<&'_ str> for TaskId<IdType> {
52    type Error = TaskIdError<IdType::Err>;
53
54    fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
55        Self::from_str(value)
56    }
57}
58
59impl<IdType: Display> Display for TaskId<IdType> {
60    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
61        Display::fmt(&self.0, f)
62    }
63}
64
65impl<Args: Sync, Ctx: Sync, IdType: Sync + Send + Clone> FromRequest<Task<Args, Ctx, IdType>>
66    for TaskId<IdType>
67{
68    type Error = MissingDataError;
69    async fn from_request(task: &Task<Args, Ctx, IdType>) -> Result<Self, Self::Error> {
70        task.parts.task_id.clone().ok_or(MissingDataError::NotFound(
71            std::any::type_name::<TaskId<IdType>>().to_string(),
72        ))
73    }
74}
75
76mod random_id {
77    use super::*;
78    use std::convert::Infallible;
79    use std::sync::atomic::{AtomicU64, Ordering};
80    use std::time::{SystemTime, UNIX_EPOCH};
81
82    const ALPHABET: &[u8] = b"abcdefghijkmnopqrstuvwxyz23456789-";
83    const BASE: u64 = 34;
84    const TIME_LEN: usize = 6;
85    const RANDOM_LEN: usize = 5;
86
87    /// A simple, unique, time-ordered ID (zero-deps).
88    ///
89    /// Consider using a ulid/uuid/nanoid in backend implementation
90    /// This is a placeholder and does not guarantee/tested as the other implementations
91    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
92    #[derive(Debug, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
93    pub struct RandomId(String);
94
95    impl FromStr for RandomId {
96        type Err = Infallible;
97        fn from_str(s: &str) -> Result<Self, Self::Err> {
98            Ok(RandomId(s.to_owned()))
99        }
100    }
101
102    impl TryFrom<&'_ str> for RandomId {
103        type Error = Infallible;
104
105        fn try_from(value: &'_ str) -> Result<Self, Self::Error> {
106            Self::from_str(value)
107        }
108    }
109
110    impl Display for RandomId {
111        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112            Display::fmt(&self.0, f)
113        }
114    }
115
116    impl Default for RandomId {
117        fn default() -> Self {
118            RandomId(unique_id())
119        }
120    }
121
122    // Atomic counter to ensure uniqueness within same millisecond
123    static COUNTER: AtomicU64 = AtomicU64::new(0);
124
125    /// Converts a number to base-64 using the NanoID alphabet.
126    fn encode_base64(mut value: u64, length: usize) -> String {
127        let mut buf = vec![b'A'; length];
128        for i in (0..length).rev() {
129            buf[i] = ALPHABET[(value % BASE) as usize];
130            value /= BASE;
131        }
132        String::from_utf8(buf).unwrap()
133    }
134
135    /// Generates a unique, time-ordered NanoID-style string (zero-deps).
136    pub(super) fn unique_id() -> String {
137        let timestamp = current_time_millis();
138        let time_str = encode_base64(timestamp, TIME_LEN);
139
140        // Counter ensures uniqueness across fast calls
141        let count = COUNTER.fetch_add(1, Ordering::Relaxed);
142        let rand_part = encode_base64(xorshift64(timestamp ^ count), RANDOM_LEN);
143
144        format!("{time_str}{rand_part}")
145    }
146
147    /// Returns current time in milliseconds since UNIX epoch.
148    fn current_time_millis() -> u64 {
149        SystemTime::now()
150            .duration_since(UNIX_EPOCH)
151            .unwrap_or_default()
152            .as_millis() as u64
153    }
154
155    /// Simple xorshift PRNG
156    fn xorshift64(mut x: u64) -> u64 {
157        x ^= x << 13;
158        x ^= x >> 7;
159        x ^= x << 17;
160        x
161    }
162}