ironflow_store/memory/mod.rs
1//! In-memory [`Store`](crate::store::Store) implementation for development and testing.
2//!
3//! [`InMemoryStore`] uses `Arc<RwLock<..>>` internally, making it safe to share
4//! across tasks. Data is lost when the process exits.
5//!
6//! # Examples
7//!
8//! ```no_run
9//! use std::collections::HashMap;
10//! use ironflow_store::prelude::*;
11//! use serde_json::json;
12//!
13//! # async fn example() -> Result<(), ironflow_store::error::StoreError> {
14//! let store = InMemoryStore::new();
15//!
16//! let run = store.create_run(NewRun {
17//! workflow_name: "test".to_string(),
18//! trigger: TriggerKind::Manual,
19//! payload: json!({}),
20//! max_retries: 3,
21//! handler_version: None,
22//! labels: HashMap::new(),
23//! scheduled_at: None,
24//! created_by: None,
25//! idempotency_key: None,
26//! max_cost_usd: None,
27//! }).await?.into_run();
28//!
29//! assert_eq!(run.status.state, RunStatus::Pending);
30//! # Ok(())
31//! # }
32//! ```
33
34use std::collections::HashMap;
35use std::sync::Arc;
36
37use tokio::sync::RwLock;
38use uuid::Uuid;
39
40use crate::entities::User;
41
42mod api_key_store;
43mod approval_delegation_store;
44mod artifact_store;
45mod audit_log_store;
46mod log_store;
47mod run_store;
48mod schedule_store;
49mod secret_store;
50mod stats_history;
51mod user_store;
52
53#[derive(Debug, Default)]
54pub(super) struct State {
55 pub(super) runs: HashMap<Uuid, crate::entities::Run>,
56 /// Idempotency key -> run holding it. Guarded by the same lock as `runs`,
57 /// so check-then-insert is atomic.
58 pub(super) idempotency_keys: HashMap<String, Uuid>,
59 pub(super) steps: HashMap<Uuid, crate::entities::Step>,
60 pub(super) step_dependencies: Vec<crate::entities::StepDependency>,
61 pub(super) artifacts: HashMap<Uuid, crate::entities::Artifact>,
62 pub(super) users: HashMap<Uuid, User>,
63 pub(super) api_keys: HashMap<Uuid, crate::entities::ApiKey>,
64 pub(super) secrets: HashMap<String, EncryptedSecret>,
65 pub(super) schedules: HashMap<Uuid, crate::entities::Schedule>,
66 pub(super) approval_delegations: HashMap<Uuid, crate::entities::ApprovalDelegation>,
67 pub(super) audit_logs: Vec<crate::entities::AuditLogEntry>,
68 pub(super) log_entries: Vec<crate::entities::LogEntry>,
69}
70
71#[derive(Debug, Clone)]
72pub(super) struct EncryptedSecret {
73 pub(super) id: Uuid,
74 pub(super) key: String,
75 #[cfg(feature = "secret-store")]
76 pub(super) encrypted_value: Vec<u8>,
77 #[cfg(feature = "secret-store")]
78 pub(super) nonce: Vec<u8>,
79 #[cfg(feature = "secret-store")]
80 pub(super) key_version: i32,
81 pub(super) created_at: chrono::DateTime<chrono::Utc>,
82 pub(super) updated_at: chrono::DateTime<chrono::Utc>,
83}
84
85/// In-memory store backed by `Arc<RwLock<..>>`.
86///
87/// Thread-safe and cheap to clone. All data is held in memory and lost on drop.
88/// Implements [`Store`](crate::store::Store) so a single `Arc<InMemoryStore>`
89/// covers runs, users, API keys, and secrets.
90///
91/// # Examples
92///
93/// ```
94/// use ironflow_store::memory::InMemoryStore;
95///
96/// let store = InMemoryStore::new();
97/// let store2 = store.clone(); // cheap Arc clone
98/// ```
99#[derive(Debug, Clone)]
100pub struct InMemoryStore {
101 pub(super) state: Arc<RwLock<State>>,
102 #[cfg(feature = "secret-store")]
103 pub(super) key_ring: Option<Arc<crate::crypto::KeyRing>>,
104}
105
106impl InMemoryStore {
107 /// Create a new empty in-memory store.
108 ///
109 /// # Examples
110 ///
111 /// ```
112 /// use ironflow_store::memory::InMemoryStore;
113 ///
114 /// let store = InMemoryStore::new();
115 /// ```
116 pub fn new() -> Self {
117 Self {
118 state: Arc::new(RwLock::new(State::default())),
119 #[cfg(feature = "secret-store")]
120 key_ring: None,
121 }
122 }
123
124 /// Set a single, unversioned master key for secret encryption.
125 ///
126 /// Shorthand for a key ring holding this key alone at
127 /// [`LEGACY_KEY_VERSION`](crate::crypto::LEGACY_KEY_VERSION).
128 ///
129 /// Required before using [`SecretStore`](crate::secret_store::SecretStore)
130 /// methods that read/write secret values. Without a key, those methods
131 /// return [`StoreError::Crypto`](crate::error::StoreError::Crypto).
132 ///
133 /// Listing and deleting secrets works without a key.
134 ///
135 /// # Examples
136 ///
137 /// ```
138 /// use ironflow_store::memory::InMemoryStore;
139 /// use ironflow_store::crypto::MasterKey;
140 ///
141 /// # fn example() -> Result<(), ironflow_store::crypto::CryptoError> {
142 /// let mut store = InMemoryStore::new();
143 /// let key = MasterKey::from_hex(
144 /// "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
145 /// )?;
146 /// store.set_master_key(key);
147 /// # Ok(())
148 /// # }
149 /// ```
150 #[cfg(feature = "secret-store")]
151 pub fn set_master_key(&mut self, key: crate::crypto::MasterKey) {
152 self.set_key_ring(crate::crypto::KeyRing::single(key));
153 }
154
155 /// Set the versioned key ring for secret encryption.
156 ///
157 /// New secrets are encrypted with the ring's active version; existing ones
158 /// are decrypted with whichever version they were written with.
159 ///
160 /// # Examples
161 ///
162 /// ```
163 /// use ironflow_store::memory::InMemoryStore;
164 /// use ironflow_store::crypto::KeyRing;
165 ///
166 /// # fn example() -> Result<(), ironflow_store::crypto::CryptoError> {
167 /// let mut store = InMemoryStore::new();
168 /// let spec = format!("1:{},2:{}", "aa".repeat(32), "bb".repeat(32));
169 /// store.set_key_ring(KeyRing::from_spec(&spec, Some(2))?);
170 /// # Ok(())
171 /// # }
172 /// ```
173 #[cfg(feature = "secret-store")]
174 pub fn set_key_ring(&mut self, ring: crate::crypto::KeyRing) {
175 self.key_ring = Some(Arc::new(ring));
176 }
177
178 /// Override a run's `created_at` timestamp for testing retention policies.
179 ///
180 /// # Examples
181 ///
182 /// ```no_run
183 /// use chrono::{Utc, TimeDelta};
184 /// use ironflow_store::memory::InMemoryStore;
185 /// use uuid::Uuid;
186 ///
187 /// # async fn example(store: &InMemoryStore, run_id: Uuid) {
188 /// let old = Utc::now() - TimeDelta::days(100);
189 /// store.set_run_created_at(run_id, old).await;
190 /// # }
191 /// ```
192 pub async fn set_run_created_at(
193 &self,
194 run_id: Uuid,
195 created_at: chrono::DateTime<chrono::Utc>,
196 ) {
197 let mut state = self.state.write().await;
198 if let Some(run) = state.runs.get_mut(&run_id) {
199 run.created_at = created_at;
200 }
201 }
202}
203
204impl Default for InMemoryStore {
205 fn default() -> Self {
206 Self::new()
207 }
208}
209
210#[cfg(test)]
211mod tests {
212 use std::collections::HashMap;
213
214 use serde_json::json;
215
216 use crate::entities::{NewRun, TriggerKind};
217
218 use super::InMemoryStore;
219
220 pub(crate) fn new_run_req(name: &str) -> NewRun {
221 NewRun {
222 created_by: None,
223 workflow_name: name.to_string(),
224 trigger: TriggerKind::Manual,
225 payload: json!({}),
226 max_retries: 3,
227 handler_version: None,
228 labels: HashMap::new(),
229 scheduled_at: None,
230 idempotency_key: None,
231 max_cost_usd: None,
232 }
233 }
234
235 pub(crate) async fn create_terminal_run(
236 store: &InMemoryStore,
237 name: &str,
238 status: crate::entities::RunStatus,
239 ) -> crate::entities::Run {
240 use crate::store::RunStore;
241
242 let run = store
243 .create_run(new_run_req(name))
244 .await
245 .unwrap()
246 .into_run();
247 store
248 .update_run_status(run.id, crate::entities::RunStatus::Running)
249 .await
250 .unwrap();
251 store.update_run_status(run.id, status).await.unwrap();
252 store.get_run(run.id).await.unwrap().unwrap()
253 }
254}