autumn-web 0.8.0

An opinionated, convention-over-configuration web framework for Rust
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
//! Unit tests for the double-entry rules and the idempotency key (#1837).
//!
//! Everything here runs without a database: `Transaction::validate` is what
//! `post` calls before its first `INSERT`, so the zero-sum invariant is
//! testable on its own. The store itself is proved in
//! `autumn/tests/sqlite_money_ledger.rs` and
//! `autumn/tests/integration/money_ledger_postgres.rs`.

use super::*;
use crate::money::{Eur, Money, Usd};

fn usd(minor: i64) -> Money<Usd> {
    Money::<Usd>::from_minor(minor)
}

fn key(text: &str) -> IdempotencyKey {
    IdempotencyKey::new(text).expect("valid key")
}

fn balanced() -> Vec<Posting> {
    vec![
        Posting::debit("customer:wallet", usd(2500)),
        Posting::credit("platform:revenue", usd(2500)),
    ]
}

// ── Zero-sum ────────────────────────────────────────────────────────────────

#[test]
fn a_balanced_transaction_validates() {
    let checked = Transaction::new(key("k1"), balanced()).validate().unwrap();
    assert_eq!(checked.currency(), Usd::currency());
    assert_eq!(checked.total().minor(), 2500);
    assert_eq!(checked.request_hash().len(), 64);
}

#[test]
fn debits_that_do_not_equal_credits_are_refused() {
    let transfer = Transaction::new(
        key("k1"),
        vec![
            Posting::debit("customer:wallet", usd(2500)),
            Posting::credit("platform:revenue", usd(2499)),
        ],
    );
    assert!(matches!(
        transfer.validate(),
        Err(LedgerError::Unbalanced {
            debits: 2500,
            credits: 2499,
            currency: "USD",
        })
    ));
}

#[test]
fn a_many_sided_transaction_balances_across_all_of_it() {
    // A marketplace split: one charge, three destinations.
    let transfer = Transaction::new(
        key("k1"),
        vec![
            Posting::debit("customer:wallet", usd(10_000)),
            Posting::credit("seller:1", usd(7000)),
            Posting::credit("seller:2", usd(2000)),
            Posting::credit("platform:fees", usd(1000)),
        ],
    );
    assert_eq!(transfer.validate().unwrap().total().minor(), 10_000);
}

#[test]
fn an_empty_or_one_sided_transaction_does_not_balance_by_default() {
    assert!(matches!(
        Transaction::new(key("k1"), Vec::new()).validate(),
        Err(LedgerError::PostingCount { count: 0 })
    ));
    assert!(matches!(
        Transaction::new(key("k1"), vec![Posting::debit("a", usd(100))]).validate(),
        Err(LedgerError::PostingCount { count: 1 })
    ));
    // Two postings, both debits: the sum is not zero, and the message says why.
    assert!(matches!(
        Transaction::new(
            key("k1"),
            vec![Posting::debit("a", usd(100)), Posting::debit("b", usd(100))],
        )
        .validate(),
        Err(LedgerError::OneSided)
    ));
}

#[test]
fn a_transaction_that_moves_nothing_is_refused() {
    let transfer = Transaction::new(
        key("k1"),
        vec![Posting::debit("a", usd(0)), Posting::credit("b", usd(0))],
    );
    assert!(matches!(
        transfer.validate(),
        Err(LedgerError::ZeroPosting { .. })
    ));
}

/// A zero line has no side the store can read back: a zero debit and a zero
/// credit both store as `0`, and `Side::of(0)` is a debit. Refused rather than
/// written as a posting that changes side on the way out.
#[test]
fn a_zero_line_inside_a_real_transaction_is_refused() {
    let transfer = Transaction::new(
        key("k1"),
        vec![
            Posting::debit("a", usd(2500)),
            Posting::credit("b", usd(2500)),
            Posting::credit("c", usd(0)),
        ],
    );
    assert!(matches!(
        transfer.validate(),
        Err(LedgerError::ZeroPosting { account }) if account == "c"
    ));
}

#[test]
fn mixed_currencies_are_refused() {
    let transfer = Transaction::new(
        key("k1"),
        vec![
            Posting::debit("a", usd(2500)),
            Posting::credit("b", Money::<Eur>::from_minor(2500)),
        ],
    );
    assert!(matches!(
        transfer.validate(),
        Err(LedgerError::MixedCurrencies {
            expected: "USD",
            found: "EUR",
        })
    ));
}

#[test]
fn a_negative_amount_belongs_to_the_side_not_to_the_value() {
    let transfer = Transaction::new(
        key("k1"),
        vec![
            Posting::debit("a", usd(-2500)),
            Posting::credit("b", usd(2500)),
        ],
    );
    assert!(matches!(
        transfer.validate(),
        Err(LedgerError::NegativeAmount { .. })
    ));
}

#[test]
fn the_extreme_value_cannot_reach_the_ledger() {
    // `i64::MIN` has no positive form, so it can only arrive as a negative
    // amount — which is refused before anything tries to negate it.
    let posting = Posting::credit("a", usd(i64::MIN));
    assert!(matches!(
        posting.signed_minor(),
        Err(LedgerError::NegativeAmount { .. })
    ));
}

#[test]
fn a_sum_that_leaves_i64_is_an_overflow_not_a_wrap() {
    let transfer = Transaction::new(
        key("k1"),
        vec![
            Posting::debit("a", usd(i64::MAX)),
            Posting::debit("b", usd(i64::MAX)),
            Posting::credit("c", usd(i64::MAX)),
        ],
    );
    assert!(matches!(
        transfer.validate(),
        Err(LedgerError::Money(MoneyError::Overflow))
    ));
}

#[test]
fn empty_and_over_long_text_is_refused() {
    assert!(matches!(
        IdempotencyKey::new(""),
        Err(LedgerError::InvalidText {
            field: "idempotency key",
            ..
        })
    ));
    assert!(matches!(
        IdempotencyKey::new("x".repeat(256)),
        Err(LedgerError::InvalidText {
            field: "idempotency key",
            ..
        })
    ));
    assert!(matches!(
        Transaction::new(
            key("k1"),
            vec![Posting::debit("", usd(100)), Posting::credit("b", usd(100))],
        )
        .validate(),
        Err(LedgerError::InvalidText {
            field: "account id",
            ..
        })
    ));
    assert!(matches!(
        Transaction::new(key("k1"), balanced())
            .memo("m".repeat(1025))
            .validate(),
        Err(LedgerError::InvalidText { field: "memo", .. })
    ));
}

/// A NUL byte is refused in validation, on every backend.
///
/// Postgres `TEXT` cannot hold one, so binding it fails as a database error —
/// a 500 for what is a bad request. `SQLite` stores it happily, so the two
/// backends would disagree. Validation refuses it first, and both answer 422.
#[test]
fn a_nul_byte_in_text_is_refused() {
    assert!(matches!(
        IdempotencyKey::new("order\u{0}1"),
        Err(LedgerError::InvalidText {
            field: "idempotency key",
            ..
        })
    ));
    assert!(matches!(
        Transaction::new(
            key("k1"),
            vec![
                Posting::debit("cash\u{0}", usd(100)),
                Posting::credit("b", usd(100)),
            ],
        )
        .validate(),
        Err(LedgerError::InvalidText {
            field: "account id",
            ..
        })
    ));
    assert!(matches!(
        Transaction::new(key("k1"), balanced())
            .memo("paid\u{0}up")
            .validate(),
        Err(LedgerError::InvalidText { field: "memo", .. })
    ));
}

// ── Sides ───────────────────────────────────────────────────────────────────

#[test]
fn sides_carry_the_sign_the_store_writes() {
    let debit = Posting::debit("a", usd(2500));
    assert!(debit.is_debit());
    assert_eq!(debit.side(), Side::Debit);
    assert_eq!(debit.signed_minor().unwrap(), 2500);
    assert_eq!(debit.amount().minor(), 2500);

    let credit = Posting::credit("b", usd(2500));
    assert!(credit.is_credit());
    assert_eq!(credit.side(), Side::Credit);
    assert_eq!(credit.signed_minor().unwrap(), -2500);
    assert_eq!(credit.amount().minor(), 2500);
}

// ── Idempotency keys ────────────────────────────────────────────────────────

#[test]
fn a_derived_key_is_stable_across_build_order() {
    let forward = IdempotencyKey::derive("order:9911", &balanced());
    let reversed = IdempotencyKey::derive(
        "order:9911",
        &[
            Posting::credit("platform:revenue", usd(2500)),
            Posting::debit("customer:wallet", usd(2500)),
        ],
    );
    assert_eq!(forward, reversed);
    assert_eq!(forward.as_str().len(), 64);
}

#[test]
fn a_derived_key_changes_with_the_money() {
    let base = IdempotencyKey::derive("order:9911", &balanced());
    let other_amount = IdempotencyKey::derive(
        "order:9911",
        &[
            Posting::debit("customer:wallet", usd(2501)),
            Posting::credit("platform:revenue", usd(2501)),
        ],
    );
    let other_account = IdempotencyKey::derive(
        "order:9911",
        &[
            Posting::debit("customer:other", usd(2500)),
            Posting::credit("platform:revenue", usd(2500)),
        ],
    );
    let other_namespace = IdempotencyKey::derive("order:9912", &balanced());
    let other_side = IdempotencyKey::derive(
        "order:9911",
        &[
            Posting::credit("customer:wallet", usd(2500)),
            Posting::debit("platform:revenue", usd(2500)),
        ],
    );
    for other in [other_amount, other_account, other_namespace, other_side] {
        assert_ne!(base, other);
    }
}

#[test]
fn the_namespace_and_the_postings_cannot_run_together() {
    // A length-prefixed hash: moving a character from the namespace into an
    // account id must not produce the same key.
    let left = IdempotencyKey::derive(
        "ab",
        &[Posting::debit("c", usd(1)), Posting::credit("d", usd(1))],
    );
    let right = IdempotencyKey::derive(
        "a",
        &[Posting::debit("bc", usd(1)), Posting::credit("d", usd(1))],
    );
    assert_ne!(left, right);
}

#[test]
fn the_request_hash_ignores_the_memo_and_the_order() {
    let plain = Transaction::new(key("k1"), balanced()).validate().unwrap();
    let described = Transaction::new(key("k1"), balanced())
        .memo("order 9911, retried")
        .validate()
        .unwrap();
    assert_eq!(plain.request_hash(), described.request_hash());

    let reordered = Transaction::new(
        key("k1"),
        vec![
            Posting::credit("platform:revenue", usd(2500)),
            Posting::debit("customer:wallet", usd(2500)),
        ],
    )
    .validate()
    .unwrap();
    assert_eq!(plain.request_hash(), reordered.request_hash());
}

#[test]
fn the_request_hash_changes_with_the_money() {
    let base = Transaction::new(key("k1"), balanced()).validate().unwrap();
    let different = Transaction::new(
        key("k1"),
        vec![
            Posting::debit("customer:wallet", usd(2501)),
            Posting::credit("platform:revenue", usd(2501)),
        ],
    )
    .validate()
    .unwrap();
    assert_ne!(base.request_hash(), different.request_hash());
}

// ── Accounts ────────────────────────────────────────────────────────────────

#[test]
fn accounts_allow_a_negative_balance_unless_told_otherwise() {
    let wallet = Account::new("customer:wallet", Usd::currency());
    assert!(wallet.allows_negative());
    assert_eq!(wallet.currency(), Usd::currency());
    assert_eq!(wallet.id(), "customer:wallet");

    let float = Account::new("platform:float", Usd::currency()).disallow_negative();
    assert!(!float.allows_negative());
}

// ── Error mapping ───────────────────────────────────────────────────────────

#[test]
fn errors_carry_the_status_a_handler_should_return() {
    use axum::http::StatusCode;

    assert_eq!(
        LedgerError::Unbalanced {
            debits: 1,
            credits: 2,
            currency: "USD"
        }
        .http_status(),
        StatusCode::UNPROCESSABLE_ENTITY
    );
    assert_eq!(
        LedgerError::KeyReuse {
            key: "k".to_owned()
        }
        .http_status(),
        StatusCode::CONFLICT
    );
    assert_eq!(
        LedgerError::NegativeBalance {
            account: "a".to_owned(),
            balance: -1,
            currency: "USD"
        }
        .http_status(),
        StatusCode::CONFLICT
    );
    assert_eq!(
        LedgerError::Money(MoneyError::Overflow).http_status(),
        StatusCode::INTERNAL_SERVER_ERROR
    );
    assert_eq!(
        LedgerError::Database(diesel::result::Error::NotFound).http_status(),
        StatusCode::INTERNAL_SERVER_ERROR
    );
    assert_eq!(
        LedgerError::Conflict {
            key: "k".to_owned()
        }
        .http_status(),
        StatusCode::CONFLICT
    );
    assert_eq!(
        LedgerError::NotInTransaction.http_status(),
        StatusCode::INTERNAL_SERVER_ERROR
    );
    assert_eq!(
        LedgerError::ZeroPosting {
            account: "a".to_owned()
        }
        .http_status(),
        StatusCode::UNPROCESSABLE_ENTITY
    );
}

/// `MAX_PARTS` is checked before the weights are built, so a `parts` taken from
/// a request cannot ask for an allocation the machine has to abort on.
#[test]
fn splitting_into_more_parts_than_allowed_is_refused() {
    use crate::money::{MAX_PARTS, MoneyError};

    assert_eq!(
        Money::<Usd>::from_minor(100).split(usize::MAX),
        Err(MoneyError::InvalidWeights)
    );
    assert_eq!(
        Money::<Usd>::from_minor(100).split(MAX_PARTS.saturating_add(1)),
        Err(MoneyError::InvalidWeights)
    );
    assert_eq!(
        Money::<Usd>::from_minor(100)
            .split(MAX_PARTS)
            .unwrap()
            .len(),
        MAX_PARTS
    );
}

#[test]
fn a_handler_gets_the_same_status_through_autumn_error() {
    use crate::error::AutumnError;
    use axum::http::StatusCode;

    let reuse = AutumnError::from(LedgerError::KeyReuse {
        key: "k".to_owned(),
    });
    assert_eq!(reuse.status(), StatusCode::CONFLICT);

    let unbalanced = AutumnError::from(LedgerError::Unbalanced {
        debits: 1,
        credits: 2,
        currency: "USD",
    });
    assert_eq!(unbalanced.status(), StatusCode::UNPROCESSABLE_ENTITY);
}

#[test]
fn every_error_says_what_went_wrong() {
    let message = LedgerError::Unbalanced {
        debits: 2500,
        credits: 2499,
        currency: "USD",
    }
    .to_string();
    assert!(message.contains("2500"), "{message}");
    assert!(message.contains("2499"), "{message}");
    assert!(message.contains("USD"), "{message}");
}