backie/
runnable.rs

1use crate::task::{CurrentTask, TaskHash};
2use crate::BackoffMode;
3use async_trait::async_trait;
4use serde::{de::DeserializeOwned, ser::Serialize};
5use std::fmt::Debug;
6
7/// The [`BackgroundTask`] trait is used to define the behaviour of a task. You must implement this
8/// trait for all tasks you want to execute.
9///
10/// The [`BackgroundTask::TASK_NAME`] attribute must be unique for the whole application. This
11/// attribute is critical for reconstructing the task back from the database.
12///
13/// The [`BackgroundTask::AppData`] can be used to argument the task with application specific
14/// contextual information. This is useful for example to pass a database connection pool to the
15/// task or other application configuration.
16///
17/// The [`BackgroundTask::run`] method is the main method of the task. It is executed by the
18/// the task queue workers.
19///
20///
21/// # Example
22/// ```
23/// use async_trait::async_trait;
24/// use backie::{BackgroundTask, CurrentTask};
25/// use serde::{Deserialize, Serialize};
26///
27/// #[derive(Serialize, Deserialize)]
28/// pub struct MyTask {}
29///
30/// #[async_trait]
31/// impl BackgroundTask for MyTask {
32///     const TASK_NAME: &'static str = "my_task_unique_name";
33///     type AppData = ();
34///     type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
35///
36///     async fn run(&self, task: CurrentTask, context: Self::AppData) -> Result<(), Self::Error> {
37///         // Do something
38///         Ok(())
39///     }
40/// }
41/// ```
42#[async_trait]
43pub trait BackgroundTask: Serialize + DeserializeOwned + Sync + Send + 'static {
44    /// Unique name of the task.
45    ///
46    /// This MUST be unique for the whole application.
47    const TASK_NAME: &'static str;
48
49    /// Task queue where this task will be executed.
50    ///
51    /// Used to route to which workers are going to be executing this task. It uses the default
52    /// task queue if not changed.
53    const QUEUE: &'static str = "default";
54
55    /// Number of retries for tasks.
56    ///
57    /// By default, it is set to 3.
58    const MAX_RETRIES: i32 = 3;
59
60    /// Backoff mode for tasks.
61    const BACKOFF_MODE: BackoffMode = BackoffMode::ExponentialBackoff;
62
63    /// The application data provided to this task at runtime.
64    type AppData: Clone + Send + 'static;
65
66    /// An application custom error type.
67    type Error: Debug + Send + 'static;
68
69    /// Execute the task. This method should define its logic
70    async fn run(&self, task: CurrentTask, context: Self::AppData) -> Result<(), Self::Error>;
71
72    /// If set to true, no new tasks with the same metadata will be inserted
73    /// By default it is set to false.
74    fn uniq(&self) -> Option<TaskHash> {
75        None
76    }
77}