apalis_core/task/
mod.rs

1//! Utilities for creating and managing tasks.
2//!
3//! The [`Task`] component encapsulates a unit of work to be executed,
4//! along with its associated context, metadata, and execution status. The [`Parts`]
5//! struct contains metadata, attempt tracking, extensions, and scheduling information for each task.
6//!
7//! # Overview
8//!
9//! In `apalis`, tasks are designed to represent discrete units of work that can be scheduled, retried, and tracked
10//! throughout their lifecycle. Each task consists of arguments (`args`) describing the work to be performed,
11//! and an [`Parts`] (`parts`) containing metadata and control information.
12//!
13//! ## [`Task`]
14//!
15//! The [`Task`] struct is generic over:
16//! - `Args`: The type of arguments or payload for the task.
17//! - `Ctx`: Ctxdata associated with the task, such as custom fields or backend-specific information.
18//! - `IdType`: The type used for uniquely identifying the task (defaults to [`RandomId`]).
19//!
20//! ## [`Parts`]
21//!
22//! The [`Parts`] struct provides the following:
23//! - `task_id`: Optionally stores a unique identifier for the task.
24//! - `data`: An [`Extensions`] container for storing arbitrary per-task data (e.g., middleware extensions).
25//! - `attempt`: Tracks how many times the task has been attempted.
26//! - `metadata`: Custom metadata for the task, provided by the backend or user.
27//! - `status`: The current [`Status`] of the task (e.g., Pending, Running, Completed, Failed).
28//! - `run_at`: The UNIX timestamp (in seconds) when the task should be run.
29//!
30//! The execution context is essential for tracking the state and metadata of a task as it moves through
31//! the system. It enables features such as retries, scheduling, and extensibility via the `Extensions` type.
32//!
33//! # Modules
34//!
35//! - [`attempt`]: Tracks the number of attempts a task has been executed.
36//! - [`builder`]: Utilities for constructing tasks.
37//! - [`data`]: Data types for task payloads.
38//! - [`extensions`]: Extension storage for tasks.
39//! - [`metadata`]: Ctxdata types for tasks.
40//! - [`status`]: Status tracking for tasks.
41//! - [`task_id`]: Types for uniquely identifying tasks.
42//!
43//! # Examples
44//!
45//! ## Creating a new task with default metadata
46//!
47//! ```rust
48//! # use apalis_core::task::{Task, Parts};
49//! # use apalis_core::task::builder::TaskBuilder;
50//! let task: Task<String, ()> = TaskBuilder::new("my work".to_string()).build();
51//! ```
52//!
53//! ## Creating a task with custom metadata
54//!
55//! ```rust
56//! # use apalis_core::task::{Task, Parts};
57//! # use apalis_core::task::builder::TaskBuilder;
58//! # use apalis_core::task::extensions::Extensions;
59//! 
60//! #[derive(Default, Clone)]
61//! struct MyCtx { priority: u8 }
62//! let task: Task<String, Extensions> = TaskBuilder::new("important work".to_string())
63//!     .meta(MyCtx { priority: 5 })
64//!     .build();
65//! ```
66//!
67//! ## Accessing and modifying the execution context
68//!
69//! ```rust
70//! use apalis_core::task::{Task, Parts, status::Status};
71//! let mut task = Task::<String, ()>::new("work".to_string());
72//! task.parts.status = Status::Running;
73//! task.parts.attempt.increment();
74//! ```
75//!
76//! ## Using Extensions for per-task data
77//!
78//! ```rust
79//! # use apalis_core::task::builder::TaskBuilder;
80//! use apalis_core::task::{Task, extensions::Extensions};
81//! #[derive(Debug, Clone, PartialEq)]
82//! pub struct TracingId(String);
83//! let mut extensions = Extensions::default();
84//! extensions.insert(TracingId("abc123".to_owned()));
85//! let task: Task<String, ()> = TaskBuilder::new("work".to_string()).with_data(extensions).build();
86//! assert_eq!(task.parts.data.get::<TracingId>(), Some(&TracingId("abc123".to_owned())));
87//! ```
88//!
89//! # See Also
90//!
91//! - [`Task`]: Represents a unit of work to be executed.
92//! - [`Parts`]: Holds metadata, status, and control information for a task.
93//! - [`Extensions`]: Type-safe storage for per-task data.
94//! - [`Status`]: Enum representing the lifecycle state of a task.
95//! - [`Attempt`]: Tracks the number of execution attempts for a task.
96//! - [`TaskId`]: Unique identifier type for tasks.
97//! - [`FromRequest`]: Trait for extracting data from task contexts.
98//! - [`IntoResponse`]: Trait for converting tasks into response types.
99//! - [`TaskBuilder`]: Fluent builder for constructing tasks with optional configuration.
100//! - [`RandomId`]: Default unique identifier type for tasks.
101//!
102//! [`TaskBuilder`]: crate::task::builder::TaskBuilder
103//! [`IntoResponse`]: crate::task_fn::into_response::IntoResponse
104//! [`FromRequest`]: crate::task_fn::from_request::FromRequest
105
106use std::{
107    fmt::Debug,
108    time::{SystemTime, UNIX_EPOCH},
109};
110
111use crate::{
112    task::{
113        attempt::Attempt,
114        builder::TaskBuilder,
115        extensions::Extensions,
116        status::Status,
117        task_id::{RandomId, TaskId},
118    },
119    task_fn::FromRequest,
120};
121
122pub mod attempt;
123pub mod builder;
124pub mod data;
125pub mod extensions;
126pub mod metadata;
127pub mod status;
128pub mod task_id;
129
130/// Represents a task which will be executed
131/// Should be considered a single unit of work
132#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
133#[derive(Debug, Clone, Default)]
134pub struct Task<Args, Context, IdType = RandomId> {
135    /// The argument task part
136    pub args: Args,
137    /// Parts of the task eg id, attempts and context
138    pub parts: Parts<Context, IdType>,
139}
140
141/// Component parts of a `Task`
142#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
143#[derive(Debug, Default)]
144pub struct Parts<Context, IdType = RandomId> {
145    /// The task's id if allocated
146    pub task_id: Option<TaskId<IdType>>,
147
148    /// The tasks's extensions
149    #[cfg_attr(feature = "serde", serde(skip))]
150    pub data: Extensions,
151
152    /// The tasks's attempts
153    /// Keeps track of the number of attempts a task has been worked on
154    pub attempt: Attempt,
155
156    /// The task specific data provided by the backend
157    pub ctx: Context,
158
159    /// The task status
160    pub status: Status,
161
162    /// The time a task should be run
163    pub run_at: u64,
164}
165
166impl<Ctx, IdType: Clone> Clone for Parts<Ctx, IdType>
167where
168    Ctx: Clone,
169{
170    fn clone(&self) -> Self {
171        Self {
172            task_id: self.task_id.clone(),
173            data: self.data.clone(),
174            attempt: self.attempt.clone(),
175            ctx: self.ctx.clone(),
176            status: self.status.clone(),
177            run_at: self.run_at,
178        }
179    }
180}
181
182impl<Args, Ctx, IdType> Task<Args, Ctx, IdType> {
183    /// Creates a new [Task]
184    pub fn new(args: Args) -> Self
185    where
186        Ctx: Default,
187    {
188        Self::new_with_data(args, Extensions::default(), Ctx::default())
189    }
190
191    /// Creates a task with context provided
192    pub fn new_with_ctx(req: Args, ctx: Ctx) -> Self {
193        Self {
194            args: req,
195            parts: Parts {
196                ctx,
197                task_id: Default::default(),
198                attempt: Default::default(),
199                data: Default::default(),
200                status: Status::Pending,
201                run_at: {
202                    let now = SystemTime::now();
203                    let duration_since_epoch =
204                        now.duration_since(UNIX_EPOCH).expect("Time went backwards");
205                    duration_since_epoch.as_secs()
206                },
207            },
208        }
209    }
210
211    /// Creates a task with data and context provided
212    pub fn new_with_data(req: Args, data: Extensions, ctx: Ctx) -> Self {
213        Self {
214            args: req,
215            parts: Parts {
216                ctx,
217                task_id: Default::default(),
218                attempt: Default::default(),
219                data,
220                status: Status::Pending,
221                run_at: {
222                    let now = SystemTime::now();
223                    let duration_since_epoch =
224                        now.duration_since(UNIX_EPOCH).expect("Time went backwards");
225                    duration_since_epoch.as_secs()
226                },
227            },
228        }
229    }
230
231    /// Take the task into its parts
232    pub fn take(self) -> (Args, Parts<Ctx, IdType>) {
233        (self.args, self.parts)
234    }
235
236    /// Extract a value of type `T` from the task's context
237    ///
238    /// Uses [FromRequest] trait to extract the value.
239    pub async fn extract<T: FromRequest<Self>>(&self) -> Result<T, T::Error> {
240        T::from_request(self).await
241    }
242
243    /// Converts the task into a builder pattern.
244    pub fn into_builder(self) -> TaskBuilder<Args, Ctx, IdType> {
245        TaskBuilder {
246            args: self.args,
247            ctx: self.parts.ctx,
248            attempt: Some(self.parts.attempt),
249            data: self.parts.data,
250            status: Some(self.parts.status),
251            run_at: Some(self.parts.run_at),
252            task_id: self.parts.task_id,
253        }
254    }
255}
256
257impl<Args, Ctx, IdType> Task<Args, Ctx, IdType> {
258    /// Maps the `args` field using the provided function, consuming the task.
259    pub fn try_map<F, NewArgs, Err>(self, f: F) -> Result<Task<NewArgs, Ctx, IdType>, Err>
260    where
261        F: FnOnce(Args) -> Result<NewArgs, Err>,
262    {
263        Ok(Task {
264            args: f(self.args)?,
265            parts: self.parts,
266        })
267    }
268    /// Maps the `args` field using the provided function, consuming the task.
269    pub fn map<F, NewArgs>(self, f: F) -> Task<NewArgs, Ctx, IdType>
270    where
271        F: FnOnce(Args) -> NewArgs,
272    {
273        Task {
274            args: f(self.args),
275            parts: self.parts,
276        }
277    }
278
279    /// Maps both `args` and `parts` together.
280    pub fn map_all<F, NewArgs, NewCtx>(self, f: F) -> Task<NewArgs, NewCtx, IdType>
281    where
282        F: FnOnce(Args, Parts<Ctx, IdType>) -> (NewArgs, Parts<NewCtx, IdType>),
283    {
284        let (args, parts) = f(self.args, self.parts);
285        Task { args, parts: parts }
286    }
287
288    /// Maps only the `parts` field.
289    pub fn map_parts<F, NewCtx>(self, f: F) -> Task<Args, NewCtx, IdType>
290    where
291        F: FnOnce(Parts<Ctx, IdType>) -> Parts<NewCtx, IdType>,
292    {
293        Task {
294            args: self.args,
295            parts: f(self.parts),
296        }
297    }
298}