skilj 0.2.0

Event sourcing on Postgres with Dynamic Consistency Boundaries: consistency per command instead of per aggregate, with GraphQL and REST APIs generated from your types.
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
//! End-to-end tests for `POST /v1/commands/trigger` (docs/architecture.md
//! [ยง8](../../docs/architecture.md#open-for-a-future-pass) item 4) - a real HTTP request, through `Skilj::rest_router()`,
//! through the `Arc<dyn CommandDispatcher>` bridge, into a real
//! `decide()`, and back out through `process_command`'s persistence.
//! Same `DATABASE_URL`-then-embedded-Postgres-then-skip harness as
//! `skilj-core/tests/persistence.rs`/`skilj/tests/reconciliation.rs` -
//! see either's own doc comment for the details, not repeated a third
//! time here.

use axum::body::Body;
use axum::http::{Request, StatusCode};
use chrono::{SubsecRound, Utc};
use http_body_util::BodyExt;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use skilj::{requires_role, CommandType, EventType, Skilj};
use skilj_core::access_control::{self, AccessLevel, Role, RoleAccessMapping, RoleStatus};
use skilj_core::bootstrap::ContextCreator;
use skilj_core::db::{self, Pool};
use skilj_core::event_store::{BoundedContext, BoundedContextStatus, Event};
use skilj_core::plugin::BoundedContextEvent;
use skilj_core::shared::{
    generate_token_id, generate_token_secret, CommandDecision, EventSpec, TagMapping,
};
use tower::ServiceExt;

// --- fixtures ---

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct MoneyDepositedPayload {
    amount: i64,
}

struct MoneyDeposited;

impl EventType for MoneyDeposited {
    type Payload = MoneyDepositedPayload;
    const NAME: &'static str = "MoneyDeposited";
    fn direct_creation_allowed() -> bool {
        true
    }
}

enum BankingEvent {
    // Never read - decide() below doesn't consult matching_events -
    // built only to satisfy CommandType::Event's own BoundedContextEvent
    // bound.
    #[allow(dead_code)]
    MoneyDeposited(MoneyDepositedPayload),
}

impl BoundedContextEvent for BankingEvent {
    fn try_from_event(event: &Event) -> Option<Result<Self, serde_json::Error>> {
        match event.event_type.name.as_str() {
            "MoneyDeposited" => {
                Some(serde_json::from_str(&event.payload).map(BankingEvent::MoneyDeposited))
            }
            _ => None,
        }
    }
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct WithdrawPayload {
    amount: i64,
}

struct WithdrawMoney;

impl CommandType for WithdrawMoney {
    type Payload = WithdrawPayload;
    type Event = BankingEvent;
    const NAME: &'static str = "WithdrawMoney";
    fn rest_trigger_allowed() -> bool {
        true
    }
    /// A real, non-empty `tag_mappings` entry - the previously-panicking
    /// `derive_tags` path (`todo!()` for any non-empty `tag_mappings`),
    /// now exercised for real over the actual REST surface, not just at
    /// the pure-function layer. See `command_trigger_derives_real_tags_
    /// from_a_real_tag_mapping` below.
    fn tag_mappings() -> Vec<TagMapping> {
        vec![TagMapping {
            key: "amount".into(),
            field: "amount".into(),
            blind: false,
        }]
    }
    /// Cross-tenant write fix (docs/architecture.md's own write-up of
    /// these passes) - reuses the existing `amount` tag mapping as the
    /// owner dimension, purely so `command_trigger_rejects_...`/
    /// `command_trigger_succeeds_when_...` below have a real declared
    /// owner to test a scoped `CommandToken` against, over the actual
    /// REST surface. Every *other* test in this file mints its token
    /// with `scope: None` (`setup()`'s own default), so this is
    /// vacuously true for them - no behaviour change to anything already
    /// passing here.
    fn owner_tag_key() -> Option<&'static str> {
        Some("amount")
    }
    /// Deliberately simple: rejects anything over 1000, otherwise emits
    /// one `MoneyDeposited` event carrying the same amount - just enough
    /// behaviour to exercise both `CommandTrigger` outcomes (ยง5.4/ยง7.3)
    /// without needing a second registered command type.
    fn decide(payload: &Self::Payload, _matching_events: &[Self::Event]) -> CommandDecision {
        if payload.amount > 1000 {
            CommandDecision::Rejected {
                reason: "insufficient funds".to_string(),
                kind: "insufficient_funds".to_string(),
            }
        } else {
            CommandDecision::Accepted {
                events: vec![EventSpec {
                    event_type: "MoneyDeposited".to_string(),
                    payload: serde_json::json!({ "amount": payload.amount }),
                }],
            }
        }
    }
}

/// Registered but never actually triggered over REST in these tests
/// (`rest_trigger_allowed` defaults to `false`, left unset here) - exists
/// solely so `command_dispatcher().required_role(...)` has a real,
/// reconciled command type to look up. `#[requires_role(...)]` (ยง1.3.1)
/// is the whole point of this fixture.
struct CloseAccount;

#[requires_role("treasury_officer")]
impl CommandType for CloseAccount {
    type Payload = WithdrawPayload;
    type Event = BankingEvent;
    const NAME: &'static str = "CloseAccount";
    fn decide(_payload: &Self::Payload, _matching_events: &[Self::Event]) -> CommandDecision {
        CommandDecision::Accepted { events: vec![] }
    }
}

/// issue #98 over REST: a `CommandToken` may submit it, but the
/// submission becomes a pending proposal instead of a decided command.
struct TransferMoney;

impl CommandType for TransferMoney {
    type Payload = WithdrawPayload;
    type Event = BankingEvent;
    const NAME: &'static str = "TransferMoney";
    fn rest_trigger_allowed() -> bool {
        true
    }
    fn requires_approval() -> bool {
        true
    }
    fn decide(payload: &Self::Payload, _matching_events: &[Self::Event]) -> CommandDecision {
        CommandDecision::Accepted {
            events: vec![EventSpec {
                event_type: "MoneyDeposited".to_string(),
                payload: serde_json::json!({ "amount": payload.amount }),
            }],
        }
    }
}

// --- provisioning: DATABASE_URL, else embedded Postgres, else skip ---

struct TestDb {
    database_url: String,
    pool: Pool,
}

static TEST_DB: tokio::sync::OnceCell<Option<TestDb>> = tokio::sync::OnceCell::const_new();

fn runtime() -> &'static tokio::runtime::Runtime {
    static RUNTIME: std::sync::OnceLock<tokio::runtime::Runtime> = std::sync::OnceLock::new();
    RUNTIME.get_or_init(|| {
        tokio::runtime::Runtime::new()
            .expect("failed to build a tokio runtime for command_trigger tests")
    })
}

async fn test_db() -> Option<(String, Pool)> {
    TEST_DB
        .get_or_init(provision)
        .await
        .as_ref()
        .map(|db| (db.database_url.clone(), db.pool.clone()))
}

async fn connect_and_migrate(database_url: &str, label: &str) -> Option<Pool> {
    let pool = match db::connect(database_url).await {
        Ok(pool) => pool,
        Err(e) => {
            eprintln!("skipping: connecting to {label} failed: {e}");
            return None;
        }
    };
    if let Err(e) = db::migrate(&pool).await {
        eprintln!("skipping: migrating {label} failed: {e}");
        return None;
    }
    Some(pool)
}

async fn provision() -> Option<TestDb> {
    let database_url = skilj_test_support::database_url("skilj_command_trigger_test").await?;

    let pool = connect_and_migrate(&database_url, "the test database").await?;
    Some(TestDb { database_url, pool })
}

fn unique_name(prefix: &str) -> String {
    format!("{prefix}_{}", generate_token_id())
}

fn test_now() -> chrono::DateTime<Utc> {
    Utc::now().trunc_subsecs(6)
}

/// Builds a fully reconciled `Skilj` (both `MoneyDeposited`/`WithdrawMoney`
/// registered) plus a real, minted `CommandToken` for `WithdrawMoney` -
/// everything a `POST /v1/commands/trigger` test needs to send a real
/// request against a real router. The trailing `RoleAccessMapping`/
/// `CommandType` are for callers that need to mint a second,
/// differently-scoped token of their own (cross-tenant write fix,
/// docs/architecture.md's own write-up of these passes) - every other
/// test in this file only destructures the first four.
async fn setup() -> (
    Skilj,
    String,
    Pool,
    String,
    RoleAccessMapping,
    skilj_core::event_store::CommandType,
) {
    setup_with_pool(skilj_core::db::PgPoolOptions::new().max_connections(4)).await
}

/// [`setup`] with the `Skilj`'s own pool options chosen by the caller.
async fn setup_with_pool(
    pool_options: skilj_core::db::PgPoolOptions,
) -> (
    Skilj,
    String,
    Pool,
    String,
    RoleAccessMapping,
    skilj_core::event_store::CommandType,
) {
    let (database_url, pool) = test_db()
        .await
        .expect("test_db() must be Some - caller already checked");

    let external_subject = unique_name("subject");
    let role = Role {
        id: generate_token_id(),
        external_subject: external_subject.clone(),
        name: "Reconciliation Role".to_string(),
        superadmin: false,
        status: RoleStatus::Active,
        created_at: test_now(),
        revoked_at: None,
    };
    db::insert_role(&pool, &role).await.unwrap();

    let bc_name = unique_name("banking");
    let bc = BoundedContext {
        name: bc_name.clone(),
        status: BoundedContextStatus::Active,
        created_at: test_now(),
        created_by: ContextCreator::SystemCreator,
        template: None,
    };
    db::insert_bounded_context(&pool, &bc).await.unwrap();

    let mapping = RoleAccessMapping {
        role: role.clone(),
        bounded_context: bc.clone(),
        level: AccessLevel::Admin,
        can_read_sensitive: false,
        scope: None,
        capabilities: Default::default(),
        delegable: Default::default(),
        status: RoleStatus::Active,
        created_at: test_now(),
        revoked_at: None,
    };
    db::insert_role_access_mapping(&pool, &mapping)
        .await
        .unwrap();

    // Small per-instance pool: every test leaks a live `Skilj`, so the default
    // 10-connection pools of ~10 tests exhaust the shared embedded Postgres's
    // 100 connections and the last `build()` fails with `PoolTimedOut`.

    let (skilj, report) = Skilj::builder(database_url)
        .pool_options(pool_options)
        .bounded_context(bc_name.clone())
        .event_type::<MoneyDeposited>()
        .command_type::<WithdrawMoney>()
        .command_type::<CloseAccount>()
        .command_type::<TransferMoney>()
        .reconciliation_role(external_subject)
        .build()
        .await
        .unwrap();
    assert_eq!(report.skipped_no_access, Vec::<String>::new());

    let command_type = db::get_command_type(&pool, &bc_name, "WithdrawMoney")
        .await
        .unwrap()
        .unwrap();
    let token = access_control::create_command_token(
        &mapping,
        &command_type,
        generate_token_id(),
        generate_token_secret(),
        None,
        test_now(),
    )
    .unwrap();
    db::insert_command_token(&pool, &token).await.unwrap();

    let credential = format!("{}.{}", token.id, token.secret);
    (skilj, credential, pool, bc_name, mapping, command_type)
}

#[test]
fn an_approval_required_trigger_creates_a_pending_proposal() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, _credential, pool, bc_name, mapping, _) = setup().await;
        let command_type = db::get_command_type(&pool, &bc_name, "TransferMoney")
            .await
            .unwrap()
            .unwrap();
        let token = access_control::create_command_token(
            &mapping,
            &command_type,
            generate_token_id(),
            generate_token_secret(),
            None,
            test_now(),
        )
        .unwrap();
        db::insert_command_token(&pool, &token).await.unwrap();
        let credential = format!("{}.{}", token.id, token.secret);

        let request = Request::builder()
            .method("POST")
            .uri("/v1/commands/trigger")
            .header("authorization", format!("Bearer {credential}"))
            .header("content-type", "application/json")
            .body(Body::from(
                serde_json::json!({ "payload": { "amount": 7 } }).to_string(),
            ))
            .unwrap();
        let response = skilj.rest_router().oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(body["accepted"], serde_json::json!(false), "{body}");
        assert_eq!(body["pendingApproval"], serde_json::json!(true), "{body}");
        let proposal_id = body["proposalId"].as_str().expect("a proposal id");
        let proposals = db::list_command_proposals(
            &pool,
            &bc_name,
            Some(skilj_core::approvals::CommandProposalStatus::Pending),
            Some("TransferMoney"),
            None,
            Utc::now(),
        )
        .await
        .unwrap();
        assert_eq!(proposals.len(), 1);
        assert_eq!(proposals[0].id, proposal_id);
        assert_eq!(proposals[0].payload, r#"{"amount":7}"#);
    });
}

/// Every write to a bounded context holds its `sequence` lock, and every
/// other writer waits on that lock holding a pooled connection. A holder
/// that then read through the pool - a write's sync projections (ยง116), a
/// command batch leader's idempotency-key lookup (ยง117, forced here by
/// giving every command a key) - could never get a connection once more
/// writers waited than the pool had, and everything failed at the
/// acquire timeout.
#[test]
fn commands_and_direct_writes_beyond_the_pool_size_all_complete() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, command_credential, pool, bc_name, mapping, _) = setup_with_pool(
            skilj_core::db::PgPoolOptions::new()
                .max_connections(3)
                .acquire_timeout(std::time::Duration::from_secs(10)),
        )
        .await;
        let event_type = db::get_event_type(&pool, &bc_name, "MoneyDeposited")
            .await
            .unwrap()
            .unwrap();
        let direct_token = access_control::create_direct_creation_token(
            &mapping,
            &event_type,
            generate_token_id(),
            generate_token_secret(),
            None,
            test_now(),
        )
        .unwrap();
        db::insert_direct_creation_token(&pool, &direct_token)
            .await
            .unwrap();
        let direct_credential = format!("{}.{}", direct_token.id, direct_token.secret);
        let router = skilj.rest_router();

        let requests = (0..48).map(|i| {
            let router = router.clone();
            let (uri, credential, status) = if i % 2 == 0 {
                (
                    "/v1/commands/trigger",
                    command_credential.clone(),
                    StatusCode::OK,
                )
            } else {
                (
                    "/v1/events/direct",
                    direct_credential.clone(),
                    StatusCode::CREATED,
                )
            };
            async move {
                let mut request = Request::builder()
                    .method("POST")
                    .uri(uri)
                    .header("authorization", format!("Bearer {credential}"))
                    .header("content-type", "application/json");
                if status == StatusCode::OK {
                    request = request.header("Idempotency-Key", format!("key-{i}"));
                }
                let request = request
                    .body(Body::from(format!(r#"{{"payload":{{"amount":{i}}}}}"#)))
                    .unwrap();
                let response = router.oneshot(request).await.unwrap();
                let actual = response.status();
                let body = response.into_body().collect().await.unwrap().to_bytes();
                assert_eq!(actual, status, "{uri}: {}", String::from_utf8_lossy(&body));
            }
        });
        // Longer than the pool's acquire timeout: a stall shows up as
        // an acquire error in a response, a slow runner just finishes.
        tokio::time::timeout(
            std::time::Duration::from_secs(30),
            futures_util::future::join_all(requests),
        )
        .await
        .expect("concurrent writes stalled on the connection pool");

        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(events.len(), 48);
    });
}

/// The deterministic form of the test above, for the command path. The
/// bounded context's `sequence` lock is held from outside; a command with
/// an idempotency key queues for it first, then two direct writes, each
/// holding one of the pool's three connections. When the lock is released
/// the command gets it and must look its key up. It used to do that
/// through the pool - all three connections were taken, two of them by
/// writers waiting behind it, so it waited out the acquire timeout and
/// failed, and so did they (docs/architecture.md ยง117).
#[test]
fn a_command_holding_the_lock_needs_no_second_connection() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, command_credential, pool, bc_name, mapping, _) = setup_with_pool(
            skilj_core::db::PgPoolOptions::new()
                .max_connections(3)
                .acquire_timeout(std::time::Duration::from_secs(5)),
        )
        .await;
        let event_type = db::get_event_type(&pool, &bc_name, "MoneyDeposited")
            .await
            .unwrap()
            .unwrap();
        let direct_token = access_control::create_direct_creation_token(
            &mapping,
            &event_type,
            generate_token_id(),
            generate_token_secret(),
            None,
            test_now(),
        )
        .unwrap();
        db::insert_direct_creation_token(&pool, &direct_token)
            .await
            .unwrap();
        let direct_credential = format!("{}.{}", direct_token.id, direct_token.secret);
        let router = skilj.rest_router();

        let send = |uri: &'static str, credential: String, key: Option<&'static str>| {
            let router = router.clone();
            tokio::spawn(async move {
                let mut request = Request::builder()
                    .method("POST")
                    .uri(uri)
                    .header("authorization", format!("Bearer {credential}"))
                    .header("content-type", "application/json");
                if let Some(key) = key {
                    request = request.header("Idempotency-Key", key);
                }
                let request = request
                    .body(Body::from(r#"{"payload":{"amount":5}}"#))
                    .unwrap();
                let response = router.oneshot(request).await.unwrap();
                let status = response.status();
                let body = response.into_body().collect().await.unwrap().to_bytes();
                (status, String::from_utf8_lossy(&body).into_owned())
            })
        };

        // The test's own pool, not the `Skilj`'s.
        let mut blocker = pool.begin().await.unwrap();
        sqlx::query(sqlx::AssertSqlSafe(format!(
            "SELECT next_value FROM \"bc_{bc_name}\".sequence FOR UPDATE"
        )))
        .execute(&mut *blocker)
        .await
        .unwrap();

        let command = send(
            "/v1/commands/trigger",
            command_credential,
            Some("only-once"),
        );
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        let writes = [
            send("/v1/events/direct", direct_credential.clone(), None),
            send("/v1/events/direct", direct_credential, None),
        ];
        tokio::time::sleep(std::time::Duration::from_millis(500)).await;
        blocker.commit().await.unwrap();

        let (status, body) = tokio::time::timeout(std::time::Duration::from_secs(4), command)
            .await
            .expect("the command stalled waiting for a second pooled connection")
            .unwrap();
        assert_eq!(status, StatusCode::OK, "{body}");
        for write in writes {
            let (status, body) = tokio::time::timeout(std::time::Duration::from_secs(4), write)
                .await
                .expect("a direct write stalled behind the command")
                .unwrap();
            assert_eq!(status, StatusCode::CREATED, "{body}");
        }
    });
}

#[test]
fn command_trigger_accepts_and_persists_triggered_events() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let request = Request::builder()
            .method("POST")
            .uri("/v1/commands/trigger")
            .header("authorization", format!("Bearer {credential}"))
            .header("content-type", "application/json")
            .body(Body::from(r#"{"payload":{"amount":20}}"#))
            .unwrap();

        let response = router.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(json["accepted"], true);
        let sequences = json["triggeredEventSequences"]
            .as_array()
            .expect("triggeredEventSequences must be present and an array when accepted");
        assert_eq!(sequences.len(), 1);

        // The highest-risk new code path this pass added: reading a
        // stored `command_triggered` origin back reconstructs the whole
        // embedded `Command` correctly, not just the Event's own fields.
        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(events.len(), 1);
        match &events[0].origin {
            skilj_core::event_store::EventOrigin::CommandTriggered { command } => {
                assert_eq!(command.command_type.name, "WithdrawMoney");
                assert_eq!(command.payload, r#"{"amount":20}"#);
            }
            other => panic!("expected a CommandTriggered origin, got {other:?}"),
        }
    });
}

/// issue #12, real end-to-end: a genuine retry with the same
/// `Idempotency-Key` header returns the identical `triggeredEventSequences`
/// and `deduplicated: true`, and only one set of events actually exists -
/// not just that the response looks right, but that nothing was
/// double-applied.
#[test]
fn command_trigger_deduplicates_a_repeated_idempotency_key() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let request = || {
            Request::builder()
                .method("POST")
                .uri("/v1/commands/trigger")
                .header("authorization", format!("Bearer {credential}"))
                .header("content-type", "application/json")
                .header("Idempotency-Key", "retry-1")
                .body(Body::from(r#"{"payload":{"amount":20}}"#))
                .unwrap()
        };

        let first_response = router.clone().oneshot(request()).await.unwrap();
        assert_eq!(first_response.status(), StatusCode::OK);
        let first_body = first_response
            .into_body()
            .collect()
            .await
            .unwrap()
            .to_bytes();
        let first_json: serde_json::Value = serde_json::from_slice(&first_body).unwrap();
        assert_eq!(first_json["accepted"], true);
        assert_eq!(first_json["deduplicated"], false);
        let first_sequences = first_json["triggeredEventSequences"].clone();

        let second_response = router.oneshot(request()).await.unwrap();
        assert_eq!(second_response.status(), StatusCode::OK);
        let second_body = second_response
            .into_body()
            .collect()
            .await
            .unwrap()
            .to_bytes();
        let second_json: serde_json::Value = serde_json::from_slice(&second_body).unwrap();
        assert_eq!(second_json["accepted"], true);
        assert_eq!(
            second_json["deduplicated"], true,
            "a repeated Idempotency-Key must be reported as deduplicated"
        );
        assert_eq!(
            second_json["triggeredEventSequences"], first_sequences,
            "a dedup hit must return the *original* sequences, not a fresh decision"
        );

        // Only one event actually exists - the second request inserted
        // nothing.
        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(
            events.len(),
            1,
            "a deduplicated retry must not double-apply the command"
        );
    });
}

/// Security-review finding on `CrossContextRoute` (docs/architecture.md
/// [ยง36](../../docs/architecture.md#cross-context-route)): a caller-supplied `Idempotency-Key` using the reserved
/// `skilj-cross-context-route:` prefix must be rejected outright, not
/// silently accepted into the same shared `idempotency_keys` table
/// `CrossContextRoute`'s own background task writes into - see
/// `skilj_core::event_store::reject_reserved_idempotency_key`'s own doc
/// comment for why this matters (without it, an ordinary Write-level
/// caller could pre-plant a route's own future key and silently
/// swallow a real cross-context delivery).
#[test]
fn command_trigger_rejects_a_reserved_idempotency_key_prefix() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let request = Request::builder()
            .method("POST")
            .uri("/v1/commands/trigger")
            .header("authorization", format!("Bearer {credential}"))
            .header("content-type", "application/json")
            .header(
                "Idempotency-Key",
                "skilj-cross-context-route:some-other-route:42",
            )
            .body(Body::from(r#"{"payload":{"amount":20}}"#))
            .unwrap();
        let response = router.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "reserved_idempotency_key_prefix");

        // Nothing was written under that key, or at all - the rejection
        // happens before dispatch, the same as any other authorisation
        // failure.
        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(events.len(), 0);
    });
}

/// Real end-to-end proof of the drift audit's #10 fix (`valid_payload` -
/// see project memory `skilj-drift-audit-2026-08-18`): the request body
/// is decoded as generic JSON at the wire layer (`CommandTriggerRequest.
/// payload: serde_json::Value`), so a wrong-typed field like this one
/// reaches `authorise_command_trigger`'s own new `valid_payload` guard
/// rather than failing to deserialize earlier - proving the rejection is
/// real over the actual REST surface, not just at the pure-function
/// layer `skilj-core/tests/command_processing.rs` already covers.
#[test]
fn command_trigger_rejects_a_payload_that_does_not_match_the_schema_with_400() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, _pool, _bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let request = Request::builder()
            .method("POST")
            .uri("/v1/commands/trigger")
            .header("authorization", format!("Bearer {credential}"))
            .header("content-type", "application/json")
            .body(Body::from(r#"{"payload":{"amount":"not a number"}}"#))
            .unwrap();

        let response = router.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "payload_does_not_match_schema");
    });
}

/// Proof, over the real REST surface (not just `skilj-core`'s pure
/// `derive_tags` unit tests), that a bounded context registering a real
/// `tag_mappings` entry and then triggering a matching command no longer
/// panics - `WithdrawMoney::tag_mappings()` above declares a real
/// mapping, and `db::insert_command_and_events`'s round trip is what
/// `process_command`'s own `derive_tags` call feeds into `Command.
/// consistency_tags`/`Event.tags` alike.
#[test]
fn command_trigger_derives_real_tags_from_a_real_tag_mapping() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let request = Request::builder()
            .method("POST")
            .uri("/v1/commands/trigger")
            .header("authorization", format!("Bearer {credential}"))
            .header("content-type", "application/json")
            .body(Body::from(r#"{"payload":{"amount":20}}"#))
            .unwrap();

        let response = router.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);

        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(events.len(), 1);
        match &events[0].origin {
            skilj_core::event_store::EventOrigin::CommandTriggered { command } => {
                assert_eq!(
                    command.consistency_tags,
                    vec![skilj_core::shared::Tag {
                        key: "amount".into(),
                        value: Some("20".into()),
                    }]
                );
            }
            other => panic!("expected a CommandTriggered origin, got {other:?}"),
        }
    });
}

/// Cross-tenant write fix (docs/architecture.md's own write-up of these
/// passes), the real end-to-end proof - the previously open gap this
/// pass closes: `setup()`'s own token has `scope: None`, so this mints a
/// *second*, real `CommandToken` scoped to `"20"` and proves it can no
/// longer trigger `WithdrawMoney` for a *different* owner - over the
/// actual REST surface and a real HTTP status, not just
/// `authorise_command_trigger`'s own pure-function unit tests in
/// `skilj-core/tests/command_processing.rs`. Also the regression test
/// for a real bug this same pass found while writing it:
/// `Error::GrantScopeMismatch` had no entry in `skilj-rest`'s own
/// `status_for` table, so it fell through to 500 instead of 403 the
/// first time this became reachable over REST at all - see that table's
/// own comment.
#[test]
fn command_trigger_rejects_a_command_whose_owner_does_not_match_the_tokens_scope() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, _credential, pool, bc_name, mapping, command_type) = setup().await;
        let scoped_token = access_control::create_command_token(
            &mapping,
            &command_type,
            generate_token_id(),
            generate_token_secret(),
            Some("20".into()),
            test_now(),
        )
        .unwrap();
        db::insert_command_token(&pool, &scoped_token)
            .await
            .unwrap();
        let scoped_credential = format!("{}.{}", scoped_token.id, scoped_token.secret);
        let router = skilj.rest_router();

        let request = Request::builder()
            .method("POST")
            .uri("/v1/commands/trigger")
            .header("authorization", format!("Bearer {scoped_credential}"))
            .header("content-type", "application/json")
            .body(Body::from(r#"{"payload":{"amount":999}}"#))
            .unwrap();

        let response = router.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "grant_scope_mismatch");

        // Nothing was written - a rejected authorisation never reaches
        // process_command at all.
        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert!(events.is_empty());
    });
}

/// The success half of the same obligation - the identical scoped token
/// triggers normally when the payload's own derived owner tag matches.
#[test]
fn command_trigger_succeeds_when_the_owner_matches_the_tokens_scope() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, _credential, pool, bc_name, mapping, command_type) = setup().await;
        let scoped_token = access_control::create_command_token(
            &mapping,
            &command_type,
            generate_token_id(),
            generate_token_secret(),
            Some("20".into()),
            test_now(),
        )
        .unwrap();
        db::insert_command_token(&pool, &scoped_token)
            .await
            .unwrap();
        let scoped_credential = format!("{}.{}", scoped_token.id, scoped_token.secret);
        let router = skilj.rest_router();

        let request = Request::builder()
            .method("POST")
            .uri("/v1/commands/trigger")
            .header("authorization", format!("Bearer {scoped_credential}"))
            .header("content-type", "application/json")
            .body(Body::from(r#"{"payload":{"amount":20}}"#))
            .unwrap();

        let response = router.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["accepted"], true);

        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(events.len(), 1);
    });
}

#[test]
fn command_trigger_returns_a_rejection_as_200_not_an_error() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, _pool, _bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let request = Request::builder()
            .method("POST")
            .uri("/v1/commands/trigger")
            .header("authorization", format!("Bearer {credential}"))
            .header("content-type", "application/json")
            .body(Body::from(r#"{"payload":{"amount":5000}}"#))
            .unwrap();

        let response = router.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(json["accepted"], false);
        assert_eq!(json["rejectionKind"], "insufficient_funds");
        assert!(json.get("triggeredEventSequences").is_none());
    });
}

#[test]
fn command_trigger_rejects_a_malformed_credential() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, _credential, _pool, _bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let request = Request::builder()
            .method("POST")
            .uri("/v1/commands/trigger")
            .header("authorization", "Bearer not-a-real-credential")
            .header("content-type", "application/json")
            .body(Body::from(r#"{"payload":{"amount":20}}"#))
            .unwrap();

        let response = router.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
    });
}

/// `CommandDispatcher::required_role` (ยง1.3.1) after a real reconciliation
/// pass - not exercised over HTTP, since REST triggering never consults
/// it (`CommandToken` is its own, separate grant); this is what
/// `skilj-graphql`'s eventual mutation resolver will call before
/// dispatching ([ยง8](../../docs/architecture.md#open-for-a-future-pass) item 5).
#[test]
fn command_dispatcher_required_role_reflects_the_requires_role_attribute() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, _credential, _pool, bc_name, _, _) = setup().await;
        let dispatcher = skilj.command_dispatcher();

        // #[requires_role("treasury_officer")] on CloseAccount...
        assert_eq!(
            dispatcher.required_role(&bc_name, "CloseAccount"),
            Some(Some("treasury_officer"))
        );
        // ...vs. WithdrawMoney, registered with no attribute at all -
        // still `Some`, since it's a real registered command type, but
        // no extra gate.
        assert_eq!(
            dispatcher.required_role(&bc_name, "WithdrawMoney"),
            Some(None)
        );
        // A name that was never registered at all - the outer `None`,
        // mirroring `dispatch`'s own "pair doesn't match anything"
        // convention.
        assert_eq!(dispatcher.required_role(&bc_name, "NoSuchCommand"), None);
    });
}

/// Every read of many events resolves their origins in one batch - a
/// command-triggered event embeds its whole originating command - where it
/// used to resolve each row's command one at a time, several queries each
/// (docs/architecture.md ยง125). Each such read must still give exactly
/// what the unchanged single-row read gives for every event, over a mix of
/// command-triggered and directly created ones.
#[test]
fn batched_event_reads_match_the_single_row_read() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, command_credential, pool, bc_name, mapping, _) = setup().await;
        let event_type = db::get_event_type(&pool, &bc_name, "MoneyDeposited")
            .await
            .unwrap()
            .unwrap();
        let direct_token = access_control::create_direct_creation_token(
            &mapping,
            &event_type,
            generate_token_id(),
            generate_token_secret(),
            None,
            test_now(),
        )
        .unwrap();
        db::insert_direct_creation_token(&pool, &direct_token)
            .await
            .unwrap();
        let direct_credential = format!("{}.{}", direct_token.id, direct_token.secret);
        let router = skilj.rest_router();
        for i in 0..12 {
            let (uri, credential) = if i % 3 == 2 {
                ("/v1/events/direct", &direct_credential)
            } else {
                ("/v1/commands/trigger", &command_credential)
            };
            let request = Request::builder()
                .method("POST")
                .uri(uri)
                .header("authorization", format!("Bearer {credential}"))
                .header("content-type", "application/json")
                .body(Body::from(format!(r#"{{"payload":{{"amount":{i}}}}}"#)))
                .unwrap();
            let response = router.clone().oneshot(request).await.unwrap();
            assert!(
                response.status().is_success(),
                "{uri}: {}",
                response.status()
            );
        }

        let mut expected = Vec::new();
        for sequence in 0..12 {
            expected.push(
                db::get_event_by_sequence(&pool, &bc_name, sequence)
                    .await
                    .unwrap()
                    .unwrap(),
            );
        }
        assert_eq!(
            expected
                .iter()
                .filter(|e| matches!(
                    e.origin,
                    skilj_core::event_store::EventOrigin::CommandTriggered { .. }
                ))
                .count(),
            8
        );

        assert_eq!(
            db::list_events_for_bounded_context(&pool, &bc_name)
                .await
                .unwrap(),
            expected
        );
        assert_eq!(
            db::list_events_for_bounded_context_from(&pool, &bc_name, 3)
                .await
                .unwrap(),
            expected[4..]
        );
        assert_eq!(
            db::list_events_for_bounded_context_from_limited(&pool, &bc_name, 3, 5)
                .await
                .unwrap(),
            expected[4..9]
        );
        assert_eq!(
            db::list_recent_events_for_bounded_context(&pool, &bc_name, 4)
                .await
                .unwrap(),
            expected[8..]
        );
        assert_eq!(
            db::list_events(&pool, &bc_name, "MoneyDeposited")
                .await
                .unwrap(),
            expected
        );
        assert_eq!(
            db::list_events_from(&pool, &bc_name, "MoneyDeposited", 5)
                .await
                .unwrap(),
            expected[6..]
        );
        assert_eq!(
            db::list_events_from_limited(&pool, &bc_name, "MoneyDeposited", 5, 3)
                .await
                .unwrap(),
            expected[6..9]
        );
    });
}

/// Listing commands resolves their command types in one batch, where it
/// used to resolve each row's type (and that type's bounded context and
/// creator Role) one at a time (docs/architecture.md ยง126). The listing
/// and a `fetchCommands` page walked in chunks of 3 must each give exactly
/// what the single-row read gives, in recording order.
#[test]
fn batched_command_reads_match_the_single_row_read() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let router = skilj.rest_router();
        for i in 0..8 {
            let request = Request::builder()
                .method("POST")
                .uri("/v1/commands/trigger")
                .header("authorization", format!("Bearer {credential}"))
                .header("content-type", "application/json")
                .body(Body::from(format!(r#"{{"payload":{{"amount":{i}}}}}"#)))
                .unwrap();
            let response = router.clone().oneshot(request).await.unwrap();
            assert_eq!(response.status(), StatusCode::OK);
        }

        let listed = db::list_commands_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(listed.len(), 8);
        for command in &listed {
            assert_eq!(
                Some(command),
                db::get_command_by_external_id(&pool, &bc_name, &command.id)
                    .await
                    .unwrap()
                    .as_ref()
            );
        }

        let mut walked = Vec::new();
        let page = db::collect_command_page(&pool, &bc_name, -1, 3, |chunk, remaining| {
            walked.extend(chunk.iter().cloned());
            Ok(chunk.iter().take(remaining).cloned().collect())
        })
        .await
        .unwrap();
        assert_eq!(page, listed[..3]);
        assert_eq!(walked, listed[..3]);
        let mut all = Vec::new();
        db::collect_command_page(&pool, &bc_name, -1, 100, |chunk, _| {
            all.extend(chunk.iter().cloned());
            Ok(Vec::new())
        })
        .await
        .unwrap();
        assert_eq!(all, listed);
    });
}

/// An `Idempotency-Key` longer than 255 characters is a 400 before
/// anything runs (docs/architecture.md ยง134).
#[test]
fn command_trigger_refuses_an_overlong_idempotency_key() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let request = Request::builder()
            .method("POST")
            .uri("/v1/commands/trigger")
            .header("authorization", format!("Bearer {credential}"))
            .header("content-type", "application/json")
            .header("Idempotency-Key", "k".repeat(256))
            .body(Body::from(r#"{"payload":{"amount":20}}"#))
            .unwrap();
        let response = skilj.rest_router().oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["code"], "idempotency_key_too_long");
        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(events.len(), 0);
    });
}

/// issue #47, `rule DryRunTriggerCommand`: `POST
/// /v1/commands/dry-run` answers what a trigger with this token would
/// decide - and only that - while writing nothing. Both outcomes, then
/// a real trigger to show the dry-runs used up nothing: the first real
/// event still gets the first sequence, and no command row exists from
/// before it.
#[test]
fn command_dry_run_answers_the_outcome_only_and_persists_nothing() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let post = |uri: &'static str, body: &'static str| {
            let router = router.clone();
            let credential = credential.clone();
            async move {
                let request = Request::builder()
                    .method("POST")
                    .uri(uri)
                    .header("authorization", format!("Bearer {credential}"))
                    .header("content-type", "application/json")
                    .body(Body::from(body))
                    .unwrap();
                let response = router.oneshot(request).await.unwrap();
                let status = response.status();
                let body = response.into_body().collect().await.unwrap().to_bytes();
                (
                    status,
                    serde_json::from_slice::<serde_json::Value>(&body).unwrap(),
                )
            }
        };

        let (status, json) = post("/v1/commands/dry-run", r#"{"payload":{"amount":20}}"#).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(json, serde_json::json!({ "accepted": true }));

        let (status, json) = post("/v1/commands/dry-run", r#"{"payload":{"amount":5000}}"#).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(
            json,
            serde_json::json!({
                "accepted": false,
                "rejectionReason": "insufficient funds",
                "rejectionKind": "insufficient_funds",
            })
        );

        assert!(db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap()
            .is_empty());
        assert!(db::list_commands_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap()
            .is_empty());

        let (status, json) = post("/v1/commands/trigger", r#"{"payload":{"amount":20}}"#).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(json["triggeredEventSequences"], serde_json::json!([0]));
        assert_eq!(
            db::list_commands_for_bounded_context(&pool, &bc_name)
                .await
                .unwrap()
                .len(),
            1
        );

        // The schema is checked as for a trigger.
        let (status, _) = post("/v1/commands/dry-run", r#"{"payload":{"amount":"x"}}"#).await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
    });
}

/// `POST /v1/commands/trigger/batch` with `body`, answered as JSON.
async fn trigger_batch(
    router: &axum::Router,
    credential: &str,
    body: serde_json::Value,
) -> (StatusCode, serde_json::Value) {
    let request = Request::builder()
        .method("POST")
        .uri("/v1/commands/trigger/batch")
        .header("authorization", format!("Bearer {credential}"))
        .header("content-type", "application/json")
        .body(Body::from(body.to_string()))
        .unwrap();
    let response = router.clone().oneshot(request).await.unwrap();
    let status = response.status();
    let body = response.into_body().collect().await.unwrap().to_bytes();
    (status, serde_json::from_slice(&body).unwrap())
}

/// docs/architecture.md ยง227: every command answered in order, each as a
/// single trigger would answer it - an acceptance, a rejection, and a
/// payload off the schema refused with the status a single trigger gets -
/// and the refused one doesn't stop the command after it.
#[test]
fn a_trigger_batch_answers_each_command_in_order() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let (status, json) = trigger_batch(
            &router,
            &credential,
            serde_json::json!({ "commands": [
                { "payload": { "amount": 20 } },
                { "payload": { "amount": 5000 } },
                { "payload": { "amount": "twenty" } },
                { "payload": { "amount": 30 }, "correlationId": "batch-corr" },
            ]}),
        )
        .await;
        assert_eq!(status, StatusCode::OK, "{json}");
        let outcomes = json["outcomes"].as_array().unwrap();
        assert_eq!(outcomes.len(), 4, "{json}");
        assert_eq!(outcomes[0]["accepted"], true);
        assert_eq!(outcomes[1]["accepted"], false);
        assert_eq!(outcomes[1]["rejectionKind"], "insufficient_funds");
        assert_eq!(outcomes[2]["error"]["status"], 400, "{json}");
        assert!(outcomes[2]["error"]["code"].is_string());
        assert_eq!(outcomes[3]["accepted"], true);
        assert_eq!(outcomes[3]["correlationId"], "batch-corr");

        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        let amounts: Vec<String> = events.iter().map(|e| e.payload.clone()).collect();
        assert_eq!(amounts, vec![r#"{"amount":20}"#, r#"{"amount":30}"#]);
        assert_eq!(
            outcomes[0]["triggeredEventSequences"][0],
            events[0].sequence
        );
        assert_eq!(
            outcomes[3]["triggeredEventSequences"][0],
            events[1].sequence
        );
    });
}

/// A key an earlier command of the same batch was accepted under
/// deduplicates the later one, as two single triggers would; resending
/// the batch deduplicates both.
#[test]
fn a_trigger_batch_deduplicates_keys_within_and_across_batches() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let router = skilj.rest_router();
        let body = serde_json::json!({ "commands": [
            { "payload": { "amount": 20 }, "idempotencyKey": "k-1" },
            { "payload": { "amount": 20 }, "idempotencyKey": "k-1" },
        ]});

        let (status, first) = trigger_batch(&router, &credential, body.clone()).await;
        assert_eq!(status, StatusCode::OK, "{first}");
        assert_eq!(first["outcomes"][0]["deduplicated"], false);
        assert_eq!(first["outcomes"][1]["deduplicated"], true);
        assert_eq!(
            first["outcomes"][1]["triggeredEventSequences"],
            first["outcomes"][0]["triggeredEventSequences"]
        );

        let (_, again) = trigger_batch(&router, &credential, body).await;
        assert_eq!(again["outcomes"][0]["deduplicated"], true);
        assert_eq!(again["outcomes"][1]["deduplicated"], true);

        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(events.len(), 1);
    });
}

/// Over `max_items_per_batch` (100 by default) the batch is refused
/// whole, nothing processed; an empty one is answered with no outcomes;
/// a reserved key is refused for its own command only.
#[test]
fn a_trigger_batch_over_the_limit_is_refused_whole() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let commands: Vec<_> = (0..101)
            .map(|_| serde_json::json!({ "payload": { "amount": 1 } }))
            .collect();
        let (status, json) = trigger_batch(
            &router,
            &credential,
            serde_json::json!({ "commands": commands }),
        )
        .await;
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(json["code"], "batch_too_large");

        let (status, json) =
            trigger_batch(&router, &credential, serde_json::json!({ "commands": [] })).await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(json["outcomes"], serde_json::json!([]));

        let (_, json) = trigger_batch(
            &router,
            &credential,
            serde_json::json!({ "commands": [
                { "payload": { "amount": 1 }, "idempotencyKey": "skilj-cross-context-route:x" },
                { "payload": { "amount": 2 } },
            ]}),
        )
        .await;
        assert_eq!(json["outcomes"][0]["error"]["status"], 400, "{json}");
        assert_eq!(json["outcomes"][1]["accepted"], true, "{json}");

        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(events.len(), 1);
    });
}

/// docs/architecture.md ยง227: with `stopAtFirstFailure`, the commands after
/// the first refused one answer `not_processed` (409) and are not
/// triggered; sent again, they are.
#[test]
fn a_trigger_batch_can_stop_at_its_first_failure() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let router = skilj.rest_router();

        let (status, json) = trigger_batch(
            &router,
            &credential,
            serde_json::json!({ "stopAtFirstFailure": true, "commands": [
                { "payload": { "amount": 20 } },
                { "payload": { "amount": 5000 } },
                { "payload": { "amount": "twenty" } },
                { "payload": { "amount": 30 } },
            ]}),
        )
        .await;
        assert_eq!(status, StatusCode::OK, "{json}");
        let outcomes = json["outcomes"].as_array().unwrap();
        assert_eq!(outcomes[0]["accepted"], true);
        // A rejection is an answer, not a failure: it doesn't stop the batch.
        assert_eq!(outcomes[1]["accepted"], false);
        assert_eq!(outcomes[2]["error"]["status"], 400, "{json}");
        assert_eq!(outcomes[3]["error"]["status"], 409, "{json}");
        assert_eq!(outcomes[3]["error"]["code"], "not_processed");

        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(events.len(), 1);
    });
}

/// `rest_router()` served on a local port, for an HTTP client.
async fn serve_rest(skilj: &Skilj) -> String {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let url = format!("http://{}", listener.local_addr().unwrap());
    let router = skilj.rest_router();
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
    url
}

/// docs/architecture.md ยง227: the bridges' batch client against the real
/// route - a rejection is done, the first refused command stops the count,
/// and nothing after it was triggered.
#[test]
fn the_bridges_batch_client_counts_what_the_trigger_route_got_done() {
    runtime().block_on(async {
        if test_db().await.is_none() {
            return;
        }
        let (skilj, credential, pool, bc_name, _, _) = setup().await;
        let url = serve_rest(&skilj).await;
        let mapping = skilj_bridge::InboundMapping {
            credential,
            action: skilj_bridge::InboundAction::Trigger {
                command_type: "WithdrawMoney".to_string(),
            },
        };
        let bodies = [
            serde_json::json!({ "payload": { "amount": 20 } }),
            serde_json::json!({ "payload": { "amount": 5000 } }),
            serde_json::json!({ "payload": { "amount": "twenty" } }),
            serde_json::json!({ "payload": { "amount": 30 } }),
        ];
        let keys = ["m-1", "m-2", "m-3", "m-4"];
        let items: Vec<_> = bodies
            .iter()
            .zip(keys)
            .map(|(body, key)| skilj_bridge::InboundItem {
                body,
                idempotency_key: Some(key),
            })
            .collect();
        let batcher = skilj_bridge::InboundBatcher::new(skilj_bridge::InboundBatching::default());
        let done = skilj_bridge::post_inbound_batch(
            &reqwest::Client::new(),
            &url,
            &mapping,
            &batcher,
            &items,
        )
        .await;
        assert_eq!(done, 2);
        assert_eq!(batcher.max_items(), 100);
        let events = db::list_events_for_bounded_context(&pool, &bc_name)
            .await
            .unwrap();
        assert_eq!(events.len(), 1);

        // Sent again from the start: the keyed one is a duplicate, still done.
        let done = skilj_bridge::post_inbound_batch(
            &reqwest::Client::new(),
            &url,
            &mapping,
            &batcher,
            &items[..2],
        )
        .await;
        assert_eq!(done, 2);
        assert_eq!(
            db::list_events_for_bounded_context(&pool, &bc_name)
                .await
                .unwrap()
                .len(),
            1
        );
    });
}