architecturekit 0.11.0

Building blocks for DDD-based applications with CQRS and event sourcing, on top of the EventSourcingDB by the native web.
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
// These tests mirror the tests of catching up of TestProjection,
// TestCheckpointFailure, TestBatching, TestPanickingProjection and
// TestTypedProjection of ArchitectureKit for Go, against a database. Running
// a projection that follows the events comes with the next slice.
//
// A projection is of one kind by its trait, so a projection that is
// transactional as well can not be handed to the wrong function, nor can a nil
// projection be handed over at all. The projections of the tests yield before
// they do anything, as a real one waits for its target.

use std::{
    fmt,
    sync::{Arc, Mutex},
};

use super::{
    CounterEvent, Incremented, Reset, Unrelated,
    database::{Database, subject_for},
};
use crate::{
    Categorized, Category, Envelope, EventOn, Precondition, Projection, ProjectionError,
    ResumableProjection, Store, Subjects, Transaction, TransactionalProjection,
};

/// The failure of a projection of a test, of the given category.
#[derive(Debug)]
struct Refused(Category);

impl fmt::Display for Refused {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "refused ({})", self.0)
    }
}

impl std::error::Error for Refused {}

impl Categorized for Refused {
    fn category(&self) -> Option<Category> {
        Some(self.0)
    }
}

/// Where a projection of a test panics or fails.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum Trouble {
    #[default]
    None,
    RefusesToApply,
    RefusesToReadTheCheckpoint,
    PanicsIn(&'static str),
}

impl Trouble {
    fn panics_in(self, function: &'static str) {
        assert!(
            self != Trouble::PanicsIn(function),
            "the projection panics in {function}"
        );
    }
}

/// Adds up the increments it applies, and remembers what it applied and saved.
#[derive(Default)]
struct Totals {
    applied: Mutex<Vec<String>>,
    saved: Mutex<Vec<String>>,
    checkpoint: Mutex<Option<String>>,
    total: Mutex<i64>,
    trouble: Trouble,
    batch_size: usize,
}

impl Totals {
    fn applied(&self) -> Vec<String> {
        self.applied.lock().expect("not poisoned").clone()
    }

    fn saved(&self) -> Vec<String> {
        self.saved.lock().expect("not poisoned").clone()
    }

    fn total(&self) -> i64 {
        *self.total.lock().expect("not poisoned")
    }
}

impl Projection for Totals {
    type Event = CounterEvent;
    type Error = Refused;

    async fn apply(&self, event: Envelope<CounterEvent>) -> Result<(), Refused> {
        tokio::task::yield_now().await;
        self.trouble.panics_in("apply");
        if self.trouble == Trouble::RefusesToApply {
            return Err(Refused(Category::Transient));
        }

        self.applied.lock().expect("not poisoned").push(event.id);
        if let CounterEvent::Incremented(incremented) = event.data {
            *self.total.lock().expect("not poisoned") += incremented.by;
        }

        Ok(())
    }
}

impl ResumableProjection for Totals {
    async fn checkpoint(&self) -> Result<Option<String>, Refused> {
        tokio::task::yield_now().await;
        self.trouble.panics_in("checkpoint");
        if self.trouble == Trouble::RefusesToReadTheCheckpoint {
            return Err(Refused(Category::Transient));
        }

        Ok(self.checkpoint.lock().expect("not poisoned").clone())
    }

    async fn save_checkpoint(&self, event_id: &str) -> Result<(), Refused> {
        tokio::task::yield_now().await;
        self.trouble.panics_in("save_checkpoint");
        self.saved
            .lock()
            .expect("not poisoned")
            .push(event_id.to_owned());
        *self.checkpoint.lock().expect("not poisoned") = Some(event_id.to_owned());

        Ok(())
    }

    fn catch_up_batch_size(&self) -> usize {
        self.batch_size
    }
}

/// The total of a ledger together with the ID of the last event it counts.
type Committed = Arc<Mutex<(i64, Option<String>)>>;

/// A ledger whose transactions add up the increments, and which keeps the
/// committed total together with the ID of the last event.
#[derive(Default)]
struct Ledger {
    committed: Committed,
    trouble: Trouble,
}

struct Booking {
    committed: Committed,
    pending: i64,
    trouble: Trouble,
}

impl Ledger {
    fn committed(&self) -> (i64, Option<String>) {
        self.committed.lock().expect("not poisoned").clone()
    }
}

impl TransactionalProjection for Ledger {
    type Event = CounterEvent;
    type Error = Refused;
    type Transaction = Booking;

    async fn checkpoint(&self) -> Result<Option<String>, Refused> {
        tokio::task::yield_now().await;
        self.trouble.panics_in("checkpoint");

        Ok(self.committed.lock().expect("not poisoned").1.clone())
    }

    async fn begin(&self) -> Result<Booking, Refused> {
        tokio::task::yield_now().await;
        self.trouble.panics_in("begin");

        Ok(Booking {
            committed: Arc::clone(&self.committed),
            pending: 0,
            trouble: self.trouble,
        })
    }
}

impl Transaction for Booking {
    type Event = CounterEvent;
    type Error = Refused;

    async fn apply(&mut self, event: Envelope<CounterEvent>) -> Result<(), Refused> {
        tokio::task::yield_now().await;
        self.trouble.panics_in("apply");
        if let CounterEvent::Incremented(incremented) = event.data {
            self.pending += incremented.by;
        }

        Ok(())
    }

    async fn commit(self, last_event_id: &str) -> Result<(), Refused> {
        tokio::task::yield_now().await;
        self.trouble.panics_in("commit");
        let mut committed = self.committed.lock().expect("not poisoned");
        committed.0 += self.pending;
        committed.1 = Some(last_event_id.to_owned());

        Ok(())
    }

    async fn rollback(self) -> Result<(), Refused> {
        tokio::task::yield_now().await;

        Ok(())
    }
}

/// Keeps every event as it is stored, to check what a projection of stored
/// events gets.
struct Stored(Mutex<Vec<eventsourcingdb::Event>>);

impl Projection for Stored {
    type Event = eventsourcingdb::Event;
    type Error = Refused;

    async fn apply(&self, event: Envelope<eventsourcingdb::Event>) -> Result<(), Refused> {
        tokio::task::yield_now().await;
        self.0.lock().expect("not poisoned").push(event.data);

        Ok(())
    }
}

/// Writes increments by the given amounts to the subject, and returns their
/// IDs.
async fn increment(store: &Store, subject: &str, amounts: &[i64]) -> Vec<String> {
    store
        .write(
            amounts
                .iter()
                .map(|by| EventOn::new(subject, &Incremented { by: *by }))
                .collect(),
            vec![Precondition::unconditionally()],
        )
        .await
        .expect("the events are written")
        .iter()
        .map(|event| event.id().to_owned())
        .collect()
}

#[tokio::test]
async fn applies_what_is_stored() {
    let database = Database::start().await;
    let store = database.store().await;
    let subject = subject_for("catch-up");
    let _ = increment(&store, &subject, &[1, 2, 3]).await;
    let totals = Totals::default();

    store
        .catch_up_projection(&Subjects::exact(&subject), &totals)
        .await
        .expect("the projection catches up");

    assert_eq!(totals.total(), 6);
}

#[tokio::test]
async fn reads_a_subject_tree() {
    let database = Database::start().await;
    let store = database.store().await;
    let _ = increment(&store, "/books/42", &[1]).await;
    let _ = increment(&store, "/books/42/notes", &[2]).await;
    let _ = increment(&store, "/readers/7", &[4]).await;
    let totals = Totals::default();

    store
        .catch_up_projection(&Subjects::tree("/books"), &totals)
        .await
        .expect("the projection catches up");

    assert_eq!(totals.total(), 3);
}

#[tokio::test]
async fn leaves_out_events_of_types_the_projection_has_no_variant_for() {
    let database = Database::start().await;
    let store = database.store().await;
    let subject = subject_for("catch-up-unknown");
    let _ = increment(&store, &subject, &[1]).await;
    let _ = store
        .write(
            vec![EventOn::new(&subject, &Unrelated {})],
            vec![Precondition::unconditionally()],
        )
        .await
        .expect("the unrelated event is written");
    let totals = Totals::default();

    store
        .catch_up_projection(&Subjects::exact(&subject), &totals)
        .await
        .expect("the projection catches up");

    assert_eq!(totals.applied(), ["0"]);
}

#[tokio::test]
async fn has_nothing_to_do_without_events() {
    let database = Database::start().await;
    let totals = Totals::default();

    database
        .store()
        .await
        .catch_up_projection(&Subjects::tree("/"), &totals)
        .await
        .expect("there is nothing to do");

    assert_eq!(totals.applied(), Vec::<String>::new());
}

#[tokio::test]
async fn resumes_from_its_checkpoint() {
    let database = Database::start().await;
    let store = database.store().await;
    let subject = subject_for("catch-up-resumable");
    let ids = increment(&store, &subject, &[1, 2, 3]).await;
    let totals = Totals {
        checkpoint: Mutex::new(Some(ids[0].clone())),
        ..Totals::default()
    };

    store
        .catch_up_resumable_projection(&Subjects::exact(&subject), &totals)
        .await
        .expect("the projection catches up");

    assert_eq!(totals.applied(), &ids[1..]);
    assert_eq!(totals.saved(), &ids[1..]);
    assert_eq!(totals.total(), 5);
}

#[tokio::test]
async fn saves_the_checkpoint_once_per_batch_while_catching_up() {
    let database = Database::start().await;
    let store = database.store().await;
    let subject = subject_for("catch-up-batches");
    let ids = increment(&store, &subject, &[1, 1, 1, 1, 1]).await;
    let totals = Totals {
        batch_size: 2,
        ..Totals::default()
    };

    store
        .catch_up_resumable_projection(&Subjects::exact(&subject), &totals)
        .await
        .expect("the projection catches up");

    assert_eq!(
        totals.saved(),
        [ids[1].clone(), ids[3].clone(), ids[4].clone()]
    );
}

#[tokio::test]
async fn reports_a_failing_apply_with_its_category() {
    let database = Database::start().await;
    let store = database.store().await;
    let subject = subject_for("catch-up-refused");
    let _ = increment(&store, &subject, &[1]).await;
    let totals = Totals {
        trouble: Trouble::RefusesToApply,
        ..Totals::default()
    };

    let failure = store
        .catch_up_projection(&Subjects::exact(&subject), &totals)
        .await
        .expect_err("the projection refuses");

    assert!(
        matches!(failure, ProjectionError::Projection { .. }),
        "{failure:?}"
    );
    assert_eq!(
        failure.category(),
        Some(Category::Transient),
        "catching up once does not try again"
    );
}

#[tokio::test]
async fn stops_when_the_checkpoint_can_not_be_read() {
    let database = Database::start().await;
    let store = database.store().await;
    let subject = subject_for("catch-up-checkpoint");
    let _ = increment(&store, &subject, &[1]).await;
    let totals = Totals {
        trouble: Trouble::RefusesToReadTheCheckpoint,
        ..Totals::default()
    };

    let failure = store
        .catch_up_resumable_projection(&Subjects::exact(&subject), &totals)
        .await
        .expect_err("the checkpoint can not be read");

    assert!(
        matches!(failure, ProjectionError::Projection { .. }),
        "{failure:?}"
    );
    assert_eq!(totals.applied(), Vec::<String>::new());
}

#[tokio::test]
async fn commits_a_transaction_with_the_last_event_id_and_resumes_from_it() {
    let database = Database::start().await;
    let store = database.store().await;
    let subject = subject_for("catch-up-transactional");
    let first = increment(&store, &subject, &[1, 2]).await;
    let ledger = Ledger::default();

    store
        .catch_up_transactional_projection(&Subjects::exact(&subject), &ledger)
        .await
        .expect("the projection catches up");
    assert_eq!(ledger.committed(), (3, Some(first[1].clone())));

    let second = increment(&store, &subject, &[4]).await;
    store
        .catch_up_transactional_projection(&Subjects::exact(&subject), &ledger)
        .await
        .expect("the projection catches up again");
    assert_eq!(
        ledger.committed(),
        (7, Some(second[0].clone())),
        "it went on from its checkpoint"
    );
}

#[tokio::test]
async fn comes_back_from_catching_up_as_an_error_wherever_the_projection_panics() {
    let database = Database::start().await;
    let store = database.store().await;
    let subject = subject_for("catch-up-panics");
    let _ = increment(&store, &subject, &[1]).await;
    let subjects = Subjects::exact(&subject);

    let mut failures = Vec::new();
    for function in ["apply", "checkpoint", "save_checkpoint"] {
        let totals = Totals {
            trouble: Trouble::PanicsIn(function),
            ..Totals::default()
        };
        failures.push((
            function,
            store
                .catch_up_resumable_projection(&subjects, &totals)
                .await,
        ));
    }
    for function in ["apply", "checkpoint", "begin", "commit"] {
        let ledger = Ledger {
            trouble: Trouble::PanicsIn(function),
            ..Ledger::default()
        };
        failures.push((
            function,
            store
                .catch_up_transactional_projection(&subjects, &ledger)
                .await,
        ));
    }

    for (function, result) in failures {
        let failure = result.expect_err(function);
        assert!(
            matches!(&failure, ProjectionError::Panicked { message } if message.contains(function)),
            "{function}: {failure:?}"
        );
        assert_eq!(failure.category(), Some(Category::Permanent), "{function}");
    }
}

#[tokio::test]
async fn hands_a_projection_of_stored_events_every_event_with_its_hash() {
    let database = Database::start().await;
    let store = database.store().await;
    let subject = subject_for("catch-up-stored");
    let _ = increment(&store, &subject, &[1]).await;
    let _ = store
        .write(
            vec![
                EventOn::new(&subject, &Reset {}),
                EventOn::new(&subject, &Unrelated {}),
            ],
            vec![Precondition::unconditionally()],
        )
        .await
        .expect("the events are written");
    let stored = Stored(Mutex::new(Vec::new()));

    store
        .catch_up_projection(&Subjects::exact(&subject), &stored)
        .await
        .expect("the projection catches up");

    let events = stored.0.lock().expect("not poisoned");
    assert_eq!(events.len(), 3, "every event, whatever its type");
    assert!(
        events.iter().all(|event| event.verify_hash().is_ok()),
        "the events keep their hashes"
    );
}