Skip to main content

wabot_feature_async/
lib.rs

1//! # wabot-feature-async
2//!
3//! Rust port of `wabot-ts/src/feature/async`. Provides:
4//!
5//! * [`Job`] / [`CronJob`] entities + state transitions.
6//! * `JobRepository` / `CronJobRepository` traits (implementations in
7//!   addon crates such as `wabot-addon-async-in-memory`).
8//! * [`CommandRegistry`] / [`CronRegistry`] — the Rust analogue of
9//!   `AsyncMetadataStore`, populated by [`run_async_workers`] from the
10//!   handler entries the `#[command_handler]` / `#[cron_handler]`
11//!   macros emit.
12//! * Long-running loops: [`run_scheduler_loop`], [`JobExecutor`],
13//!   [`JobRunner`], [`JobWatchdog`], [`CronScheduler`].
14//! * Per-key [`Locker`] — [`InProcessLocker`] today; Phase 5b adds a
15//!   Postgres-backed variant, swapped in via [`register_locker`].
16//! * [`run_command`] / [`schedule_command`] for enqueueing a typed
17//!   command (TS: `Async.runCommand` / `Async.scheduleCommand`).
18//!
19//! ## Wiring a process
20//!
21//! ```ignore
22//! let c = Container::new();
23//! register_job_repository(&c, Arc::new(InMemoryJobRepository::new()));
24//! register_cron_job_repository(&c, Arc::new(InMemoryCronJobRepository::new()));
25//! register_async_runtime(&c);
26//!
27//! tokio::spawn(run_async_workers(
28//!     c.clone(),
29//!     vec![SendEmailHandler::__handler_entry(&c)],
30//!     vec![NightlyCleanupHandler::__cron_entry(&c)],
31//! ));
32//!
33//! run_command(&c, &SendEmail { to: "a@b.c".into() }).await?;
34//! ```
35
36pub mod command;
37pub mod cron_job;
38pub mod cron_scheduler;
39pub mod dedup;
40pub mod executor;
41pub mod handler;
42pub mod job;
43pub mod locker;
44pub mod registry;
45pub mod repository;
46pub mod runner;
47pub mod scheduler;
48pub mod types;
49
50pub use command::CommandData;
51pub use cron_job::{CronJob, CronJobData};
52pub use cron_scheduler::CronScheduler;
53pub use dedup::compute_dedup_key;
54pub use executor::JobExecutor;
55pub use handler::{CommandHandlerEntry, CommandInvokeFn, CronHandlerEntry, CronInvokeFn};
56pub use job::{Job, JobData};
57pub use locker::{InProcessLocker, Locker, LockerExt};
58pub use registry::{CommandRegistry, CronRegistry};
59pub use repository::{CronJobRepository, JobRepository};
60pub use runner::JobRunner;
61pub use scheduler::{
62    register_cron_job_repository, register_job_repository, register_locker, run_command,
63    run_scheduler_loop, schedule_command, schedule_job, AsyncRuntimeConfig, DynCronJobRepository,
64    DynJobRepository, DynLocker, ScheduleAt,
65};
66pub use types::{handler_error, AsyncError, AsyncResult, DedupConfig, JobOptions, MisfirePolicy};
67pub use watchdog::JobWatchdog;
68
69mod watchdog;
70
71use std::sync::Arc;
72
73use wabot_core::injection::Container;
74
75/// Wire every async-subsystem singleton into the container in one
76/// call. Run *after* registering concrete `JobRepository` /
77/// `CronJobRepository` implementations (see [`register_job_repository`]
78/// / [`register_cron_job_repository`]).
79///
80/// Pre-registered [`AsyncRuntimeConfig`] and [`DynLocker`] values are
81/// left alone, so an app can tune intervals or install a distributed
82/// locker before calling this.
83pub fn register_async_runtime(c: &Container) {
84    use wabot_core::injection::IsSingleton;
85    if !c.is_registered::<AsyncRuntimeConfig>() {
86        AsyncRuntimeConfig::register_in(c);
87    }
88    if !c.is_registered::<DynLocker>() {
89        register_locker(c, Arc::new(InProcessLocker::new()));
90    }
91    CommandRegistry::register_in(c);
92    CronRegistry::register_in(c);
93    JobRunner::register_in(c);
94    JobExecutor::register_in(c);
95    JobWatchdog::register_in(c);
96    CronScheduler::register_in(c);
97}
98
99/// Boot the scheduler + watchdog + cron-scheduler loops for the given
100/// command and cron handler registrations.
101///
102/// TS analogue: `runCommandHandlers([…])` + `runCronHandlers([…])`,
103/// merged because Rust has no module-load side effects to sequence.
104///
105/// Returns once one of the loops exits — typically only at process
106/// shutdown. For interactive use, spawn it on a tokio task.
107pub async fn run_async_workers(
108    container: Container,
109    commands: Vec<CommandHandlerEntry>,
110    crons: Vec<CronHandlerEntry>,
111) -> Result<(), AsyncError> {
112    let registry: Arc<CommandRegistry> = container.resolve();
113    for entry in commands.iter().cloned() {
114        registry.register(entry);
115    }
116    let cron_registry: Arc<CronRegistry> = container.resolve();
117    for entry in crons.iter().cloned() {
118        // A cron tick queues an ordinary Job under the cron's command
119        // name, so the runner needs a CommandRegistry entry for it too.
120        // The bridge discards the (always-null) job payload — cron
121        // handlers take no arguments.
122        registry.register(cron_command_entry(&entry));
123        cron_registry.register(entry);
124    }
125
126    let executor: Arc<JobExecutor> = container.resolve();
127    let watchdog: Arc<JobWatchdog> = container.resolve();
128    let cron_scheduler: Arc<CronScheduler> = container.resolve();
129
130    let mut all_command_names: Vec<String> =
131        commands.iter().map(|e| e.command_name.clone()).collect();
132    for cron in &crons {
133        if !all_command_names.contains(&cron.command_name) {
134            all_command_names.push(cron.command_name.clone());
135        }
136    }
137    for name in &all_command_names {
138        executor.add_command(name);
139        watchdog.add_command(name);
140        tracing::info!(command = %name, "config COMMAND");
141    }
142
143    cron_scheduler.reconcile(&crons).await?;
144
145    let config: Arc<AsyncRuntimeConfig> = container.resolve();
146    let cfg_for_scheduler = (*config).clone();
147    let cfg_for_watchdog = (*config).clone();
148    let cfg_for_cron = (*config).clone();
149
150    let repo = scheduler::resolve_job_repository(&container)?;
151    let locker = scheduler::resolve_locker(&container)?;
152
153    let container_for_scheduler = container.clone();
154    let executor_for_scheduler = executor.clone();
155    let scheduler_task = tokio::spawn(async move {
156        run_scheduler_loop(
157            container_for_scheduler,
158            repo,
159            executor_for_scheduler,
160            locker,
161            cfg_for_scheduler,
162        )
163        .await;
164    });
165
166    let watchdog_task = tokio::spawn(async move {
167        watchdog
168            .run_loop(cfg_for_watchdog.watchdog_interval_seconds)
169            .await;
170    });
171
172    let cron_task = tokio::spawn(async move {
173        cron_scheduler
174            .run_loop(cfg_for_cron.cron_interval_seconds)
175            .await;
176    });
177
178    // Wait for any task to finish — they normally run forever.
179    tokio::select! {
180        _ = scheduler_task => {}
181        _ = watchdog_task => {}
182        _ = cron_task => {}
183    }
184    Ok(())
185}
186
187/// Adapt a cron entry into the command entry the `JobRunner` dispatches
188/// through when the cron's queued Job comes up for execution.
189/// Wrap a cron entry so the job runner can execute it: a cron tick
190/// queues an ordinary `Job` under the cron's command name, and the
191/// bridge discards the (always-null) payload.
192///
193/// Public so a test harness can install the same bridge instead of
194/// writing a second one that could drift.
195pub fn cron_command_entry(cron: &CronHandlerEntry) -> CommandHandlerEntry {
196    let cron_invoke = cron.invoke.clone();
197    let invoke: CommandInvokeFn = Arc::new(move |c, _payload| {
198        let cron_invoke = cron_invoke.clone();
199        Box::pin(async move { (cron_invoke)(c).await })
200    });
201    CommandHandlerEntry {
202        command_name: cron.command_name.clone(),
203        options: cron.options.clone(),
204        dedup: None,
205        invoke,
206    }
207}