Skip to main content

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