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)
40
41use crate::backend::codec::IdentityCodec;
42use crate::features_table;
43use crate::task::extensions::Extensions;
44use crate::{
45    backend::{Backend, TaskStream},
46    task::{
47        task_id::{RandomId, TaskId},
48        Task,
49    },
50    worker::context::WorkerContext,
51};
52use futures_channel::mpsc::{unbounded, SendError};
53use futures_core::ready;
54use futures_sink::Sink;
55use futures_util::{
56    stream::{self, BoxStream},
57    FutureExt, SinkExt, Stream, StreamExt,
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        Pin::new(&mut *lock).start_send_unpin(item)
177    }
178
179    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
180        let mut lock = ready!(self.inner.lock().poll_unpin(cx));
181        Pin::new(&mut *lock).poll_flush_unpin(cx)
182    }
183
184    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
185        let mut lock = ready!(self.inner.lock().poll_unpin(cx));
186        Pin::new(&mut *lock).poll_close_unpin(cx)
187    }
188}
189
190impl<Args, Ctx> std::fmt::Debug for MemoryStorage<Args, Ctx> {
191    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192        f.debug_struct("MemoryStorage")
193            .field("sender", &self.sender)
194            .field("receiver", &"<Stream>")
195            .finish()
196    }
197}
198
199impl<Args, Ctx> Stream for MemoryStorage<Args, Ctx> {
200    type Item = Task<Args, Ctx>;
201
202    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
203        self.receiver.poll_next_unpin(cx)
204    }
205}
206
207// MemoryStorage as a Backend
208impl<Args: 'static + Clone + Send, Ctx: 'static + Default> Backend<Args>
209    for MemoryStorage<Args, Ctx>
210{
211    type IdType = RandomId;
212
213    type Context = Ctx;
214
215    type Error = SendError;
216    type Stream = TaskStream<Task<Args, Ctx>, SendError>;
217    type Layer = Identity;
218    type Beat = BoxStream<'static, Result<(), Self::Error>>;
219
220    type Codec = IdentityCodec;
221
222    fn heartbeat(&self, _: &WorkerContext) -> Self::Beat {
223        stream::once(async { Ok(()) }).boxed()
224    }
225    fn middleware(&self) -> Self::Layer {
226        Identity::new()
227    }
228
229    fn poll(self, _worker: &WorkerContext) -> Self::Stream {
230        let stream = self.receiver.boxed().map(|r| Ok(Some(r))).boxed();
231        stream
232    }
233}