apalis_redis/
context.rs

1use apalis_core::{
2    task::{Task, metadata::MetadataExt},
3    task_fn::FromRequest,
4};
5use serde::{Deserialize, Serialize, de::DeserializeOwned};
6use std::convert::Infallible;
7use ulid::Ulid;
8
9/// The context for a redis storage job
10#[derive(Clone, Debug, Serialize, Deserialize)]
11pub struct RedisContext {
12    /// The maximum number of attempts for the task
13    pub max_attempts: u32,
14    /// The worker that has locked the task, if any
15    pub lock_by: Option<String>,
16    /// Additional metadata associated with the task
17    pub meta: serde_json::Map<String, serde_json::Value>,
18}
19
20impl Default for RedisContext {
21    fn default() -> Self {
22        Self {
23            max_attempts: 5,
24            lock_by: None,
25            meta: serde_json::Map::new(),
26        }
27    }
28}
29
30impl<T: Serialize + DeserializeOwned> MetadataExt<T> for RedisContext {
31    type Error = serde_json::Error;
32    fn extract(&self) -> Result<T, serde_json::Error> {
33        self.meta.extract()
34    }
35    fn inject(&mut self, value: T) -> Result<(), serde_json::Error> {
36        self.meta.inject(value)
37    }
38}
39
40impl<Args: Sync> FromRequest<Task<Args, RedisContext, Ulid>> for RedisContext {
41    type Error = Infallible;
42    async fn from_request(req: &Task<Args, RedisContext, Ulid>) -> Result<Self, Self::Error> {
43        Ok(req.parts.ctx.clone())
44    }
45}