ironflow_store/store.rs
1//! The [`RunStore`] trait — async storage abstraction for runs and steps.
2//!
3//! Implement this trait to plug in any backing store. Built-in implementations:
4//!
5//! - [`InMemoryStore`](crate::memory::InMemoryStore) — development and testing.
6//! - `PostgresStore` — production (behind the `store-postgres` feature).
7
8use std::future::Future;
9use std::pin::Pin;
10
11use chrono::{DateTime, Utc};
12use uuid::Uuid;
13
14use crate::api_key_store::ApiKeyStore;
15use crate::approval_delegation_store::ApprovalDelegationStore;
16use crate::artifact_store::ArtifactStore;
17use crate::audit_log_store::AuditLogStore;
18use crate::entities::{
19 ConcurrencyGroupBacklog, LeaseRequest, NewRun, NewStep, NewStepDependency, Page, PurgePolicy,
20 PurgeableRun, ReapedRun, Run, RunCreation, RunFilter, RunStats, RunStatus, RunUpdate,
21 StatsHistoryBucket, StatsHistoryFilter, Step, StepApproval, StepDependency, StepUpdate,
22};
23use crate::error::StoreError;
24use crate::log_store::LogStore;
25use crate::provider_account_store::ProviderAccountStore;
26use crate::schedule_store::ScheduleStore;
27use crate::secret_store::SecretStore;
28use crate::signal_store::SignalStore;
29use crate::user_store::UserStore;
30
31/// Boxed future for [`RunStore`] methods — ensures object safety for `dyn RunStore`.
32pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, StoreError>> + Send + 'a>>;
33
34/// Error recorded on a run that exhausted its retries through lease expiries.
35///
36/// Set by [`RunStore::reap_expired_leases`] when a run has been recovered more
37/// than `max_retries` times.
38pub const LEASE_EXPIRED_ERROR: &str = "worker lease expired";
39
40/// Error recorded on a step that was running when its worker lost the lease.
41///
42/// Set by the reaper on the `Running` steps of a run that
43/// [`RunStore::reap_expired_leases`] requeued. The engine executes such a step
44/// again at the same position when the run is picked up, keeping the
45/// interrupted record in the step history.
46///
47/// # Examples
48///
49/// ```
50/// use ironflow_store::store::{LEASE_EXPIRED_ERROR, STEP_INTERRUPTED_ERROR};
51///
52/// assert_eq!(STEP_INTERRUPTED_ERROR, "interrupted: worker lease lost");
53/// assert_ne!(STEP_INTERRUPTED_ERROR, LEASE_EXPIRED_ERROR);
54/// ```
55pub const STEP_INTERRUPTED_ERROR: &str = "interrupted: worker lease lost";
56
57/// Async storage abstraction for workflow runs and steps.
58///
59/// All methods return a [`StoreFuture`] (boxed future) to maintain object safety,
60/// allowing the store to be used as `Arc<dyn RunStore>`.
61///
62/// # Examples
63///
64/// ```no_run
65/// use std::collections::HashMap;
66/// use ironflow_store::prelude::*;
67/// use serde_json::json;
68/// use uuid::Uuid;
69///
70/// # async fn example() -> Result<(), ironflow_store::error::StoreError> {
71/// let store = InMemoryStore::new();
72///
73/// let run = store.create_run(NewRun {
74/// workflow_name: "deploy".to_string(),
75/// trigger: TriggerKind::Manual,
76/// payload: json!({}),
77/// max_retries: 3,
78/// handler_version: None,
79/// labels: HashMap::new(),
80/// scheduled_at: None,
81/// created_by: None,
82/// idempotency_key: None,
83/// concurrency_key: None,
84/// concurrency_limits: Vec::new(),
85/// max_cost_usd: None,
86/// }).await?.into_run();
87///
88/// let fetched = store.get_run(run.id).await?;
89/// assert!(fetched.is_some());
90/// # Ok(())
91/// # }
92/// ```
93pub trait RunStore: Send + Sync {
94 /// Create a new run in `Pending` status.
95 ///
96 /// When [`NewRun::idempotency_key`] is set and already bound to a run created
97 /// within [`IDEMPOTENCY_WINDOW`](crate::entities::IDEMPOTENCY_WINDOW), nothing is
98 /// inserted and that run is returned as [`RunCreation::Existing`]. A key bound to
99 /// an older run is released and reused for the new one.
100 ///
101 /// Concurrent calls sharing the same key resolve to a single run: exactly one
102 /// receives [`RunCreation::Created`], the others [`RunCreation::Existing`].
103 ///
104 /// When [`NewRun::concurrency_key`] is set, the idempotency lookup runs first,
105 /// then the key is checked: concurrent calls sharing it are serialized, and
106 /// at most one non-terminal run holds it at a time.
107 ///
108 /// [`NewRun::concurrency_limits`] is validated before anything is written.
109 ///
110 /// # Errors
111 ///
112 /// Returns [`StoreError::ConcurrencyConflict`](crate::error::StoreError::ConcurrencyConflict)
113 /// when a run that is not Completed, Failed, Warning or Cancelled already
114 /// holds [`NewRun::concurrency_key`],
115 /// [`StoreError::InvalidConcurrencyLimit`](crate::error::StoreError::InvalidConcurrencyLimit)
116 /// when [`NewRun::concurrency_limits`] holds an empty or too long group, a
117 /// zero limit or a duplicated group, and a database error when the backing
118 /// store fails.
119 fn create_run(&self, req: NewRun) -> StoreFuture<'_, RunCreation>;
120
121 /// Look up the run bound to an idempotency key.
122 ///
123 /// Returns `None` when the key is unknown, or when the run holding it is older
124 /// than [`IDEMPOTENCY_WINDOW`](crate::entities::IDEMPOTENCY_WINDOW).
125 fn find_run_by_idempotency_key(&self, key: &str) -> StoreFuture<'_, Option<Run>>;
126
127 /// Get a run by ID. Returns `None` if not found.
128 fn get_run(&self, id: Uuid) -> StoreFuture<'_, Option<Run>>;
129
130 /// List runs matching the given filter, with pagination.
131 ///
132 /// Results are ordered by `created_at` descending (newest first).
133 fn list_runs(&self, filter: RunFilter, page: u32, per_page: u32) -> StoreFuture<'_, Page<Run>>;
134
135 /// Update a run's status with FSM validation.
136 ///
137 /// # Errors
138 ///
139 /// Returns [`StoreError::InvalidTransition`] if the transition is not allowed.
140 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
141 fn update_run_status(&self, id: Uuid, new_status: RunStatus) -> StoreFuture<'_, ()>;
142
143 /// Apply a partial update to a run.
144 ///
145 /// # Errors
146 ///
147 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
148 fn update_run(&self, id: Uuid, update: RunUpdate) -> StoreFuture<'_, ()>;
149
150 /// List the non-terminal descendants of a run, oldest first.
151 ///
152 /// A descendant is a sub-workflow run
153 /// ([`TriggerKind::Workflow`](crate::entities::TriggerKind::Workflow))
154 /// reached from `run_id` through
155 /// [`PARENT_RUN_ID_LABEL`](crate::entities::PARENT_RUN_ID_LABEL), at any
156 /// depth. Terminal runs are not returned, but their own descendants are:
157 /// a child left running under a finished parent is still found. Labels are
158 /// data, so a chain that loops back on itself is followed once and never
159 /// returns `run_id` itself.
160 ///
161 /// Returns an empty list for an unknown run or a run without children.
162 ///
163 /// # Errors
164 ///
165 /// Returns a database error when the backing store fails.
166 fn list_active_descendants(&self, run_id: Uuid) -> StoreFuture<'_, Vec<Run>>;
167
168 /// Atomically pick the oldest pending run and transition it to `Running`.
169 ///
170 /// In PostgreSQL, this uses `SELECT FOR UPDATE SKIP LOCKED` for safe
171 /// multi-worker concurrency. The in-memory implementation uses a write lock.
172 ///
173 /// When `lease` is `Some`, the worker lease is attached in the same
174 /// transaction as the status change, so a run is never `Running` without an
175 /// owner. Pass `None` for callers that execute runs in-process and cannot
176 /// refresh a lease (inline execution, API-side resume): those runs are never
177 /// recovered by [`reap_expired_leases`](Self::reap_expired_leases).
178 ///
179 /// Concurrency groups gate the pick: a run carrying
180 /// [`Run::concurrency_limits`] is skipped while, for any of its groups, the
181 /// number of root runs in state `Running` carrying that group is already at
182 /// or above the run's own limit for it. Sleeping, awaiting approval,
183 /// retrying and pending runs do not count, and sub-workflow runs
184 /// ([`TriggerKind::Workflow`](crate::entities::TriggerKind::Workflow)) are
185 /// never counted. A held-back run does not block the queue: the oldest
186 /// eligible run wins. The check is atomic across concurrent callers, so a
187 /// group never exceeds its limit.
188 ///
189 /// Returns `None` if no pending runs are available.
190 fn pick_next_pending(&self, lease: Option<LeaseRequest>) -> StoreFuture<'_, Option<Run>>;
191
192 /// Extend the worker lease on a run and return the new expiry.
193 ///
194 /// # Errors
195 ///
196 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
197 /// Returns [`StoreError::LeaseLost`] if the run is no longer `Running` or if
198 /// the lease belongs to another worker — the caller must stop executing it.
199 fn renew_lease(&self, id: Uuid, lease: LeaseRequest) -> StoreFuture<'_, DateTime<Utc>>;
200
201 /// Count, for each concurrency group, the due runs it currently holds back.
202 ///
203 /// A run is counted when it is pending or retrying, due (no
204 /// `scheduled_at` in the future) and not pickable because the group is
205 /// saturated for its own limit (see [`pick_next_pending`](Self::pick_next_pending)).
206 /// A run held back by two groups counts in both. Groups holding back no
207 /// run are omitted. Results are sorted by group name.
208 ///
209 /// # Errors
210 ///
211 /// Returns a database error when the backing store fails.
212 ///
213 /// # Examples
214 ///
215 /// ```no_run
216 /// use ironflow_store::store::RunStore;
217 ///
218 /// # async fn example(store: &dyn RunStore) -> Result<(), ironflow_store::error::StoreError> {
219 /// for backlog in store.count_blocked_runs_by_group().await? {
220 /// println!("{}: {} runs held back", backlog.group, backlog.blocked_runs);
221 /// }
222 /// # Ok(())
223 /// # }
224 /// ```
225 fn count_blocked_runs_by_group(&self) -> StoreFuture<'_, Vec<ConcurrencyGroupBacklog>>;
226
227 /// Recover runs whose worker lease expired, at most `limit` per call.
228 ///
229 /// Each recovered run has [`Run::lease_recoveries`] incremented and its lease
230 /// cleared, then goes back to `Pending` — or to `Failed` with
231 /// [`LEASE_EXPIRED_ERROR`] once more than `max_retries` recoveries happened.
232 /// Runs without a lease are never touched.
233 ///
234 /// [`Run::retry_count`], and so the attempt number of the steps created
235 /// afterwards, is left unchanged: a requeued run resumes in the same attempt
236 /// and replays the steps it already finished.
237 ///
238 /// The whole batch is atomic per run (`FOR UPDATE SKIP LOCKED` in
239 /// PostgreSQL), so concurrent reapers never recover the same run twice.
240 ///
241 /// Callers are responsible for the side effects that follow a recovery:
242 /// failing orphaned steps and publishing status-change events.
243 fn reap_expired_leases(&self, limit: u32) -> StoreFuture<'_, Vec<ReapedRun>>;
244
245 /// Atomically claim approval steps whose SLA deadline has passed.
246 ///
247 /// Returns the claimed steps with their *pre-claim* `approval_deadline_at`
248 /// still populated, so the caller can report which deadline fired. The
249 /// timer is cleared in the same transaction, so a deadline fires at most
250 /// once even with several API instances running the escalator (the
251 /// PostgreSQL implementation uses `FOR UPDATE SKIP LOCKED`).
252 ///
253 /// Only steps still in [`StepStatus::AwaitingApproval`](crate::entities::StepStatus::AwaitingApproval)
254 /// are returned.
255 ///
256 /// Delivery is at most once: a caller that crashes between the claim and
257 /// the escalation leaves the gate open with no timer, the same trade-off
258 /// [`reap_expired_leases`](Self::reap_expired_leases) accepts.
259 fn claim_due_approval_deadlines(&self, limit: u32) -> StoreFuture<'_, Vec<Step>>;
260
261 /// Atomically wake the `Sleeping` runs whose `scheduled_at` has passed, at
262 /// most `limit` per call.
263 ///
264 /// Each claimed run goes `Sleeping -> Pending` (`delay_elapsed`) and has
265 /// its `scheduled_at` cleared in the same transaction, so a run is woken
266 /// exactly once even with several API instances running the waker (the
267 /// PostgreSQL implementation uses `FOR UPDATE SKIP LOCKED`). Runs are
268 /// claimed oldest `scheduled_at` first.
269 ///
270 /// Returns the runs as they are after the transition. Callers decide how
271 /// the requeued runs resume: a worker picks them up, or the API resumes
272 /// them in-process when it has no worker.
273 ///
274 /// # Errors
275 ///
276 /// Returns [`StoreError`] on storage failure.
277 fn claim_due_sleeping_runs(&self, limit: u32) -> StoreFuture<'_, Vec<Run>>;
278
279 /// Create a new step for a run.
280 ///
281 /// # Errors
282 ///
283 /// Returns [`StoreError::RunNotFound`] if the parent run does not exist.
284 fn create_step(&self, step: NewStep) -> StoreFuture<'_, Step>;
285
286 /// Apply a partial update to a step after execution.
287 ///
288 /// # Errors
289 ///
290 /// Returns [`StoreError::StepNotFound`] if the step does not exist.
291 fn update_step(&self, id: Uuid, update: StepUpdate) -> StoreFuture<'_, ()>;
292
293 /// Get a single step by ID. Returns `None` if not found.
294 fn get_step(&self, id: Uuid) -> StoreFuture<'_, Option<Step>>;
295
296 /// List all steps for a run, ordered by position ascending.
297 fn list_steps(&self, run_id: Uuid) -> StoreFuture<'_, Vec<Step>>;
298
299 /// Record a vote on an approval gate and return the updated step.
300 ///
301 /// The vote is appended atomically to [`Step::approvals`] unless the same
302 /// [`StepApproval::user_id`] already voted, in which case the step is
303 /// returned unchanged. Recording a vote never resolves the gate: the
304 /// caller compares the vote count against the step's
305 /// [`approval_requirement`](Step::approval_requirement).
306 ///
307 /// # Errors
308 ///
309 /// Returns [`StoreError::StepNotFound`] if the step does not exist.
310 fn record_step_approval(&self, step_id: Uuid, approval: StepApproval) -> StoreFuture<'_, Step>;
311
312 /// Get aggregated statistics across runs matching the filter.
313 ///
314 /// Returns counts of runs by terminal state, counts of active runs
315 /// (`Pending`, `Running`, `Retrying`, `AwaitingApproval` or `Sleeping`),
316 /// the number of runs awaiting approval, and totals for cost and duration.
317 /// Computed efficiently by the store implementation (single SQL query in
318 /// PostgreSQL).
319 ///
320 /// Pass [`RunFilter::default()`] to get stats across all runs.
321 fn get_stats(&self, filter: RunFilter) -> StoreFuture<'_, RunStats>;
322
323 /// Get time-bucketed historical statistics for trend charts.
324 ///
325 /// Aggregates runs created during the filter's period into time buckets
326 /// based on its granularity, counting every run status and computing
327 /// duration percentiles. Applies the same run filters as
328 /// [`get_stats`](Self::get_stats) (workflow substring, status, labels,
329 /// steps, author). Bucket boundaries are UTC and weeks start on Monday
330 /// (see [`HistoryGranularity::bucket_start`](crate::entities::HistoryGranularity::bucket_start)).
331 /// Returns buckets ordered by time ascending; empty buckets are omitted.
332 ///
333 /// # Errors
334 ///
335 /// Returns [`StoreError::Database`] on underlying store failures.
336 ///
337 /// # Examples
338 ///
339 /// ```no_run
340 /// use ironflow_store::entities::{StatsHistoryFilter, HistoryPeriod, HistoryGranularity};
341 /// use ironflow_store::store::RunStore;
342 ///
343 /// # async fn example(store: &dyn RunStore) -> Result<(), ironflow_store::error::StoreError> {
344 /// let filter = StatsHistoryFilter {
345 /// period: HistoryPeriod::SevenDays,
346 /// granularity: HistoryGranularity::OneDay,
347 /// ..StatsHistoryFilter::default()
348 /// };
349 /// let buckets = store.get_stats_history(filter).await?;
350 /// for b in &buckets {
351 /// println!("{}: {} completed, {} failed", b.time, b.completed, b.failed);
352 /// }
353 /// # Ok(())
354 /// # }
355 /// ```
356 fn get_stats_history(
357 &self,
358 filter: StatsHistoryFilter,
359 ) -> StoreFuture<'_, Vec<StatsHistoryBucket>>;
360
361 /// Create step dependency edges in batch.
362 ///
363 /// Each entry records that `step_id` depends on `depends_on`.
364 /// Duplicate edges are silently ignored.
365 ///
366 /// # Errors
367 ///
368 /// Returns [`StoreError`] if a referenced step does not exist.
369 fn create_step_dependencies(&self, deps: Vec<NewStepDependency>) -> StoreFuture<'_, ()>;
370
371 /// List all step dependencies for a given run.
372 ///
373 /// Returns every edge where either `step_id` or `depends_on` belongs
374 /// to the run. Ordered by `created_at` ascending.
375 fn list_step_dependencies(&self, run_id: Uuid) -> StoreFuture<'_, Vec<StepDependency>>;
376
377 /// List runs eligible for purging according to the given policy.
378 ///
379 /// A run is eligible when it is in a terminal state ([`RunStatus::is_terminal`])
380 /// **and** either older than `policy.max_age_days` or exceeding
381 /// `policy.max_runs_per_workflow` for its workflow (oldest first).
382 ///
383 /// Runs in non-terminal states (`Pending`, `Running`, `Retrying`,
384 /// `AwaitingApproval`) are never returned.
385 ///
386 /// # Examples
387 ///
388 /// ```no_run
389 /// use ironflow_store::entities::PurgePolicy;
390 /// use ironflow_store::store::RunStore;
391 ///
392 /// # async fn example(store: &dyn RunStore) -> Result<(), ironflow_store::error::StoreError> {
393 /// let policy = PurgePolicy { max_age_days: 90, max_runs_per_workflow: 1000, dry_run: false };
394 /// let purgeable = store.list_purgeable_runs(&policy, 100).await?;
395 /// for p in &purgeable {
396 /// println!("purge {} ({}): {}", p.run_id, p.workflow_name, p.reason);
397 /// }
398 /// # Ok(())
399 /// # }
400 /// ```
401 fn list_purgeable_runs(
402 &self,
403 policy: &PurgePolicy,
404 batch_size: u32,
405 ) -> StoreFuture<'_, Vec<PurgeableRun>>;
406
407 /// Delete a run and all its associated data (steps, step dependencies).
408 ///
409 /// Returns the `storage_key` of every artifact that belonged to the run,
410 /// so the caller can delete the corresponding blobs from the blob store.
411 ///
412 /// # Errors
413 ///
414 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
415 ///
416 /// # Examples
417 ///
418 /// ```no_run
419 /// use ironflow_store::store::RunStore;
420 /// use uuid::Uuid;
421 ///
422 /// # async fn example(store: &dyn RunStore, run_id: Uuid) -> Result<(), ironflow_store::error::StoreError> {
423 /// let storage_keys = store.delete_run(run_id).await?;
424 /// // Caller deletes blobs from the blob store using these keys.
425 /// # Ok(())
426 /// # }
427 /// ```
428 fn delete_run(&self, id: Uuid) -> StoreFuture<'_, Vec<String>>;
429
430 /// Apply a partial update to a run and return the updated run.
431 ///
432 /// Combines [`update_run`](Self::update_run) and [`get_run`](Self::get_run) in
433 /// a single operation to avoid an extra round-trip. Store implementations
434 /// may override this for efficiency (e.g. reading within the same transaction).
435 ///
436 /// The default implementation calls `update_run` followed by `get_run`.
437 ///
438 /// # Errors
439 ///
440 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
441 /// Returns [`StoreError::InvalidTransition`] if the status transition is not allowed.
442 fn update_run_returning(&self, id: Uuid, update: RunUpdate) -> StoreFuture<'_, Run> {
443 Box::pin(async move {
444 self.update_run(id, update).await?;
445 self.get_run(id).await?.ok_or(StoreError::RunNotFound(id))
446 })
447 }
448}
449
450/// Unified storage abstraction combining all store capabilities.
451///
452/// Implementors provide runs, steps, users, API keys, and secrets
453/// through a single type. Pick one backend (in-memory or PostgreSQL)
454/// and it handles everything.
455///
456/// Both [`InMemoryStore`](crate::memory::InMemoryStore) and
457/// [`PostgresStore`](crate::postgres::PostgresStore) implement this trait.
458///
459/// # Examples
460///
461/// ```no_run
462/// use std::collections::HashMap;
463/// use std::sync::Arc;
464/// use ironflow_store::prelude::*;
465///
466/// # async fn example() -> Result<(), ironflow_store::error::StoreError> {
467/// let store: Arc<dyn Store> = Arc::new(InMemoryStore::new());
468///
469/// // All capabilities through one reference
470/// let _run = store.create_run(NewRun {
471/// workflow_name: "deploy".to_string(),
472/// trigger: TriggerKind::Manual,
473/// payload: serde_json::json!({}),
474/// max_retries: 3,
475/// handler_version: None,
476/// labels: HashMap::new(),
477/// scheduled_at: None,
478/// created_by: None,
479/// idempotency_key: None,
480/// concurrency_key: None,
481/// concurrency_limits: Vec::new(),
482/// max_cost_usd: None,
483/// }).await?.into_run();
484/// let _users = store.count_users().await?;
485/// # Ok(())
486/// # }
487/// ```
488pub trait Store:
489 RunStore
490 + UserStore
491 + ApiKeyStore
492 + SecretStore
493 + AuditLogStore
494 + ArtifactStore
495 + LogStore
496 + ScheduleStore
497 + ApprovalDelegationStore
498 + ProviderAccountStore
499 + SignalStore
500{
501}
502
503impl<
504 T: RunStore
505 + UserStore
506 + ApiKeyStore
507 + SecretStore
508 + AuditLogStore
509 + ArtifactStore
510 + LogStore
511 + ScheduleStore
512 + ApprovalDelegationStore
513 + ProviderAccountStore
514 + SignalStore,
515> Store for T
516{
517}