Skip to main content

durable/
lib.rs

1pub mod ctx;
2pub mod error;
3pub mod executor;
4pub mod scheduler;
5
6pub use ctx::Ctx;
7pub use ctx::RetryPolicy;
8pub use ctx::StartResult;
9pub use ctx::{TaskQuery, TaskSort, TaskSummary};
10pub use durable_db::entity::sea_orm_active_enums::TaskStatus;
11pub use durable_macros::{step, workflow};
12pub use error::DurableError;
13pub use executor::{Executor, HeartbeatConfig, RecoveredTask};
14pub use scheduler::{SchedulerConfig, next_run};
15pub use sea_orm::DatabaseTransaction;
16
17// Re-export so macro-generated code can reference `durable::inventory::submit!`
18pub use inventory;
19
20use sea_orm::{ConnectOptions, Database, DatabaseConnection};
21use sea_orm_migration::MigratorTrait;
22use std::future::Future;
23use std::pin::Pin;
24use std::sync::RwLock;
25use uuid::Uuid;
26
27/// Global executor ID set by [`init`]. Read by [`Ctx::start`] to tag tasks
28/// so heartbeat-based recovery can find them after a crash.
29static EXECUTOR_ID: RwLock<Option<String>> = RwLock::new(None);
30
31/// Returns the executor ID set by [`init`], or `None` if `init` was not called.
32pub fn executor_id() -> Option<String> {
33    EXECUTOR_ID.read().ok().and_then(|g| g.clone())
34}
35
36// ── Workflow auto-registration ──────────────────────────────────
37
38/// Type alias for a workflow resume function pointer.
39pub type ResumeFn = fn(Ctx) -> Pin<Box<dyn Future<Output = Result<(), DurableError>> + Send>>;
40
41/// A compiled-in registration of a workflow function for automatic crash recovery.
42///
43/// Produced by `#[durable::workflow]` and collected at link time by `inventory`.
44/// Only workflows with a single `ctx: Ctx` parameter are registered.
45pub struct WorkflowRegistration {
46    /// The handler name — matches the function name, used for recovery lookup
47    /// via the `handler` column in `durable.task`.
48    pub name: &'static str,
49    /// Resumes the workflow given a `Ctx`. Return type is erased; during
50    /// recovery we only care about driving the workflow to completion.
51    pub resume_fn: ResumeFn,
52}
53
54inventory::collect!(WorkflowRegistration);
55
56/// Look up a registered workflow by name.
57pub fn find_workflow(name: &str) -> Option<&'static WorkflowRegistration> {
58    inventory::iter::<WorkflowRegistration>().find(|r| r.name == name)
59}
60
61// ── Initialization ──────────────────────────────────────────────
62
63/// Resume a failed workflow from its last completed step (DBOS-style).
64///
65/// Resets the workflow from FAILED → RUNNING, resets failed child steps to
66/// PENDING, and re-dispatches the registered workflow function. Completed
67/// steps replay from their checkpointed outputs.
68///
69/// If no `WorkflowRegistration` is found for the workflow's handler, the
70/// workflow is still reset but not auto-dispatched — use `Ctx::from_id()`
71/// to drive it manually.
72///
73/// ```ignore
74/// durable::resume_workflow(&db, workflow_id).await?;
75/// ```
76pub async fn resume_workflow(
77    db: &DatabaseConnection,
78    task_id: uuid::Uuid,
79) -> Result<(), DurableError> {
80    let handler = Ctx::resume_failed(db, task_id).await?;
81
82    // Look up registered handler and auto-dispatch with recovery
83    let lookup_key = handler.as_deref().unwrap_or("");
84    if let Some(reg) = find_workflow(lookup_key) {
85        let db_inner = db.clone();
86        let resume = reg.resume_fn;
87        tokio::spawn(async move {
88            tracing::info!(
89                id = %task_id,
90                "re-dispatching resumed workflow"
91            );
92            run_workflow_with_recovery(db_inner, task_id, resume).await;
93        });
94    } else {
95        tracing::warn!(
96            id = %task_id,
97            handler = ?handler,
98            "no registered handler for resumed workflow — use Ctx::from_id() to resume manually"
99        );
100    }
101
102    Ok(())
103}
104
105/// Initialize durable: connect to Postgres, run migrations, start heartbeat,
106/// recover stale tasks, and auto-resume registered workflows.
107///
108/// After this call, [`Ctx::start`] automatically tags tasks with the executor
109/// ID for crash recovery. Recovered root workflows that have a matching
110/// `#[durable::workflow]` registration are automatically spawned as tokio
111/// tasks.
112///
113/// Uses [`HeartbeatConfig::default()`] (60 s heartbeat, 180 s staleness).
114/// For custom intervals use [`init_with_config`].
115///
116/// ```ignore
117/// let (db, recovered) = durable::init("postgres://localhost/mydb").await?;
118/// ```
119pub async fn init(
120    database_url: &str,
121) -> Result<(DatabaseConnection, Vec<RecoveredTask>), DurableError> {
122    init_with_config(database_url, HeartbeatConfig::default()).await
123}
124
125/// Like [`init`] but with a custom [`HeartbeatConfig`].
126pub async fn init_with_config(
127    database_url: &str,
128    config: HeartbeatConfig,
129) -> Result<(DatabaseConnection, Vec<RecoveredTask>), DurableError> {
130    let mut opt = ConnectOptions::new(database_url);
131    opt.set_schema_search_path("public,durable");
132    let db = Database::connect(opt).await?;
133
134    // Run migrations
135    durable_db::Migrator::up(&db, None).await?;
136
137    // Create executor with a unique ID for this process
138    let eid = format!("exec-{}-{}", std::process::id(), uuid::Uuid::new_v4());
139    if let Ok(mut guard) = EXECUTOR_ID.write() {
140        *guard = Some(eid.clone());
141    }
142    let executor = Executor::new(db.clone(), eid);
143
144    // Write initial heartbeat so other workers know we're alive
145    executor.heartbeat().await?;
146
147    let mut all_recovered = Vec::new();
148
149    // Recover stale tasks: timeout/deadline-based
150    let recovered = executor.recover().await?;
151    if !recovered.is_empty() {
152        tracing::info!(
153            "recovered {} stale tasks (timeout/deadline)",
154            recovered.len()
155        );
156    }
157    all_recovered.extend(recovered);
158
159    // Recover stale tasks: heartbeat-based (dead workers, unknown executors, orphaned NULL)
160    let recovered = executor
161        .recover_stale_tasks(config.staleness_threshold)
162        .await?;
163    if !recovered.is_empty() {
164        tracing::info!(
165            "recovered {} stale tasks from dead/unknown workers",
166            recovered.len()
167        );
168    }
169    all_recovered.extend(recovered);
170
171    // Reset orphaned RUNNING steps of recovered workflows back to PENDING
172    if !all_recovered.is_empty() {
173        let recovered_ids: Vec<Uuid> = all_recovered.iter().map(|r| r.id).collect();
174        match executor.reset_orphaned_steps(&recovered_ids).await {
175            Ok(n) if n > 0 => {
176                tracing::info!("reset {n} orphaned steps to PENDING");
177            }
178            Err(e) => tracing::warn!("failed to reset orphaned steps: {e}"),
179            _ => {}
180        }
181    }
182
183    // Auto-dispatch registered workflows
184    dispatch_recovered(&db, &all_recovered);
185
186    // Start background heartbeat loop
187    executor.start_heartbeat(&config);
188
189    // Start recovery loop that also auto-dispatches
190    start_recovery_dispatch_loop(
191        db.clone(),
192        executor.executor_id().to_string(),
193        config.staleness_threshold,
194    );
195
196    // Start cron scheduler loop
197    scheduler::start_scheduler_loop(
198        db.clone(),
199        executor.executor_id().to_string(),
200        &SchedulerConfig::default(),
201    );
202
203    tracing::info!("durable initialized (executor={})", executor.executor_id());
204    Ok((db, all_recovered))
205}
206
207/// Default backoff between automatic workflow recovery attempts.
208const RECOVERY_BACKOFF: std::time::Duration = std::time::Duration::from_secs(5);
209
210/// Run a workflow with automatic recovery on failure (DBOS-style).
211///
212/// When the workflow function returns `Err`:
213/// 1. Mark the workflow FAILED
214/// 2. If `recovery_count < max_recovery_attempts`, reset and re-execute
215/// 3. If recovery limit exceeded, leave it FAILED
216///
217/// Completed steps replay from checkpoints on each recovery attempt.
218async fn run_workflow_with_recovery(db: DatabaseConnection, task_id: Uuid, resume_fn: ResumeFn) {
219    loop {
220        match Ctx::from_id(&db, task_id).await {
221            Ok(ctx) => {
222                // Run the workflow, catching both Err returns and panics (.unwrap(), etc.)
223                let result = tokio::task::spawn(async move { (resume_fn)(ctx).await }).await;
224
225                let err_msg = match result {
226                    Ok(Ok(())) => return, // workflow completed successfully
227                    Ok(Err(e)) => e.to_string(),
228                    Err(join_err) => {
229                        // Panic or cancellation inside the spawned task
230                        if join_err.is_panic() {
231                            let panic_msg = match join_err.into_panic().downcast::<String>() {
232                                Ok(msg) => *msg,
233                                Err(payload) => match payload.downcast::<&str>() {
234                                    Ok(msg) => msg.to_string(),
235                                    Err(_) => "unknown panic".to_string(),
236                                },
237                            };
238                            format!("panic: {panic_msg}")
239                        } else {
240                            "task cancelled".to_string()
241                        }
242                    }
243                };
244
245                // Mark workflow as FAILED
246                if let Err(fail_err) = Ctx::fail_by_id(&db, task_id, &err_msg).await {
247                    tracing::error!(
248                        id = %task_id,
249                        error = %fail_err,
250                        "failed to mark workflow as FAILED"
251                    );
252                    return;
253                }
254
255                tracing::warn!(
256                    id = %task_id,
257                    error = %err_msg,
258                    "workflow failed, attempting automatic recovery"
259                );
260
261                // Attempt auto-recovery
262                match Ctx::resume_failed(&db, task_id).await {
263                    Ok(_) => {
264                        tracing::info!(
265                            id = %task_id,
266                            "workflow auto-recovery: reset succeeded, re-executing"
267                        );
268                        tokio::time::sleep(RECOVERY_BACKOFF).await;
269                        continue; // re-execute the workflow
270                    }
271                    Err(DurableError::MaxRecoveryExceeded(_)) => {
272                        tracing::error!(
273                            id = %task_id,
274                            "workflow exceeded max recovery attempts, staying FAILED"
275                        );
276                        return;
277                    }
278                    Err(recover_err) => {
279                        tracing::error!(
280                            id = %task_id,
281                            error = %recover_err,
282                            "workflow auto-recovery failed"
283                        );
284                        return;
285                    }
286                }
287            }
288            Err(e) => {
289                tracing::error!(
290                    id = %task_id,
291                    error = %e,
292                    "failed to attach to workflow"
293                );
294                return;
295            }
296        }
297    }
298}
299
300/// Spawn registered workflow functions for recovered root tasks.
301/// Tasks are already RUNNING (claimed atomically by the recovery SQL).
302fn dispatch_recovered(db: &DatabaseConnection, recovered: &[RecoveredTask]) {
303    for task in recovered {
304        // Only auto-dispatch root workflows (children are driven by their parent)
305        if task.parent_id.is_some() {
306            continue;
307        }
308
309        let lookup_key = task.handler.as_deref().unwrap_or(&task.name);
310        if let Some(reg) = find_workflow(lookup_key) {
311            let db_inner = db.clone();
312            let task_id = task.id;
313            let task_name = task.name.clone();
314            let resume = reg.resume_fn;
315            tokio::spawn(async move {
316                tracing::info!(
317                    workflow = %task_name,
318                    id = %task_id,
319                    "auto-resuming recovered workflow"
320                );
321                run_workflow_with_recovery(db_inner, task_id, resume).await;
322            });
323        } else {
324            tracing::warn!(
325                workflow = %task.name,
326                handler = ?task.handler,
327                id = %task.id,
328                "no registered handler for recovered task — use Ctx::from_id() to resume manually"
329            );
330        }
331    }
332}
333
334/// Spawn a background loop that recovers stale tasks AND auto-dispatches them.
335fn start_recovery_dispatch_loop(
336    db: DatabaseConnection,
337    executor_id: String,
338    staleness_threshold: std::time::Duration,
339) {
340    tokio::spawn(async move {
341        let executor = Executor::new(db.clone(), executor_id);
342        let mut ticker = tokio::time::interval(staleness_threshold);
343        loop {
344            ticker.tick().await;
345
346            // Collect all recovered workflow IDs so we can reset their orphaned steps.
347            let mut all_recovered_ids = Vec::new();
348
349            // Timeout-based recovery
350            match executor.recover().await {
351                Ok(ref recovered) if !recovered.is_empty() => {
352                    tracing::info!(
353                        "recovered {} stale tasks (timeout/deadline)",
354                        recovered.len()
355                    );
356                    all_recovered_ids.extend(recovered.iter().map(|r| r.id));
357                    dispatch_recovered(&db, recovered);
358                }
359                Err(e) => tracing::warn!("timeout recovery failed: {e}"),
360                _ => {}
361            }
362
363            // Heartbeat-based recovery
364            match executor.recover_stale_tasks(staleness_threshold).await {
365                Ok(ref recovered) if !recovered.is_empty() => {
366                    tracing::info!(
367                        "recovered {} stale tasks from dead workers",
368                        recovered.len()
369                    );
370                    all_recovered_ids.extend(recovered.iter().map(|r| r.id));
371                    dispatch_recovered(&db, recovered);
372                }
373                Err(e) => tracing::warn!("heartbeat recovery failed: {e}"),
374                _ => {}
375            }
376
377            // Reset orphaned RUNNING steps of recovered workflows back to
378            // PENDING so they can be re-executed. Without this, steps that
379            // committed TX1 (set RUNNING) but crashed before TX2 (checkpoint)
380            // would be permanently stuck.
381            if !all_recovered_ids.is_empty() {
382                match executor.reset_orphaned_steps(&all_recovered_ids).await {
383                    Ok(n) if n > 0 => {
384                        tracing::info!("reset {n} orphaned steps to PENDING");
385                    }
386                    Err(e) => tracing::warn!("failed to reset orphaned steps: {e}"),
387                    _ => {}
388                }
389            }
390        }
391    });
392}
393
394/// Initialize durable: connect to Postgres and run migrations only.
395///
396/// Does **not** start heartbeat or recovery loops, and does **not** set the
397/// global executor ID. Use this for tests, migrations-only scripts, or when
398/// you manage the [`Executor`] yourself.
399///
400/// ```ignore
401/// let db = durable::init_db("postgres://localhost/mydb").await?;
402/// ```
403pub async fn init_db(database_url: &str) -> Result<DatabaseConnection, DurableError> {
404    let mut opt = ConnectOptions::new(database_url);
405    opt.set_schema_search_path("public,durable");
406    let db = Database::connect(opt).await?;
407    durable_db::Migrator::up(&db, None).await?;
408    tracing::info!("durable initialized (db only)");
409    Ok(db)
410}