jmap-server 0.4.2

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
//! Shared backend infrastructure for all JMAP server crates.
//!
//! Re-exports the marker traits and the `SetError` types from `jmap-types` and adds the result types,
//! `BackendChangesError`, `BackendQueryError`, and [`JmapBackend`] supertrait. Domain crates add
//! their write-side methods and domain-specific error variants on top.

pub use jmap_types::{
    GetObject, JmapObject, QueryObject, ReservedExtrasKey, SetError, SetErrorType, SetObject,
};

/// Error type returned by create/update/destroy backend methods.
#[non_exhaustive]
#[derive(Debug)]
pub enum BackendSetError<E> {
    /// A well-typed JMAP [`SetError`] to place verbatim in the
    /// `notCreated`/`notUpdated`/`notDestroyed` map.
    ///
    /// Boxed so the `Err` arm of a backend `Result` stays pointer-sized
    /// (`SetError` is over 200 bytes; clippy `result_large_err`).
    SetError(Box<SetError>),
    /// An unexpected storage-layer error.
    Other(E),
}

impl<E: std::fmt::Display> std::fmt::Display for BackendSetError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SetError(se) => write!(f, "set error: {se}"),
            Self::Other(e) => write!(f, "{e}"),
        }
    }
}

impl<E: std::error::Error + 'static> std::error::Error for BackendSetError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Other(e) => Some(e),
            _ => None,
        }
    }
}

impl<E> From<SetError> for BackendSetError<E> {
    fn from(e: SetError) -> Self {
        Self::SetError(Box::new(e))
    }
}

impl<E> From<Box<SetError>> for BackendSetError<E> {
    fn from(e: Box<SetError>) -> Self {
        Self::SetError(e)
    }
}

impl<E: std::fmt::Display> BackendSetError<E> {
    /// Split into the per-object [`SetError`] (`Ok`) or a redacted
    /// method-level `serverFail` (`Err`).
    ///
    /// RFC 8620 ยง5.3 places a per-object `SetError` in the
    /// `notCreated`/`notUpdated`/`notDestroyed` map, so the `SetError`
    /// variant is returned unchanged for the caller to insert there.
    /// [`Other`](Self::Other) becomes
    /// `JmapError::server_fail(SERVER_FAIL_INTERNAL_DESC)`: the inner
    /// error's `Display` text never reaches the wire (bd:JMAP-jfia.36).
    ///
    /// There is deliberately no `From<BackendSetError<E>> for JmapError`:
    /// a `?` on that impl would turn per-object set errors into
    /// method-level errors.
    ///
    /// [`SERVER_FAIL_INTERNAL_DESC`]: crate::handlers::SERVER_FAIL_INTERNAL_DESC
    ///
    /// # Errors
    ///
    /// Returns the redacted `serverFail` [`JmapError`](jmap_types::JmapError) for
    /// [`Other`](Self::Other).
    pub fn into_set_error_or_method_error(self) -> Result<SetError, jmap_types::JmapError> {
        match self {
            Self::SetError(se) => Ok(*se),
            Self::Other(e) => Err(crate::handlers::server_fail_from_backend(&e)),
        }
    }
}

/// The `notCreated` / `notUpdated` / `notDestroyed` map value for a
/// backend `/set` failure (RFC 8620 ยง5.3).
///
/// [`BackendSetError::SetError`] serializes verbatim;
/// [`BackendSetError::Other`] becomes a `serverFail` with the fixed
/// [`SERVER_FAIL_INTERNAL_DESC`](crate::SERVER_FAIL_INTERNAL_DESC)
/// description, so the inner error's `Display` text never reaches the
/// wire (bd:JMAP-jfia.36). Every `*-server` crate maps per-object backend
/// errors through this one function.
pub fn backend_set_error_value<E: std::fmt::Display>(err: BackendSetError<E>) -> serde_json::Value {
    match err {
        BackendSetError::SetError(se) => serde_json::Value::from(*se),
        BackendSetError::Other(e) => crate::handlers::server_fail_value_from_backend(&e),
    }
}

// ---------------------------------------------------------------------------
// Backend error envelopes
// ---------------------------------------------------------------------------

/// Error type returned by [`JmapBackend::get_changes`] and
/// [`JmapBackend::query_changes`].
///
/// The two non-`Other` variants map to the RFC 8620 ยง5.6 wire errors
/// `cannotCalculateChanges` and `tooManyChanges`; `/changes` (ยง5.2) has
/// only the former (see [`changes_error_from_backend`](crate::changes_error_from_backend)).
#[non_exhaustive]
#[derive(Debug)]
pub enum BackendChangesError<E> {
    /// The server has no usable change log for the given `sinceState`
    /// and cannot supply incremental changes โ€” the client MUST
    /// discard ALL locally cached objects for the affected type,
    /// reset its local state token to the empty string, and perform a
    /// full resync (`/get` with `ids: null`). Partial recovery is not
    /// permitted. Maps to `cannotCalculateChanges` (RFC 8620 ยง5.6;
    /// authoritative behavior documented in jmapio/jmap-js
    /// `mail-model.js`).
    CannotCalculate,
    /// The change window exceeds what the server can supply in a
    /// single response. Maps to `tooManyChanges` with the `limit` as the
    /// suggested maximum for `/queryChanges` (RFC 8620 ยง5.6). `/changes`
    /// has no such error (ยง5.2), so
    /// [`changes_error_from_backend`](crate::changes_error_from_backend)
    /// maps it to `cannotCalculateChanges` there; a `get_changes` backend
    /// over `maxChanges` SHOULD instead return an intermediate state with
    /// `has_more_changes` set.
    TooManyChanges {
        /// Maximum window size the server can supply in a single
        /// `/changes` response, the suggested maximum the client may
        /// retry with.
        limit: u64,
    },
    /// An unexpected storage-layer error.
    Other(E),
}

impl<E: std::fmt::Display> std::fmt::Display for BackendChangesError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::CannotCalculate => write!(f, "cannot calculate changes"),
            Self::TooManyChanges { limit } => write!(f, "too many changes (limit: {limit})"),
            Self::Other(e) => write!(f, "{e}"),
        }
    }
}

impl<E: std::error::Error + 'static> std::error::Error for BackendChangesError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Other(e) => Some(e),
            _ => None,
        }
    }
}

impl<E> From<E> for BackendChangesError<E> {
    fn from(e: E) -> Self {
        Self::Other(e)
    }
}

impl<E: std::error::Error> From<BackendChangesError<E>> for jmap_types::JmapError {
    fn from(e: BackendChangesError<E>) -> Self {
        match e {
            BackendChangesError::CannotCalculate => {
                jmap_types::JmapError::cannot_calculate_changes()
            }
            BackendChangesError::TooManyChanges { limit } => {
                jmap_types::JmapError::too_many_changes_with_limit(limit)
            }
            // bd:JMAP-jfia.1 / bd:JMAP-wlip.2 โ€” the `Other` arm wraps a
            // backend `Error` whose `Display` impl is contractually
            // forbidden from carrying credential/blob/PII text but which
            // we still treat as untrusted at the wire boundary. Use the
            // same static [`SERVER_FAIL_INTERNAL_DESC`] string that the
            // [`server_fail_from_backend`] handler-layer helper uses so
            // the defence-in-depth chain (backend Display contract โ†’
            // handler helper โ†’ this From impl) cannot be bypassed by
            // handlers that take the ergonomic `.map_err(JmapError::from)?`
            // path on `BackendChangesError`.
            //
            // [`SERVER_FAIL_INTERNAL_DESC`]: crate::handlers::SERVER_FAIL_INTERNAL_DESC
            // [`server_fail_from_backend`]: crate::handlers::server_fail_from_backend
            BackendChangesError::Other(_inner) => {
                jmap_types::JmapError::server_fail(crate::handlers::SERVER_FAIL_INTERNAL_DESC)
            }
        }
    }
}

/// Error type returned by [`JmapBackend::query_objects`].
///
/// RFC 8620 ยง5.5 lets a `/query` fail with method errors that only the
/// backend can detect (`unsupportedFilter`, `unsupportedSort`,
/// `anchorNotFound`, ...). [`Self::Method`] carries such an error to the
/// client unchanged; [`Self::Other`] is an internal storage-layer failure
/// that handlers surface as the redacted `serverFail`.
#[non_exhaustive]
#[derive(Debug)]
pub enum BackendQueryError<E> {
    /// An RFC 8620 ยง5.5 method error, returned to the client as-is
    /// (type and description). Backends MUST NOT put internal error
    /// text in it.
    Method(jmap_types::JmapError),
    /// An unexpected storage-layer error.
    Other(E),
}

impl<E: std::fmt::Display> std::fmt::Display for BackendQueryError<E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Method(e) => write!(f, "{e}"),
            Self::Other(e) => write!(f, "{e}"),
        }
    }
}

impl<E: std::error::Error + 'static> std::error::Error for BackendQueryError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Method(_) => None,
            Self::Other(e) => Some(e),
        }
    }
}

impl<E> From<E> for BackendQueryError<E> {
    fn from(e: E) -> Self {
        Self::Other(e)
    }
}

impl<E> From<BackendQueryError<E>> for jmap_types::JmapError {
    fn from(e: BackendQueryError<E>) -> Self {
        match e {
            BackendQueryError::Method(err) => err,
            // Same redaction as `BackendChangesError::Other`: the backend
            // error's text never reaches the wire.
            BackendQueryError::Other(_inner) => {
                jmap_types::JmapError::server_fail(crate::handlers::SERVER_FAIL_INTERNAL_DESC)
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Result types
// ---------------------------------------------------------------------------

/// Result of a `/changes` call (RFC 8620 ยง5.2).
#[derive(Debug)]
#[non_exhaustive]
pub struct ChangesResult {
    /// Ids of objects that were created since `sinceState`.
    pub created: Vec<jmap_types::Id>,
    /// Ids of objects that were updated since `sinceState`.
    pub updated: Vec<jmap_types::Id>,
    /// Ids of objects that were destroyed since `sinceState`.
    pub destroyed: Vec<jmap_types::Id>,
    /// `true` if there are more changes beyond this batch.
    pub has_more_changes: bool,
    /// The current state token after applying all reported changes.
    pub new_state: jmap_types::State,
    /// The `updatedProperties` response argument (RFC 8621 ยง2.2,
    /// draft-ietf-jmap-metadata-04 ยง3.3): the only properties that may
    /// have changed on every id in [`updated`](Self::updated), or `None`
    /// when any other property may have changed or the backend cannot
    /// tell. [`crate::handle_changes`] sends `null` when `updated` is
    /// empty, whatever this holds.
    pub updated_properties: Option<Vec<String>>,
}

impl ChangesResult {
    /// Construct a [`ChangesResult`].
    pub fn new(
        created: Vec<jmap_types::Id>,
        updated: Vec<jmap_types::Id>,
        destroyed: Vec<jmap_types::Id>,
        has_more_changes: bool,
        new_state: jmap_types::State,
    ) -> Self {
        Self {
            created,
            updated,
            destroyed,
            has_more_changes,
            new_state,
            updated_properties: None,
        }
    }

    /// Set [`updated_properties`](Self::updated_properties); [`Self::new`]
    /// leaves it `None`.
    #[must_use]
    pub fn with_updated_properties(mut self, updated_properties: Option<Vec<String>>) -> Self {
        self.updated_properties = updated_properties;
        self
    }
}

/// Result of a `/query` call (RFC 8620 ยง5.5).
#[derive(Debug)]
#[non_exhaustive]
pub struct QueryResult {
    /// The ordered list of matching object ids.
    pub ids: Vec<jmap_types::Id>,
    /// The 0-based index of the first returned id in the complete result list.
    ///
    /// RFC 8620 ยง5.5 specifies this as `UnsignedInt` in the response โ€”
    /// a non-negative integer (bd:JMAP-wlip.25). The request-side
    /// position parameter accepts negative values as end-relative
    /// offsets, but the response position cannot validly be negative.
    /// Backends that derive `position` from a request-side `i64`
    /// offset MUST clamp / normalize to `u64` before constructing this
    /// struct.
    pub position: u64,
    /// Total number of results, if the backend can calculate it.
    pub total: Option<u64>,
    /// Opaque query state token for subsequent `/queryChanges` calls.
    pub query_state: jmap_types::State,
    /// Whether the backend supports `/queryChanges` for this query.
    pub can_calculate_changes: bool,
}

impl QueryResult {
    /// Construct a [`QueryResult`].
    pub fn new(
        ids: Vec<jmap_types::Id>,
        position: u64,
        total: Option<u64>,
        query_state: jmap_types::State,
        can_calculate_changes: bool,
    ) -> Self {
        Self {
            ids,
            position,
            total,
            query_state,
            can_calculate_changes,
        }
    }

    /// Construct a [`QueryResult`] from a signed request-side position,
    /// clamping negatives to `0` and normalizing to `u64`
    /// (bd:JMAP-jfia.25).
    ///
    /// RFC 8620 ยง5.5 specifies the response `position` as `UnsignedInt`,
    /// but the request-side `position` parameter accepts negative
    /// values as end-relative offsets. Backends typically receive the
    /// signed value, walk the offset into the result list, and need
    /// to surface the resulting 0-based index. This constructor takes
    /// the resolved-offset value and clamps to `u64`, matching the
    /// spec contract.
    ///
    /// Negative inputs clamp to `0` (representing "the start of the
    /// result list"). Backends that have already done the
    /// offset-to-index resolution and have a `u64` already SHOULD use
    /// the plain [`Self::new`] constructor instead.
    pub fn new_clamped(
        ids: Vec<jmap_types::Id>,
        position_signed: i64,
        total: Option<u64>,
        query_state: jmap_types::State,
        can_calculate_changes: bool,
    ) -> Self {
        // i64::max(_, 0) then cast to u64 โ€” both fit in u64 because
        // i64 >= 0 has range [0, i64::MAX], which is a strict subset
        // of u64's range.
        let position = u64::try_from(position_signed.max(0)).unwrap_or(0);
        Self::new(ids, position, total, query_state, can_calculate_changes)
    }
}

/// One entry in the `added` list of a `/queryChanges` response (RFC 8620 ยง5.6).
#[derive(Debug)]
#[non_exhaustive]
pub struct AddedItem {
    /// The id of the newly-added object.
    pub id: jmap_types::Id,
    /// Its 0-based position in the result list after applying all changes.
    pub index: u64,
}

impl AddedItem {
    /// Construct an [`AddedItem`].
    pub fn new(id: jmap_types::Id, index: u64) -> Self {
        Self { id, index }
    }
}

/// Result of a `/queryChanges` call (RFC 8620 ยง5.6).
#[derive(Debug)]
#[non_exhaustive]
pub struct QueryChangesResult {
    /// The query state token supplied by the client in `sinceQueryState`.
    pub old_query_state: jmap_types::State,
    /// The current query state token.
    pub new_query_state: jmap_types::State,
    /// Total number of results in the new query, if the backend can calculate it.
    pub total: Option<u64>,
    /// Ids removed from the result set since `oldQueryState`.
    pub removed: Vec<jmap_types::Id>,
    /// Ids added to the result set since `oldQueryState`, with their positions.
    pub added: Vec<AddedItem>,
}

impl QueryChangesResult {
    /// Construct a [`QueryChangesResult`].
    pub fn new(
        old_query_state: jmap_types::State,
        new_query_state: jmap_types::State,
        total: Option<u64>,
        removed: Vec<jmap_types::Id>,
        added: Vec<AddedItem>,
    ) -> Self {
        Self {
            old_query_state,
            new_query_state,
            total,
            removed,
            added,
        }
    }
}

// ---------------------------------------------------------------------------
// Changes parameters
// ---------------------------------------------------------------------------

/// The `/changes` arguments (RFC 8620 ยง5.2) passed to
/// [`JmapBackend::get_changes`], after `accountId`.
///
/// `#[non_exhaustive]` for the same reason as [`QueryParams`]. Build one
/// with [`ChangesParams::new`], which takes the one required argument,
/// `sinceState`, and the setters:
///
/// ```
/// # use jmap_server::ChangesParams;
/// let since = jmap_server::State::from("s1");
/// let params = ChangesParams::new(&since).max_changes(Some(50));
/// assert_eq!(params.max_changes, Some(50));
/// assert!(!params.ignore_metadata_only_changes);
/// ```
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct ChangesParams<'a> {
    /// `sinceState`, the state the client already has.
    pub since_state: &'a jmap_types::State,
    /// `maxChanges`; `None` means no client limit.
    pub max_changes: Option<u64>,
    /// `ignoreMetadataOnlyChanges` (draft-ietf-jmap-metadata-04 ยง3.3):
    /// when `true`, a backend that tracks per-update changed properties
    /// MUST leave out of `updated` every id whose only changes are to
    /// `metadata` and/or `privateMetadata`, and those ids do not count
    /// toward `max_changes`. [`crate::handle_changes`] sets it `true`
    /// for a request whose `using` lacks `urn:ietf:params:jmap:metadata`
    /// (-04 ยง3). A backend that does not support metadata ignores it.
    pub ignore_metadata_only_changes: bool,
}

impl<'a> ChangesParams<'a> {
    /// Changes since `since_state`, with no `maxChanges` and
    /// `ignoreMetadataOnlyChanges` false (its -04 ยง3.3 default).
    pub fn new(since_state: &'a jmap_types::State) -> Self {
        Self {
            since_state,
            max_changes: None,
            ignore_metadata_only_changes: false,
        }
    }

    /// Set [`max_changes`](Self::max_changes).
    #[must_use]
    pub fn max_changes(mut self, max_changes: Option<u64>) -> Self {
        self.max_changes = max_changes;
        self
    }

    /// Set [`ignore_metadata_only_changes`](Self::ignore_metadata_only_changes).
    #[must_use]
    pub fn ignore_metadata_only_changes(mut self, ignore: bool) -> Self {
        self.ignore_metadata_only_changes = ignore;
        self
    }
}

// ---------------------------------------------------------------------------
// Query parameters
// ---------------------------------------------------------------------------

/// The `/query` arguments (RFC 8620 ยง5.5) passed to
/// [`JmapBackend::query_objects`], after `accountId`.
///
/// `#[non_exhaustive]` so a new RFC or extension argument is a new field,
/// not a breaking change to every backend (bd:JMAP-wf92.7). Backends read
/// the public fields; callers build one with [`QueryParams::new`] and the
/// setters:
///
/// ```
/// # use jmap_server::{JmapObject, QueryObject, QueryParams};
/// # #[derive(serde::Serialize, serde::Deserialize)]
/// # struct Foo;
/// # impl JmapObject for Foo { const TYPE_NAME: &'static str = "Foo"; type Property = (); }
/// # impl QueryObject for Foo { type Filter = serde_json::Value; type Comparator = serde_json::Value; }
/// let filter = serde_json::json!({"text": "hello"});
/// let params = QueryParams::<Foo>::new().filter(Some(&filter)).limit(Some(50));
/// assert_eq!(params.position, 0);
/// ```
#[non_exhaustive]
pub struct QueryParams<'a, O: QueryObject> {
    /// `filter`; `None` matches every object.
    pub filter: Option<&'a O::Filter>,
    /// `sort`; `None` leaves the order to the server.
    pub sort: Option<&'a [O::Comparator]>,
    /// `limit`; `None` means no client limit.
    pub limit: Option<u64>,
    /// `position`. Negative values count from the end of the results
    /// (RFC 8620 ยง5.5); ignored when `anchor` is set.
    pub position: i64,
    /// `anchor`: start the page at this id's index instead of `position`.
    pub anchor: Option<&'a jmap_types::Id>,
    /// `anchorOffset`, added to the anchor's index; ignored without an
    /// `anchor`.
    pub anchor_offset: i64,
}

impl<'a, O: QueryObject> QueryParams<'a, O> {
    /// The RFC 8620 ยง5.5 defaults: no filter, sort, limit or anchor, and
    /// `position` and `anchorOffset` 0.
    pub fn new() -> Self {
        Self {
            filter: None,
            sort: None,
            limit: None,
            position: 0,
            anchor: None,
            anchor_offset: 0,
        }
    }

    /// Set [`filter`](Self::filter).
    #[must_use]
    pub fn filter(mut self, filter: Option<&'a O::Filter>) -> Self {
        self.filter = filter;
        self
    }

    /// Set [`sort`](Self::sort).
    #[must_use]
    pub fn sort(mut self, sort: Option<&'a [O::Comparator]>) -> Self {
        self.sort = sort;
        self
    }

    /// Set [`limit`](Self::limit).
    #[must_use]
    pub fn limit(mut self, limit: Option<u64>) -> Self {
        self.limit = limit;
        self
    }

    /// Set [`position`](Self::position).
    #[must_use]
    pub fn position(mut self, position: i64) -> Self {
        self.position = position;
        self
    }

    /// Set [`anchor`](Self::anchor).
    #[must_use]
    pub fn anchor(mut self, anchor: Option<&'a jmap_types::Id>) -> Self {
        self.anchor = anchor;
        self
    }

    /// Set [`anchor_offset`](Self::anchor_offset).
    #[must_use]
    pub fn anchor_offset(mut self, anchor_offset: i64) -> Self {
        self.anchor_offset = anchor_offset;
        self
    }
}

impl<O: QueryObject> Default for QueryParams<'_, O> {
    fn default() -> Self {
        Self::new()
    }
}

// Manual impls: derives would wrongly require `O: Clone` / `O: Debug`.
impl<O: QueryObject> Clone for QueryParams<'_, O> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<O: QueryObject> Copy for QueryParams<'_, O> {}

impl<O: QueryObject> std::fmt::Debug for QueryParams<'_, O>
where
    O::Filter: std::fmt::Debug,
    O::Comparator: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("QueryParams")
            .field("filter", &self.filter)
            .field("sort", &self.sort)
            .field("limit", &self.limit)
            .field("position", &self.position)
            .field("anchor", &self.anchor)
            .field("anchor_offset", &self.anchor_offset)
            .finish()
    }
}

/// The `/queryChanges` arguments (RFC 8620 ยง5.6) passed to
/// [`JmapBackend::query_changes`], after `accountId`.
///
/// `#[non_exhaustive]` for the same reason as [`QueryParams`]. Build one
/// with [`QueryChangesParams::new`], which takes the one required
/// argument, `sinceQueryState`, and the setters.
#[non_exhaustive]
pub struct QueryChangesParams<'a, O: QueryObject> {
    /// `sinceQueryState`, the `queryState` the client already has.
    pub since_query_state: &'a jmap_types::State,
    /// `filter`, as passed to the original `/query`.
    pub filter: Option<&'a O::Filter>,
    /// `sort`, as passed to the original `/query`.
    pub sort: Option<&'a [O::Comparator]>,
    /// `maxChanges`; `None` means no client limit.
    pub max_changes: Option<u64>,
    /// `upToId`: the last id in the client's cached results.
    pub up_to_id: Option<&'a jmap_types::Id>,
    /// `collapseThreads`, meaningful only for `Email/queryChanges`
    /// (RFC 8621 ยง4.5); `false` for every other type.
    pub collapse_threads: bool,
}

impl<'a, O: QueryObject> QueryChangesParams<'a, O> {
    /// Changes since `since_query_state`, with no filter, sort,
    /// `maxChanges` or `upToId`, and `collapseThreads` false.
    pub fn new(since_query_state: &'a jmap_types::State) -> Self {
        Self {
            since_query_state,
            filter: None,
            sort: None,
            max_changes: None,
            up_to_id: None,
            collapse_threads: false,
        }
    }

    /// Set [`filter`](Self::filter).
    #[must_use]
    pub fn filter(mut self, filter: Option<&'a O::Filter>) -> Self {
        self.filter = filter;
        self
    }

    /// Set [`sort`](Self::sort).
    #[must_use]
    pub fn sort(mut self, sort: Option<&'a [O::Comparator]>) -> Self {
        self.sort = sort;
        self
    }

    /// Set [`max_changes`](Self::max_changes).
    #[must_use]
    pub fn max_changes(mut self, max_changes: Option<u64>) -> Self {
        self.max_changes = max_changes;
        self
    }

    /// Set [`up_to_id`](Self::up_to_id).
    #[must_use]
    pub fn up_to_id(mut self, up_to_id: Option<&'a jmap_types::Id>) -> Self {
        self.up_to_id = up_to_id;
        self
    }

    /// Set [`collapse_threads`](Self::collapse_threads).
    #[must_use]
    pub fn collapse_threads(mut self, collapse_threads: bool) -> Self {
        self.collapse_threads = collapse_threads;
        self
    }
}

impl<O: QueryObject> Clone for QueryChangesParams<'_, O> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<O: QueryObject> Copy for QueryChangesParams<'_, O> {}

impl<O: QueryObject> std::fmt::Debug for QueryChangesParams<'_, O>
where
    O::Filter: std::fmt::Debug,
    O::Comparator: std::fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("QueryChangesParams")
            .field("since_query_state", &self.since_query_state)
            .field("filter", &self.filter)
            .field("sort", &self.sort)
            .field("max_changes", &self.max_changes)
            .field("up_to_id", &self.up_to_id)
            .field("collapse_threads", &self.collapse_threads)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// JmapBackend โ€” the read-side supertrait
// ---------------------------------------------------------------------------

/// Read-side backend supertrait shared by all JMAP server crates.
///
/// Domain-specific backend traits (`MailBackend`, `ChatBackend`, etc.) require
/// this trait as a supertrait and add write-side methods on top.
///
/// Only the read operations that have an identical signature across all JMAP
/// object types belong here. Write operations (`create_object`, `update_object`,
/// `destroy_object`) and domain-specific operations remain in the domain crate.
///
/// [`QueryChangesParams::collapse_threads`] is included for
/// `Email/queryChanges` (RFC 8621 ยง4.5). Non-mail backends may ignore it.
///
/// This trait is not object-safe by design (generic methods). Use
/// `Arc<impl JmapBackend>` when sharing across tasks.
///
/// # CallerCtx
///
/// Every backend method takes a `caller: &Self::CallerCtx` parameter as the
/// first argument after `&self`. This is the per-request authentication /
/// authorisation context produced by the caller's auth layer and forwarded
/// unchanged through [`crate::Dispatcher::dispatch`] โ†’ [`crate::JmapHandler`]
/// โ†’ the registered closure โ†’ the backend.
///
/// Implementations that do not need an auth identity can use the unit type:
///
/// ```rust,ignore
/// impl JmapBackend for MyBackend {
///     type Error = MyError;
///     type CallerCtx = ();
///     // ...
/// }
/// ```
///
/// Implementations that do need to differentiate behaviour per caller (e.g.
/// applying per-user visibility rules, or rejecting reads with
/// `forbidden` when the caller is not the owner of the account) read the
/// `caller` parameter to decide.
///
/// The trait bound `Clone + Send + 'static` is what [`crate::Dispatcher`]
/// requires; the bound is repeated here so the supertrait can stand on its
/// own without depending on the dispatcher.
pub trait JmapBackend: Send + Sync + 'static {
    /// The error type returned by storage operations.
    ///
    /// # Security
    ///
    /// The `Display` impl of this type is surfaced through
    /// [`BackendSetError::Other`]'s and [`BackendChangesError::Other`]'s
    /// own `Display` impls, which in turn flow into
    /// [`crate::request_error`]'s `RequestError::Display` output. When a
    /// downstream consumer wires tracing-style logging on top, the
    /// formatted error text lands in operator logs verbatim.
    ///
    /// Implementations MUST NOT include any of the following in this
    /// type's `Display` output:
    ///
    /// - **Credential material** โ€” auth tokens, passwords, push
    ///   verification codes, invite codes, session cookies, or anything
    ///   derived byte-for-byte from an `Authorization`-header value.
    /// - **Blob content** โ€” email bodies, sieve scripts, file contents,
    ///   or any user-supplied opaque payload. An error like
    ///   `"sieve parse error at line 42: <script excerpt>"` violates
    ///   this โ€” emit the line number and a short type-only summary
    ///   ("sieve parse error at line 42: unexpected token") and let the
    ///   server log the full script body separately under a redacted
    ///   path.
    /// - **PII shaped like an email address** in any code path that an
    ///   unauthenticated caller can trigger. Wrapping a downstream
    ///   service error that interpolates the caller's email is the
    ///   common foot-gun.
    ///
    /// Errors that wrap a downstream-service failure should sanitize
    /// the downstream error text โ€” or strip it entirely and replace it
    /// with a static summary โ€” before constructing the `Display`
    /// string. The same rule applies to every extension `*Backend`
    /// trait that inherits this associated type by transitivity:
    /// `MailBackend::Error`, `ChatBackend::Error`,
    /// `CalendarsBackend::Error`, `TasksBackend::Error`,
    /// `ContactsBackend::Error`, `FileNodeBackend::Error`, and
    /// `SharingBackend::Error` are all the same `JmapBackend::Error`
    /// associated type โ€” the contract here governs all of them.
    ///
    /// Precedent: bd:JMAP-sc1b.79 redacted `BearerAuth` and `BasicAuth`
    /// at the type-derive level; bd:JMAP-sc1b.100 documents the
    /// equivalent contract at the trait-associated-type level.
    type Error: std::error::Error + Send + Sync + 'static;

    /// The per-request caller context type produced by the auth layer and
    /// forwarded by [`crate::Dispatcher::dispatch`] into every method call.
    ///
    /// Use `()` when no auth context is needed.
    ///
    /// The bound is `Clone + Send + Sync + 'static`:
    /// - `Clone` because [`crate::Dispatcher`] clones the value once per
    ///   method call in the batch.
    /// - `Send + 'static` because each method call is spawned on a
    ///   [`tokio::task`].
    /// - `Sync` because handler method bodies take `&Self::CallerCtx`
    ///   and hold that reference across `.await` boundaries inside a
    ///   `Send` future (a `&T` is `Send` iff `T: Sync`).
    type CallerCtx: Clone + Send + Sync + 'static;

    /// Return `true` if the given account exists in this backend.
    ///
    /// Handlers call this at the start of each method to return
    /// `accountNotFound` (RFC 8620 ยง3.6.2) rather than surfacing
    /// the wrong error when `accountId` is unknown.
    ///
    /// # Performance contract (bd:JMAP-jfia.27)
    ///
    /// Implementations SHOULD return in sub-millisecond time. The
    /// JMAP standard handlers (`handle_get`, `handle_changes`,
    /// `handle_query`, `handle_query_changes`) each call
    /// `account_exists` at the START of the method, BEFORE delegating
    /// to the per-domain backend. A typical JMAP request batch is
    /// 4โ€“16 method calls; a naive remote round-trip per call would
    /// add 4โ€“16ร— the network latency to every batch.
    ///
    /// Acceptable backing strategies: in-memory cache (the
    /// reference `MemoryBackend` impls all use this); an indexed
    /// primary-key lookup against a local database; a bloom filter
    /// for negative lookups paired with a cache for positives. A
    /// naive `SELECT 1 FROM accounts WHERE id = ?` against a remote
    /// database is INCORRECT for this method even though it would
    /// return the right value โ€” the round-trip cost is the bug.
    ///
    /// The dispatcher does not cache this call across the method
    /// calls in a single batch (workspace-architectural decision โ€”
    /// the dispatcher is intentionally stateless across the batch
    /// loop). Caching is the backend implementor's responsibility.
    fn account_exists(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
    ) -> impl std::future::Future<Output = Result<bool, Self::Error>> + Send;

    /// Fetch objects by id (or all objects when `ids` is `None`).
    ///
    /// `properties` is the list of property names requested by the client
    /// (RFC 8620 ยง5.1). `None` means the client did not send a `properties`
    /// field; the backend should return all properties. When `Some`, the backend
    /// MAY filter the response to only the named properties, but is not required
    /// to โ€” implementations that always return all properties are correct.
    ///
    /// Returns `(found, not_found)` โ€” objects that exist and ids that do not.
    ///
    /// # Unknown `account_id`
    ///
    /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
    /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
    /// [`Self::account_exists`] before calling this method and return
    /// `accountNotFound` (RFC 8620 ยง3.6.2) themselves, so implementations
    /// need not repeat that check. A caller that bypasses those handlers can
    /// still reach this method with an unknown account; backends SHOULD then
    /// return `Ok` with an empty `found` list and every requested id in `not_found`. Returning `Err` is permitted but surfaces as
    /// `serverFail`, not `accountNotFound`.
    fn get_objects<O: GetObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        ids: Option<&[jmap_types::Id]>,
        properties: Option<&[String]>,
    ) -> impl std::future::Future<Output = Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error>> + Send;

    /// Return the current state token for an object type in the given account.
    ///
    /// # Unknown `account_id`
    ///
    /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
    /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
    /// [`Self::account_exists`] before calling this method and return
    /// `accountNotFound` (RFC 8620 ยง3.6.2) themselves, so implementations
    /// need not repeat that check. A caller that bypasses those handlers can
    /// still reach this method with an unknown account; backends SHOULD then
    /// return `Ok` with the state token an empty account would report. Returning `Err` is permitted but surfaces as
    /// `serverFail`, not `accountNotFound`.
    fn get_state<O: JmapObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
    ) -> impl std::future::Future<Output = Result<jmap_types::State, Self::Error>> + Send;

    /// Return changes since `params.since_state`, up to
    /// `params.max_changes` entries, honouring
    /// `params.ignore_metadata_only_changes` (see [`ChangesParams`]).
    ///
    /// # Unknown `account_id`
    ///
    /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
    /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
    /// [`Self::account_exists`] before calling this method and return
    /// `accountNotFound` (RFC 8620 ยง3.6.2) themselves, so implementations
    /// need not repeat that check. A caller that bypasses those handlers can
    /// still reach this method with an unknown account; backends SHOULD then
    /// return `Ok` with a [`ChangesResult`] whose change lists are empty. Returning `Err` is permitted but surfaces as
    /// `serverFail`, not `accountNotFound`.
    fn get_changes<O: JmapObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        params: ChangesParams<'_>,
    ) -> impl std::future::Future<Output = Result<ChangesResult, BackendChangesError<Self::Error>>> + Send;

    /// Execute a `/query` and return a page of matching ids.
    ///
    /// `params.position` may be negative โ€” negative values are relative to
    /// the end of the result set per RFC 8620 ยง5.5 (e.g. -1 means the last
    /// result).
    ///
    /// `params.anchor` and `params.anchor_offset` are the RFC 8620 ยง5.5
    /// `anchor` and `anchorOffset` arguments. With an `anchor`, `position` MUST be
    /// ignored and the page starts at the anchor's index in the filtered,
    /// sorted results plus `anchor_offset`, clamped to 0; an anchor not in
    /// the results is [`JmapError::anchor_not_found`] via
    /// [`BackendQueryError::Method`]. Without one, `anchor_offset` MUST be
    /// ignored. [`QueryResult::position`] is the page's actual start index.
    /// [`crate::resolve_query_start`] implements this over an in-memory id
    /// list.
    ///
    /// [`JmapError::anchor_not_found`]: jmap_types::JmapError::anchor_not_found
    ///
    /// # Filter and sort handling
    ///
    /// Implementations MUST honour the supplied `filter` and `sort` arguments
    /// efficiently โ€” typically by pushing both into the indexed storage layer
    /// (database WHERE / ORDER BY, search index, etc.). Returning every
    /// matching id and relying on the caller to paginate after the fact
    /// degenerates to O(n) per page for IMAP-migration accounts.
    ///
    /// Handler implementations in `jmap-*-server` crates SHOULD NOT
    /// post-filter or post-sort the backend's result; doing so re-introduces
    /// the O(n) cost this method exists to avoid. The Mailbox handler in
    /// `jmap-mail-server` is the canonical example of pushing filter/sort
    /// fully into the backend.
    ///
    /// # Errors
    ///
    /// Return [`BackendQueryError::Method`] for an RFC 8620 ยง5.5 method
    /// error (`unsupportedFilter`, `unsupportedSort`, `anchorNotFound`,
    /// ...); handlers pass it to the client unchanged. Return
    /// [`BackendQueryError::Other`] (or use `?` on `Self::Error`) for an
    /// internal failure; handlers surface it as a redacted `serverFail`.
    ///
    /// # Unknown `account_id`
    ///
    /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
    /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
    /// [`Self::account_exists`] before calling this method and return
    /// `accountNotFound` (RFC 8620 ยง3.6.2) themselves, so implementations
    /// need not repeat that check. A caller that bypasses those handlers can
    /// still reach this method with an unknown account; backends SHOULD then
    /// return `Ok` with an empty [`QueryResult`] page. Returning `Err` is permitted but surfaces as
    /// `serverFail`, not `accountNotFound`.
    fn query_objects<O: QueryObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        params: QueryParams<'_, O>,
    ) -> impl std::future::Future<Output = Result<QueryResult, BackendQueryError<Self::Error>>> + Send;

    /// Execute a `/queryChanges` and return deltas since `since_query_state`.
    ///
    /// `params.collapse_threads` is only meaningful for `Email/queryChanges`
    /// (RFC 8621 ยง4.5); it is `false` for all other object types.
    ///
    /// # Unknown `account_id`
    ///
    /// The standard handlers ([`crate::handle_get`], [`crate::handle_changes`],
    /// [`crate::handle_query`], [`crate::handle_query_changes`]) check
    /// [`Self::account_exists`] before calling this method and return
    /// `accountNotFound` (RFC 8620 ยง3.6.2) themselves, so implementations
    /// need not repeat that check. A caller that bypasses those handlers can
    /// still reach this method with an unknown account; backends SHOULD then
    /// return `Ok` with a [`QueryChangesResult`] whose `removed` and `added` lists are empty. Returning `Err` is permitted but surfaces as
    /// `serverFail`, not `accountNotFound`.
    fn query_changes<O: QueryObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        params: QueryChangesParams<'_, O>,
    ) -> impl std::future::Future<
        Output = Result<QueryChangesResult, BackendChangesError<Self::Error>>,
    > + Send;

    /// The caller's stable identity within this account namespace.
    ///
    /// Returns `None` for deployments that have not wired identity
    /// (test fixtures, single-user dev servers). A `None`-returning
    /// backend CANNOT honor JMAP semantics that depend on caller
    /// identity โ€” chat role-hierarchy, calendar ACLs, sharing/myRights,
    /// per-user $seen on shared mailboxes, per-user metadata
    /// `privateMetadata` filtering, etc. Authentication is still the HTTP
    /// layer's job; this method exposes the result of that
    /// authentication to the JMAP layer for in-method semantics.
    ///
    /// Implementations MUST NOT mint identity โ€” they MUST read it
    /// from the `CallerCtx` populated by the HTTP/auth middleware
    /// before `dispatch()` was called.
    ///
    /// Backends that honor identity-dependent semantics MUST override
    /// this method. Handlers and downstream backend traits MAY rely on
    /// it being correct when it returns `Some`.
    ///
    /// # Why an associated function and not a method (bd:JMAP-wlip.6 / bd:JMAP-jfia.13)
    ///
    /// The signature deliberately takes `caller: &Self::CallerCtx`
    /// without a `&self` receiver. Backends therefore have no access
    /// to their own storage state from inside `principal_id`. The
    /// auth-layer middleware MUST pre-resolve the principal (e.g. map
    /// a JWT `sub` claim to a local `Id` via an internal lookup) and
    /// stash the result inside `CallerCtx` *before* it calls
    /// `dispatch`. The JMAP layer reads the pre-resolved value here;
    /// no JIT lookup is possible.
    ///
    /// This is a structural enforcement of the "identity is not the
    /// JMAP layer's job to mint" rule. A consumer that wants
    /// JIT-resolved identity (e.g. database-backed JWT โ†’ principal
    /// mapping) wires that mapping into the HTTP layer's `CallerCtx`
    /// construction step instead of trying to fit it inside the
    /// backend's `principal_id` impl.
    ///
    /// **Decision record (bd:JMAP-jfia.13)**: a future reviewer or AI
    /// tool will reasonably suggest "this is an oversight, surely the
    /// backend wants `&self` access to its identity store" and propose
    /// `fn principal_id(&self, caller: ...) -> ...`. That suggestion
    /// is **WRONG** and must be rejected: the function-vs-method
    /// distinction is the structural enforcement of the no-JIT-lookup
    /// policy. Comments alone could be ignored; the type system makes
    /// the wrong thing impossible. Defending this shape protects the
    /// workspace identity-seam policy from drift.
    fn principal_id(caller: &Self::CallerCtx) -> Option<&jmap_types::Id> {
        let _ = caller;
        None
    }

    /// Maximum number of objects this account permits in a single
    /// `/set` call (RFC 8620 ยง5.3 `maxObjectsInSet`) (bd:JMAP-ayoz.41.1).
    ///
    /// Counts the sum of `create` + `update` + `destroy` entries in the
    /// wire arguments. Handlers MUST enforce this at the top of every
    /// `handle_*_set` via [`crate::helpers::enforce_max_objects_in_set`]
    /// so a single batched request cannot drive O(MยทN) work against
    /// the storage layer.
    ///
    /// The default value `500` mirrors the workspace's testjig Session
    /// JSON advertised cap and matches common Fastmail / Cyrus IMAP
    /// server defaults. The cap is a *floor* on permissiveness, not a
    /// floor on capability โ€” backends MAY override per account (Free vs
    /// Pro tier, multi-tenant SaaS, etc.). The `caller` and `account_id`
    /// arguments are passed even though the default impl ignores them
    /// so production backends can vary without an API break.
    ///
    /// Returning `0` makes every non-empty `/set` call fail with
    /// `requestTooLarge` (defensive read-only mode). Returning
    /// `u64::MAX` effectively disables the cap (NOT recommended โ€” the
    /// cap is a DoS defence and disabling it forfeits that defence).
    ///
    /// # Why on `JmapBackend` and not a per-extension `XxxLimits` struct
    ///
    /// `maxObjectsInSet` is RFC 8620 ยง5.3 base-protocol scope, not an
    /// extension concept. Putting it on the foundation supertrait
    /// covers all 8 extension server crates with one default impl;
    /// per-extension `XxxLimits` structs are the right shape for
    /// extension-specific caps (per-Space content limits, per-Mailbox
    /// message size, etc. per workspace AGENTS.md "Backend caps and
    /// limits") but are out of scope here.
    fn max_objects_in_set(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
        let _ = (caller, account_id);
        500
    }

    /// Maximum number of ids this account permits in a single `/get`
    /// call (RFC 8620 ยง5.1 `maxObjectsInGet`) (bd:JMAP-yt1w.31).
    ///
    /// Handlers MUST enforce this at the top of every `/get` handler via
    /// [`crate::helpers::enforce_max_objects_in_get`]; the generic
    /// [`handle_get`](crate::handle_get) already does. A null `ids` (fetch
    /// all) is not counted.
    ///
    /// The default value `500` is the RFC 8620 ยง2 suggested minimum and
    /// mirrors [`JmapBackend::max_objects_in_set`]. Backends MAY override
    /// per account; the `caller` and `account_id` arguments exist for
    /// that. Keep the value in step with the `maxObjectsInGet` advertised
    /// in the Session object.
    fn max_objects_in_get(&self, caller: &Self::CallerCtx, account_id: &jmap_types::Id) -> u64 {
        let _ = (caller, account_id);
        500
    }

    /// The draft-ietf-jmap-metadata-04 ยง1.2.1 DataTypeMetadataInfo of `O`
    /// in `account_id`, as seen by `caller`, or [`None`] when the account's
    /// `urn:ietf:params:jmap:metadata` capability does not list `O`.
    ///
    /// Handlers use it where the wire shape depends on it: `Foo/get`
    /// returns `metadata` as an object (`{}` when nothing is stored),
    /// applies the `metadata/` subselectors and never returns
    /// `privateMetadata` when `supportsPrivate` is false (-04 ยง2, ยง3.1,
    /// through [`MetadataProjection`](crate::MetadataProjection));
    /// `Foo/copy` copies neither property into an account that does not
    /// list `O` (-04 ยง3.4). Keep it in step with the `dataTypes`
    /// advertised in the Session object.
    ///
    /// Default: [`None`], a backend without metadata.
    fn metadata_info<O: JmapObject>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
    ) -> Option<jmap_metadata_types::DataTypeMetadataInfo> {
        let _ = (caller, account_id);
        None
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    /// Oracle (RFC 8620 ยง5.6): `CannotCalculate` maps to the
    /// `cannotCalculateChanges` wire error.
    #[test]
    fn backend_changes_error_cannot_calculate_maps_to_cannot_calculate_changes() {
        let err = jmap_types::JmapError::from(
            BackendChangesError::<std::convert::Infallible>::CannotCalculate,
        );
        assert_eq!(
            err.error_type.to_string(),
            "cannotCalculateChanges",
            "CannotCalculate must produce cannotCalculateChanges; got: {:?}",
            err.error_type
        );
    }

    /// Oracle: BackendChangesError::TooManyChanges { limit: N } (N > 0) maps to
    /// tooManyChanges with the suggested limit.
    #[test]
    fn backend_changes_error_nonzero_limit_maps_to_too_many_changes() {
        let err = jmap_types::JmapError::from(
            BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 50 },
        );
        assert_eq!(
            err.error_type.to_string(),
            "tooManyChanges",
            "limit=50 must produce tooManyChanges; got: {:?}",
            err.error_type
        );
    }

    /// Oracle (CHANGELOG, fc81085f): "A zero limit now maps to
    /// tooManyChanges like any other value", so `limit: 0` is not an alias
    /// for `cannotCalculateChanges`. Expected wire object is hand-written.
    #[test]
    fn backend_changes_error_zero_limit_maps_to_too_many_changes() {
        let err = jmap_types::JmapError::from(
            BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 0 },
        );
        assert_eq!(
            serde_json::to_value(&err).unwrap(),
            serde_json::json!({"type": "tooManyChanges", "limit": 0})
        );
    }

    /// Oracle (bd:JMAP-jfia.1 / bd:JMAP-wlip.2): the
    /// `From<BackendChangesError<E>> for JmapError` impl MUST NOT echo
    /// the wrapped backend error's `Display` text into the resulting
    /// `JmapError`'s description. The defence-in-depth contract is that
    /// even if a backend implementor accidentally violates the
    /// [`JmapBackend::Error`] Display MUST-NOT (credential / blob /
    /// PII), the leaked text never reaches the wire โ€” and the
    /// ergonomic `.map_err(JmapError::from)?` path that
    /// `handle_changes` / `handle_query_changes` take on
    /// `BackendChangesError` must redact identically to the explicit
    /// `server_fail_from_backend(&e)` helper used elsewhere.
    ///
    /// Test vector: an `Other` variant whose Display contains a canary
    /// string resembling a credential leak. The canary literal is
    /// hand-built and not derived from any production type's
    /// behaviour. Mirrors
    /// `server_fail_from_backend_drops_display_text` in
    /// `handlers.rs`.
    #[test]
    fn backend_changes_error_other_drops_display_text() {
        #[derive(Debug)]
        struct LeakyError(&'static str);
        impl std::fmt::Display for LeakyError {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(self.0)
            }
        }
        impl std::error::Error for LeakyError {}

        const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
        let err: BackendChangesError<LeakyError> = BackendChangesError::Other(LeakyError(CANARY));

        let jmap_err = jmap_types::JmapError::from(err);

        // Serialize to wire shape and assert the canary is absent from
        // the resulting JSON. The error_invocation wraps a JmapError as
        // { "type": "serverFail", "description": "..." } โ€” both fields
        // are wire-visible.
        let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
        let wire_str = wire.to_string();
        assert!(
            !wire_str.contains(CANARY),
            "From<BackendChangesError<E>> for JmapError must not echo \
             backend error Display onto the wire; got {wire_str}"
        );
        // The description MUST be exactly SERVER_FAIL_INTERNAL_DESC.
        assert_eq!(
            wire["description"],
            crate::handlers::SERVER_FAIL_INTERNAL_DESC,
            "description must be the static 'internal error' string"
        );
        assert_eq!(wire["type"], "serverFail");
    }

    /// Oracle (bd:JMAP-jfia.36): `into_set_error_or_method_error` on
    /// `Other` MUST NOT echo the wrapped error's `Display` text; the
    /// wire form is exactly `{"type":"serverFail","description":"internal
    /// error"}` (hand-written expected JSON). The canary literal is
    /// hand-built. Mirrors `backend_changes_error_other_drops_display_text`.
    #[test]
    fn backend_set_error_other_drops_display_text() {
        struct LeakyError(&'static str);
        impl std::fmt::Display for LeakyError {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(self.0)
            }
        }

        const CANARY: &str = "TOKEN-DO-NOT-LEAK-c0ffee";
        let err: BackendSetError<LeakyError> = BackendSetError::Other(LeakyError(CANARY));

        let Err(jmap_err) = err.into_set_error_or_method_error() else {
            panic!("Other must map to a method-level JmapError");
        };
        let wire = serde_json::to_value(&jmap_err).expect("JmapError must serialize");
        assert!(
            !wire.to_string().contains(CANARY),
            "into_set_error_or_method_error must not echo backend Display; got {wire}"
        );
        assert_eq!(
            wire,
            serde_json::json!({"type": "serverFail", "description": "internal error"})
        );
    }

    /// Oracle (RFC 8620 ยง5.3): a per-object `SetError` belongs in the
    /// `notCreated`/`notUpdated`/`notDestroyed` map, so the `SetError`
    /// arm must come back as `Ok` with its wire form intact
    /// (hand-written expected JSON).
    #[test]
    fn backend_set_error_set_error_passes_through() {
        let err: BackendSetError<std::fmt::Error> =
            BackendSetError::SetError(Box::new(SetError::new(SetErrorType::Forbidden)));
        let se = err
            .into_set_error_or_method_error()
            .expect("SetError arm must be Ok");
        assert_eq!(
            serde_json::to_value(&se).expect("SetError must serialize"),
            serde_json::json!({"type": "forbidden"})
        );
    }

    /// Oracle (RFC 8620 ยง5.3): a per-object `SetError` is the
    /// `notCreated`/`notUpdated`/`notDestroyed` map value verbatim
    /// (hand-written expected JSON).
    #[test]
    fn backend_set_error_value_set_error_is_verbatim() {
        let err: BackendSetError<std::fmt::Error> = BackendSetError::SetError(Box::new(
            SetError::new(SetErrorType::NotFound).with_description("gone"),
        ));
        assert_eq!(
            backend_set_error_value(err),
            serde_json::json!({"type": "notFound", "description": "gone"})
        );
    }

    /// Oracle (bd:JMAP-jfia.36): `Other` becomes exactly
    /// `{"type":"serverFail","description":"internal error"}` and never
    /// carries the wrapped error's `Display` text (hand-written expected
    /// JSON, hand-built canary).
    #[test]
    fn backend_set_error_value_other_is_redacted_server_fail() {
        const CANARY: &str = "TOKEN-DO-NOT-LEAK-5e7e44";
        let err: BackendSetError<&str> = BackendSetError::Other(CANARY);
        let wire = backend_set_error_value(err);
        assert!(!wire.to_string().contains(CANARY), "leaked: {wire}");
        assert_eq!(
            wire,
            serde_json::json!({"type": "serverFail", "description": "internal error"})
        );
    }

    /// Hand-built storage error for the stub backend and the error-envelope
    /// tests; its `Display` text is a fixed literal.
    #[derive(Debug)]
    struct StubError;

    impl std::fmt::Display for StubError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str("stub")
        }
    }
    impl std::error::Error for StubError {}

    /// Minimal backend that implements only the required trait methods, so
    /// tests observe the provided (default) methods. The required methods
    /// are never invoked.
    struct StubBackend;

    impl JmapBackend for StubBackend {
        type Error = StubError;
        type CallerCtx = ();

        async fn account_exists(
            &self,
            _caller: &(),
            _account_id: &jmap_types::Id,
        ) -> Result<bool, Self::Error> {
            unreachable!("stub backend: only default methods are exercised")
        }

        async fn get_objects<O: GetObject + Send + Sync>(
            &self,
            _caller: &(),
            _account_id: &jmap_types::Id,
            _ids: Option<&[jmap_types::Id]>,
            _properties: Option<&[String]>,
        ) -> Result<(Vec<O>, Vec<jmap_types::Id>), Self::Error> {
            unreachable!("stub backend: only default methods are exercised")
        }

        async fn get_state<O: JmapObject + Send + Sync>(
            &self,
            _caller: &(),
            _account_id: &jmap_types::Id,
        ) -> Result<jmap_types::State, Self::Error> {
            unreachable!("stub backend: only default methods are exercised")
        }

        async fn get_changes<O: JmapObject + Send + Sync>(
            &self,
            _caller: &(),
            _account_id: &jmap_types::Id,
            _params: ChangesParams<'_>,
        ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
            unreachable!("stub backend: only default methods are exercised")
        }

        async fn query_objects<O: QueryObject + Send + Sync>(
            &self,
            _caller: &(),
            _account_id: &jmap_types::Id,
            _params: QueryParams<'_, O>,
        ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
            unreachable!("stub backend: only default methods are exercised")
        }

        async fn query_changes<O: QueryObject + Send + Sync>(
            &self,
            _caller: &(),
            _account_id: &jmap_types::Id,
            _params: QueryChangesParams<'_, O>,
        ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
            unreachable!("stub backend: only default methods are exercised")
        }
    }

    /// Oracle (bd:JMAP-ga0q.1): `JmapBackend::principal_id` has a default impl
    /// that returns `None`. A backend whose `CallerCtx = ()` and that does NOT
    /// override `principal_id` inherits that default and signals "identity not
    /// wired" to callers. JMAP semantics that depend on caller identity must
    /// treat `None` as a hard "cannot honor".
    #[test]
    fn principal_id_default_impl_returns_none_for_unit_caller_ctx() {
        let caller: <StubBackend as JmapBackend>::CallerCtx = ();
        let id = <StubBackend as JmapBackend>::principal_id(&caller);
        assert!(
            id.is_none(),
            "default principal_id impl must return None; got Some({:?})",
            id
        );
    }

    /// Oracle (bd:JMAP-ayoz.41.1): `JmapBackend::max_objects_in_set`
    /// has a default impl that returns `500`. The constant is the
    /// workspace's testjig Session JSON advertised cap; a backend that
    /// does not override the method inherits a sane DoS-defence
    /// default rather than silently disabling the cap.
    #[test]
    fn max_objects_in_set_default_impl_returns_500() {
        let backend = StubBackend;
        let caller: <StubBackend as JmapBackend>::CallerCtx = ();
        let id = jmap_types::Id::from("any-account");
        assert_eq!(
            backend.max_objects_in_set(&caller, &id),
            500,
            "default max_objects_in_set must return 500"
        );
    }

    /// Oracle (trait docs, same rationale as `max_objects_in_set`): the
    /// default `JmapBackend::max_objects_in_get` cap is `500`, so a backend
    /// that does not override it keeps the RFC 8620 ยง5.1 `requestTooLarge`
    /// guard enabled.
    #[test]
    fn max_objects_in_get_default_impl_returns_500() {
        let caller: <StubBackend as JmapBackend>::CallerCtx = ();
        let id = jmap_types::Id::from("any-account");
        assert_eq!(StubBackend.max_objects_in_get(&caller, &id), 500);
    }

    /// Oracle: hand-written expected strings. The `SetError` arm prefixes
    /// the `SetError` Display (`<type>: <description>`), and `Other` is
    /// transparent over the wrapped error.
    #[test]
    fn backend_set_error_display() {
        let se: BackendSetError<StubError> = BackendSetError::SetError(Box::new(
            SetError::new(SetErrorType::NotFound).with_description("gone"),
        ));
        assert_eq!(se.to_string(), "set error: notFound: gone");
        assert_eq!(BackendSetError::Other(StubError).to_string(), "stub");
    }

    /// Oracle: hand-written expected strings for every variant.
    #[test]
    fn backend_changes_error_display() {
        assert_eq!(
            BackendChangesError::<StubError>::CannotCalculate.to_string(),
            "cannot calculate changes"
        );
        assert_eq!(
            BackendChangesError::<StubError>::TooManyChanges { limit: 7 }.to_string(),
            "too many changes (limit: 7)"
        );
        assert_eq!(BackendChangesError::Other(StubError).to_string(), "stub");
    }

    /// Oracle: `Method` displays the wrapped `JmapError` unchanged and
    /// `Other` is transparent over the wrapped error (hand-written strings).
    #[test]
    fn backend_query_error_display() {
        let method = jmap_types::JmapError::server_fail("x");
        let expected = method.to_string();
        assert_eq!(
            BackendQueryError::<StubError>::Method(method).to_string(),
            expected
        );
        assert_eq!(BackendQueryError::Other(StubError).to_string(), "stub");
    }

    /// Oracle (`std::error::Error::source` contract): only the `Other`
    /// variant wraps an underlying error, so only it reports a source, and
    /// that source is the wrapped value.
    #[test]
    fn backend_errors_source_is_wrapped_other_only() {
        use std::error::Error as _;

        let is_stub = |e: Option<&(dyn std::error::Error + 'static)>| {
            e.is_some_and(|s| s.downcast_ref::<StubError>().is_some())
        };

        assert!(is_stub(BackendSetError::Other(StubError).source()));
        assert!(
            BackendSetError::<StubError>::from(SetError::new(SetErrorType::Forbidden))
                .source()
                .is_none()
        );

        assert!(is_stub(BackendChangesError::from(StubError).source()));
        assert!(
            BackendChangesError::<StubError>::CannotCalculate
                .source()
                .is_none()
        );
        assert!(
            BackendChangesError::<StubError>::TooManyChanges { limit: 1 }
                .source()
                .is_none()
        );

        assert!(is_stub(BackendQueryError::from(StubError).source()));
        assert!(
            BackendQueryError::<StubError>::Method(jmap_types::JmapError::server_fail("x"))
                .source()
                .is_none()
        );
    }
}