Skip to main content

tablo_jobs/
job.rs

1//! What a job is, and the type-erased run a worker keeps for each kind.
2
3use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
4
5use serde::{Serialize, de::DeserializeOwned};
6use topcoat::context::Cx;
7
8/// A kind of background work, whose fields are its payload.
9///
10/// ```rust
11/// use serde::{Deserialize, Serialize};
12/// use tablo_jobs::Job;
13/// use topcoat::context::Cx;
14///
15/// #[derive(Serialize, Deserialize)]
16/// struct SyncSeats {
17///     team: u64,
18/// }
19///
20/// impl Job for SyncSeats {
21///     const KIND: &'static str = "sync-seats";
22///
23///     fn lane(&self) -> Option<String> {
24///         Some(format!("team:{}", self.team))
25///     }
26///
27///     async fn run(self, cx: &Cx) -> topcoat::Result<()> {
28///         // Read the team as it is now, and push its seat count.
29///         # let _ = cx;
30///         Ok(())
31///     }
32/// }
33/// ```
34///
35/// - `run` may run twice for one enqueue, after a crash or a lapsed lock, so it is idempotent.
36/// - It reads the world as it is when it runs, not as it was at enqueue: the payload names rows, it
37///   does not copy them.
38/// - The payload lives in the database and its backups in clear: it carries no secret.
39/// - A run past [`TIMEOUT`](Self::TIMEOUT) is dropped at its next `.await`. A run that blocks its
40///   thread instead outlives its lock, and another worker starts it again beside it: blocking work
41///   goes through `tokio::task::spawn_blocking`.
42pub trait Job: Serialize + DeserializeOwned + Send + Sync + 'static {
43    /// What the queue calls this kind. A queued job of a kind no worker registers waits, so a
44    /// rename keeps the old name registered until the queue holds none.
45    const KIND: &'static str;
46    /// How many runs it gets before it turns [`Dead`](crate::JobState::Dead).
47    const MAX_ATTEMPTS: u32 = 8;
48    /// How long a run may take before it counts as failed. The claim locks the job a minute
49    /// longer, so no other worker takes over a live run.
50    const TIMEOUT: Duration = Duration::from_mins(2);
51
52    /// The lane it runs in: of the jobs sharing a lane, one runs at a time across every worker.
53    /// `None`, the default, runs beside anything.
54    fn lane(&self) -> Option<String> {
55        None
56    }
57
58    /// Does the work, reading what it needs from `cx`: the context
59    /// [`PanelHandle::context`](tablo_core::PanelHandle::context) builds, with what
60    /// [`Worker::context`](crate::Worker::context) adds. An error retries it with backoff until
61    /// it has spent its attempts.
62    fn run(self, cx: &Cx) -> impl Future<Output = topcoat::Result<()>> + Send;
63}
64
65pub(crate) type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
66
67/// One kind's run: its payload parsed, then run against a context.
68pub(crate) type Run =
69    Arc<dyn for<'a> Fn(&'a str, &'a Cx) -> BoxFuture<'a, topcoat::Result<()>> + Send + Sync>;
70
71/// What a worker keeps of a registered kind.
72#[derive(Clone)]
73pub(crate) struct Kind {
74    pub(crate) run: Run,
75    pub(crate) timeout: Duration,
76}
77
78/// `J`'s run and timeout.
79pub(crate) fn kind_of<J: Job>() -> Kind {
80    Kind {
81        run: Arc::new(|payload, cx| {
82            Box::pin(async move { serde_json::from_str::<J>(payload)?.run(cx).await })
83        }),
84        timeout: J::TIMEOUT,
85    }
86}