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
17pub 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
27static EXECUTOR_ID: RwLock<Option<String>> = RwLock::new(None);
30
31pub fn executor_id() -> Option<String> {
33 EXECUTOR_ID.read().ok().and_then(|g| g.clone())
34}
35
36pub type ResumeFn = fn(Ctx) -> Pin<Box<dyn Future<Output = Result<(), DurableError>> + Send>>;
40
41pub struct WorkflowRegistration {
46 pub name: &'static str,
49 pub resume_fn: ResumeFn,
52}
53
54inventory::collect!(WorkflowRegistration);
55
56pub fn find_workflow(name: &str) -> Option<&'static WorkflowRegistration> {
58 inventory::iter::<WorkflowRegistration>().find(|r| r.name == name)
59}
60
61pub 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 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
105pub async fn init(
120 database_url: &str,
121) -> Result<(DatabaseConnection, Vec<RecoveredTask>), DurableError> {
122 init_with_config(database_url, HeartbeatConfig::default()).await
123}
124
125pub 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 durable_db::Migrator::up(&db, None).await?;
136
137 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 executor.heartbeat().await?;
146
147 let mut all_recovered = Vec::new();
148
149 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 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 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 dispatch_recovered(&db, &all_recovered);
185
186 executor.start_heartbeat(&config);
188
189 start_recovery_dispatch_loop(
191 db.clone(),
192 executor.executor_id().to_string(),
193 config.staleness_threshold,
194 );
195
196 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
207const RECOVERY_BACKOFF: std::time::Duration = std::time::Duration::from_secs(5);
209
210async 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 let result = tokio::task::spawn(async move { (resume_fn)(ctx).await }).await;
224
225 let err_msg = match result {
226 Ok(Ok(())) => return, Ok(Err(e)) => e.to_string(),
228 Err(join_err) => {
229 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 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 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; }
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
300fn dispatch_recovered(db: &DatabaseConnection, recovered: &[RecoveredTask]) {
303 for task in recovered {
304 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
334fn 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 let mut all_recovered_ids = Vec::new();
348
349 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 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 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
394pub 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}