jmap-server 0.5.0

Backend-agnostic JMAP server framework (RFC 8620): parsing, ResultReference resolution, and Dispatcher
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
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
//! Backend-agnostic JMAP server framework (RFC 8620).
//!
//! Provides request parsing, ResultReference resolution, HTTP response helpers,
//! the [`Dispatcher`] machinery, shared backend infrastructure, and generic
//! JMAP method handlers.
//!
//! # Version coupling with `jmap-types` (bd:JMAP-wlip.18)
//!
//! This crate re-exports the wire-format types from `jmap-types`
//! (`Id`, `JmapError`, `JmapRequest`, `JmapResponse`, `Invocation`,
//! `PushSubscription`, `ResultReference`, `Argument`, `State`, `UTCDate`)
//! plus the marker traits (`GetObject`, `JmapObject`, `QueryObject`,
//! `SetObject`).
//! The public API of this crate is therefore *coupled* to
//! `jmap-types`' public API: any breaking change to a re-exported
//! type in `jmap-types` is a breaking change here, even when this
//! crate's own surface is otherwise additive.
//!
//! **SemVer pin discipline**: consumers that depend on both
//! `jmap-server` and `jmap-types` directly MUST pin the `jmap-types`
//! version to the exact version `jmap-server` resolves to. The
//! simplest path is to NOT depend on `jmap-types` directly and use
//! `jmap_server::{Id, JmapError, ...}` instead — re-exports
//! guarantee consistency. Depending on both with mismatched versions
//! produces cargo's "expected `jmap_types::Id`, found `jmap_types::Id`"
//! error (same type name, two different version hashes).

#![forbid(unsafe_code)]

pub use jmap_types::{
    Argument, Id, Invocation, JmapError, JmapRequest, JmapResponse, PushSubscription,
    ResultReference, State, UTCDate,
};

mod backend;
mod handlers;
mod helpers;

pub use backend::{
    AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesParams,
    ChangesResult, GetObject, JmapBackend, JmapObject, QueryChangesParams, QueryChangesResult,
    QueryObject, QueryParams, QueryResult, ReservedExtrasKey, SetError, SetErrorType, SetObject,
    backend_set_error_value,
};
pub use handlers::{
    SERVER_FAIL_INTERNAL_DESC, changes_error_from_backend, handle_changes, handle_get,
    handle_get_with_metadata, handle_query, handle_query_changes, server_fail_from_backend,
    server_fail_value_from_backend,
};
pub use helpers::{
    CREATE_ID_PLACEHOLDER, MergePatchError, MetadataProjection, PatchPathError, apply_jmap_patch,
    apply_patch_object, bool_arg, check_patch_paths, check_read_only_patch,
    enforce_max_objects_in_get, enforce_max_objects_in_set, extract_account_id, filter_arg,
    is_client_updatable, json_merge_patch, json_type_name, limit_or_max, not_found_json,
    now_utc_string, now_utc_string_checked, optional_arg, parse_max_changes, parse_wire_id,
    query_anchor_args, reject_did_bearing_properties, reject_metadata_filter_arg,
    reject_metadata_filter_without_capability, reject_read_only_patch, reject_server_set,
    resolve_creation_ref, resolve_query_offset, resolve_query_start, serialize_value,
    strip_read_only_patch, take_bool_arg, uses_metadata, utc_date_from_epoch_seconds,
};

mod parse;
mod push;
mod response;

pub use parse::{check_known_capabilities, parse_request, parse_request_bytes, resolve_args};
pub use push::{
    MAX_PUSH_EXPIRY_SECS, PushSubscriptionBackend, StoredPushSubscription, is_deliverable,
    register_push_subscription_handlers, state_change_for,
};
pub use response::{RequestError, error_invocation, error_status, request_error};

use std::{
    collections::{BTreeMap, HashMap},
    fmt,
    future::Future,
    pin::Pin,
    sync::Arc,
};

use serde_json::Value;
use tokio::task;

/// The successful result of one [`JmapHandler::call`].
///
/// `#[non_exhaustive]` so fields can be added without breaking handler
/// crates; build it with [`HandlerOutput::new`] and
/// [`HandlerOutput::with_extra`].
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct HandlerOutput {
    /// The method's response arguments. The dispatcher pairs this with the
    /// call's method name and call id as the primary response invocation.
    pub primary: Value,
    /// Zero or more invocations appended to `methodResponses` immediately
    /// after the primary response, in order. Most handlers leave this
    /// empty. RFC 8621 §7.5 `EmailSubmission/set` uses it for the implicit
    /// `Email/set` response for `onSuccessUpdateEmail`.
    pub extra_invocations: Vec<Invocation>,
}

impl HandlerOutput {
    /// A handler result with only a primary response.
    pub fn new(primary: Value) -> Self {
        Self {
            primary,
            extra_invocations: Vec::new(),
        }
    }

    /// Set the invocations to append after the primary response.
    pub fn with_extra(mut self, extra_invocations: Vec<Invocation>) -> Self {
        self.extra_invocations = extra_invocations;
        self
    }
}

/// The return type for all [`JmapHandler`] implementations.
///
/// Handlers must return a `Send` future.  The concrete type is a heap-allocated
/// trait object so the trait itself remains object-safe.
pub type HandlerFuture = Pin<Box<dyn Future<Output = Result<HandlerOutput, JmapError>> + Send>>;

/// Everything [`Dispatcher::dispatch`] hands a [`JmapHandler`] for one
/// method call (RFC 8620 §3.2 Invocation, plus the caller).
///
/// `#[non_exhaustive]` so the dispatcher can pass more per-call context
/// (a deadline, a tracing span, the request's creation ids) without
/// breaking every handler (bd:JMAP-wf92.7). Handlers read the public
/// fields; code that calls a handler directly builds one with
/// [`CallContext::new`].
///
/// Fields are owned because the returned [`HandlerFuture`] is
/// `'static`.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct CallContext<CallerCtx> {
    /// The registered method name for this call. One handler may be
    /// registered under several names (e.g. `"Foo/get"` and
    /// `"Bar/get"`); this tells them apart.
    pub method: String,
    /// The client-supplied method call id (RFC 8620 §3.2). The
    /// dispatcher echoes it in the response; handlers may use it for
    /// logging or correlation.
    pub call_id: String,
    /// The call's arguments, with result references already resolved
    /// (RFC 8620 §3.7).
    pub args: Value,
    /// Whatever the auth layer produced, passed to
    /// [`Dispatcher::dispatch`] and cloned for each call.
    pub caller: CallerCtx,
    /// Creation id to server-assigned id for every record created
    /// earlier in this request, plus the client's initial `createdIds`
    /// (RFC 8620 §3.3, §5.3). A `/set` handler resolves `#`-prefixed
    /// Id-typed values against it with [`resolve_creation_ref`]; the
    /// dispatcher cannot, because only the handler knows which
    /// properties are Id-typed (bd:JMAP-8ypy).
    pub created_ids: BTreeMap<Id, Id>,
    /// The request's `using` capability URIs (RFC 8620 §3.3). Extensions
    /// change method behaviour per request on it; e.g.
    /// draft-ietf-jmap-metadata-05 §3 extends `Foo/changes` only for
    /// requests whose `using` includes `urn:ietf:params:jmap:metadata`.
    pub using: Vec<String>,
}

impl<CallerCtx> CallContext<CallerCtx> {
    /// A context for one method call.
    pub fn new(
        method: impl Into<String>,
        call_id: impl Into<String>,
        args: Value,
        caller: CallerCtx,
    ) -> Self {
        Self {
            method: method.into(),
            call_id: call_id.into(),
            args,
            caller,
            created_ids: BTreeMap::new(),
            using: Vec::new(),
        }
    }

    /// Set [`CallContext::created_ids`]; [`CallContext::new`] leaves it
    /// empty.
    pub fn with_created_ids(mut self, created_ids: BTreeMap<Id, Id>) -> Self {
        self.created_ids = created_ids;
        self
    }

    /// Set [`CallContext::using`]; [`CallContext::new`] leaves it empty.
    pub fn with_using(mut self, using: Vec<String>) -> Self {
        self.using = using;
        self
    }
}

/// Implement this for each JMAP method handler.
///
/// `CallerCtx` is whatever your auth layer produces — an `Identity`, a session
/// token, `()`, etc. The dispatcher passes it through unchanged.
///
/// # /set response contract
///
/// Handlers for `/set` methods (RFC 8620 §5.3) that create objects MUST include
/// an `"id"` field (type string) in each entry of the `"created"` map.  The
/// dispatcher reads this field to accumulate `createdIds` in the response.
/// Entries without an `"id"` field are silently skipped — the dispatcher cannot
/// retroactively error a method call that already returned success.
pub trait JmapHandler<CallerCtx>: Send + Sync {
    /// Handle one method call. See [`CallContext`] for what `cx` carries.
    fn call(&self, cx: CallContext<CallerCtx>) -> HandlerFuture;
}

/// Walk a `/set` handler's primary response and accumulate every
/// `created[client_id].id` pair into `sink` (RFC 8620 §3.4
/// `createdIds`) (bd:JMAP-wlip.10).
///
/// Lives next to the [`JmapHandler`] doc contract that requires
/// every entry of `created` to contain a string `"id"` field. Entries
/// that violate the contract — no `"id"` key, or an `"id"` of a
/// non-string type — are silently skipped, because the dispatcher
/// cannot produce a method-level error for a method call that already
/// succeeded. The shared helper makes the silent-skip behaviour
/// auditable in one place rather than inlined in the dispatcher loop.
///
/// Non-`/set` primary responses (no `"created"` key at the top level,
/// or `"created"` of a non-Object type) leave `sink` unchanged.
///
/// Collision semantics (bd:JMAP-jfia.3): when a creationId in the
/// `/set` response collides with an entry already in `sink` — whether
/// from an earlier `/set` call in the same batch OR from the client's
/// pre-populated `createdIds` map — `BTreeMap::insert` silently
/// overwrites: last write wins. The pre-populated collision case is
/// exercised by
/// [`tests::created_ids_pre_populated_collision_last_write_wins`].
/// See the dispatcher call site for the full rationale.
fn extract_created_ids_into(primary: &Value, sink: &mut BTreeMap<Id, Id>) {
    let Some(map) = primary.get("created").and_then(|v| v.as_object()) else {
        return;
    };
    for (client_id, created_obj) in map {
        if let Some(id_val) = created_obj.get("id").and_then(|v| v.as_str()) {
            sink.insert(Id::from(client_id.as_str()), Id::from(id_val));
        }
    }
}

/// Dispatches a [`JmapRequest`] to registered method handlers.
///
/// Register handlers with [`Dispatcher::register`], then call
/// [`Dispatcher::dispatch`] per request.  `CallerCtx` is cloned for each
/// method call in the batch, so it must be `Clone`.
///
/// `CallerCtx` must also be `'static` because each handler call is spawned as
/// a [`tokio::task`].  To share non-static data (e.g. a database connection),
/// wrap it in `Arc<T>` — `Arc` is `Clone + Send + 'static` when `T: Send + Sync`.
///
/// # Thread safety
///
/// `Dispatcher` is both `Send` and `Sync`.  Register handlers on one thread,
/// then wrap in `Arc` and share across tasks — `dispatch` takes `&self` and is
/// safe to call concurrently.
pub struct Dispatcher<CallerCtx> {
    handlers: HashMap<String, Arc<dyn JmapHandler<CallerCtx>>>,
    guard: Option<MethodGuard<CallerCtx>>,
}

type MethodGuard<CallerCtx> = Box<dyn Fn(&str, &CallerCtx) -> Result<(), JmapError> + Send + Sync>;

/// Returned by [`Dispatcher::try_register`] when a handler is already
/// registered under the requested method name.
///
/// Added in bd:JMAP-jfia.4 alongside `try_register` to make the
/// duplicate-registration foot-gun explicit at the call site rather
/// than silently dropping a binding.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DuplicateMethodError {
    /// The method name that was already registered.
    pub method: String,
}

impl std::fmt::Display for DuplicateMethodError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "handler already registered for method {:?}", self.method)
    }
}

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

impl<CallerCtx: Clone + Send + 'static> Dispatcher<CallerCtx> {
    /// Create an empty dispatcher with no registered handlers.
    pub fn new() -> Self {
        Self {
            handlers: HashMap::new(),
            guard: None,
        }
    }

    /// Install a guard that every method call must pass before its handler
    /// runs.
    ///
    /// [`Dispatcher::dispatch`] calls `guard` with the method name and the
    /// caller after resolving the call's result references and before
    /// looking up its handler. An `Err` becomes that call's error response
    /// (RFC 8620 §3.6.2), in its place in `methodResponses`; the handler
    /// does not run, and later calls in the batch are still processed.
    /// A rejected call produces no result for later references to resolve
    /// against (RFC 8620 §3.7).
    ///
    /// Without a guard every call reaches its handler. Setting a guard
    /// again replaces the previous one.
    pub fn set_guard(
        &mut self,
        guard: impl Fn(&str, &CallerCtx) -> Result<(), JmapError> + Send + Sync + 'static,
    ) {
        self.guard = Some(Box::new(guard));
    }

    /// Register a handler for the given method name.
    ///
    /// **Registering the same name twice silently replaces the earlier
    /// handler.** This is a real foot-gun in the workspace pattern where
    /// each extension crate ships a `register_*_handlers` macro that
    /// registers ~10 method names against a single `Dispatcher`: a typo
    /// or accidental double-registration drops one binding with no
    /// diagnostic, and the handler that "never fires" is hard to debug
    /// (bd:JMAP-jfia.4). Prefer [`Dispatcher::try_register`] in new
    /// code; `register` is kept for ergonomic call sites where the
    /// silent-overwrite is the deliberate choice (e.g. a test fixture
    /// that overrides a handler for a specific scenario).
    ///
    /// Using `Arc` rather than `Box` allows the same handler instance to be
    /// shared across multiple method name registrations (via `Arc::clone`).
    pub fn register(
        &mut self,
        method: impl Into<String>,
        handler: Arc<dyn JmapHandler<CallerCtx>>,
    ) {
        self.handlers.insert(method.into(), handler);
    }

    /// Register a handler for the given method name, returning an error
    /// if the method name is already registered.
    ///
    /// This is the recommended registration entry point for production
    /// code paths (bd:JMAP-jfia.4). Unlike [`Dispatcher::register`], a
    /// duplicate method name produces
    /// [`DuplicateMethodError`] rather than silently replacing the
    /// existing handler, surfacing the collision at the call site that
    /// caused it.
    ///
    /// On `Err(DuplicateMethodError)` the dispatcher's handler map is
    /// left unchanged — the existing handler is preserved and the
    /// would-be registration is dropped.
    ///
    /// Using `Arc` rather than `Box` allows the same handler instance to be
    /// shared across multiple method name registrations (via `Arc::clone`).
    ///
    /// # Errors
    ///
    /// Returns [`DuplicateMethodError`] when `method` is already
    /// registered.
    pub fn try_register(
        &mut self,
        method: impl Into<String>,
        handler: Arc<dyn JmapHandler<CallerCtx>>,
    ) -> Result<(), DuplicateMethodError> {
        let method = method.into();
        if self.handlers.contains_key(&method) {
            return Err(DuplicateMethodError { method });
        }
        self.handlers.insert(method, handler);
        Ok(())
    }

    /// Process a validated [`JmapRequest`] and return a [`JmapResponse`].
    ///
    /// Method calls are processed sequentially per RFC 8620 §3.3.  Each
    /// handler runs in a `tokio::task::spawn` for panic isolation: a panicking
    /// handler returns a `serverFail` invocation rather than crashing the
    /// connection task, and emits one `tracing::error!` event with only the
    /// `method` and `call_id` fields (never the panic payload or arguments).
    ///
    /// `CallerCtx` must be `Clone + Send + 'static`; see the struct-level doc.
    ///
    /// # Runtime requirement (bd:JMAP-jfia.24)
    ///
    /// `dispatch` invokes [`tokio::task::spawn`] internally and
    /// therefore **requires a Tokio runtime in scope at the call
    /// site**. The async-fn signature itself does not advertise this
    /// requirement — there is no `?Send` async-trait bound and no
    /// `Spawner` parameter — but calling `dispatch` without a Tokio
    /// runtime will panic at the first method call with a
    /// `there is no reactor running` error.
    ///
    /// This is a structural coupling to the Tokio ecosystem.
    /// Production consumers running under `tokio::main` /
    /// `Runtime::block_on` already satisfy this; consumers
    /// experimenting with alternative runtimes (`async-std`,
    /// `smol`, `embassy`, etc.) cannot use `Dispatcher` without
    /// either a Tokio compat shim or a custom dispatcher
    /// re-implementation. Decoupling the spawn mechanism is a
    /// major-bump API change tracked separately.
    ///
    /// # Cancellation
    ///
    /// Dropping the future returned by `dispatch` does **not** cancel
    /// method calls that are already running (bd:JMAP-wlip.34). Each
    /// call runs in its own [`tokio::task::spawn`]ed task, and tokio
    /// does not abort a task when its `JoinHandle` is dropped, so a
    /// running call finishes and only its response is lost. Calls
    /// later in the batch that had not started yet are never run.
    ///
    /// This is deliberate: a client that disconnects (for example,
    /// the HTTP connection closes) can never interrupt a backend
    /// mid-write and leave a `/set` half applied. `dispatch` takes no
    /// cancellation token, and [`JmapHandler::call`] receives none.
    ///
    /// The cost is that a disconnected client cannot stop an
    /// expensive call (a large `Email/query`, a slow full-text
    /// search): the backend does the full work anyway, and a client
    /// that opens and drops many requests can use this to consume
    /// server resources. Bound that cost in the backend, for example
    /// with `tokio::time::timeout` or an RPC deadline around each
    /// storage call, and limit request concurrency per client.
    ///
    /// For a clean shutdown, stop accepting new requests and let
    /// in-flight `dispatch` calls and their spawned tasks finish; a
    /// shutdown signal that drops `dispatch` futures does not reach
    /// the spawned tasks.
    pub async fn dispatch(
        &self,
        request: JmapRequest,
        caller: CallerCtx,
        session_state: State,
    ) -> JmapResponse {
        let mut method_responses: Vec<Invocation> = Vec::with_capacity(request.method_calls.len());
        let client_sent_created_ids = request.created_ids.is_some();
        let mut created_ids: BTreeMap<Id, Id> = request.created_ids.unwrap_or_default();

        for Invocation {
            name: method,
            arguments: mut args,
            call_id,
        } in request.method_calls
        {
            // Resolve ResultReferences from prior responses.
            if let Err(e) = resolve_args(&mut args, &method_responses)
                .and_then(|()| parse::check_filter_depth(&args))
            {
                method_responses.push(error_invocation(&call_id, e));
                continue;
            }

            if let Some(Err(e)) = self.guard.as_ref().map(|guard| guard(&method, &caller)) {
                method_responses.push(error_invocation(&call_id, e));
                continue;
            }

            // Look up the handler.
            let Some(handler) = self.handlers.get(&method).map(Arc::clone) else {
                method_responses.push(error_invocation(&call_id, JmapError::unknown_method()));
                continue;
            };

            let caller_clone = caller.clone();
            let method_clone = method.clone();
            let call_id_clone = call_id.clone();
            // ponytail: clones the map per call; it is bounded by
            // maxCallsInRequest x maxObjectsInSet. Arc it if that grows.
            let created_ids_snapshot = created_ids.clone();
            let using = request.using.clone();

            // Run in a spawned task for panic isolation.
            let result: Result<Result<HandlerOutput, JmapError>, tokio::task::JoinError> =
                task::spawn(async move {
                    handler
                        .call(
                            CallContext::new(method_clone, call_id_clone, args, caller_clone)
                                .with_created_ids(created_ids_snapshot)
                                .with_using(using),
                        )
                        .await
                })
                .await;

            match result {
                Ok(Ok(HandlerOutput {
                    primary: primary_value,
                    extra_invocations,
                })) => {
                    // Accumulate createdIds from every /set response: RFC 8620
                    // §5.3 says the server "MUST keep a simple map for the
                    // duration of the request" so later calls can resolve
                    // "#" references (bd:JMAP-8ypy). The map is echoed in
                    // the response only when the client sent createdIds
                    // (RFC 8620 §3.4).
                    //
                    // Duplicate-creationId behaviour (bd:JMAP-wlip.7,
                    // bd:JMAP-jfia.3): BTreeMap::insert silently overwrites
                    // on duplicate key. Two flavours of duplicate:
                    //
                    //   (a) Intra-batch: a client reuses the same
                    //   creationId across two /set calls in the same
                    //   batch (e.g. "c1" in both Mailbox/set and
                    //   Email/set). The second mapping wins and the
                    //   first is lost.
                    //
                    //   (b) Pre-populated collision: a client
                    //   pre-populates createdIds with X->A and a /set
                    //   call in the same batch returns X->B (B != A).
                    //   The /set value wins and the pre-populated A is
                    //   lost. This is reachable via long-lived
                    //   background tasks replaying a queued request
                    //   whose creationIds overlap with the current
                    //   session's batch.
                    //
                    // RFC 8620 §3.4 does not explicitly require either
                    // last-write-wins or rejection; the convention here
                    // is last-write-wins because (a) the response order
                    // is deterministic so the behaviour is at least
                    // reproducible, (b) detecting either flavour of
                    // duplicate would require either a per-batch
                    // creationId pre-check (adds a HashSet allocation
                    // per request) or a second pass over
                    // method_responses after dispatch, and (c) this
                    // crate is the canonical foundation for every
                    // *-server extension — a wire-behaviour change
                    // (e.g. reject-on-collision) would ripple to every
                    // downstream consumer and is out of scope for a
                    // foundation crate without an RFC mandate.
                    //
                    // Clients SHOULD generate unique creationIds across
                    // a batch and SHOULD NOT pre-populate creationIds
                    // that any /set call in the same batch will
                    // produce. Both collision flavours are exercised
                    // explicitly by
                    // [`tests::created_ids_intra_batch_collision_last_write_wins`]
                    // and
                    // [`tests::created_ids_pre_populated_collision_last_write_wins`]
                    // so a future refactor that flips the order is
                    // caught.
                    extract_created_ids_into(&primary_value, &mut created_ids);
                    // Push the primary response first, then any extra invocations
                    // appended by the handler (e.g. onSuccessUpdateEmail from
                    // EmailSubmission/set, RFC 8621 §7.5).  Order is preserved.
                    method_responses.push(Invocation::new(method, primary_value, call_id));
                    method_responses.extend(extra_invocations);
                }
                Ok(Err(e)) => {
                    method_responses.push(error_invocation(&call_id, e));
                }
                Err(join_err) => {
                    // Panics and cancellations both map to serverFail, but with
                    // distinct descriptions to aid server-side diagnostics.
                    let desc = if join_err.is_cancelled() {
                        "task cancelled"
                    } else {
                        "internal error"
                    };
                    // Side channel so operators can tell a caught panic from a
                    // handler's own serverFail (bd:JMAP-jfia.29). Only the
                    // method name and call id: the panic payload and the
                    // arguments may carry secrets. Passed as `&str` so text
                    // formatters escape the client-chosen call id.
                    if join_err.is_panic() {
                        tracing::error!(
                            method = method.as_str(),
                            call_id = call_id.as_str(),
                            "method handler panicked"
                        );
                    }
                    method_responses.push(error_invocation(&call_id, JmapError::server_fail(desc)));
                }
            }
        }

        let created_ids = client_sent_created_ids.then_some(created_ids);

        JmapResponse::new(method_responses, session_state, created_ids)
    }
}

impl<CallerCtx: Clone + Send + 'static> Default for Dispatcher<CallerCtx> {
    fn default() -> Self {
        Self::new()
    }
}

impl<CallerCtx> fmt::Debug for Dispatcher<CallerCtx> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Dispatcher")
            .field("methods", &self.handlers.keys())
            .field("guard", &self.guard.is_some())
            .finish()
    }
}

// ---------------------------------------------------------------------------
// ClosureHandler — generic backend-wrapping JmapHandler that forwards CallerCtx
// ---------------------------------------------------------------------------

/// Type alias for the closure stored inside [`ClosureHandler`].
///
/// The closure gets the shared backend and the call's [`CallContext`]
/// (method name, call id, arguments and caller). Taking the context as
/// one `#[non_exhaustive]` struct lets the dispatcher pass more per-call
/// context later without changing this signature (bd:JMAP-wf92.7).
pub type BackendCallFn<B, C> =
    dyn Fn(Arc<B>, CallContext<C>) -> HandlerFuture + Send + Sync + 'static;

/// A [`JmapHandler`] that wraps an async closure over a shared backend and
/// forwards `CallerCtx` to it.
///
/// Use this when your handler closures need per-request context — for
/// example, an auth identity that controls which data the handler can
/// access. The closure receives the whole [`CallContext`] and reads the
/// fields it needs.
///
/// # Usage
///
/// ```rust,ignore
/// use jmap_server::{ClosureHandler, Dispatcher};
/// use std::sync::Arc;
///
/// #[derive(Clone)]
/// struct AuthCtx { user_id: String }
///
/// let handler: Arc<ClosureHandler<MyBackend, AuthCtx>> =
///     Arc::new(ClosureHandler::new(
///         Arc::new(my_backend),
///         |b, cx| {
///             Box::pin(async move {
///                 // cx.caller.user_id is available here
///                 handle_something(&*b, cx.args, &cx.caller.user_id).await
///             })
///         },
///     ));
///
/// let mut dispatcher: Dispatcher<AuthCtx> = Dispatcher::new();
/// dispatcher.register("MyMethod/get", handler);
/// ```
/// A [`JmapHandler`] handle wrapping a shared backend + an async
/// closure. Construct via [`ClosureHandler::new`] — the fields are
/// crate-private (bd:JMAP-jfia.5) to keep the handle opaque, prevent
/// post-construction hot-swap of the closure or backend, and let the
/// constructor remain the sole site that enforces invariants when
/// future fields (per-handler tracing context, metrics handle, etc.)
/// are added.
#[non_exhaustive]
pub struct ClosureHandler<B: Send + Sync + 'static, C: Clone + Send + 'static> {
    /// Shared reference to the backend implementation, passed to the
    /// closure on every method call. Crate-private to keep
    /// `ClosureHandler` an opaque handle (bd:JMAP-jfia.5).
    pub(crate) backend: Arc<B>,
    /// The async closure invoked for each JMAP method call this handler
    /// receives from the dispatcher. Crate-private to keep
    /// `ClosureHandler` an opaque handle (bd:JMAP-jfia.5).
    pub(crate) call_fn: Box<BackendCallFn<B, C>>,
}

impl<B: Send + Sync + 'static, C: Clone + Send + 'static> ClosureHandler<B, C> {
    /// Construct a [`ClosureHandler`] wrapping a shared backend and an
    /// async closure (bd:JMAP-wlip.17).
    ///
    /// This is the supported construction path. The struct is
    /// `#[non_exhaustive]` so future fields (per-handler tracing
    /// context, metrics handle, timeout, etc.) can be added without a
    /// major-version bump — external callers MUST go through `new`
    /// rather than struct-literal syntax.
    ///
    /// The `call_fn` parameter is generic over
    /// `F: Fn(Arc<B>, CallContext<C>) + Send + Sync + 'static`
    /// (bd:JMAP-jfia.40), so callers can pass a closure directly
    /// without wrapping it in `Box::new`; an already-boxed closure also
    /// satisfies the bound. Internally, the closure is boxed once at
    /// construction and stored as `Box<BackendCallFn<B, C>>`.
    pub fn new<F>(backend: Arc<B>, call_fn: F) -> Self
    where
        F: Fn(Arc<B>, CallContext<C>) -> HandlerFuture + Send + Sync + 'static,
    {
        Self {
            backend,
            call_fn: Box::new(call_fn),
        }
    }
}

impl<B: Send + Sync + 'static, C: Clone + Send + 'static> JmapHandler<C> for ClosureHandler<B, C> {
    fn call(&self, cx: CallContext<C>) -> HandlerFuture {
        (self.call_fn)(Arc::clone(&self.backend), cx)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{Value, json};
    use std::sync::{Arc, Mutex};

    // Compile-time: Dispatcher must be Send + Sync so it can be wrapped in Arc
    // and shared across tokio tasks.  This assertion catches future regressions
    // that would silently break thread-safety (e.g., adding a Cell or Rc field).
    #[allow(dead_code)]
    fn assert_dispatcher_send_sync() {
        fn check<T: Send + Sync>() {}
        check::<Dispatcher<String>>();
        check::<Dispatcher<()>>();
    }

    // -----------------------------------------------------------------------
    // Test handler implementations
    // -----------------------------------------------------------------------

    /// Returns a fixed Value regardless of inputs.
    struct EchoHandler(Value);

    impl<C: Clone + Send + 'static> JmapHandler<C> for EchoHandler {
        fn call(&self, _cx: CallContext<C>) -> HandlerFuture {
            let v = self.0.clone();
            Box::pin(async move { Ok(HandlerOutput::new(v)) })
        }
    }

    /// Returns a fixed error.
    struct ErrorHandler(JmapError);

    impl JmapHandler<String> for ErrorHandler {
        fn call(&self, _cx: CallContext<String>) -> HandlerFuture {
            let e = self.0.clone();
            Box::pin(async move { Err(e) })
        }
    }

    /// Captures the resolved args it was called with.
    struct CaptureArgsHandler(Arc<Mutex<Option<Value>>>);

    impl JmapHandler<String> for CaptureArgsHandler {
        fn call(&self, cx: CallContext<String>) -> HandlerFuture {
            let args = cx.args;
            let slot = self.0.clone();
            Box::pin(async move {
                *slot.lock().expect("test: mutex poisoned") = Some(args);
                Ok(HandlerOutput::new(json!({})))
            })
        }
    }

    /// Captures the caller value it was called with.
    struct CaptureCallerHandler(Arc<Mutex<Option<String>>>);

    impl JmapHandler<String> for CaptureCallerHandler {
        fn call(&self, cx: CallContext<String>) -> HandlerFuture {
            let caller = cx.caller;
            let slot = self.0.clone();
            Box::pin(async move {
                *slot.lock().expect("test: mutex poisoned") = Some(caller);
                Ok(HandlerOutput::new(json!({})))
            })
        }
    }

    /// Panics unconditionally.
    struct PanicHandler;

    impl JmapHandler<String> for PanicHandler {
        fn call(&self, _cx: CallContext<String>) -> HandlerFuture {
            Box::pin(async move { panic!("deliberate test panic") })
        }
    }

    // -----------------------------------------------------------------------
    // Helper: build a minimal JmapRequest with a single method call.
    // -----------------------------------------------------------------------

    fn single_call(method: &str, args: Value, call_id: &str) -> JmapRequest {
        JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![Invocation::new(method, args, call_id)],
            None,
        )
    }

    // -----------------------------------------------------------------------
    // Basic dispatch
    // -----------------------------------------------------------------------

    /// Oracle: RFC 8620 §7.1 — unknownMethod when no handler is registered.
    #[tokio::test]
    async fn unknown_method_returns_error_invocation() {
        let d: Dispatcher<String> = Dispatcher::new();
        let req = single_call("Foo/get", json!({}), "c0");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 1);
        let Invocation {
            arguments: args,
            call_id,
            ..
        } = &resp.method_responses[0];
        assert_eq!(call_id, "c0");
        assert_eq!(args["type"], "unknownMethod");
    }

    /// Oracle: RFC 8620 §3.5 — successful call appears in methodResponses.
    #[tokio::test]
    async fn known_method_success() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
        let req = single_call("Foo/get", json!({}), "c1");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 1);
        let Invocation {
            name: method,
            arguments: args,
            call_id,
        } = &resp.method_responses[0];
        assert_eq!(method, "Foo/get");
        assert_eq!(call_id, "c1");
        assert_eq!(args["list"], json!([]));
    }

    /// A FilterCondition wrapped in `levels` nested `AND` operators.
    fn nested_filter(levels: usize) -> Value {
        (0..levels).fold(
            json!({ "text": "x" }),
            |inner, _| json!({ "operator": "AND", "conditions": [inner] }),
        )
    }

    /// Oracle: RFC 8620 §5.5 (rfc8620.txt:2626) — `unsupportedFilter`
    /// "The "filter" is syntactically valid, but the server cannot process
    /// it", and the 32-level cap documented on `parse_request`. A filter
    /// one operator level past the cap is refused before the handler runs.
    #[tokio::test]
    async fn filter_nested_past_cap_is_unsupported_filter() {
        let slot = Arc::new(Mutex::new(None));
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Foo/query", Arc::new(CaptureArgsHandler(slot.clone())));
        let req = single_call("Foo/query", json!({ "filter": nested_filter(33) }), "c0");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        let Invocation {
            name, arguments, ..
        } = &resp.method_responses[0];
        assert_eq!(name, "error");
        assert_eq!(arguments["type"], "unsupportedFilter");
        assert!(
            slot.lock().expect("test: mutex poisoned").is_none(),
            "handler must not run on a refused filter"
        );
    }

    /// Positive control for the cap: 32 operator levels, the documented
    /// limit, still reach the handler unchanged.
    #[tokio::test]
    async fn filter_nested_at_cap_reaches_handler() {
        let slot = Arc::new(Mutex::new(None));
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Foo/query", Arc::new(CaptureArgsHandler(slot.clone())));
        let args = json!({ "filter": nested_filter(32) });
        let req = single_call("Foo/query", args.clone(), "c0");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses[0].name, "Foo/query");
        assert_eq!(*slot.lock().expect("test: mutex poisoned"), Some(args));
    }

    /// Oracle: RFC 8620 §3.6.2 — method-level errors appear in methodResponses.
    #[tokio::test]
    async fn handler_returns_error() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Foo/get", Arc::new(ErrorHandler(JmapError::forbidden())));
        let req = single_call("Foo/get", json!({}), "c2");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 1);
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert_eq!(args["type"], "forbidden");
    }

    /// Oracle (bd:JMAP-yt1w.30): RFC 8620 §5.3 (rfc8620.txt L2166-2170):
    /// "The following additional errors may be returned instead of the
    /// "Foo/set" response: "requestTooLarge": The total number of objects
    /// to create, update, or destroy exceeds the maximum number the server
    /// is willing to process in a single method call." The over-cap
    /// Foo/set gets an "error" invocation of type requestTooLarge in
    /// place of its response, and the next method call in the same
    /// request still runs.
    #[tokio::test]
    async fn set_over_max_objects_is_method_error_request_too_large() {
        struct CappedSetHandler;

        impl JmapHandler<String> for CappedSetHandler {
            fn call(&self, cx: CallContext<String>) -> HandlerFuture {
                let args = cx.args;
                Box::pin(async move {
                    let map = args.as_object().cloned().unwrap_or_default();
                    enforce_max_objects_in_set(&map, 1)?;
                    Ok(HandlerOutput::new(json!({"created": {}})))
                })
            }
        }

        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Foo/set", Arc::new(CappedSetHandler));
        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![
                Invocation::new(
                    "Foo/set",
                    json!({"accountId": "a1", "destroy": ["x1", "x2"]}),
                    "c0",
                ),
                Invocation::new("Foo/get", json!({"accountId": "a1"}), "c1"),
            ],
            None,
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 2);
        let Invocation {
            name,
            arguments: args,
            call_id,
        } = &resp.method_responses[0];
        assert_eq!(name, "error");
        assert_eq!(call_id, "c0");
        assert_eq!(args["type"], "requestTooLarge");
        let Invocation {
            name,
            arguments: args,
            call_id,
        } = &resp.method_responses[1];
        assert_eq!(name, "Foo/get");
        assert_eq!(call_id, "c1");
        assert_eq!(args["list"], json!([]));
    }

    /// Oracle (bd:JMAP-jfia.4): try_register MUST return Ok for the
    /// first registration of a method name, and Err(DuplicateMethodError)
    /// for any subsequent registration of the same name. On Err the
    /// dispatcher's handler map MUST be left unchanged — the
    /// already-registered handler stays in place.
    #[tokio::test]
    async fn try_register_succeeds_then_errors_on_duplicate() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        let first = Arc::new(EchoHandler(json!({"v": "first"})));
        let second = Arc::new(EchoHandler(json!({"v": "second"})));

        d.try_register("Foo/get", first)
            .expect("first registration must succeed");

        let err = d
            .try_register("Foo/get", second)
            .expect_err("second registration must error");
        assert_eq!(err.method, "Foo/get");
        assert_eq!(
            err.to_string(),
            "handler already registered for method \"Foo/get\""
        );

        // The first handler MUST still be the one that fires — try_register
        // must NOT have replaced it as a side-effect of the error path.
        let req = single_call("Foo/get", json!({}), "c0");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert_eq!(
            args["v"], "first",
            "try_register error path must not replace the existing handler"
        );
    }

    /// Oracle (bd:JMAP-jfia.4): register (the silent-overwrite variant)
    /// MUST continue to replace on duplicate, since established consumers
    /// depend on that ergonomic for test fixtures. Pins the contract so
    /// a future refactor that "fixes" register's silent overwrite is
    /// caught.
    #[tokio::test]
    async fn register_silently_overwrites_on_duplicate() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Foo/get", Arc::new(EchoHandler(json!({"v": "first"}))));
        d.register("Foo/get", Arc::new(EchoHandler(json!({"v": "second"}))));

        let req = single_call("Foo/get", json!({}), "c0");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert_eq!(args["v"], "second", "register must replace on duplicate");
    }

    /// Oracle: RFC 8620 §3.4 — sessionState in response matches what dispatcher was given.
    #[tokio::test]
    async fn session_state_echoed() {
        let d: Dispatcher<String> = Dispatcher::new();
        let req = JmapRequest::new(vec!["urn:ietf:params:jmap:core".into()], vec![], None);
        let resp = d.dispatch(req, "alice".into(), "my-state-123".into()).await;
        assert_eq!(resp.session_state.as_ref(), "my-state-123");
    }

    // -----------------------------------------------------------------------
    // Batch
    // -----------------------------------------------------------------------

    /// Oracle: RFC 8620 §3.3 — methodCalls processed in order, all responses present.
    /// Also covers: error in one method does not abort the batch (RFC 8620 §3.6.2).
    #[tokio::test]
    async fn mixed_batch_all_responses_in_order() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("M/a", Arc::new(EchoHandler(json!({"ok": true}))));
        // "M/b" is NOT registered → unknownMethod
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![
                Invocation::new("M/a", json!({}), "c0"),
                Invocation::new("M/b", json!({}), "c1"),
                Invocation::new("M/a", json!({}), "c2"),
            ],
            None,
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(
            resp.method_responses.len(),
            3,
            "all three calls must produce a response"
        );
        // responses[0]: M/a success
        assert_eq!(resp.method_responses[0].call_id, "c0");
        assert!(
            resp.method_responses[0].arguments.get("type").is_none(),
            "c0 must not be an error"
        );
        // responses[1]: M/b unknownMethod
        assert_eq!(resp.method_responses[1].call_id, "c1");
        assert_eq!(resp.method_responses[1].arguments["type"], "unknownMethod");
        // responses[2]: M/a success (error in [1] did not abort the batch)
        assert_eq!(resp.method_responses[2].call_id, "c2");
        assert!(
            resp.method_responses[2].arguments.get("type").is_none(),
            "c2 must not be an error"
        );
    }

    /// Oracle: RFC 8620 §3.6.2 — error in one method does not abort subsequent calls.
    #[tokio::test]
    async fn error_does_not_abort_subsequent_calls() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("M/ok", Arc::new(EchoHandler(json!({"ok": true}))));
        d.register("M/err", Arc::new(ErrorHandler(JmapError::forbidden())));
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![
                Invocation::new("M/err", json!({}), "c0"),
                Invocation::new("M/ok", json!({}), "c1"),
            ],
            None,
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 2);
        assert_eq!(resp.method_responses[0].arguments["type"], "forbidden");
        assert!(
            resp.method_responses[1].arguments.get("type").is_none(),
            "second call must succeed"
        );
    }

    // -----------------------------------------------------------------------
    // Panic isolation
    // -----------------------------------------------------------------------

    /// Oracle: RFC 8620 §7.1 serverFail; PLAN.md panic isolation design decision.
    #[tokio::test]
    async fn panicking_handler_returns_server_fail() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Panic/now", Arc::new(PanicHandler));
        let req = single_call("Panic/now", json!({}), "c0");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 1);
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert_eq!(
            args["type"], "serverFail",
            "panicking handler must produce serverFail"
        );
    }

    /// Oracle (bd:JMAP-wlip.12): security invariant — panic payloads
    /// may contain secrets and MUST NOT leak through ANY field of the
    /// error invocation, not just `description`. A future refactor that
    /// surfaces panic-payload text through a typed `context`, an
    /// `innerError` nested object, or any other field would slip past a
    /// single-field check.
    ///
    /// The assertion walks the entire methodResponse args Value
    /// recursively and asserts that no string anywhere in the tree
    /// contains the canary `"deliberate test panic"` from
    /// [`PanicHandler`].
    ///
    /// **Decision record (bd:JMAP-jfia.14)**: a future "simplify" pass
    /// will reasonably suggest narrowing this to a single-field check
    /// against `args["description"]` because that is where panic
    /// payloads land today. That suggestion is **WRONG** and must be
    /// rejected: a single-field check encodes the current
    /// implementation rather than the security invariant. The
    /// recursive walk encodes the actual invariant ("panic-payload
    /// text does not leak to the wire, ANYWHERE in the response shape")
    /// and survives refactors of the error shape. Defending this
    /// shape protects the workspace credential/PII redaction policy
    /// from drift.
    #[tokio::test]
    async fn panic_message_not_in_response() {
        /// Returns `true` iff any `Value::String` in the tree
        /// contains `needle`.
        fn value_contains_recursive(v: &Value, needle: &str) -> bool {
            match v {
                Value::String(s) => s.contains(needle),
                Value::Array(arr) => arr.iter().any(|x| value_contains_recursive(x, needle)),
                Value::Object(o) => o.values().any(|x| value_contains_recursive(x, needle)),
                Value::Null | Value::Bool(_) | Value::Number(_) => false,
            }
        }

        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Panic/now", Arc::new(PanicHandler));
        let req = single_call("Panic/now", json!({}), "c0");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert!(
            !value_contains_recursive(args, "deliberate test panic"),
            "panic message must not leak into ANY field of the response: {args}"
        );
    }

    // -----------------------------------------------------------------------
    // ResultReference end-to-end
    // -----------------------------------------------------------------------

    /// Oracle: RFC 8620 §3.7 — #-prefixed args resolved from prior responses before handler call.
    #[tokio::test]
    async fn result_reference_resolved_before_dispatch() {
        let captured = Arc::new(Mutex::new(None::<Value>));
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register(
            "Foo/get",
            Arc::new(EchoHandler(json!({"list": [{"id": "item-1"}]}))),
        );
        d.register(
            "Bar/query",
            Arc::new(CaptureArgsHandler(Arc::clone(&captured))),
        );
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![
                Invocation::new("Foo/get", json!({}), "c0"),
                Invocation::new(
                    "Bar/query",
                    json!({"#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/list/0/id"}}),
                    "c1",
                ),
            ],
            None,
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 2);
        // c1 must succeed, not be an error
        assert!(
            resp.method_responses[1].arguments.get("type").is_none(),
            "Bar/query must succeed after ResultReference resolution"
        );
        // Handler must have received the resolved value, not the original #ids object
        let got = captured
            .lock()
            .unwrap()
            .clone()
            .expect("CaptureArgsHandler was not called");
        assert_eq!(
            got["ids"],
            json!("item-1"),
            "resolved value must be the string item-1"
        );
        assert!(
            got.get("#ids").is_none(),
            "#ids key must have been replaced"
        );
    }

    /// Oracle: RFC 8620 §3.7 — resolution failure → error for that call, batch continues.
    #[tokio::test]
    async fn result_reference_failure_stops_that_call() {
        let d: Dispatcher<String> = Dispatcher::new();
        let req = single_call(
            "Foo/get",
            json!({"#ids": {"resultOf": "nonexistent", "name": "Foo/get", "path": "/x"}}),
            "c0",
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 1);
        let Invocation {
            arguments: args, ..
        } = &resp.method_responses[0];
        assert!(
            args.get("type").is_some(),
            "failed ResultReference must produce an error invocation"
        );
    }

    // -----------------------------------------------------------------------
    // createdIds
    // -----------------------------------------------------------------------

    /// Oracle: RFC 8620 §3.3 createdIds — server-assigned IDs returned from /set
    /// responses are accumulated into resp.created_ids when client sent createdIds.
    #[tokio::test]
    async fn created_ids_accumulated_from_set_response() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register(
            "Foo/set",
            Arc::new(EchoHandler(
                json!({"created": {"client-1": {"id": "server-abc"}}}),
            )),
        );
        // Client sends createdIds (empty map) to signal it wants the response field.
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![Invocation::new("Foo/set", json!({}), "c0")],
            Some(std::collections::BTreeMap::new()),
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        let ids = resp
            .created_ids
            .as_ref()
            .expect("created_ids must be Some when client sent createdIds");
        assert_eq!(
            ids.get(&Id::from("client-1")),
            Some(&Id::from("server-abc")),
            "client-1 must map to server-abc"
        );
    }

    /// Captures the `created_ids` it was called with.
    struct CaptureCreatedIdsHandler(Arc<Mutex<Option<BTreeMap<Id, Id>>>>);

    impl JmapHandler<String> for CaptureCreatedIdsHandler {
        fn call(&self, cx: CallContext<String>) -> HandlerFuture {
            *self.0.lock().expect("test: mutex poisoned") = Some(cx.created_ids);
            Box::pin(async move { Ok(HandlerOutput::new(json!({}))) })
        }
    }

    /// Oracle: RFC 8620 §5.3 — "the server MUST keep a simple map for
    /// the duration of the request of creation id to record id for each
    /// newly created record, so it can substitute in the correct value
    /// if necessary in later method calls". The map exists whether or
    /// not the client sent createdIds; only the response echo depends on
    /// that (RFC 8620 §3.4).
    #[tokio::test]
    async fn created_ids_reach_later_call_without_client_created_ids() {
        let slot = Arc::new(Mutex::new(None));
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register(
            "Graph/set",
            Arc::new(EchoHandler(json!({"created": {"g": {"id": "G1"}}}))),
        );
        d.register(
            "GraphNode/set",
            Arc::new(CaptureCreatedIdsHandler(Arc::clone(&slot))),
        );
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![
                Invocation::new("Graph/set", json!({}), "c0"),
                Invocation::new("GraphNode/set", json!({}), "c1"),
            ],
            None,
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        let seen = slot
            .lock()
            .expect("test: mutex poisoned")
            .take()
            .expect("GraphNode/set handler must run");
        assert_eq!(
            seen,
            BTreeMap::from([(Id::from("g"), Id::from("G1"))]),
            "later call must see the earlier creation"
        );
        assert!(
            resp.created_ids.is_none(),
            "response omits createdIds when the client did not send it"
        );
    }

    /// Oracle: RFC 8620 §5.3 — "an initial set of creation id to real id
    /// values may be passed with a request"; the first call must already
    /// see them.
    #[tokio::test]
    async fn created_ids_initial_map_reaches_first_call() {
        let slot = Arc::new(Mutex::new(None));
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register(
            "Email/set",
            Arc::new(CaptureCreatedIdsHandler(Arc::clone(&slot))),
        );
        let initial = BTreeMap::from([(Id::from("m"), Id::from("M1"))]);
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![Invocation::new("Email/set", json!({}), "c0")],
            Some(initial.clone()),
        );
        d.dispatch(req, "alice".into(), "s0".into()).await;
        let seen = slot.lock().expect("test: mutex poisoned").take();
        assert_eq!(seen, Some(initial));
    }

    /// Oracle: RFC 8620 §3.4 — createdIds omitted when no objects were created.
    #[tokio::test]
    async fn created_ids_absent_when_no_set() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
        let req = single_call("Foo/get", json!({}), "c0");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert!(
            resp.created_ids.is_none(),
            "created_ids must be None when no /set call created objects"
        );
    }

    /// Oracle: RFC 8620 §3.3 — createdIds accumulates across ALL /set calls in the batch.
    #[tokio::test]
    async fn created_ids_accumulated_across_multiple_set_calls() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register(
            "A/set",
            Arc::new(EchoHandler(json!({"created": {"cA": {"id": "sA"}}}))),
        );
        d.register(
            "B/set",
            Arc::new(EchoHandler(json!({"created": {"cB": {"id": "sB"}}}))),
        );
        // Client sends createdIds to signal it wants the response field.
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![
                Invocation::new("A/set", json!({}), "c0"),
                Invocation::new("B/set", json!({}), "c1"),
            ],
            Some(std::collections::BTreeMap::new()),
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        let ids = resp
            .created_ids
            .as_ref()
            .expect("created_ids must be Some when client sent createdIds");
        assert_eq!(
            ids.get(&Id::from("cA")),
            Some(&Id::from("sA")),
            "cA must be present"
        );
        assert_eq!(
            ids.get(&Id::from("cB")),
            Some(&Id::from("sB")),
            "cB must be present"
        );
    }

    /// Oracle: RFC 8620 §3.4 — pre-populated client createdIds are preserved and
    /// new /set entries are merged in alongside them.
    #[tokio::test]
    async fn created_ids_merges_with_pre_populated_map() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register(
            "Foo/set",
            Arc::new(EchoHandler(
                json!({"created": {"client-new": {"id": "server-new"}}}),
            )),
        );
        // Client sends a pre-populated createdIds map.
        let mut initial = std::collections::BTreeMap::new();
        initial.insert(Id::from("client-old"), Id::from("server-old"));
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![Invocation::new("Foo/set", json!({}), "c0")],
            Some(initial),
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        let ids = resp
            .created_ids
            .as_ref()
            .expect("created_ids must be Some when client sent createdIds");
        assert_eq!(
            ids.get(&Id::from("client-old")),
            Some(&Id::from("server-old")),
            "pre-populated entry must be preserved"
        );
        assert_eq!(
            ids.get(&Id::from("client-new")),
            Some(&Id::from("server-new")),
            "new /set entry must be merged in"
        );
    }

    /// Oracle (bd:JMAP-jfia.3): when the client pre-populates
    /// `createdIds` with `X -> A` and a `/set` call in the same batch
    /// returns `X -> B` (`B != A`), the dispatcher applies last-write-
    /// wins semantics: the response carries `X -> B`, and the
    /// pre-populated `A` is dropped. This is surprising and the spec is
    /// ambiguous on which semantics is correct (RFC 8620 §3.4), but
    /// matches the intra-batch duplicate convention documented at the
    /// dispatch call site and avoids a wire-behaviour change in the
    /// canonical foundation crate. The test exists to catch a future
    /// refactor that silently flips the order to first-write-wins.
    #[tokio::test]
    async fn created_ids_pre_populated_collision_last_write_wins() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register(
            "Foo/set",
            Arc::new(EchoHandler(
                json!({"created": {"client-X": {"id": "server-B"}}}),
            )),
        );
        // Client pre-populates client-X -> server-A.
        let mut initial = std::collections::BTreeMap::new();
        initial.insert(Id::from("client-X"), Id::from("server-A"));
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![Invocation::new("Foo/set", json!({}), "c0")],
            Some(initial),
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        let ids = resp
            .created_ids
            .as_ref()
            .expect("created_ids must be Some when client sent createdIds");
        assert_eq!(
            ids.get(&Id::from("client-X")),
            Some(&Id::from("server-B")),
            "last-write-wins: /set response overrides pre-populated entry"
        );
        assert_eq!(
            ids.len(),
            1,
            "no extra entries should appear from the collision"
        );
    }

    /// Oracle (bd:JMAP-jfia.3): when two `/set` calls in the same batch
    /// report the same creationId with different values, the
    /// dispatcher applies last-write-wins: the second `/set` response's
    /// mapping is the one preserved in the final `createdIds` map. The
    /// existing dispatch call-site comment documents this convention
    /// (bd:JMAP-wlip.7); the test pins it.
    #[tokio::test]
    async fn created_ids_intra_batch_collision_last_write_wins() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register(
            "A/set",
            Arc::new(EchoHandler(json!({"created": {"cX": {"id": "sA"}}}))),
        );
        d.register(
            "B/set",
            Arc::new(EchoHandler(json!({"created": {"cX": {"id": "sB"}}}))),
        );
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![
                Invocation::new("A/set", json!({}), "c0"),
                Invocation::new("B/set", json!({}), "c1"),
            ],
            Some(std::collections::BTreeMap::new()),
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        let ids = resp
            .created_ids
            .as_ref()
            .expect("created_ids must be Some when client sent createdIds");
        assert_eq!(
            ids.get(&Id::from("cX")),
            Some(&Id::from("sB")),
            "last-write-wins: second /set call's mapping for cX preserved"
        );
        assert_eq!(
            ids.len(),
            1,
            "no extra entries should appear from the collision"
        );
    }

    // -----------------------------------------------------------------------
    // Method guard
    // -----------------------------------------------------------------------

    /// Oracle: RFC 8620 §3.6.2 — a method-level error is returned as an
    /// `["error", {"type": ...}, callId]` response in place of that call's
    /// response, and later calls in the batch are still processed.
    #[tokio::test]
    async fn guard_rejection_replaces_only_that_call() {
        let captured = Arc::new(Mutex::new(None::<String>));
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Foo/get", Arc::new(EchoHandler(json!({"list": []}))));
        d.register(
            "Bar/set",
            Arc::new(CaptureCallerHandler(Arc::clone(&captured))),
        );
        d.set_guard(|method, caller: &String| {
            if method == "Bar/set" && caller == "mallory" {
                Err(JmapError::forbidden())
            } else {
                Ok(())
            }
        });
        let batch = || {
            JmapRequest::new(
                vec!["urn:ietf:params:jmap:core".into()],
                vec![
                    Invocation::new("Foo/get", json!({}), "c0"),
                    Invocation::new("Bar/set", json!({}), "c1"),
                    Invocation::new("Foo/get", json!({}), "c2"),
                ],
                None,
            )
        };

        let resp = d.dispatch(batch(), "mallory".into(), "s0".into()).await;
        let got: Vec<(String, Value, String)> = resp
            .method_responses
            .into_iter()
            .map(|i| (i.name, i.arguments, i.call_id))
            .collect();
        assert_eq!(
            got,
            vec![
                ("Foo/get".into(), json!({"list": []}), "c0".into()),
                ("error".into(), json!({"type": "forbidden"}), "c1".into()),
                ("Foo/get".into(), json!({"list": []}), "c2".into()),
            ]
        );
        assert!(
            captured.lock().unwrap().is_none(),
            "rejected call's handler must not run"
        );

        let resp = d.dispatch(batch(), "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses[1].name, "Bar/set");
        assert_eq!(captured.lock().unwrap().as_deref(), Some("alice"));
    }

    /// Oracle: bd:JMAP-v9py.15.8 decision — the guard runs after result
    /// references resolve (RFC 8620 §3.7 `invalidResultReference` wins) and
    /// before handler lookup (a rejected unregistered method gets the
    /// guard's error, not RFC 8620 §3.6.2 `unknownMethod`).
    #[tokio::test]
    async fn guard_runs_after_reference_resolution_before_lookup() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.set_guard(|_, _: &String| Err(JmapError::forbidden()));
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![
                Invocation::new(
                    "Foo/get",
                    json!({"#ids": {"resultOf": "nonexistent", "name": "Foo/get", "path": "/x"}}),
                    "c0",
                ),
                Invocation::new("Unregistered/get", json!({}), "c1"),
            ],
            None,
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 2);
        assert_eq!(
            resp.method_responses[0].arguments["type"],
            "invalidResultReference"
        );
        assert_eq!(resp.method_responses[1].arguments["type"], "forbidden");
    }

    // -----------------------------------------------------------------------
    // CallerCtx
    // -----------------------------------------------------------------------

    /// Oracle: PLAN.md CallerCtx design — caller value passed through to handler unchanged.
    #[tokio::test]
    async fn caller_ctx_passed_to_handler() {
        let captured = Arc::new(Mutex::new(None::<String>));
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register(
            "Foo/get",
            Arc::new(CaptureCallerHandler(Arc::clone(&captured))),
        );
        let req = single_call("Foo/get", json!({}), "c0");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert!(
            resp.method_responses[0].arguments.get("type").is_none(),
            "must succeed"
        );
        let got = captured
            .lock()
            .unwrap()
            .clone()
            .expect("handler was not called");
        assert_eq!(got, "alice", "caller must be passed through unchanged");
    }

    /// Oracle: PLAN.md — CallerCtx = () must work (unit type as auth context).
    #[tokio::test]
    async fn unit_caller_ctx_works() {
        let mut d: Dispatcher<()> = Dispatcher::new();
        d.register("Foo/get", Arc::new(EchoHandler(json!({"ok": true}))));
        let req = single_call("Foo/get", json!({}), "c0");
        let resp = d.dispatch(req, (), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 1);
        assert!(
            resp.method_responses[0].arguments.get("type").is_none(),
            "must succeed with () caller"
        );
    }

    // -----------------------------------------------------------------------
    // Extra invocations
    // -----------------------------------------------------------------------

    /// A handler that returns both a primary response and one extra invocation.
    ///
    /// Models RFC 8621 §7.5 EmailSubmission/set with onSuccessUpdateEmail: the
    /// submission response is primary; the implied Email/set call is extra.
    struct ExtraInvocationHandler;

    impl JmapHandler<String> for ExtraInvocationHandler {
        fn call(&self, _cx: CallContext<String>) -> HandlerFuture {
            Box::pin(async move {
                let primary = json!({"type": "primary"});
                let extra: Vec<Invocation> = vec![Invocation::new(
                    "Extra/call",
                    json!({"type": "extra"}),
                    "x0",
                )];
                Ok(HandlerOutput::new(primary).with_extra(extra))
            })
        }
    }

    /// Oracle: handler returning extra invocations → both primary and extra appear in
    /// methodResponses in order (primary first, then extra).
    #[tokio::test]
    async fn extra_invocations_appended_after_primary() {
        let mut d: Dispatcher<String> = Dispatcher::new();
        d.register("Sub/set", Arc::new(ExtraInvocationHandler));
        let req = single_call("Sub/set", json!({}), "c0");
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;

        assert_eq!(
            resp.method_responses.len(),
            2,
            "primary + 1 extra = 2 total invocations"
        );
        // First: the primary Sub/set response.
        assert_eq!(resp.method_responses[0].name, "Sub/set");
        assert_eq!(resp.method_responses[0].call_id, "c0");
        assert_eq!(resp.method_responses[0].arguments["type"], "primary");
        // Second: the appended extra invocation.
        assert_eq!(resp.method_responses[1].name, "Extra/call");
        assert_eq!(resp.method_responses[1].call_id, "x0");
        assert_eq!(resp.method_responses[1].arguments["type"], "extra");
    }

    /// Oracle: ClosureHandler forwards CallerCtx to the closure.
    /// The closure receives the exact same value that was passed to dispatch().
    #[tokio::test]
    async fn closure_handler_forwards_caller() {
        #[derive(Clone)]
        struct Ctx(String);

        struct DummyBackend;

        // Use a shared capture to record what ctx the closure received.
        let received: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
        let received_clone = Arc::clone(&received);

        let handler: Arc<ClosureHandler<DummyBackend, Ctx>> = Arc::new(ClosureHandler::new(
            Arc::new(DummyBackend),
            move |_b: Arc<DummyBackend>, cx: CallContext<Ctx>| {
                let cap = Arc::clone(&received_clone);
                Box::pin(async move {
                    *cap.lock().unwrap() = Some(cx.caller.0.clone());
                    Ok(HandlerOutput::new(serde_json::json!({})))
                })
            },
        ));

        let ctx = Ctx("alice".to_owned());
        handler
            .call(CallContext::new(
                "Test/get",
                "c1",
                serde_json::json!({}),
                ctx,
            ))
            .await
            .expect("handler must succeed");

        assert_eq!(
            received.lock().unwrap().as_deref(),
            Some("alice"),
            "CallerCtx must be forwarded to the closure"
        );
    }

    /// Oracle: RFC 8620 §3.2 — an Invocation is a method name, its
    /// arguments and a method call id. Dispatching `["Foo/get",
    /// {"accountId": "a1"}, "c7"]` through a ClosureHandler MUST hand the
    /// closure exactly that name, id and arguments (the method name was
    /// dropped before bd:JMAP-wf92.7).
    #[tokio::test]
    async fn closure_handler_receives_method_call_id_and_args() {
        struct DummyBackend;
        let seen: Arc<Mutex<Option<(String, String, Value)>>> = Arc::new(Mutex::new(None));
        let seen_clone = Arc::clone(&seen);
        let handler = ClosureHandler::new(
            Arc::new(DummyBackend),
            move |_b: Arc<DummyBackend>, cx: CallContext<()>| {
                *seen_clone.lock().unwrap() = Some((cx.method, cx.call_id, cx.args));
                Box::pin(async { Ok(HandlerOutput::new(json!({}))) }) as HandlerFuture
            },
        );
        let mut d: Dispatcher<()> = Dispatcher::new();
        d.register("Foo/get", Arc::new(handler));
        d.dispatch(
            single_call("Foo/get", json!({"accountId": "a1"}), "c7"),
            (),
            "s0".into(),
        )
        .await;
        assert_eq!(
            seen.lock().unwrap().take(),
            Some((
                "Foo/get".to_owned(),
                "c7".to_owned(),
                json!({"accountId": "a1"})
            ))
        );
    }

    /// Oracle: RFC 8620 §3.3 — the Request object's `using` is "The set
    /// of capabilities the client wishes to use"; draft-ietf-jmap-metadata-05
    /// §3 makes `Foo/changes` behaviour depend on whether it "includes
    /// urn:ietf:params:jmap:metadata", so the dispatcher MUST hand every
    /// handler the request's `using` list unchanged.
    #[tokio::test]
    async fn dispatch_passes_request_using_to_handler() {
        struct DummyBackend;
        let seen: Arc<Mutex<Option<Vec<String>>>> = Arc::new(Mutex::new(None));
        let seen_clone = Arc::clone(&seen);
        let handler = ClosureHandler::new(
            Arc::new(DummyBackend),
            move |_b: Arc<DummyBackend>, cx: CallContext<()>| {
                *seen_clone.lock().unwrap() = Some(cx.using);
                Box::pin(async { Ok(HandlerOutput::new(json!({}))) }) as HandlerFuture
            },
        );
        let mut d: Dispatcher<()> = Dispatcher::new();
        d.register("Foo/changes", Arc::new(handler));
        let req = JmapRequest::new(
            vec![
                "urn:ietf:params:jmap:core".into(),
                "urn:ietf:params:jmap:metadata".into(),
            ],
            vec![Invocation::new(
                "Foo/changes",
                json!({"accountId": "a1", "sinceState": "s1"}),
                "c0",
            )],
            None,
        );
        d.dispatch(req, (), "s0".into()).await;
        assert_eq!(
            seen.lock().unwrap().take(),
            Some(vec![
                "urn:ietf:params:jmap:core".to_owned(),
                "urn:ietf:params:jmap:metadata".to_owned(),
            ])
        );
    }

    /// Oracle: ClosureHandler implements JmapHandler<C> and can be
    /// registered with Dispatcher<C>.
    #[test]
    fn closure_handler_is_jmap_handler() {
        // Compile-time check: ClosureHandler<B, C> must satisfy JmapHandler<C>.
        fn assert_handler<C: Clone + Send + 'static, H: JmapHandler<C>>(_: &H) {}

        struct DummyBackend;
        #[derive(Clone)]
        struct Ctx;

        let h = ClosureHandler::new(Arc::new(DummyBackend), |_b, _cx| {
            Box::pin(async { Ok(HandlerOutput::new(serde_json::json!({}))) })
        });
        assert_handler::<Ctx, _>(&h);
    }
}