eventfold-es 0.2.0

Embedded event-sourcing framework built on eventfold
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Aggregate trait and ReduceFn adapter.

use crate::command::CommandContext;
use serde::{Serialize, de::DeserializeOwned};
use uuid::Uuid;

/// A domain aggregate whose state is derived from its event history.
///
/// The implementing type itself serves as the aggregate's state.
/// State is built by folding domain events through the [`apply`](Aggregate::apply) method.
///
/// # Associated Types
///
/// - `Command`: the set of commands this aggregate can handle.
/// - `DomainEvent`: the set of events this aggregate can produce and apply.
/// - `Error`: command rejection / validation error.
///
/// # Contract
///
/// - [`handle`](Aggregate::handle) must be a pure decision function: no I/O, no side effects.
///   It validates a command against the current state and returns zero or more events.
/// - [`apply`](Aggregate::apply) must be a pure, total function. It takes ownership of
///   the current state and a reference to a domain event, returning the next state.
///   Unknown event variants should be ignored for forward compatibility.
pub trait Aggregate:
    Default + Clone + Serialize + DeserializeOwned + Send + Sync + 'static
{
    /// Identifies this aggregate type (e.g. "order"). Used as a directory name.
    const AGGREGATE_TYPE: &'static str;

    /// The set of commands this aggregate can handle.
    type Command: Send + 'static;

    /// The set of events this aggregate can produce and apply.
    type DomainEvent: Serialize + DeserializeOwned + Send + Sync + Clone + 'static;

    /// Command rejection / validation error type.
    type Error: std::error::Error + Send + Sync + 'static;

    /// Validate a command against the current state and produce events.
    ///
    /// Returns `Ok(vec![])` if the command is a no-op.
    /// Returns `Err` to reject the command.
    fn handle(&self, cmd: Self::Command) -> Result<Vec<Self::DomainEvent>, Self::Error>;

    /// Apply a single event to produce the next state.
    ///
    /// Unknown event variants should be ignored (return `self` unchanged)
    /// to maintain forward compatibility.
    fn apply(self, event: &Self::DomainEvent) -> Self;
}

/// Inner reduce function used as a function pointer for `eventfold::ReduceFn<A>`.
///
/// Attempts to deserialize the event data into `A::DomainEvent`. On success,
/// delegates to `A::apply`. On failure (unknown or malformed event), returns
/// the state unchanged for forward compatibility.
fn reduce<A: Aggregate>(state: A, event: &eventfold::Event) -> A {
    // Attempt to interpret the raw eventfold event as a domain event.
    // The domain event uses adjacently tagged serde (`"type"` + `"data"`),
    // so we reconstruct the tagged JSON object from the eventfold fields.
    let tagged = if event.data.is_null() {
        // Fieldless variant: just `{"type": "VariantName"}`
        serde_json::json!({ "type": event.event_type })
    } else {
        // Variant with data: `{"type": "VariantName", "data": ...}`
        serde_json::json!({
            "type": event.event_type,
            "data": event.data,
        })
    };

    match serde_json::from_value::<A::DomainEvent>(tagged) {
        Ok(domain_event) => state.apply(&domain_event),
        // Unknown or malformed event type -- skip for forward compatibility.
        Err(_) => state,
    }
}

/// Build an `eventfold::ReduceFn<A>` that deserializes each `eventfold::Event`
/// into `A::DomainEvent` and delegates to `A::apply`.
///
/// Unknown or malformed events are silently skipped (state returned unchanged),
/// providing forward compatibility with new event types.
///
/// # Returns
///
/// A function pointer `fn(A, &eventfold::Event) -> A` suitable for use with
/// `eventfold::View::new` or `EventLog::builder().view()`.
///
/// # Examples
///
/// ```
/// use eventfold_es::{Aggregate, CommandContext};
/// ```
pub fn reducer<A: Aggregate>() -> eventfold::ReduceFn<A> {
    reduce::<A>
}

/// Convert a domain event and command context into an `eventfold::Event`.
///
/// The `DomainEvent` must use `#[serde(tag = "type", content = "data")]` adjacently
/// tagged serialization. The `"type"` field becomes `eventfold::Event::event_type`
/// and the remaining payload becomes `eventfold::Event::data`.
///
/// # Arguments
///
/// * `domain_event` - Reference to the domain event to convert.
/// * `ctx` - Command context carrying actor, correlation ID, and metadata.
///
/// # Returns
///
/// An `eventfold::Event` populated with the event type, data, and any
/// context-derived metadata (actor, correlation ID, extra metadata).
///
/// # Errors
///
/// Returns `serde_json::Error` if the domain event cannot be serialized.
pub fn to_eventfold_event<A: Aggregate>(
    domain_event: &A::DomainEvent,
    ctx: &CommandContext,
) -> serde_json::Result<eventfold::Event> {
    // Serialize the domain event. Because of adjacently tagged serde, this
    // produces an object like `{"type": "Incremented"}` or
    // `{"type": "Added", "data": {"amount": 5}}`.
    let value = serde_json::to_value(domain_event)?;
    let obj = value
        .as_object()
        .expect("adjacently tagged enum must serialize to a JSON object");

    let event_type = obj["type"]
        .as_str()
        .expect("adjacently tagged enum must have a string 'type' field");

    // Data may be absent for fieldless variants.
    let data = obj.get("data").cloned().unwrap_or(serde_json::Value::Null);

    let mut event = eventfold::Event::new(event_type, data).with_id(Uuid::new_v4().to_string());

    // Propagate actor from the command context.
    if let Some(ref actor) = ctx.actor {
        event = event.with_actor(actor);
    }

    // Build metadata: start from ctx.metadata (if an Object), then merge
    // correlation_id. Only attach if non-empty.
    let mut meta_map = match ctx.metadata {
        Some(serde_json::Value::Object(ref map)) => map.clone(),
        _ => serde_json::Map::new(),
    };

    if let Some(ref cid) = ctx.correlation_id {
        meta_map.insert(
            "correlation_id".to_string(),
            serde_json::Value::String(cid.clone()),
        );
    }

    if let Some(ref device_id) = ctx.source_device {
        meta_map.insert(
            "source_device".to_string(),
            serde_json::Value::String(device_id.clone()),
        );
    }

    if !meta_map.is_empty() {
        event = event.with_meta(serde_json::Value::Object(meta_map));
    }

    Ok(event)
}

#[cfg(test)]
pub(crate) mod test_fixtures {
    use super::Aggregate;
    use serde::{Deserialize, Serialize};

    /// A simple counter aggregate used as a test fixture.
    #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
    pub(crate) struct Counter {
        pub value: u64,
    }

    /// Commands that can be issued to the `Counter` aggregate.
    pub(crate) enum CounterCommand {
        Increment,
        Decrement,
        Add(u64),
    }

    /// Domain events produced by the `Counter` aggregate.
    ///
    /// Uses adjacently tagged serialization (`"type"` + `"data"`) which is the
    /// convention for all `DomainEvent` types in this crate.
    #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
    #[serde(tag = "type", content = "data")]
    pub(crate) enum CounterEvent {
        Incremented,
        Decremented,
        Added { amount: u64 },
    }

    /// Errors that can occur when handling a `CounterCommand`.
    #[derive(Debug, thiserror::Error)]
    pub(crate) enum CounterError {
        #[error("cannot decrement: counter is already zero")]
        AlreadyZero,
    }

    impl Aggregate for Counter {
        const AGGREGATE_TYPE: &'static str = "counter";

        type Command = CounterCommand;
        type DomainEvent = CounterEvent;
        type Error = CounterError;

        fn handle(&self, cmd: Self::Command) -> Result<Vec<Self::DomainEvent>, Self::Error> {
            match cmd {
                CounterCommand::Increment => Ok(vec![CounterEvent::Incremented]),
                CounterCommand::Decrement => {
                    if self.value == 0 {
                        return Err(CounterError::AlreadyZero);
                    }
                    Ok(vec![CounterEvent::Decremented])
                }
                CounterCommand::Add(n) => Ok(vec![CounterEvent::Added { amount: n }]),
            }
        }

        fn apply(mut self, event: &Self::DomainEvent) -> Self {
            match event {
                CounterEvent::Incremented => self.value += 1,
                CounterEvent::Decremented => self.value -= 1,
                CounterEvent::Added { amount } => self.value += amount,
            }
            self
        }
    }
}

#[cfg(test)]
mod tests {
    use super::Aggregate;
    use super::test_fixtures::{Counter, CounterCommand, CounterError, CounterEvent};

    #[test]
    fn handle_increment() {
        let counter = Counter::default();
        let events = counter.handle(CounterCommand::Increment).unwrap();
        assert_eq!(events, vec![CounterEvent::Incremented]);
    }

    #[test]
    fn handle_decrement_nonzero() {
        let counter = Counter { value: 5 };
        let events = counter.handle(CounterCommand::Decrement).unwrap();
        assert_eq!(events, vec![CounterEvent::Decremented]);
    }

    #[test]
    fn handle_decrement_at_zero() {
        let counter = Counter::default();
        let result = counter.handle(CounterCommand::Decrement);
        assert!(result.is_err());
        // Verify the specific error variant via its message.
        let err = result.unwrap_err();
        assert!(
            matches!(err, CounterError::AlreadyZero),
            "expected AlreadyZero, got: {err}"
        );
    }

    #[test]
    fn handle_add() {
        let counter = Counter::default();
        let events = counter.handle(CounterCommand::Add(5)).unwrap();
        assert_eq!(events, vec![CounterEvent::Added { amount: 5 }]);
    }

    #[test]
    fn apply_incremented() {
        let counter = Counter::default().apply(&CounterEvent::Incremented);
        assert_eq!(counter.value, 1);
    }

    #[test]
    fn apply_decremented() {
        let counter = Counter { value: 3 }.apply(&CounterEvent::Decremented);
        assert_eq!(counter.value, 2);
    }

    #[test]
    fn apply_added() {
        let counter = Counter::default().apply(&CounterEvent::Added { amount: 5 });
        assert_eq!(counter.value, 5);
    }

    #[test]
    fn handle_then_apply_roundtrip() {
        let counter = Counter::default();
        let events = counter.handle(CounterCommand::Increment).unwrap();
        // Fold all produced events through `apply` to derive the final state.
        let final_state = events
            .iter()
            .fold(Counter::default(), |state, event| state.apply(event));
        assert_eq!(final_state.value, 1);
    }

    // --- reducer / to_eventfold_event bridge tests ---

    use super::{reducer, to_eventfold_event};
    use crate::command::CommandContext;

    #[test]
    fn reducer_roundtrip_increment() {
        let event =
            to_eventfold_event::<Counter>(&CounterEvent::Incremented, &CommandContext::default())
                .unwrap();

        let state = reducer::<Counter>()(Counter::default(), &event);
        assert_eq!(state.value, 1);
    }

    #[test]
    fn reducer_roundtrip_added() {
        let event = to_eventfold_event::<Counter>(
            &CounterEvent::Added { amount: 5 },
            &CommandContext::default(),
        )
        .unwrap();

        let state = reducer::<Counter>()(Counter::default(), &event);
        assert_eq!(state.value, 5);
    }

    #[test]
    fn reducer_unknown_event_skipped() {
        // An event type that Counter does not recognize should leave state
        // unchanged, providing forward compatibility.
        let event = eventfold::Event::new("UnknownType", serde_json::json!({}));
        let state = reducer::<Counter>()(Counter::default(), &event);
        assert_eq!(state.value, 0);
    }

    #[test]
    fn context_propagates_actor() {
        let ctx = CommandContext::default().with_actor("user-1");
        let event = to_eventfold_event::<Counter>(&CounterEvent::Incremented, &ctx).unwrap();

        assert_eq!(event.actor, Some("user-1".into()));
    }

    #[test]
    fn context_propagates_correlation_id() {
        let ctx = CommandContext::default().with_correlation_id("req-abc");
        let event = to_eventfold_event::<Counter>(&CounterEvent::Incremented, &ctx).unwrap();

        // The correlation_id should appear inside the event's meta object.
        let meta = event.meta.expect("meta should be present");
        assert_eq!(meta["correlation_id"], "req-abc");
    }

    #[test]
    fn fieldless_variant_roundtrip() {
        // Incremented has no fields. Verify to_eventfold_event produces a
        // valid event that the reducer can fold back into state.
        let event =
            to_eventfold_event::<Counter>(&CounterEvent::Incremented, &CommandContext::default())
                .unwrap();

        // Verify the event_type is correct and data is null (no payload).
        assert_eq!(event.event_type, "Incremented");
        assert!(event.data.is_null());

        // Round-trip through the reducer.
        let state = reducer::<Counter>()(Counter::default(), &event);
        assert_eq!(state.value, 1);
    }

    // --- UUID v4 event ID tests ---

    #[test]
    fn to_eventfold_event_assigns_uuid_v4_id() {
        let event =
            to_eventfold_event::<Counter>(&CounterEvent::Incremented, &CommandContext::default())
                .unwrap();

        // The event must carry a Some(id) that is a valid UUID v4 string.
        let id = event.id.expect("event.id should be Some");

        // Parse with the uuid crate to validate format and version.
        let parsed = uuid::Uuid::parse_str(&id)
            .unwrap_or_else(|e| panic!("event id '{id}' is not a valid UUID: {e}"));
        assert_eq!(
            parsed.get_version(),
            Some(uuid::Version::Random),
            "event id '{id}' is not UUID v4 (version = {:?})",
            parsed.get_version()
        );

        // Also verify the lowercase hyphenated format matches the canonical
        // UUID v4 regex from the acceptance criteria.
        assert_eq!(id, parsed.as_hyphenated().to_string());
    }

    #[test]
    fn to_eventfold_event_produces_distinct_ids() {
        let ctx = CommandContext::default();
        let event_a = to_eventfold_event::<Counter>(&CounterEvent::Incremented, &ctx).unwrap();
        let event_b = to_eventfold_event::<Counter>(&CounterEvent::Incremented, &ctx).unwrap();

        // Two successive calls must produce different IDs.
        assert_ne!(
            event_a.id, event_b.id,
            "successive events must have distinct ids"
        );
    }

    #[test]
    fn context_propagates_source_device() {
        let ctx = CommandContext::default().with_source_device("device-xyz");
        let event = to_eventfold_event::<Counter>(&CounterEvent::Incremented, &ctx).unwrap();

        let meta = event.meta.expect("meta should be present");
        assert_eq!(meta["source_device"], "device-xyz");
    }

    #[test]
    fn context_propagates_source_device_and_correlation_id() {
        let ctx = CommandContext::default()
            .with_correlation_id("req-abc")
            .with_source_device("device-xyz");
        let event = to_eventfold_event::<Counter>(&CounterEvent::Incremented, &ctx).unwrap();

        let meta = event.meta.expect("meta should be present");
        assert_eq!(meta["correlation_id"], "req-abc");
        assert_eq!(meta["source_device"], "device-xyz");
    }

    #[test]
    fn context_merges_source_device_with_existing_metadata() {
        let ctx = CommandContext::default()
            .with_metadata(serde_json::json!({"foo": "bar", "level": 3}))
            .with_source_device("device-xyz");
        let event = to_eventfold_event::<Counter>(&CounterEvent::Incremented, &ctx).unwrap();

        let meta = event.meta.expect("meta should be present");
        assert_eq!(meta["foo"], "bar");
        assert_eq!(meta["level"], 3);
        assert_eq!(meta["source_device"], "device-xyz");
    }

    #[test]
    fn all_none_context_produces_no_meta() {
        // When source_device, correlation_id, and metadata are all None,
        // the resulting event should have meta == None (no empty object).
        let ctx = CommandContext::default();
        assert!(ctx.source_device.is_none());
        assert!(ctx.correlation_id.is_none());
        assert!(ctx.metadata.is_none());

        let event = to_eventfold_event::<Counter>(&CounterEvent::Incremented, &ctx).unwrap();
        assert!(
            event.meta.is_none(),
            "meta should be None when all context fields are None, got: {:?}",
            event.meta
        );
    }

    #[test]
    fn reducer_applies_event_with_no_id() {
        // Simulate a pre-existing log entry that has no id field (id: None).
        // The reducer must still apply it correctly.
        let event_with_id_none = eventfold::Event::new("Incremented", serde_json::Value::Null);
        assert!(event_with_id_none.id.is_none(), "precondition: id is None");

        // Known event type advances state.
        let state = reducer::<Counter>()(Counter::default(), &event_with_id_none);
        assert_eq!(state.value, 1);

        // Unknown event type leaves state unchanged.
        let unknown_event = eventfold::Event::new("SomeFutureEvent", serde_json::json!({}));
        assert!(unknown_event.id.is_none(), "precondition: id is None");
        let state = reducer::<Counter>()(Counter::default(), &unknown_event);
        assert_eq!(state.value, 0);
    }
}