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 uuid::Uuid;
12
13use crate::api_key_store::ApiKeyStore;
14use crate::entities::{
15 NewRun, NewStep, NewStepDependency, Page, Run, RunFilter, RunStats, RunStatus, RunUpdate, Step,
16 StepDependency, StepUpdate,
17};
18use crate::error::StoreError;
19use crate::secret_store::SecretStore;
20use crate::user_store::UserStore;
21
22/// Boxed future for [`RunStore`] methods — ensures object safety for `dyn RunStore`.
23pub type StoreFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, StoreError>> + Send + 'a>>;
24
25/// Async storage abstraction for workflow runs and steps.
26///
27/// All methods return a [`StoreFuture`] (boxed future) to maintain object safety,
28/// allowing the store to be used as `Arc<dyn RunStore>`.
29///
30/// # Examples
31///
32/// ```no_run
33/// use ironflow_store::prelude::*;
34/// use serde_json::json;
35/// use uuid::Uuid;
36///
37/// # async fn example() -> Result<(), ironflow_store::error::StoreError> {
38/// let store = InMemoryStore::new();
39///
40/// let run = store.create_run(NewRun {
41/// workflow_name: "deploy".to_string(),
42/// trigger: TriggerKind::Manual,
43/// payload: json!({}),
44/// max_retries: 3,
45/// }).await?;
46///
47/// let fetched = store.get_run(run.id).await?;
48/// assert!(fetched.is_some());
49/// # Ok(())
50/// # }
51/// ```
52pub trait RunStore: Send + Sync {
53 /// Create a new run in `Pending` status.
54 fn create_run(&self, req: NewRun) -> StoreFuture<'_, Run>;
55
56 /// Get a run by ID. Returns `None` if not found.
57 fn get_run(&self, id: Uuid) -> StoreFuture<'_, Option<Run>>;
58
59 /// List runs matching the given filter, with pagination.
60 ///
61 /// Results are ordered by `created_at` descending (newest first).
62 fn list_runs(&self, filter: RunFilter, page: u32, per_page: u32) -> StoreFuture<'_, Page<Run>>;
63
64 /// Update a run's status with FSM validation.
65 ///
66 /// # Errors
67 ///
68 /// Returns [`StoreError::InvalidTransition`] if the transition is not allowed.
69 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
70 fn update_run_status(&self, id: Uuid, new_status: RunStatus) -> StoreFuture<'_, ()>;
71
72 /// Apply a partial update to a run.
73 ///
74 /// # Errors
75 ///
76 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
77 fn update_run(&self, id: Uuid, update: RunUpdate) -> StoreFuture<'_, ()>;
78
79 /// Atomically pick the oldest pending run and transition it to `Running`.
80 ///
81 /// In PostgreSQL, this uses `SELECT FOR UPDATE SKIP LOCKED` for safe
82 /// multi-worker concurrency. The in-memory implementation uses a write lock.
83 ///
84 /// Returns `None` if no pending runs are available.
85 fn pick_next_pending(&self) -> StoreFuture<'_, Option<Run>>;
86
87 /// Create a new step for a run.
88 ///
89 /// # Errors
90 ///
91 /// Returns [`StoreError::RunNotFound`] if the parent run does not exist.
92 fn create_step(&self, step: NewStep) -> StoreFuture<'_, Step>;
93
94 /// Apply a partial update to a step after execution.
95 ///
96 /// # Errors
97 ///
98 /// Returns [`StoreError::StepNotFound`] if the step does not exist.
99 fn update_step(&self, id: Uuid, update: StepUpdate) -> StoreFuture<'_, ()>;
100
101 /// Get a single step by ID. Returns `None` if not found.
102 fn get_step(&self, id: Uuid) -> StoreFuture<'_, Option<Step>>;
103
104 /// List all steps for a run, ordered by position ascending.
105 fn list_steps(&self, run_id: Uuid) -> StoreFuture<'_, Vec<Step>>;
106
107 /// Get aggregated statistics across runs matching the filter.
108 ///
109 /// Returns counts of runs by terminal state, counts of active runs,
110 /// and totals for cost and duration. Computed efficiently by the store
111 /// implementation (single SQL query in PostgreSQL).
112 ///
113 /// Pass [`RunFilter::default()`] to get stats across all runs.
114 fn get_stats(&self, filter: RunFilter) -> StoreFuture<'_, RunStats>;
115
116 /// Create step dependency edges in batch.
117 ///
118 /// Each entry records that `step_id` depends on `depends_on`.
119 /// Duplicate edges are silently ignored.
120 ///
121 /// # Errors
122 ///
123 /// Returns [`StoreError`] if a referenced step does not exist.
124 fn create_step_dependencies(&self, deps: Vec<NewStepDependency>) -> StoreFuture<'_, ()>;
125
126 /// List all step dependencies for a given run.
127 ///
128 /// Returns every edge where either `step_id` or `depends_on` belongs
129 /// to the run. Ordered by `created_at` ascending.
130 fn list_step_dependencies(&self, run_id: Uuid) -> StoreFuture<'_, Vec<StepDependency>>;
131
132 /// Apply a partial update to a run and return the updated run.
133 ///
134 /// Combines [`update_run`](Self::update_run) and [`get_run`](Self::get_run) in
135 /// a single operation to avoid an extra round-trip. Store implementations
136 /// may override this for efficiency (e.g. reading within the same transaction).
137 ///
138 /// The default implementation calls `update_run` followed by `get_run`.
139 ///
140 /// # Errors
141 ///
142 /// Returns [`StoreError::RunNotFound`] if the run does not exist.
143 /// Returns [`StoreError::InvalidTransition`] if the status transition is not allowed.
144 fn update_run_returning(&self, id: Uuid, update: RunUpdate) -> StoreFuture<'_, Run> {
145 Box::pin(async move {
146 self.update_run(id, update).await?;
147 self.get_run(id).await?.ok_or(StoreError::RunNotFound(id))
148 })
149 }
150}
151
152/// Unified storage abstraction combining all store capabilities.
153///
154/// Implementors provide runs, steps, users, API keys, and secrets
155/// through a single type. Pick one backend (in-memory or PostgreSQL)
156/// and it handles everything.
157///
158/// Both [`InMemoryStore`](crate::memory::InMemoryStore) and
159/// [`PostgresStore`](crate::postgres::PostgresStore) implement this trait.
160///
161/// # Examples
162///
163/// ```no_run
164/// use std::sync::Arc;
165/// use ironflow_store::prelude::*;
166///
167/// # async fn example() -> Result<(), ironflow_store::error::StoreError> {
168/// let store: Arc<dyn Store> = Arc::new(InMemoryStore::new());
169///
170/// // All capabilities through one reference
171/// let _run = store.create_run(NewRun {
172/// workflow_name: "deploy".to_string(),
173/// trigger: TriggerKind::Manual,
174/// payload: serde_json::json!({}),
175/// max_retries: 3,
176/// }).await?;
177/// let _users = store.count_users().await?;
178/// # Ok(())
179/// # }
180/// ```
181pub trait Store: RunStore + UserStore + ApiKeyStore + SecretStore {}
182
183impl<T: RunStore + UserStore + ApiKeyStore + SecretStore> Store for T {}