larust_queue/dispatch.rs
1//! `Job` (shared, driver-agnostic) plus `dispatch()`'s runtime driver
2//! dispatch - mirrors `larust_cache::store`'s own `match config
3//! .cache_driver.as_str() { ... }` shape, itself modeled on
4//! `larust_mail::send::deliver`'s `mail_driver` precedent.
5
6use larust_core::AppError;
7use serde::de::DeserializeOwned;
8use serde::Serialize;
9use std::future::Future;
10
11/// A unit of deferred work. Implemented once per job type, the same
12/// "app implements this once per thing" shape as `Policy<U>`/`Mailable`.
13pub trait Job: Serialize + DeserializeOwned + Send + Sync + 'static {
14 /// A stable, explicit, app-chosen tag - deliberately not
15 /// `std::any::type_name::<Self>()`. That string isn't stable across a
16 /// rename/refactor, and a row already sitting in the `jobs` table
17 /// under the old name would silently stop matching any handler.
18 const JOB_TYPE: &'static str;
19
20 /// `-> impl Future<...> + Send` rather than a plain `async fn` - the
21 /// exact spelling `larust_auth::Authenticatable::find_for_auth`
22 /// already established (see `docs/GOTCHAS.md`) to avoid the
23 /// async-fn-in-traits `Send`-propagation pitfall. Unlike `Mailable`'s
24 /// methods, a job's `handle()` is inherently real async I/O (sending
25 /// mail, calling an API, writing to the DB), so - unlike `Mailable` -
26 /// there's no sidestepping this by staying synchronous.
27 fn handle(&self) -> impl Future<Output = Result<(), AppError>> + Send;
28}
29
30/// Serializes `job` to JSON and enqueues it - durable the moment this
31/// returns `Ok`, independent of whether any `xr queue:work` process is
32/// currently running to pick it up.
33pub async fn dispatch<J: Job>(job: &J) -> Result<(), AppError> {
34 match crate::queue_driver() {
35 "redis" => crate::redis_dispatch::dispatch(job).await,
36 _ => crate::sql_dispatch::dispatch(job).await,
37 }
38}