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.into();
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::{AtomicStatus, 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(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 that is wrapped in an atomic status
160 pub status: AtomicStatus,
161
162 /// The time a task should be run
163 pub run_at: u64,
164}
165
166impl<Ctx: Debug, IdType: Debug> Debug for Parts<Ctx, IdType> {
167 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
168 f.debug_struct("Parts")
169 .field("task_id", &self.task_id)
170 .field("data", &"<Extensions>")
171 .field("attempt", &self.attempt)
172 .field("ctx", &self.ctx)
173 .field("status", &self.status.load())
174 .field("run_at", &self.run_at)
175 .finish()
176 }
177}
178
179impl<Ctx, IdType: Clone> Clone for Parts<Ctx, IdType>
180where
181 Ctx: Clone,
182{
183 fn clone(&self) -> Self {
184 Self {
185 task_id: self.task_id.clone(),
186 data: self.data.clone(),
187 attempt: self.attempt.clone(),
188 ctx: self.ctx.clone(),
189 status: self.status.clone(),
190 run_at: self.run_at,
191 }
192 }
193}
194
195impl<Args, Ctx, IdType> Task<Args, Ctx, IdType> {
196 /// Creates a new [Task]
197 pub fn new(args: Args) -> Self
198 where
199 Ctx: Default,
200 {
201 Self::new_with_data(args, Extensions::default(), Ctx::default())
202 }
203
204 /// Creates a task with context provided
205 pub fn new_with_ctx(req: Args, ctx: Ctx) -> Self {
206 Self {
207 args: req,
208 parts: Parts {
209 ctx,
210 task_id: Default::default(),
211 attempt: Default::default(),
212 data: Default::default(),
213 status: Status::Pending.into(),
214 run_at: {
215 let now = SystemTime::now();
216 let duration_since_epoch =
217 now.duration_since(UNIX_EPOCH).expect("Time went backwards");
218 duration_since_epoch.as_secs()
219 },
220 },
221 }
222 }
223
224 /// Creates a task with data and context provided
225 pub fn new_with_data(req: Args, data: Extensions, ctx: Ctx) -> Self {
226 Self {
227 args: req,
228 parts: Parts {
229 ctx,
230 task_id: Default::default(),
231 attempt: Default::default(),
232 data,
233 status: Status::Pending.into(),
234 run_at: {
235 let now = SystemTime::now();
236 let duration_since_epoch =
237 now.duration_since(UNIX_EPOCH).expect("Time went backwards");
238 duration_since_epoch.as_secs()
239 },
240 },
241 }
242 }
243
244 /// Take the task into its parts
245 pub fn take(self) -> (Args, Parts<Ctx, IdType>) {
246 (self.args, self.parts)
247 }
248
249 /// Extract a value of type `T` from the task's context
250 ///
251 /// Uses [FromRequest] trait to extract the value.
252 pub async fn extract<T: FromRequest<Self>>(&self) -> Result<T, T::Error> {
253 T::from_request(self).await
254 }
255
256 /// Converts the task into a builder pattern.
257 pub fn into_builder(self) -> TaskBuilder<Args, Ctx, IdType> {
258 TaskBuilder {
259 args: self.args,
260 ctx: self.parts.ctx,
261 attempt: Some(self.parts.attempt),
262 data: self.parts.data,
263 status: Some(self.parts.status.into()),
264 run_at: Some(self.parts.run_at),
265 task_id: self.parts.task_id,
266 }
267 }
268}
269
270impl<Args, Ctx, IdType> Task<Args, Ctx, IdType> {
271 /// Maps the `args` field using the provided function, consuming the task.
272 pub fn try_map<F, NewArgs, Err>(self, f: F) -> Result<Task<NewArgs, Ctx, IdType>, Err>
273 where
274 F: FnOnce(Args) -> Result<NewArgs, Err>,
275 {
276 Ok(Task {
277 args: f(self.args)?,
278 parts: self.parts,
279 })
280 }
281 /// Maps the `args` field using the provided function, consuming the task.
282 pub fn map<F, NewArgs>(self, f: F) -> Task<NewArgs, Ctx, IdType>
283 where
284 F: FnOnce(Args) -> NewArgs,
285 {
286 Task {
287 args: f(self.args),
288 parts: self.parts,
289 }
290 }
291
292 /// Maps both `args` and `parts` together.
293 pub fn map_all<F, NewArgs, NewCtx>(self, f: F) -> Task<NewArgs, NewCtx, IdType>
294 where
295 F: FnOnce(Args, Parts<Ctx, IdType>) -> (NewArgs, Parts<NewCtx, IdType>),
296 {
297 let (args, parts) = f(self.args, self.parts);
298 Task { args, parts: parts }
299 }
300
301 /// Maps only the `parts` field.
302 pub fn map_parts<F, NewCtx>(self, f: F) -> Task<Args, NewCtx, IdType>
303 where
304 F: FnOnce(Parts<Ctx, IdType>) -> Parts<NewCtx, IdType>,
305 {
306 Task {
307 args: self.args,
308 parts: f(self.parts),
309 }
310 }
311}