architecturekit 0.22.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
// These tests check the status and the message every failure is answered
// with, and the answers to refusals, to a value that is not a revision, and to
// an empty range that need no route:
//
// - A failure is a value of its own, so a handler that fails before it runs a
//   command answers what it fails with.
// - A request that the caller cancels is dropped, so it gets no answer.
// - The log is the one of the log crate, and its entries name the status, but
//   neither the method nor the route, which a handler does not know when it
//   answers.

use std::{convert::Infallible, error::Error, fmt, time::Duration};

use bytes::Bytes;
use http::{Response, StatusCode, header};
use log::Level;

use super::HttpError;
use crate::{
    Categorized, Category, DomainError, ExecuteError, Failure, LoadError, LowerBound, NotCaughtUp,
    Permanent, ReadOptions, Revision, Subject, SubjectScheme, Transient, UpperBound,
    check_read_options, httpapi::logs::captured,
};

/// An error of a category the test names, as an application has one.
#[derive(Debug)]
struct Refused(Option<Category>);

impl fmt::Display for Refused {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("the shelf is full")
    }
}

impl Error for Refused {}

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

fn transient() -> Transient {
    Transient::Other(Failure::new("reading the subject /books/42", None))
}

fn conflict() -> Transient {
    Transient::Conflict(Failure::new("writing to the subject /books/42", None))
}

fn permanent() -> Permanent {
    Permanent::Other(Failure::new("reading the subject /books/42", None))
}

fn outcome_unknown(cause: Option<Transient>) -> ExecuteError<DomainError> {
    ExecuteError::OutcomeUnknown(Failure::new(
        "writing to the subject /books/42",
        cause.map(Into::into),
    ))
}

fn empty_range() -> HttpError {
    check_read_options(&ReadOptions {
        lower_bound: LowerBound::FromEvent(Revision::from(5)),
        upper_bound: UpperBound::BeforeEvent(Revision::from(3)),
        ..ReadOptions::default()
    })
    .expect_err("the range is empty")
    .into()
}

fn not_a_revision() -> HttpError {
    "abc"
        .parse::<Revision>()
        .expect_err("abc is no revision")
        .into()
}

fn not_a_subject() -> HttpError {
    "books/42"
        .parse::<Subject>()
        .expect_err("books/42 is no subject")
        .into()
}

fn not_values_of_a_subject() -> HttpError {
    SubjectScheme::new("/books/{book_id}")
        .try_build(&["a.b"])
        .expect_err("a.b can not be part of a subject")
        .into()
}

/// Every kind of failure, with the status it is answered with.
fn every_kind() -> Vec<(&'static str, HttpError, StatusCode)> {
    vec![
        (
            "a caller who could not be determined",
            HttpError::unauthorized("the token has expired"),
            StatusCode::UNAUTHORIZED,
        ),
        (
            "a caller who is not allowed",
            HttpError::forbidden("only an admin may do this"),
            StatusCode::FORBIDDEN,
        ),
        (
            "something that does not exist",
            HttpError::not_found("ticket 7"),
            StatusCode::NOT_FOUND,
        ),
        (
            "a malformed request",
            HttpError::malformed("empty body"),
            StatusCode::BAD_REQUEST,
        ),
        (
            "a body that is too large",
            HttpError::too_large("at most 1048576 bytes are read"),
            StatusCode::PAYLOAD_TOO_LARGE,
        ),
        (
            "a body of another type",
            HttpError::unsupported_media_type("Content-Type is required"),
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
        ),
        (
            "a broken business rule",
            ExecuteError::Decider(DomainError::new("the book is lent out")).into(),
            StatusCode::UNPROCESSABLE_ENTITY,
        ),
        (
            "an unknown outcome",
            outcome_unknown(None).into(),
            StatusCode::INTERNAL_SERVER_ERROR,
        ),
        (
            "a view that did not catch up",
            NotCaughtUp::<Infallible>::TimedOut(Duration::from_secs(5)).into(),
            StatusCode::INTERNAL_SERVER_ERROR,
        ),
        (
            "a conflict",
            ExecuteError::<DomainError>::Transient(conflict()).into(),
            StatusCode::CONFLICT,
        ),
        (
            "a transient failure",
            ExecuteError::<DomainError>::Transient(transient()).into(),
            StatusCode::SERVICE_UNAVAILABLE,
        ),
        (
            "a permanent failure",
            ExecuteError::<DomainError>::Permanent(permanent()).into(),
            StatusCode::INTERNAL_SERVER_ERROR,
        ),
        (
            "a value that is not a revision",
            not_a_revision(),
            StatusCode::BAD_REQUEST,
        ),
        (
            "a value that is not a subject",
            not_a_subject(),
            StatusCode::BAD_REQUEST,
        ),
        (
            "values that can not compose a subject",
            not_values_of_a_subject(),
            StatusCode::BAD_REQUEST,
        ),
        ("an empty range", empty_range(), StatusCode::BAD_REQUEST),
        (
            "an error without a category",
            HttpError::of(Refused(None)),
            StatusCode::INTERNAL_SERVER_ERROR,
        ),
    ]
}

#[test]
fn maps_every_category() {
    for (name, error, status) in every_kind() {
        assert_eq!(error.status(), status, "{name}");
    }
}

#[test]
fn maps_an_error_of_an_application_by_its_category() {
    for (category, status) in [
        (Some(Category::Domain), StatusCode::UNPROCESSABLE_ENTITY),
        (Some(Category::Transient), StatusCode::SERVICE_UNAVAILABLE),
        (Some(Category::Permanent), StatusCode::INTERNAL_SERVER_ERROR),
        (None, StatusCode::INTERNAL_SERVER_ERROR),
    ] {
        assert_eq!(
            HttpError::of(Refused(category)).status(),
            status,
            "{category:?}"
        );
        assert_eq!(
            HttpError::from(ExecuteError::Decider(Refused(category))).status(),
            status,
            "a decider that fails with {category:?}"
        );
    }
}

#[test]
fn prefers_conflict_over_its_category() {
    // A conflict is transient, but 409 says more than 503.
    let error = HttpError::from(ExecuteError::<DomainError>::Transient(conflict()));

    assert_eq!(error.status(), StatusCode::CONFLICT);
}

#[test]
fn maps_an_unknown_outcome_to_500_also_if_it_wraps_a_status_that_invites_trying_again() {
    let error = HttpError::from(outcome_unknown(Some(transient())));

    assert_eq!(error.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

#[test]
fn maps_a_view_that_did_not_catch_up_to_500_also_if_it_wraps_a_status_that_invites_trying_again() {
    let error = HttpError::from(NotCaughtUp::View(transient()));

    assert_eq!(error.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

#[test]
fn maps_what_wait_for_written_returns_once_the_time_has_run_out_to_500_not_to_503() {
    let error = HttpError::from(NotCaughtUp::<Infallible>::TimedOut(Duration::from_millis(
        50,
    )));

    assert_eq!(error.status(), StatusCode::INTERNAL_SERVER_ERROR);
}

#[test]
fn maps_a_value_that_is_not_a_revision_to_400_with_its_own_text() {
    let error = not_a_revision();

    assert_eq!(error.status(), StatusCode::BAD_REQUEST);
    assert_eq!(error.message(), r#"not a revision: "abc""#);
}

#[test]
fn maps_a_value_that_is_not_a_subject_to_400_with_its_own_text() {
    let error = not_a_subject();

    assert_eq!(error.status(), StatusCode::BAD_REQUEST);
    assert_eq!(
        error.message(),
        r#"not a subject: "books/42", which does not start with a slash"#
    );
}

#[test]
fn maps_values_that_can_not_compose_a_subject_to_400_with_their_own_text() {
    let error = not_values_of_a_subject();

    assert_eq!(error.status(), StatusCode::BAD_REQUEST);
    assert_eq!(
        error.message(),
        r#"value "a.b" for "book_id" may only contain A-Z, a-z, 0-9, underscores, and hyphens"#
    );
}

#[test]
fn maps_an_empty_range_to_400() {
    assert_eq!(empty_range().status(), StatusCode::BAD_REQUEST);
}

#[test]
fn maps_a_failure_of_the_database_by_its_category() {
    assert_eq!(
        HttpError::from(LoadError::Transient(transient())).status(),
        StatusCode::SERVICE_UNAVAILABLE
    );
    assert_eq!(
        HttpError::from(LoadError::Permanent(permanent())).status(),
        StatusCode::INTERNAL_SERVER_ERROR
    );
}

/// Answers the failure, and returns the answer with what was logged meanwhile.
fn answered(error: HttpError) -> (Response<Bytes>, Vec<(Level, String)>) {
    captured(|| Response::<Bytes>::from(error))
}

fn message_of(response: &Response<Bytes>) -> String {
    let body: serde_json::Value =
        serde_json::from_slice(response.body()).expect("the answer is JSON");
    body["message"]
        .as_str()
        .expect("the answer has a message")
        .to_owned()
}

#[test]
fn explains_a_failure_the_caller_can_fix_with_its_own_text_without_logging_it() {
    for (name, error, message) in [
        (
            "a broken business rule",
            ExecuteError::Decider(DomainError::new("the book is lent out")).into(),
            "the book is lent out",
        ),
        (
            "a caller who is not allowed",
            HttpError::forbidden("only an admin may do this"),
            "forbidden: only an admin may do this",
        ),
        (
            "something that does not exist",
            HttpError::not_found("ticket 7"),
            "not found: ticket 7",
        ),
        (
            "a malformed request",
            HttpError::malformed("empty body"),
            "malformed request: empty body",
        ),
        (
            "a body that is too large",
            HttpError::too_large("at most 1048576 bytes are read"),
            "request body too large: at most 1048576 bytes are read",
        ),
        (
            "a body of another type",
            HttpError::unsupported_media_type("Content-Type is required"),
            "unsupported media type: Content-Type is required",
        ),
        (
            "a value that is not a revision",
            not_a_revision(),
            r#"not a revision: "abc""#,
        ),
        (
            "a value that is not a subject",
            not_a_subject(),
            r#"not a subject: "books/42", which does not start with a slash"#,
        ),
        (
            "values that can not compose a subject",
            not_values_of_a_subject(),
            r#"value "a.b" for "book_id" may only contain A-Z, a-z, 0-9, underscores, and hyphens"#,
        ),
        (
            "an empty range",
            empty_range(),
            r#"empty range: no event can lie from "5" and before "3""#,
        ),
    ] {
        let (response, logged) = answered(error);

        assert_eq!(message_of(&response), message, "{name}");
        assert_eq!(
            logged,
            [],
            "{name}: a failure the caller can fix is not logged"
        );
    }
}

#[test]
fn answers_a_refusal_with_a_fixed_text_and_logs_the_details_as_information() {
    for (name, error, message, cause) in [
        (
            "a caller who could not be determined",
            HttpError::unauthorized("the token has expired"),
            "unauthorized",
            "the token has expired",
        ),
        (
            "a conflict",
            ExecuteError::<DomainError>::Transient(conflict()).into(),
            "conflict: the data has changed since it was read",
            "/books/42",
        ),
    ] {
        let (response, logged) = answered(error);

        assert_eq!(message_of(&response), message, "{name}");
        assert_eq!(logged.len(), 1, "{name}: {logged:?}");
        assert_eq!(logged[0].0, Level::Info, "{name}");
        assert!(
            logged[0].1.contains(cause),
            "{name}: the details have to be logged: {logged:?}"
        );
    }
}

#[test]
fn answers_an_internal_failure_with_a_fixed_text_and_logs_it_as_an_error() {
    for (name, error, message) in [
        (
            "a transient failure",
            HttpError::from(ExecuteError::<DomainError>::Transient(transient())),
            "internal server error",
        ),
        (
            "a permanent failure",
            ExecuteError::<DomainError>::Permanent(permanent()).into(),
            "internal server error",
        ),
        (
            "an error without a category",
            HttpError::of(Refused(None)),
            "internal server error",
        ),
        (
            "an unknown outcome",
            outcome_unknown(Some(transient())).into(),
            "outcome unknown: the request may have succeeded",
        ),
        (
            "a view that did not catch up",
            NotCaughtUp::View(transient()).into(),
            "the request succeeded, but its result is not visible yet",
        ),
    ] {
        let status = error.status();
        let (response, logged) = answered(error);

        assert_eq!(message_of(&response), message, "{name}");
        assert_eq!(logged.len(), 1, "{name}: {logged:?}");
        assert_eq!(logged[0].0, Level::Error, "{name}");
        assert!(
            logged[0].1.contains(&status.as_u16().to_string()),
            "{name}: the status has to be logged: {logged:?}"
        );
        assert!(
            logged[0].1.contains("/books/42") || logged[0].1.contains("the shelf is full"),
            "{name}: the cause has to be logged: {logged:?}"
        );
    }
}

#[test]
fn answers_as_json_that_is_never_cached() {
    let (response, _) = answered(HttpError::not_found("ticket 7"));

    assert_eq!(response.status(), StatusCode::NOT_FOUND);
    assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json");
    assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
    assert_eq!(
        response.body(),
        &Bytes::from_static(b"{\"message\":\"not found: ticket 7\"}\n")
    );
}

#[test]
fn keeps_the_cause_as_its_source() {
    let error = HttpError::from(ExecuteError::Decider(DomainError::new(
        "the book is lent out",
    )));

    assert_eq!(
        error
            .source()
            .expect("the error of the decider is the source")
            .to_string(),
        "the book is lent out"
    );
    assert_eq!(error.to_string(), "the book is lent out");
}

#[cfg(feature = "axum")]
#[tokio::test]
async fn answers_through_axum_as_it_answers_otherwise() {
    use axum::response::IntoResponse;

    let response = HttpError::forbidden("only an admin may do this").into_response();

    assert_eq!(response.status(), StatusCode::FORBIDDEN);
    assert_eq!(response.headers()[header::CONTENT_TYPE], "application/json");
    assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
    assert_eq!(
        axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("the body can be read"),
        Bytes::from_static(b"{\"message\":\"forbidden: only an admin may do this\"}\n")
    );
}

#[test]
fn passes_on_the_error_of_a_view_in_memory() {
    fn read() -> Result<u8, HttpError> {
        let found: Result<u8, Infallible> = Ok(42);
        Ok(found?)
    }

    assert_eq!(read().expect("reading never fails"), 42);
}