apalis_core/backend/
mod.rs

1//! Core traits for interacting with backends
2//!
3//! The core traits and types for backends, responsible for providing sources of tasks, handling their lifecycle, and exposing middleware for internal processing.
4//! The traits here abstract over different backend implementations, allowing for extensibility and interoperability.
5//!
6//! # Overview
7//! - [`Backend`]: The primary trait representing a task source, defining methods for polling tasks, heartbeats, and middleware.
8//! - [`TaskSink`]: An extension trait for backends that support pushing tasks.
9//! - [`FetchById`], [`Update`], [`Reschedule`]: Additional traits for managing tasks.
10//! - [`Vacuum`], [`ResumeById`], [`ResumeAbandoned`]: Traits for backend maintenance and task recovery.
11//! - [`RegisterWorker`], [`ListWorkers`], [`ListTasks`]: Traits for worker management and task listing.
12//! - [`WaitForCompletion`]: A trait for waiting on task completion and checking their status.
13//!
14//!
15//! ## Default Implementations
16//!
17//! The module includes several default backend implementations, such as:
18//! - [`MemoryStorage`](memory::MemoryStorage): An in-memory backend for testing and lightweight use cases
19//! - [`Pipe`](pipe::Pipe): A simple pipe-based backend for inter-thread communication
20//! - [`CustomBackend`](custom::CustomBackend): A flexible backend allowing custom functions for task management
21use std::{future::Future, time::Duration};
22
23use futures_util::{Stream, stream::BoxStream};
24
25use crate::{
26    backend::codec::Codec,
27    error::BoxDynError,
28    task::{Task, status::Status, task_id::TaskId},
29    worker::context::WorkerContext,
30};
31
32pub mod codec;
33pub mod custom;
34pub mod pipe;
35pub mod poll_strategy;
36pub mod queue;
37pub mod shared;
38
39mod config;
40mod expose;
41mod impls;
42mod sink;
43
44pub use expose::*;
45pub use sink::*;
46
47pub use impls::guide;
48
49pub use config::ConfigExt;
50
51/// In-memory backend based on channels
52pub mod memory {
53    pub use crate::backend::impls::memory::*;
54}
55
56/// File based Backend using JSON
57#[cfg(feature = "json")]
58pub mod json {
59    pub use crate::backend::impls::json::*;
60}
61
62/// The `Backend` trait defines how workers get and manage tasks from a backend.
63///
64/// In other languages, this might be called a "Queue", "Broker", etc.
65pub trait Backend {
66    /// The type of arguments the backend handles.
67    type Args;
68    /// The type used to uniquely identify tasks.
69    type IdType: Clone;
70    /// Context associated with each task.
71    type Context: Default;
72    /// The error type returned by backend operations
73    type Error;
74    /// A stream of tasks provided by the backend.
75    type Stream: Stream<
76        Item = Result<Option<Task<Self::Args, Self::Context, Self::IdType>>, Self::Error>,
77    >;
78    /// A stream representing heartbeat signals.
79    type Beat: Stream<Item = Result<(), Self::Error>>;
80    /// The type representing backend middleware layer.
81    type Layer;
82
83    /// Returns a heartbeat stream for the given worker.
84    fn heartbeat(&self, worker: &WorkerContext) -> Self::Beat;
85    /// Returns the backend's middleware layer.
86    fn middleware(&self) -> Self::Layer;
87    /// Polls the backend for tasks for the given worker.
88    fn poll(self, worker: &WorkerContext) -> Self::Stream;
89}
90
91/// Defines the encoding/serialization aspects of a backend.
92pub trait BackendExt: Backend {
93    /// The codec used for serialization/deserialization of tasks.
94    type Codec: Codec<Self::Args, Compact = Self::Compact>;
95    /// The compact representation of task arguments.
96    type Compact;
97    /// A stream of encoded tasks provided by the backend.
98    type CompactStream: Stream<
99        Item = Result<Option<Task<Self::Compact, Self::Context, Self::IdType>>, Self::Error>,
100    >;
101
102    /// Polls the backend for encoded tasks for the given worker.
103    fn poll_compact(self, worker: &WorkerContext) -> Self::CompactStream;
104}
105
106/// Represents a stream for T.
107pub type TaskStream<T, E = BoxDynError> = BoxStream<'static, Result<Option<T>, E>>;
108/// Allows fetching a task by its ID
109pub trait FetchById<Args>: Backend {
110    /// Fetch a task by its unique identifier
111    #[allow(clippy::type_complexity)]
112    fn fetch_by_id(
113        &mut self,
114        task_id: &TaskId<Self::IdType>,
115    ) -> impl Future<Output = Result<Option<Task<Args, Self::Context, Self::IdType>>, Self::Error>> + Send;
116}
117
118/// Allows updating an existing task
119pub trait Update: Backend {
120    /// Update the given task
121    fn update(
122        &mut self,
123        task: Task<Self::Args, Self::Context, Self::IdType>,
124    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
125}
126
127/// Allows rescheduling a task for later execution
128pub trait Reschedule: Backend {
129    /// Reschedule the task after a specified duration
130    fn reschedule(
131        &mut self,
132        task: Task<Self::Args, Self::Context, Self::IdType>,
133        wait: Duration,
134    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
135}
136
137/// Allows cleaning up resources in the backend
138pub trait Vacuum: Backend {
139    /// Cleans up resources and returns the number of items vacuumed
140    fn vacuum(&mut self) -> impl Future<Output = Result<usize, Self::Error>> + Send;
141}
142
143/// Allows resuming a task by its ID
144pub trait ResumeById: Backend {
145    /// Resume a task by its ID
146    fn resume_by_id(
147        &mut self,
148        id: TaskId<Self::IdType>,
149    ) -> impl Future<Output = Result<bool, Self::Error>> + Send;
150}
151
152/// Allows fetching multiple tasks by their IDs
153pub trait ResumeAbandoned: Backend {
154    /// Resume all abandoned tasks
155    fn resume_abandoned(&mut self) -> impl Future<Output = Result<usize, Self::Error>> + Send;
156}
157
158/// Allows registering a worker with the backend
159pub trait RegisterWorker: Backend {
160    /// Registers a worker
161    fn register_worker(
162        &mut self,
163        worker_id: String,
164    ) -> impl Future<Output = Result<(), Self::Error>> + Send;
165}
166
167/// Represents the result of a task execution
168#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
169#[derive(Debug, Clone)]
170pub struct TaskResult<T> {
171    task_id: TaskId,
172    status: Status,
173    result: Result<T, String>,
174}
175
176impl<T> TaskResult<T> {
177    /// Create a new TaskResult
178    pub fn new(task_id: TaskId, status: Status, result: Result<T, String>) -> Self {
179        Self {
180            task_id,
181            status,
182            result,
183        }
184    }
185    /// Get the ID of the task
186    pub fn task_id(&self) -> &TaskId {
187        &self.task_id
188    }
189
190    /// Get the status of the task
191    pub fn status(&self) -> &Status {
192        &self.status
193    }
194
195    /// Get the result of the task
196    pub fn result(&self) -> &Result<T, String> {
197        &self.result
198    }
199
200    /// Take the result of the task
201    pub fn take(self) -> Result<T, String> {
202        self.result
203    }
204}
205
206/// Allows waiting for tasks to complete and checking their status
207pub trait WaitForCompletion<T>: Backend {
208    /// The result stream type yielding task results
209    type ResultStream: Stream<Item = Result<TaskResult<T>, Self::Error>> + Send + 'static;
210
211    /// Wait for multiple tasks to complete, yielding results as they become available
212    fn wait_for(
213        &self,
214        task_ids: impl IntoIterator<Item = TaskId<Self::IdType>>,
215    ) -> Self::ResultStream;
216
217    /// Wait for a single task to complete, yielding its result
218    fn wait_for_single(&self, task_id: TaskId<Self::IdType>) -> Self::ResultStream {
219        self.wait_for(std::iter::once(task_id))
220    }
221
222    /// Check current status of tasks without waiting
223    fn check_status(
224        &self,
225        task_ids: impl IntoIterator<Item = TaskId<Self::IdType>> + Send,
226    ) -> impl Future<Output = Result<Vec<TaskResult<T>>, Self::Error>> + Send;
227}