jmap-server 0.1.3

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
//! 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`,
//! `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, ResultReference, State, UTCDate,
};

pub mod backend;
pub mod handlers;
mod helpers;

pub use backend::{
    AddedItem, BackendChangesError, BackendSetError, ChangesResult, GetObject, JmapBackend,
    JmapObject, QueryChangesResult, QueryObject, QueryResult, ReservedExtrasKey, SetError,
    SetErrorType, SetObject, RESERVED_SET_ERROR_WIRE_NAMES,
};
pub use handlers::{
    handle_changes, handle_get, handle_query, handle_query_changes, server_fail_from_backend,
    server_fail_value_from_backend, SERVER_FAIL_INTERNAL_DESC,
};
#[allow(deprecated)]
pub use helpers::ser;
pub use helpers::{
    bool_arg, enforce_max_objects_in_set, extract_account_id, json_merge_patch, not_found_json,
    now_utc_string, now_utc_string_checked, optional_arg, resolve_query_offset, serialize_value,
    take_bool_arg, MergePatchError,
};

mod parse;
mod response;

pub use parse::{check_known_capabilities, parse_request, resolve_args};
pub use response::{error_invocation, error_status, request_error, RequestError};

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

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

/// 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.
///
/// The `Vec<Invocation>` holds zero or more additional entries to append to
/// `methodResponses` immediately after the primary response (in order).  Most
/// handlers return an empty `Vec`.  RFC 8621 §7.5 `EmailSubmission/set` uses
/// this to append the implicit `Email/set` invocation for `onSuccessUpdateEmail`.
pub type HandlerFuture =
    Pin<Box<dyn Future<Output = Result<(Value, Vec<Invocation>), JmapError>> + Send>>;

/// 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 {
    /// `method` is the registered method name for this call.  A single handler
    /// instance may be registered under multiple names (e.g. both `"Foo/get"` and
    /// `"Bar/get"`); this parameter lets the handler distinguish between them.
    ///
    /// `call_id` is the client-supplied identifier for this invocation (RFC 8620 §3.3).
    /// Handlers may use it for logging or correlation but need not echo it —
    /// the dispatcher echoes it in the response automatically.
    ///
    /// Both parameters are `String` (not `&str`) because the returned future is
    /// `'static` — it must own all data it captures.  Handlers that do not need
    /// `method`/`call_id` can ignore them; handlers that do (e.g. echo) simply
    /// capture the owned value.
    fn call(
        &self,
        method: String,
        call_id: String,
        args: Value,
        caller: 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 — `HashMap::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 HashMap<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>>>,
}

/// 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(),
        }
    }

    /// 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.
    ///
    /// `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
    ///
    /// **Per-request cancellation is not supported in the current API**
    /// (bd:JMAP-wlip.23). If this future is dropped while a handler
    /// task is running (e.g., the HTTP connection closes), the spawned
    /// [`tokio::task`] runs to completion — tokio does not cancel
    /// tasks when their `JoinHandle` is dropped. The handler result
    /// is discarded.
    ///
    /// Production consequence: a JMAP server with a long-running
    /// backend operation (e.g., `Email/query` over a 10M-mailbox
    /// account, a slow full-text search, a slow downstream-service
    /// lookup) cannot react to client disconnect. Every disconnect
    /// leaks resource consumption equal to the full backend cost.
    /// Adversarial clients can amplify this into a DoS by opening
    /// many requests and dropping them.
    ///
    /// Recommended mitigations until per-request cancellation is wired:
    ///
    /// - **Bound each backend operation's runtime at the backend
    ///   layer**, e.g. by passing a deadline / timeout from the
    ///   backend impl's storage client (`tokio::time::timeout` around
    ///   each database call, RPC deadline, etc.). The handler does
    ///   not need to know about deadlines; the backend impl does.
    /// - **Server-wide shutdown** via `tokio::select!` with a
    ///   broadcast channel from `main` works for the dispatcher loop
    ///   itself but does NOT propagate into spawned handler tasks.
    ///   To shut down cleanly, drain the dispatcher first and then
    ///   let in-flight handler tasks finish.
    ///
    /// The "implement cancellation at the handler level" advice
    /// previously given here was unworkable: the spawned task has
    /// no access to the outer dispatch-future's context (no token,
    /// no shared liveness flag), and the [`JmapHandler::call`]
    /// signature carries no cancellation token.
    ///
    /// A future revision may add an opt-in cancellation-token shape
    /// (CallerCtx-carried token, or a dispatch-time
    /// `cancel: CancellationToken` parameter that gets signalled on
    /// future-drop). That is a workspace-architectural decision —
    /// adding `tokio_util` to the dep allowlist plus threading the
    /// token through every backend trait method — and is tracked
    /// separately.
    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: HashMap<Id, Id> = request.created_ids.unwrap_or_default();

        // Invocation layout: (method_name, args, call_id) — RFC 8620 §3.3.
        for (method, mut args, call_id) in request.method_calls {
            // Resolve ResultReferences from prior responses.
            if let Err(e) = resolve_args(&mut args, &method_responses) {
                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();

            // Run in a spawned task for panic isolation.
            let result: Result<
                Result<(Value, Vec<Invocation>), JmapError>,
                tokio::task::JoinError,
            > = task::spawn(async move {
                handler
                    .call(method_clone, call_id_clone, args, caller_clone)
                    .await
            })
            .await;

            match result {
                Ok(Ok((primary_value, extra_invocations))) => {
                    // Accumulate createdIds from /set responses (RFC 8620 §3.4).
                    // Only when the client sent createdIds; otherwise the field
                    // is omitted from the response.
                    //
                    // Duplicate-creationId behaviour (bd:JMAP-wlip.7,
                    // bd:JMAP-jfia.3): HashMap::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.
                    if client_sent_created_ids {
                        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((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"
                    };
                    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())
            .finish()
    }
}

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

/// Type alias for the closure stored inside [`ClosureHandler`].
///
/// The `String` argument is the `call_id` (the client-supplied correlation
/// identifier from RFC 8620 §3.3), not the method name.  If you need the
/// method name inside the closure, register the handler with
/// [`Dispatcher::register`] and use [`JmapHandler`] directly instead.
///
/// `C` is the caller context (e.g. an auth identity) forwarded from
/// [`Dispatcher::dispatch`]. Closures that don't need it can ignore the
/// argument with `_ctx`.
pub type BackendCallFn<B, C> =
    dyn Fn(Arc<B>, String, serde_json::Value, 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. Closures that don't need the context can simply ignore the
/// `ctx` parameter.
///
/// # 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, call_id, args, ctx| {
///             Box::pin(async move {
///                 // ctx.user_id is available here
///                 handle_something(&*b, args, &ctx.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(...) + Send + Sync + 'static` (bd:JMAP-jfia.40), so
    /// callers can pass a closure directly without wrapping it in
    /// `Box::new`. Existing callers that already wrap in
    /// `Box::new(...)` continue to compile unchanged:
    /// `Box<dyn Fn(...) + Send + Sync + 'static>` itself implements
    /// `Fn(...)` via the blanket
    /// `impl<F: Fn(...)> Fn(...) for Box<F>`, so the boxed form
    /// satisfies the generic 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>, String, serde_json::Value, 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,
        _method: String,
        call_id: String,
        args: serde_json::Value,
        caller: C,
    ) -> HandlerFuture {
        (self.call_fn)(Arc::clone(&self.backend), call_id, args, caller)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::{json, Value};
    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,
            _method: String,
            _call_id: String,
            _args: Value,
            _caller: C,
        ) -> HandlerFuture {
            let v = self.0.clone();
            Box::pin(async move { Ok((v, vec![])) })
        }
    }

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

    impl JmapHandler<String> for ErrorHandler {
        fn call(
            &self,
            _method: String,
            _call_id: String,
            _args: Value,
            _caller: 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,
            _method: String,
            _call_id: String,
            args: Value,
            _caller: String,
        ) -> HandlerFuture {
            let slot = self.0.clone();
            Box::pin(async move {
                *slot.lock().expect("test: mutex poisoned") = Some(args);
                Ok((json!({}), vec![]))
            })
        }
    }

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

    impl JmapHandler<String> for CaptureCallerHandler {
        fn call(
            &self,
            _method: String,
            _call_id: String,
            _args: Value,
            caller: String,
        ) -> HandlerFuture {
            let slot = self.0.clone();
            Box::pin(async move {
                *slot.lock().expect("test: mutex poisoned") = Some(caller);
                Ok((json!({}), vec![]))
            })
        }
    }

    /// Panics unconditionally.
    struct PanicHandler;

    impl JmapHandler<String> for PanicHandler {
        fn call(
            &self,
            _method: String,
            _call_id: String,
            _args: Value,
            _caller: 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![(method.into(), args, call_id.into())],
            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 (_, 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 (method, args, call_id) = &resp.method_responses[0];
        assert_eq!(method, "Foo/get");
        assert_eq!(call_id, "c1");
        assert_eq!(args["list"], json!([]));
    }

    /// 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::not_found())));
        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 (_, args, _) = &resp.method_responses[0];
        assert_eq!(args["type"], "notFound");
    }

    /// 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 (_, 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 (_, 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![
                ("M/a".into(), json!({}), "c0".into()),
                ("M/b".into(), json!({}), "c1".into()),
                ("M/a".into(), json!({}), "c2".into()),
            ],
            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].2, "c0");
        assert!(
            resp.method_responses[0].1.get("type").is_none(),
            "c0 must not be an error"
        );
        // responses[1]: M/b unknownMethod
        assert_eq!(resp.method_responses[1].2, "c1");
        assert_eq!(resp.method_responses[1].1["type"], "unknownMethod");
        // responses[2]: M/a success (error in [1] did not abort the batch)
        assert_eq!(resp.method_responses[2].2, "c2");
        assert!(
            resp.method_responses[2].1.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![
                ("M/err".into(), json!({}), "c0".into()),
                ("M/ok".into(), json!({}), "c1".into()),
            ],
            None,
        );
        let resp = d.dispatch(req, "alice".into(), "s0".into()).await;
        assert_eq!(resp.method_responses.len(), 2);
        assert_eq!(resp.method_responses[0].1["type"], "forbidden");
        assert!(
            resp.method_responses[1].1.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 (_, 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 (_, 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![
                ("Foo/get".into(), json!({}), "c0".into()),
                (
                    "Bar/query".into(),
                    json!({"#ids": {"resultOf": "c0", "name": "Foo/get", "path": "/list/0/id"}}),
                    "c1".into(),
                ),
            ],
            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].1.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 (_, 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![("Foo/set".into(), json!({}), "c0".into())],
            Some(std::collections::HashMap::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"
        );
    }

    /// 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![
                ("A/set".into(), json!({}), "c0".into()),
                ("B/set".into(), json!({}), "c1".into()),
            ],
            Some(std::collections::HashMap::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::HashMap::new();
        initial.insert(Id::from("client-old"), Id::from("server-old"));
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![("Foo/set".into(), json!({}), "c0".into())],
            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::HashMap::new();
        initial.insert(Id::from("client-X"), Id::from("server-A"));
        let req = JmapRequest::new(
            vec!["urn:ietf:params:jmap:core".into()],
            vec![("Foo/set".into(), json!({}), "c0".into())],
            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![
                ("A/set".into(), json!({}), "c0".into()),
                ("B/set".into(), json!({}), "c1".into()),
            ],
            Some(std::collections::HashMap::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"
        );
    }

    // -----------------------------------------------------------------------
    // 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].1.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].1.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,
            _method: String,
            _call_id: String,
            _args: Value,
            _caller: String,
        ) -> HandlerFuture {
            Box::pin(async move {
                let primary = json!({"type": "primary"});
                let extra: Vec<Invocation> = vec![(
                    "Extra/call".to_owned(),
                    json!({"type": "extra"}),
                    "x0".to_owned(),
                )];
                Ok((primary, 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].0, "Sub/set");
        assert_eq!(resp.method_responses[0].2, "c0");
        assert_eq!(resp.method_responses[0].1["type"], "primary");
        // Second: the appended extra invocation.
        assert_eq!(resp.method_responses[1].0, "Extra/call");
        assert_eq!(resp.method_responses[1].2, "x0");
        assert_eq!(resp.method_responses[1].1["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>, _call_id: String, _args: Value, ctx: Ctx| {
                let cap = Arc::clone(&received_clone);
                Box::pin(async move {
                    *cap.lock().unwrap() = Some(ctx.0.clone());
                    Ok((serde_json::json!({}), vec![]))
                })
            },
        ));

        let ctx = Ctx("alice".to_owned());
        handler
            .call("Test/get".into(), "c1".into(), 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: 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, _ci, _a, _ctx| {
            Box::pin(async { Ok((serde_json::json!({}), vec![])) })
        });
        assert_handler::<Ctx, _>(&h);
    }
}