arc-core 0.2.3

Event sourcing primitives for arc framework (headless, no web dependencies)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! # Event Store Module
//!
//! Defines the [`EventStore`] trait for persisting and retrieving events.
//!
//! ## Design Principles
//!
//! - **Append-only**: events can only be added, never modified or deleted
//! - **Optimistic concurrency**: version-based conflict detection
//! - **Stream-based**: events can be loaded by aggregate or streamed globally
//! - **Audited**: every event must carry valid [`AuditMetadata`](crate::audit::AuditMetadata)
//!   when appended (HIPAA §164.312(b))
//! - **Pluggable**: multiple implementations (SQLite, Postgres, in-memory)
//!
//! ## HIPAA defense-in-depth
//!
//! `EventStore::append` MUST call `event.audit.validate()?` for each event
//! before persisting. The `CommandBus` validates first, but the store is the
//! durable boundary — it must not trust upstream.

use crate::audit::AuditError;
use crate::event::Event;
use crate::integrity::IntegrityError;
use crate::snapshot::Snapshot;
use async_trait::async_trait;
use thiserror::Error;

/// Version check strategy for optimistic concurrency control.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VersionCheck {
    /// First event for this aggregate (expected version is 0)
    New,
    /// Require aggregate to be at this exact version
    Expected(i64),
    /// Automatically load and use current version (use sparingly)
    Auto,
}

impl VersionCheck {
    pub fn version(&self) -> Option<i64> {
        match self {
            VersionCheck::New => Some(0),
            VersionCheck::Expected(v) => Some(*v),
            VersionCheck::Auto => None,
        }
    }
}

/// Errors that can occur during event store operations.
#[derive(Debug, Error)]
pub enum EventStoreError {
    /// Optimistic concurrency conflict.
    #[error("Concurrency conflict: expected version {expected}, but aggregate is at version {actual} (aggregate_id: {aggregate_id})")]
    ConcurrencyConflict {
        aggregate_id: String,
        expected: i64,
        actual: i64,
    },

    #[error("Aggregate not found: {aggregate_id}")]
    AggregateNotFound { aggregate_id: String },

    #[error(
        "Invalid event sequence: expected {expected}, got {actual} (aggregate_id: {aggregate_id})"
    )]
    InvalidSequence {
        aggregate_id: String,
        expected: i64,
        actual: i64,
    },

    /// One or more events in an `append` batch had invalid audit metadata.
    /// Defense-in-depth: the bus should have caught this first.
    #[error(
        "Audit metadata validation failed for event {event_index} (aggregate_id: {aggregate_id}): {source}"
    )]
    InvalidAudit {
        aggregate_id: String,
        event_index: usize,
        #[source]
        source: AuditError,
    },

    /// Stored event signatures are missing or do not match the recomputed
    /// integrity chain.
    #[error("Integrity validation failed: {source}")]
    Integrity {
        #[from]
        source: IntegrityError,
    },

    #[error("Database error: {message}")]
    DatabaseError { message: String },

    #[error("Serialization error: {message}")]
    SerializationError { message: String },

    #[error("I/O error: {0}")]
    IoError(#[from] std::io::Error),

    /// The store does not implement snapshot persistence. Callers fall back to
    /// replaying the full event stream.
    #[error("snapshots not supported by this store")]
    Unsupported,

    #[error("Event store error: {message}")]
    Other { message: String },
}

impl EventStoreError {
    pub fn database(message: impl Into<String>) -> Self {
        EventStoreError::DatabaseError {
            message: message.into(),
        }
    }

    pub fn serialization(message: impl Into<String>) -> Self {
        EventStoreError::SerializationError {
            message: message.into(),
        }
    }

    pub fn other(message: impl Into<String>) -> Self {
        EventStoreError::Other {
            message: message.into(),
        }
    }

    pub fn invalid_audit(
        aggregate_id: impl Into<String>,
        event_index: usize,
        source: AuditError,
    ) -> Self {
        EventStoreError::InvalidAudit {
            aggregate_id: aggregate_id.into(),
            event_index,
            source,
        }
    }
}

/// Result type for event store operations.
pub type EventStoreResult<T> = Result<T, EventStoreError>;

/// Helper for store implementations: validate every event's audit before persisting.
/// Returns `Err(EventStoreError::InvalidAudit)` on the first failure.
pub fn validate_audit_batch(aggregate_id: &str, events: &[Event]) -> EventStoreResult<()> {
    for (idx, ev) in events.iter().enumerate() {
        ev.audit
            .validate()
            .map_err(|e| EventStoreError::invalid_audit(aggregate_id, idx, e))?;
    }
    Ok(())
}

/// Trait for event store implementations.
///
/// `append` MUST invoke `validate_audit_batch` before persisting (HIPAA defense
/// in depth). The `CommandBus` also validates upstream — both layers run.
#[async_trait]
pub trait EventStore: Send + Sync {
    /// Append events to the store for a specific aggregate.
    ///
    /// Implementations must call `validate_audit_batch(aggregate_id, &events)?`
    /// before any persistence work.
    async fn append(
        &self,
        aggregate_id: &str,
        version_check: VersionCheck,
        events: Vec<Event>,
    ) -> EventStoreResult<()>;

    async fn load(&self, aggregate_id: &str) -> EventStoreResult<Vec<Event>>;

    async fn load_from(
        &self,
        aggregate_id: &str,
        from_sequence: i64,
    ) -> EventStoreResult<Vec<Event>>;

    async fn stream_all(&self, from_position: i64) -> EventStoreResult<Vec<Event>>;

    async fn get_version(&self, aggregate_id: &str) -> EventStoreResult<i64>;

    /// Persist an aggregate snapshot (upsert by `aggregate_id`).
    ///
    /// Default returns `EventStoreError::Unsupported` so stores that have not
    /// implemented snapshotting compile unchanged and fail loudly if a caller
    /// tries to save one.
    async fn save_snapshot(&self, snapshot: &Snapshot) -> EventStoreResult<()> {
        let _ = snapshot;
        Err(EventStoreError::Unsupported)
    }

    /// Load the latest snapshot for an aggregate, if one exists.
    ///
    /// Default returns `Ok(None)` — safe because the caller then replays the
    /// stream from sequence 0, which is always correct, just slower.
    async fn load_snapshot(&self, aggregate_id: &str) -> EventStoreResult<Option<Snapshot>> {
        let _ = aggregate_id;
        Ok(None)
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// In-memory implementation, public for downstream test code.
// ─────────────────────────────────────────────────────────────────────────────

#[cfg(any(test, feature = "test-utils"))]
mod in_memory {
    use super::*;
    use std::collections::HashMap;
    use std::sync::Arc;
    use tokio::sync::Mutex as TokioMutex;

    /// In-memory event store. Available to downstream crates via the
    /// `test-utils` feature flag.
    ///
    /// Validates audit metadata on every append (same contract as production
    /// stores) so behavior matches what real implementations enforce.
    #[derive(Clone, Default)]
    pub struct InMemoryEventStore {
        events: Arc<TokioMutex<Vec<Event>>>,
        snapshots: Arc<TokioMutex<HashMap<String, Snapshot>>>,
    }

    impl InMemoryEventStore {
        pub fn new() -> Self {
            Self::default()
        }
    }

    #[async_trait]
    impl EventStore for InMemoryEventStore {
        async fn append(
            &self,
            aggregate_id: &str,
            version_check: VersionCheck,
            events: Vec<Event>,
        ) -> EventStoreResult<()> {
            validate_audit_batch(aggregate_id, &events)?;

            let mut store = self.events.lock().await;

            let current_version = store
                .iter()
                .filter(|e| e.aggregate_id == aggregate_id)
                .map(|e| e.sequence)
                .max()
                .unwrap_or(0);

            if let Some(expected) = version_check.version() {
                if current_version != expected {
                    return Err(EventStoreError::ConcurrencyConflict {
                        aggregate_id: aggregate_id.to_string(),
                        expected,
                        actual: current_version,
                    });
                }
            }

            store.extend(events);
            Ok(())
        }

        async fn load(&self, aggregate_id: &str) -> EventStoreResult<Vec<Event>> {
            let store = self.events.lock().await;
            Ok(store
                .iter()
                .filter(|e| e.aggregate_id == aggregate_id)
                .cloned()
                .collect())
        }

        async fn load_from(
            &self,
            aggregate_id: &str,
            from_sequence: i64,
        ) -> EventStoreResult<Vec<Event>> {
            let store = self.events.lock().await;
            Ok(store
                .iter()
                .filter(|e| e.aggregate_id == aggregate_id && e.sequence >= from_sequence)
                .cloned()
                .collect())
        }

        async fn stream_all(&self, from_position: i64) -> EventStoreResult<Vec<Event>> {
            let store = self.events.lock().await;
            Ok(store.iter().skip(from_position as usize).cloned().collect())
        }

        async fn get_version(&self, aggregate_id: &str) -> EventStoreResult<i64> {
            let store = self.events.lock().await;
            Ok(store
                .iter()
                .filter(|e| e.aggregate_id == aggregate_id)
                .map(|e| e.sequence)
                .max()
                .unwrap_or(0))
        }

        async fn save_snapshot(&self, snapshot: &Snapshot) -> EventStoreResult<()> {
            let mut snapshots = self.snapshots.lock().await;
            snapshots.insert(snapshot.aggregate_id.clone(), snapshot.clone());
            Ok(())
        }

        async fn load_snapshot(&self, aggregate_id: &str) -> EventStoreResult<Option<Snapshot>> {
            let snapshots = self.snapshots.lock().await;
            Ok(snapshots.get(aggregate_id).cloned())
        }
    }
}

#[cfg(any(test, feature = "test-utils"))]
pub use in_memory::InMemoryEventStore;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::audit::AuditMetadata;
    use crate::event::Event;
    use serde_json::json;

    #[test]
    fn test_version_check_new() {
        assert_eq!(VersionCheck::New.version(), Some(0));
    }

    #[test]
    fn test_version_check_expected() {
        assert_eq!(VersionCheck::Expected(5).version(), Some(5));
    }

    #[test]
    fn test_version_check_auto() {
        assert_eq!(VersionCheck::Auto.version(), None);
    }

    #[test]
    fn test_error_messages() {
        let error = EventStoreError::ConcurrencyConflict {
            aggregate_id: "user-123".to_string(),
            expected: 5,
            actual: 6,
        };
        let msg = error.to_string();
        assert!(msg.contains("expected version 5"));
        assert!(msg.contains("aggregate is at version 6"));
        assert!(msg.contains("user-123"));

        assert!(EventStoreError::database("X").to_string().contains("X"));
        assert!(EventStoreError::serialization("Y")
            .to_string()
            .contains("Y"));
    }

    #[test]
    fn test_validate_audit_batch_rejects_pending() {
        let mut e = Event::new("User", "u1", 1, "X", json!({}));
        e.audit = AuditMetadata::pending();
        let err = validate_audit_batch("u1", &[e]).unwrap_err();
        assert!(matches!(
            err,
            EventStoreError::InvalidAudit { event_index: 0, .. }
        ));
    }

    #[test]
    fn test_validate_audit_batch_passes_stamped() {
        let e =
            Event::new("User", "u1", 1, "X", json!({})).with_audit(AuditMetadata::test_default());
        validate_audit_batch("u1", &[e]).expect("stamped audit must pass");
    }

    #[tokio::test]
    async fn test_in_memory_store_rejects_pending_audit() {
        let store = InMemoryEventStore::new();
        let e = Event::new("User", "u1", 1, "X", json!({})); // pending
        let err = store
            .append("u1", VersionCheck::New, vec![e])
            .await
            .unwrap_err();
        assert!(matches!(err, EventStoreError::InvalidAudit { .. }));
    }

    #[tokio::test]
    async fn test_in_memory_store_persists_stamped_event() {
        let store = InMemoryEventStore::new();
        let e =
            Event::new("User", "u1", 1, "X", json!({})).with_audit(AuditMetadata::test_default());
        store
            .append("u1", VersionCheck::New, vec![e])
            .await
            .unwrap();
        let loaded = store.load("u1").await.unwrap();
        assert_eq!(loaded.len(), 1);
    }

    #[tokio::test]
    async fn test_in_memory_snapshot_save_then_load() {
        let store = InMemoryEventStore::new();
        let snap = Snapshot::new("u1", "User", 3, json!({ "name": "Alice" }));
        store.save_snapshot(&snap).await.unwrap();
        let loaded = store.load_snapshot("u1").await.unwrap();
        assert_eq!(loaded, Some(snap));
    }

    #[tokio::test]
    async fn test_in_memory_load_snapshot_unknown_returns_none() {
        let store = InMemoryEventStore::new();
        assert_eq!(store.load_snapshot("missing").await.unwrap(), None);
    }

    #[tokio::test]
    async fn test_in_memory_snapshot_overwrites_on_resave() {
        let store = InMemoryEventStore::new();
        store
            .save_snapshot(&Snapshot::new("u1", "User", 3, json!({ "v": 3 })))
            .await
            .unwrap();
        let newer = Snapshot::new("u1", "User", 9, json!({ "v": 9 }));
        store.save_snapshot(&newer).await.unwrap();
        let loaded = store.load_snapshot("u1").await.unwrap().unwrap();
        assert_eq!(loaded.version, 9);
        assert_eq!(loaded.state["v"], 9);
    }
}