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 LeaseRequest, NewRun, NewStep, NewStepDependency, Page, PurgePolicy, PurgeableRun, ReapedRun,
20 Run, RunCreation, RunFilter, RunStats, RunStatus, RunUpdate, StatsHistoryBucket,
21 StatsHistoryFilter, Step, StepApproval, StepDependency, StepUpdate,
22};
23use crate::error::StoreError;
24use crate::log_store::LogStore;
25use crate::schedule_store::ScheduleStore;
26use crate::secret_store::SecretStore;
27use crate::user_store::UserStore;
28
29/// Boxed future for [`RunStore`] methods — ensures object safety for `dyn RunStore`.
30pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, StoreError>> + Send + 'a>>;
31
32/// Error recorded on a run that exhausted its retries through lease expiries.
33///
34/// Set by [`RunStore::reap_expired_leases`] when a run has been recovered more
35/// than `max_retries` times.
36pub const LEASE_EXPIRED_ERROR: &str = "worker lease expired";
37
38/// Async storage abstraction for workflow runs and steps.
39///
40/// All methods return a [`StoreFuture`] (boxed future) to maintain object safety,
41/// allowing the store to be used as `Arc<dyn RunStore>`.
42///
43/// # Examples
44///
45/// ```no_run
46/// use std::collections::HashMap;
47/// use ironflow_store::prelude::*;
48/// use serde_json::json;
49/// use uuid::Uuid;
50///
51/// # async fn example() -> Result<(), ironflow_store::error::StoreError> {
52/// let store = InMemoryStore::new();
53///
54/// let run = store.create_run(NewRun {
55/// workflow_name: "deploy".to_string(),
56/// trigger: TriggerKind::Manual,
57/// payload: json!({}),
58/// max_retries: 3,
59/// handler_version: None,
60/// labels: HashMap::new(),
61/// scheduled_at: None,
62/// created_by: None,
63/// idempotency_key: None,
64/// max_cost_usd: None,
65/// }).await?.into_run();
66///
67/// let fetched = store.get_run(run.id).await?;
68/// assert!(fetched.is_some());
69/// # Ok(())
70/// # }
71/// ```
72pub trait RunStore: Send + Sync {
73 /// Create a new run in `Pending` status.
74 ///
75 /// When [`NewRun::idempotency_key`] is set and already bound to a run created
76 /// within [`IDEMPOTENCY_WINDOW`](crate::entities::IDEMPOTENCY_WINDOW), nothing is
77 /// inserted and that run is returned as [`RunCreation::Existing`]. A key bound to
78 /// an older run is released and reused for the new one.
79 ///
80 /// Concurrent calls sharing the same key resolve to a single run: exactly one
81 /// receives [`RunCreation::Created`], the others [`RunCreation::Existing`].
82 fn create_run(&self, req: NewRun) -> StoreFuture<'_, RunCreation>;
83
84 /// Look up the run bound to an idempotency key.
85 ///
86 /// Returns `None` when the key is unknown, or when the run holding it is older
87 /// than [`IDEMPOTENCY_WINDOW`](crate::entities::IDEMPOTENCY_WINDOW).
88 fn find_run_by_idempotency_key(&self, key: &str) -> StoreFuture<'_, Option<Run>>;
89
90 /// Get a run by ID. Returns `None` if not found.
91 fn get_run(&self, id: Uuid) -> StoreFuture<'_, Option<Run>>;
92
93 /// List runs matching the given filter, with pagination.
94 ///
95 /// Results are ordered by `created_at` descending (newest first).
96 fn list_runs(&self, filter: RunFilter, page: u32, per_page: u32) -> StoreFuture<'_, Page<Run>>;
97
98 /// Update a run's status with FSM validation.
99 ///
100 /// # Errors
101 ///
102 /// Returns [`StoreError::InvalidTransition`] if the transition is not allowed.
103 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
104 fn update_run_status(&self, id: Uuid, new_status: RunStatus) -> StoreFuture<'_, ()>;
105
106 /// Apply a partial update to a run.
107 ///
108 /// # Errors
109 ///
110 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
111 fn update_run(&self, id: Uuid, update: RunUpdate) -> StoreFuture<'_, ()>;
112
113 /// Atomically pick the oldest pending run and transition it to `Running`.
114 ///
115 /// In PostgreSQL, this uses `SELECT FOR UPDATE SKIP LOCKED` for safe
116 /// multi-worker concurrency. The in-memory implementation uses a write lock.
117 ///
118 /// When `lease` is `Some`, the worker lease is attached in the same
119 /// transaction as the status change, so a run is never `Running` without an
120 /// owner. Pass `None` for callers that execute runs in-process and cannot
121 /// refresh a lease (inline execution, API-side resume): those runs are never
122 /// recovered by [`reap_expired_leases`](Self::reap_expired_leases).
123 ///
124 /// Returns `None` if no pending runs are available.
125 fn pick_next_pending(&self, lease: Option<LeaseRequest>) -> StoreFuture<'_, Option<Run>>;
126
127 /// Extend the worker lease on a run and return the new expiry.
128 ///
129 /// # Errors
130 ///
131 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
132 /// Returns [`StoreError::LeaseLost`] if the run is no longer `Running` or if
133 /// the lease belongs to another worker — the caller must stop executing it.
134 fn renew_lease(&self, id: Uuid, lease: LeaseRequest) -> StoreFuture<'_, DateTime<Utc>>;
135
136 /// Recover runs whose worker lease expired, at most `limit` per call.
137 ///
138 /// Each recovered run has its retry count incremented and its lease cleared,
139 /// then goes back to `Pending` — or to `Failed` with `worker lease expired`
140 /// once `max_retries` is exhausted. Runs without a lease are never touched.
141 ///
142 /// The whole batch is atomic per run (`FOR UPDATE SKIP LOCKED` in
143 /// PostgreSQL), so concurrent reapers never recover the same run twice.
144 ///
145 /// Callers are responsible for the side effects that follow a recovery:
146 /// failing orphaned steps and publishing status-change events.
147 fn reap_expired_leases(&self, limit: u32) -> StoreFuture<'_, Vec<ReapedRun>>;
148
149 /// Atomically claim approval steps whose SLA deadline has passed.
150 ///
151 /// Returns the claimed steps with their *pre-claim* `approval_deadline_at`
152 /// still populated, so the caller can report which deadline fired. The
153 /// timer is cleared in the same transaction, so a deadline fires at most
154 /// once even with several API instances running the escalator (the
155 /// PostgreSQL implementation uses `FOR UPDATE SKIP LOCKED`).
156 ///
157 /// Only steps still in [`StepStatus::AwaitingApproval`](crate::entities::StepStatus::AwaitingApproval)
158 /// are returned.
159 ///
160 /// Delivery is at most once: a caller that crashes between the claim and
161 /// the escalation leaves the gate open with no timer, the same trade-off
162 /// [`reap_expired_leases`](Self::reap_expired_leases) accepts.
163 fn claim_due_approval_deadlines(&self, limit: u32) -> StoreFuture<'_, Vec<Step>>;
164
165 /// Create a new step for a run.
166 ///
167 /// # Errors
168 ///
169 /// Returns [`StoreError::RunNotFound`] if the parent run does not exist.
170 fn create_step(&self, step: NewStep) -> StoreFuture<'_, Step>;
171
172 /// Apply a partial update to a step after execution.
173 ///
174 /// # Errors
175 ///
176 /// Returns [`StoreError::StepNotFound`] if the step does not exist.
177 fn update_step(&self, id: Uuid, update: StepUpdate) -> StoreFuture<'_, ()>;
178
179 /// Get a single step by ID. Returns `None` if not found.
180 fn get_step(&self, id: Uuid) -> StoreFuture<'_, Option<Step>>;
181
182 /// List all steps for a run, ordered by position ascending.
183 fn list_steps(&self, run_id: Uuid) -> StoreFuture<'_, Vec<Step>>;
184
185 /// Record a vote on an approval gate and return the updated step.
186 ///
187 /// The vote is appended atomically to [`Step::approvals`] unless the same
188 /// [`StepApproval::user_id`] already voted, in which case the step is
189 /// returned unchanged. Recording a vote never resolves the gate: the
190 /// caller compares the vote count against the step's
191 /// [`approval_requirement`](Step::approval_requirement).
192 ///
193 /// # Errors
194 ///
195 /// Returns [`StoreError::StepNotFound`] if the step does not exist.
196 fn record_step_approval(&self, step_id: Uuid, approval: StepApproval) -> StoreFuture<'_, Step>;
197
198 /// Get aggregated statistics across runs matching the filter.
199 ///
200 /// Returns counts of runs by terminal state, counts of active runs
201 /// (`Pending`, `Running`, `Retrying`, `AwaitingApproval` or `Sleeping`),
202 /// the number of runs awaiting approval, and totals for cost and duration.
203 /// Computed efficiently by the store implementation (single SQL query in
204 /// PostgreSQL).
205 ///
206 /// Pass [`RunFilter::default()`] to get stats across all runs.
207 fn get_stats(&self, filter: RunFilter) -> StoreFuture<'_, RunStats>;
208
209 /// Get time-bucketed historical statistics for trend charts.
210 ///
211 /// Aggregates runs created during the filter's period into time buckets
212 /// based on its granularity, counting every run status and computing
213 /// duration percentiles. Applies the same run filters as
214 /// [`get_stats`](Self::get_stats) (workflow substring, status, labels,
215 /// steps, author). Bucket boundaries are UTC and weeks start on Monday
216 /// (see [`HistoryGranularity::bucket_start`](crate::entities::HistoryGranularity::bucket_start)).
217 /// Returns buckets ordered by time ascending; empty buckets are omitted.
218 ///
219 /// # Errors
220 ///
221 /// Returns [`StoreError::Database`] on underlying store failures.
222 ///
223 /// # Examples
224 ///
225 /// ```no_run
226 /// use ironflow_store::entities::{StatsHistoryFilter, HistoryPeriod, HistoryGranularity};
227 /// use ironflow_store::store::RunStore;
228 ///
229 /// # async fn example(store: &dyn RunStore) -> Result<(), ironflow_store::error::StoreError> {
230 /// let filter = StatsHistoryFilter {
231 /// period: HistoryPeriod::SevenDays,
232 /// granularity: HistoryGranularity::OneDay,
233 /// ..StatsHistoryFilter::default()
234 /// };
235 /// let buckets = store.get_stats_history(filter).await?;
236 /// for b in &buckets {
237 /// println!("{}: {} completed, {} failed", b.time, b.completed, b.failed);
238 /// }
239 /// # Ok(())
240 /// # }
241 /// ```
242 fn get_stats_history(
243 &self,
244 filter: StatsHistoryFilter,
245 ) -> StoreFuture<'_, Vec<StatsHistoryBucket>>;
246
247 /// Create step dependency edges in batch.
248 ///
249 /// Each entry records that `step_id` depends on `depends_on`.
250 /// Duplicate edges are silently ignored.
251 ///
252 /// # Errors
253 ///
254 /// Returns [`StoreError`] if a referenced step does not exist.
255 fn create_step_dependencies(&self, deps: Vec<NewStepDependency>) -> StoreFuture<'_, ()>;
256
257 /// List all step dependencies for a given run.
258 ///
259 /// Returns every edge where either `step_id` or `depends_on` belongs
260 /// to the run. Ordered by `created_at` ascending.
261 fn list_step_dependencies(&self, run_id: Uuid) -> StoreFuture<'_, Vec<StepDependency>>;
262
263 /// List runs eligible for purging according to the given policy.
264 ///
265 /// A run is eligible when it is in a terminal state ([`RunStatus::is_terminal`])
266 /// **and** either older than `policy.max_age_days` or exceeding
267 /// `policy.max_runs_per_workflow` for its workflow (oldest first).
268 ///
269 /// Runs in non-terminal states (`Pending`, `Running`, `Retrying`,
270 /// `AwaitingApproval`) are never returned.
271 ///
272 /// # Examples
273 ///
274 /// ```no_run
275 /// use ironflow_store::entities::PurgePolicy;
276 /// use ironflow_store::store::RunStore;
277 ///
278 /// # async fn example(store: &dyn RunStore) -> Result<(), ironflow_store::error::StoreError> {
279 /// let policy = PurgePolicy { max_age_days: 90, max_runs_per_workflow: 1000, dry_run: false };
280 /// let purgeable = store.list_purgeable_runs(&policy, 100).await?;
281 /// for p in &purgeable {
282 /// println!("purge {} ({}): {}", p.run_id, p.workflow_name, p.reason);
283 /// }
284 /// # Ok(())
285 /// # }
286 /// ```
287 fn list_purgeable_runs(
288 &self,
289 policy: &PurgePolicy,
290 batch_size: u32,
291 ) -> StoreFuture<'_, Vec<PurgeableRun>>;
292
293 /// Delete a run and all its associated data (steps, step dependencies).
294 ///
295 /// Returns the `storage_key` of every artifact that belonged to the run,
296 /// so the caller can delete the corresponding blobs from the blob store.
297 ///
298 /// # Errors
299 ///
300 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
301 ///
302 /// # Examples
303 ///
304 /// ```no_run
305 /// use ironflow_store::store::RunStore;
306 /// use uuid::Uuid;
307 ///
308 /// # async fn example(store: &dyn RunStore, run_id: Uuid) -> Result<(), ironflow_store::error::StoreError> {
309 /// let storage_keys = store.delete_run(run_id).await?;
310 /// // Caller deletes blobs from the blob store using these keys.
311 /// # Ok(())
312 /// # }
313 /// ```
314 fn delete_run(&self, id: Uuid) -> StoreFuture<'_, Vec<String>>;
315
316 /// Apply a partial update to a run and return the updated run.
317 ///
318 /// Combines [`update_run`](Self::update_run) and [`get_run`](Self::get_run) in
319 /// a single operation to avoid an extra round-trip. Store implementations
320 /// may override this for efficiency (e.g. reading within the same transaction).
321 ///
322 /// The default implementation calls `update_run` followed by `get_run`.
323 ///
324 /// # Errors
325 ///
326 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
327 /// Returns [`StoreError::InvalidTransition`] if the status transition is not allowed.
328 fn update_run_returning(&self, id: Uuid, update: RunUpdate) -> StoreFuture<'_, Run> {
329 Box::pin(async move {
330 self.update_run(id, update).await?;
331 self.get_run(id).await?.ok_or(StoreError::RunNotFound(id))
332 })
333 }
334}
335
336/// Unified storage abstraction combining all store capabilities.
337///
338/// Implementors provide runs, steps, users, API keys, and secrets
339/// through a single type. Pick one backend (in-memory or PostgreSQL)
340/// and it handles everything.
341///
342/// Both [`InMemoryStore`](crate::memory::InMemoryStore) and
343/// [`PostgresStore`](crate::postgres::PostgresStore) implement this trait.
344///
345/// # Examples
346///
347/// ```no_run
348/// use std::collections::HashMap;
349/// use std::sync::Arc;
350/// use ironflow_store::prelude::*;
351///
352/// # async fn example() -> Result<(), ironflow_store::error::StoreError> {
353/// let store: Arc<dyn Store> = Arc::new(InMemoryStore::new());
354///
355/// // All capabilities through one reference
356/// let _run = store.create_run(NewRun {
357/// workflow_name: "deploy".to_string(),
358/// trigger: TriggerKind::Manual,
359/// payload: serde_json::json!({}),
360/// max_retries: 3,
361/// handler_version: None,
362/// labels: HashMap::new(),
363/// scheduled_at: None,
364/// created_by: None,
365/// idempotency_key: None,
366/// max_cost_usd: None,
367/// }).await?.into_run();
368/// let _users = store.count_users().await?;
369/// # Ok(())
370/// # }
371/// ```
372pub trait Store:
373 RunStore
374 + UserStore
375 + ApiKeyStore
376 + SecretStore
377 + AuditLogStore
378 + ArtifactStore
379 + LogStore
380 + ScheduleStore
381 + ApprovalDelegationStore
382{
383}
384
385impl<
386 T: RunStore
387 + UserStore
388 + ApiKeyStore
389 + SecretStore
390 + AuditLogStore
391 + ArtifactStore
392 + LogStore
393 + ScheduleStore
394 + ApprovalDelegationStore,
395> Store for T
396{
397}