Skip to main content

kojin_core/
task.rs

1use async_trait::async_trait;
2use serde::{Serialize, de::DeserializeOwned};
3
4use crate::backoff::BackoffStrategy;
5use crate::context::TaskContext;
6use crate::error::TaskResult;
7use crate::signature::Signature;
8
9/// A unit of work that can be enqueued and executed by a worker.
10#[async_trait]
11pub trait Task: Send + Sync + Serialize + DeserializeOwned + 'static {
12    /// Unique name used for routing. Must be stable across deploys.
13    const NAME: &'static str;
14
15    /// Default queue name.
16    const QUEUE: &'static str = "default";
17
18    /// Maximum number of retry attempts.
19    const MAX_RETRIES: u32 = 3;
20
21    /// Backoff strategy for retries.
22    fn backoff() -> BackoffStrategy {
23        BackoffStrategy::default()
24    }
25
26    /// The output type of the task.
27    type Output: Serialize + DeserializeOwned + Send;
28
29    /// Execute the task.
30    async fn run(&self, ctx: &TaskContext) -> TaskResult<Self::Output>;
31
32    /// Build a [`Signature`] from this task instance.
33    fn signature(&self) -> Signature {
34        Signature::new(
35            Self::NAME,
36            Self::QUEUE,
37            serde_json::to_value(self).expect("task must be serializable"),
38        )
39        .with_max_retries(Self::MAX_RETRIES)
40    }
41}