apalis_core/backend/impls/
memory.rs

1//! # In-memory backend based on channels
2//!
3//! An in-memory backend suitable for testing, prototyping, or lightweight task processing scenarios where persistence is not required.
4//!
5//! ## Features
6//! - Generic in-memory queue for any task type.
7//! - Implements [`Backend`] for integration with workers.
8//! - Sink support: Ability to push new tasks.
9//!
10//! A detailed feature list can be found in the [capabilities](crate::backend::memory::MemoryStorage#capabilities) section.
11//!
12//! ## Example
13//!
14//! ```rust
15//! # use apalis_core::backend::memory::MemoryStorage;
16//! # use apalis_core::worker::context::WorkerContext;
17//! # use apalis_core::worker::builder::WorkerBuilder;
18//! # use apalis_core::backend::TaskSink;
19//! # async fn task(_: u32, ctx: WorkerContext) { ctx.stop().unwrap();}
20//! #[tokio::main]
21//! async fn main() {
22//!     let mut store = MemoryStorage::new();
23//!     store.push(42).await.unwrap();
24//!
25//!     let worker = WorkerBuilder::new("int-worker")
26//!         .backend(store)
27//!         .build(task);
28//!
29//!     worker.run().await.unwrap();
30//! }
31//! ```
32//!
33//! ## Note
34//! This backend is not persistent and is intended for use cases where durability is not required.
35//! For production workloads, consider using a persistent backend such as PostgreSQL or Redis.
36//!
37//! ## See Also
38//! - [`Backend`]
39//! - [`WorkerContext`](crate::worker::context::WorkerContext)
40use crate::backend::codec::IdentityCodec;
41use crate::backend::queue::Queue;
42use crate::features_table;
43use crate::task::extensions::Extensions;
44use crate::{
45    backend::{Backend, TaskStream},
46    task::{
47        Task,
48        task_id::{RandomId, TaskId},
49    },
50    worker::context::WorkerContext,
51};
52use futures_channel::mpsc::{SendError, unbounded};
53use futures_core::ready;
54use futures_sink::Sink;
55use futures_util::{
56    FutureExt, SinkExt, Stream, StreamExt,
57    stream::{self, BoxStream},
58};
59use std::{
60    pin::Pin,
61    sync::Arc,
62    task::{Context, Poll},
63};
64use tower_layer::Identity;
65
66/// In-memory queue that is based on channels
67///
68#[doc = features_table! {
69    setup = {
70        use apalis_core::backend::memory::MemoryStorage;
71        // No migrations
72        MemoryStorage::new()
73    };,
74
75    Backend => supported("Basic Backend functionality", true),
76    TaskSink => supported("Ability to push new tasks", true),
77    Serialization => not_supported("Serialization support for arguments"),
78
79    PipeExt => not_implemented("Allow other backends to pipe to this backend"),
80    MakeShared => not_supported("Share the same JSON storage across multiple workers"),
81
82    Update => not_supported("Allow updating a task"),
83    FetchById => not_supported("Allow fetching a task by its ID"),
84    Reschedule => not_supported("Reschedule a task"),
85
86    ResumeById => not_supported("Resume a task by its ID"),
87    ResumeAbandoned => not_supported("Resume abandoned tasks"),
88    Vacuum => not_supported("Vacuum the task storage"),
89
90    Workflow => not_implemented("Flexible enough to support workflows"),
91    WaitForCompletion => not_implemented("Wait for tasks to complete without blocking"), // Requires Clone
92
93    RegisterWorker => not_supported("Allow registering a worker with the backend"),
94    ListWorkers => not_supported("List all workers registered with the backend"),
95    ListTasks => not_supported("List all tasks in the backend"),
96}]
97pub struct MemoryStorage<Args, Ctx = Extensions> {
98    pub(super) sender: MemorySink<Args, Ctx>,
99    pub(super) receiver: Pin<Box<dyn Stream<Item = Task<Args, Ctx>> + Send>>,
100}
101
102impl<Args: Send + 'static> MemoryStorage<Args, Extensions> {
103    /// Create a new in-memory storage
104    pub fn new() -> Self {
105        let (sender, receiver) = unbounded();
106        let sender = Box::new(sender)
107            as Box<dyn Sink<Task<Args, Extensions>, Error = SendError> + Send + Sync + Unpin>;
108        MemoryStorage {
109            sender: MemorySink {
110                inner: Arc::new(futures_util::lock::Mutex::new(sender)),
111            },
112            receiver: receiver.boxed(),
113        }
114    }
115}
116
117impl<Args, Ctx> Sink<Task<Args, Ctx>> for MemoryStorage<Args, Ctx> {
118    type Error = SendError;
119
120    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
121        self.as_mut().sender.poll_ready_unpin(cx)
122    }
123
124    fn start_send(mut self: Pin<&mut Self>, item: Task<Args, Ctx>) -> Result<(), Self::Error> {
125        self.as_mut().sender.start_send_unpin(item)
126    }
127
128    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
129        self.as_mut().sender.poll_flush_unpin(cx)
130    }
131
132    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
133        self.as_mut().sender.poll_close_unpin(cx)
134    }
135}
136
137/// Memory sink for sending tasks to the in-memory backend
138pub struct MemorySink<Args, Ctx = Extensions> {
139    pub(super) inner: Arc<
140        futures_util::lock::Mutex<
141            Box<dyn Sink<Task<Args, Ctx>, Error = SendError> + Send + Sync + Unpin + 'static>,
142        >,
143    >,
144}
145
146impl<Args, Ctx> std::fmt::Debug for MemorySink<Args, Ctx> {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        f.debug_struct("MemorySink")
149            .field("inner", &"<Sink>")
150            .finish()
151    }
152}
153
154impl<Args, Ctx> Clone for MemorySink<Args, Ctx> {
155    fn clone(&self) -> Self {
156        Self {
157            inner: Arc::clone(&self.inner),
158        }
159    }
160}
161
162impl<Args, Ctx> Sink<Task<Args, Ctx>> for MemorySink<Args, Ctx> {
163    type Error = SendError;
164
165    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
166        let mut lock = ready!(self.inner.lock().poll_unpin(cx));
167        Pin::new(&mut *lock).poll_ready_unpin(cx)
168    }
169
170    fn start_send(self: Pin<&mut Self>, mut item: Task<Args, Ctx>) -> Result<(), Self::Error> {
171        let mut lock = self.inner.try_lock().unwrap();
172        // Ensure task has id
173        item.parts
174            .task_id
175            .get_or_insert_with(|| TaskId::new(RandomId::default()));
176        item.parts
177            .queue
178            .get_or_insert_with(|| Queue::from(std::any::type_name::<Args>()));
179        Pin::new(&mut *lock).start_send_unpin(item)
180    }
181
182    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
183        let mut lock = ready!(self.inner.lock().poll_unpin(cx));
184        Pin::new(&mut *lock).poll_flush_unpin(cx)
185    }
186
187    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
188        let mut lock = ready!(self.inner.lock().poll_unpin(cx));
189        Pin::new(&mut *lock).poll_close_unpin(cx)
190    }
191}
192
193impl<Args, Ctx> std::fmt::Debug for MemoryStorage<Args, Ctx> {
194    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195        f.debug_struct("MemoryStorage")
196            .field("sender", &self.sender)
197            .field("receiver", &"<Stream>")
198            .finish()
199    }
200}
201
202impl<Args, Ctx> Stream for MemoryStorage<Args, Ctx> {
203    type Item = Task<Args, Ctx>;
204
205    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
206        self.receiver.poll_next_unpin(cx)
207    }
208}
209
210// MemoryStorage as a Backend
211impl<Args: 'static + Clone + Send, Ctx: 'static + Default> Backend for MemoryStorage<Args, Ctx> {
212    type Args = Args;
213    type IdType = RandomId;
214
215    type Context = Ctx;
216
217    type Error = SendError;
218    type Stream = TaskStream<Task<Args, Ctx>, SendError>;
219    type Layer = Identity;
220    type Beat = BoxStream<'static, Result<(), Self::Error>>;
221
222    type Codec = IdentityCodec;
223    type Compact = Args;
224
225    fn heartbeat(&self, _: &WorkerContext) -> Self::Beat {
226        stream::once(async { Ok(()) }).boxed()
227    }
228    fn middleware(&self) -> Self::Layer {
229        Identity::new()
230    }
231
232    fn poll(self, _worker: &WorkerContext) -> Self::Stream {
233        let stream = self.receiver.boxed().map(|r| Ok(Some(r))).boxed();
234        stream
235    }
236}