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

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

// ---------------------------------------------------------------------------
// SetError — RFC 8620 §5.3 per-object set-method error
// ---------------------------------------------------------------------------

/// A per-item error in a `/set` response (`notCreated`, `notUpdated`,
/// `notDestroyed` maps) (RFC 8620 §5.3).
///
/// Construct with [`SetError::new`] and chain the builder methods as needed.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetError {
    /// The machine-readable error type.
    #[serde(rename = "type")]
    pub error_type: SetErrorType,
    /// Optional human-readable description of the error.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Property names that caused the error (for `invalidProperties`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<Vec<String>>,
    /// The existing object id (for `alreadyExists` — RFC 8621 §5.7).
    #[serde(rename = "existingId", skip_serializing_if = "Option::is_none")]
    pub existing_id: Option<jmap_types::Id>,
    /// Maximum recipients allowed (for `tooManyRecipients` — RFC 8621 §7.5).
    #[serde(rename = "maxRecipients", skip_serializing_if = "Option::is_none")]
    pub max_recipients: Option<u64>,
    /// Invalid recipient addresses (for `invalidRecipients` — RFC 8621 §7.5).
    #[serde(rename = "invalidRecipients", skip_serializing_if = "Option::is_none")]
    pub invalid_recipients: Option<Vec<String>>,
    /// Missing blob IDs (for `blobNotFound` — RFC 8621 §5.5).
    #[serde(rename = "notFound", skip_serializing_if = "Option::is_none")]
    pub not_found: Option<Vec<jmap_types::Id>>,
    /// Maximum message size in octets (for `tooLarge` on EmailSubmission — RFC 8621 §7.5).
    #[serde(rename = "maxSize", skip_serializing_if = "Option::is_none")]
    pub max_size: Option<u64>,
    /// Catch-all for extension-defined SetError fields not covered by
    /// the typed members above.
    ///
    /// JMAP extensions sometimes ship error variants whose wire shape
    /// includes additional structured fields beyond the RFC 8620 §5.3
    /// base set — e.g. JMAP Chat's `rateLimited` SetError carries a
    /// `serverRetryAfter` UTCDate telling the client when it may
    /// retry, and `mdnAlreadySent` (RFC 8621 §7.7) is a typed
    /// extension error variant. This map preserves any such field
    /// across serialize / deserialize round-trip, mirroring the
    /// extras-preservation policy on the client-side
    /// [`jmap_types::SetError`] type.
    ///
    /// Use [`SetError::with_extra`] to populate from handler code:
    ///
    /// ```ignore
    /// SetError::new(SetErrorType::custom("rateLimited"))
    ///     .with_description("Slow mode is active for this chat")
    ///     .with_extra("serverRetryAfter", json!(retry_after_str))
    /// ```
    ///
    /// Per workspace AGENTS.md "Extras-preservation policy" — wire
    /// format is byte-identical to a pre-extras SetError when the
    /// map is empty (the `skip_serializing_if` collapses it).
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl SetError {
    /// Construct a [`SetError`] with the given type and all optional fields `None`.
    pub fn new(error_type: SetErrorType) -> Self {
        Self {
            error_type,
            description: None,
            properties: None,
            existing_id: None,
            max_recipients: None,
            invalid_recipients: None,
            not_found: None,
            max_size: None,
            extra: serde_json::Map::new(),
        }
    }

    /// Set the human-readable description.
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Set the list of property names that caused the error.
    pub fn with_properties<I, S>(mut self, props: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.properties = Some(props.into_iter().map(|s| s.into()).collect());
        self
    }

    /// Set the existing object id (used with `alreadyExists`).
    pub fn with_existing_id(mut self, id: jmap_types::Id) -> Self {
        self.existing_id = Some(id);
        self
    }

    /// Set the maximum recipients (used with `tooManyRecipients` — RFC 8621 §7.5).
    pub fn with_max_recipients(mut self, n: u64) -> Self {
        self.max_recipients = Some(n);
        self
    }

    /// Set the invalid recipient addresses (used with `invalidRecipients` — RFC 8621 §7.5).
    pub fn with_invalid_recipients<I, S>(mut self, addrs: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.invalid_recipients = Some(addrs.into_iter().map(|s| s.into()).collect());
        self
    }

    /// Set the missing blob IDs (used with `blobNotFound` — RFC 8621 §5.5).
    pub fn with_not_found(mut self, ids: Vec<jmap_types::Id>) -> Self {
        self.not_found = Some(ids);
        self
    }

    /// Set the maximum message size in octets (used with `tooLarge` on EmailSubmission — RFC 8621 §7.5).
    pub fn with_max_size(mut self, n: u64) -> Self {
        self.max_size = Some(n);
        self
    }

    /// Insert an extension-defined field into [`Self::extra`].
    ///
    /// Used by handlers to attach typed wire fields that no `with_*`
    /// builder covers — for example JMAP Chat's `rateLimited` SetError
    /// must carry a `serverRetryAfter` UTCDate:
    ///
    /// ```ignore
    /// SetError::new(SetErrorType::custom("rateLimited"))
    ///     .with_description("Slow mode is active for this chat")
    ///     .with_extra("serverRetryAfter", serde_json::json!(retry_after_str))
    /// ```
    ///
    /// The serialized wire shape merges `key`/`value` at the same
    /// level as the typed fields (via `#[serde(flatten)]` on
    /// [`Self::extra`]). Calling `with_extra("type", ...)`,
    /// `with_extra("properties", ...)`, or any other reserved
    /// wire-name will produce a malformed SetError on the wire —
    /// callers are responsible for choosing extension-namespace keys
    /// that do not collide with the typed-field wire names.
    pub fn with_extra(mut self, key: &str, value: serde_json::Value) -> Self {
        self.extra.insert(key.to_owned(), value);
        self
    }
}

impl std::fmt::Display for SetError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.error_type)?;
        if let Some(ref desc) = self.description {
            write!(f, ": {desc}")?;
        }
        Ok(())
    }
}

/// The machine-readable type for a [`SetError`] (RFC 8620 §5.3 and RFC 8621).
///
/// Extension crates define their own error strings via [`SetErrorType::custom`]
/// rather than adding variants here. This keeps the base crate stable as new
/// JMAP extension crates (calendar, contacts, etc.) are added.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum SetErrorType {
    /// The action would violate an ACL or other access control policy.
    Forbidden,
    /// Creating or modifying the object would exceed a server quota.
    OverQuota,
    /// The object is too large to be stored by the server.
    TooLarge,
    /// The server is rate-limiting this client.
    RateLimit,
    /// The object to be updated or destroyed does not exist.
    NotFound,
    /// The patch object is not a valid JSON Merge Patch or cannot be applied.
    InvalidPatch,
    /// The client requested destruction of an object that will be destroyed
    /// implicitly when another object is destroyed.
    WillDestroy,
    /// One or more properties have invalid values.
    InvalidProperties,
    /// The object type is a singleton and cannot be created or destroyed.
    Singleton,
    /// An object with the same unique key already exists.
    AlreadyExists,
    /// RFC 8621 §2.5 — Mailbox has child mailboxes and cannot be destroyed.
    MailboxHasChild,
    /// RFC 8621 §2.5 — Mailbox contains emails and `onDestroyRemoveEmails` is false.
    MailboxHasEmail,
    /// RFC 8621 §5.5 — Too many keywords on the Email.
    TooManyKeywords,
    /// RFC 8621 §5.5 — Email is in too many mailboxes.
    TooManyMailboxes,
    /// RFC 8621 §5.5 — A referenced blob was not found.
    BlobNotFound,
    /// RFC 8621 §6.3 — The `from` address is not permitted for this Identity.
    ForbiddenFrom,
    /// RFC 8621 §7.5 — The Email is invalid for submission.
    InvalidEmail,
    /// RFC 8621 §7.5 — Too many recipients.
    TooManyRecipients,
    /// RFC 8621 §7.5 — No recipients specified.
    NoRecipients,
    /// RFC 8621 §7.5 — One or more recipient addresses are invalid.
    InvalidRecipients,
    /// RFC 8621 §7.5 — The MAIL FROM address is not permitted.
    ForbiddenMailFrom,
    /// RFC 8621 §7.5 — The user does not have send permission.
    ForbiddenToSend,
    /// RFC 8621 §7.5 — The submission cannot be undone.
    CannotUnsend,
    /// An extension-defined error type not covered by the variants above.
    /// Serializes as the inner string directly (e.g. `"mdnAlreadySent"`).
    Custom(String),
}

impl SetErrorType {
    /// Construct a [`SetErrorType::Custom`] from any string.
    ///
    /// Use this in extension crates to emit domain-specific error types
    /// without adding variants to this enum.
    pub fn custom(s: impl Into<String>) -> Self {
        Self::Custom(s.into())
    }
}

impl std::fmt::Display for SetErrorType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s: &str = match self {
            Self::Forbidden => "forbidden",
            Self::OverQuota => "overQuota",
            Self::TooLarge => "tooLarge",
            Self::RateLimit => "rateLimit",
            Self::NotFound => "notFound",
            Self::InvalidPatch => "invalidPatch",
            Self::WillDestroy => "willDestroy",
            Self::InvalidProperties => "invalidProperties",
            Self::Singleton => "singleton",
            Self::AlreadyExists => "alreadyExists",
            Self::MailboxHasChild => "mailboxHasChild",
            Self::MailboxHasEmail => "mailboxHasEmail",
            Self::TooManyKeywords => "tooManyKeywords",
            Self::TooManyMailboxes => "tooManyMailboxes",
            Self::BlobNotFound => "blobNotFound",
            Self::ForbiddenFrom => "forbiddenFrom",
            Self::InvalidEmail => "invalidEmail",
            Self::TooManyRecipients => "tooManyRecipients",
            Self::NoRecipients => "noRecipients",
            Self::InvalidRecipients => "invalidRecipients",
            Self::ForbiddenMailFrom => "forbiddenMailFrom",
            Self::ForbiddenToSend => "forbiddenToSend",
            Self::CannotUnsend => "cannotUnsend",
            Self::Custom(s) => s.as_str(),
        };
        f.write_str(s)
    }
}

impl serde::Serialize for SetErrorType {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&self.to_string())
    }
}

impl<'de> serde::Deserialize<'de> for SetErrorType {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        struct Visitor;
        impl serde::de::Visitor<'_> for Visitor {
            type Value = SetErrorType;
            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a JMAP SetError type string")
            }
            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
                Ok(match v {
                    "forbidden" => SetErrorType::Forbidden,
                    "overQuota" => SetErrorType::OverQuota,
                    "tooLarge" => SetErrorType::TooLarge,
                    "rateLimit" => SetErrorType::RateLimit,
                    "notFound" => SetErrorType::NotFound,
                    "invalidPatch" => SetErrorType::InvalidPatch,
                    "willDestroy" => SetErrorType::WillDestroy,
                    "invalidProperties" => SetErrorType::InvalidProperties,
                    "singleton" => SetErrorType::Singleton,
                    "alreadyExists" => SetErrorType::AlreadyExists,
                    "mailboxHasChild" => SetErrorType::MailboxHasChild,
                    "mailboxHasEmail" => SetErrorType::MailboxHasEmail,
                    "tooManyKeywords" => SetErrorType::TooManyKeywords,
                    "tooManyMailboxes" => SetErrorType::TooManyMailboxes,
                    "blobNotFound" => SetErrorType::BlobNotFound,
                    "forbiddenFrom" => SetErrorType::ForbiddenFrom,
                    "invalidEmail" => SetErrorType::InvalidEmail,
                    "tooManyRecipients" => SetErrorType::TooManyRecipients,
                    "noRecipients" => SetErrorType::NoRecipients,
                    "invalidRecipients" => SetErrorType::InvalidRecipients,
                    "forbiddenMailFrom" => SetErrorType::ForbiddenMailFrom,
                    "forbiddenToSend" => SetErrorType::ForbiddenToSend,
                    "cannotUnsend" => SetErrorType::CannotUnsend,
                    other => SetErrorType::Custom(other.to_owned()),
                })
            }
        }
        d.deserialize_str(Visitor)
    }
}

/// 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.
    SetError(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(e)
    }
}

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

/// Error type returned by [`JmapBackend::get_changes`] and
/// [`JmapBackend::query_changes`].
#[non_exhaustive]
#[derive(Debug)]
pub enum BackendChangesError<E> {
    /// The server cannot supply incremental changes for the given `sinceState`.
    ///
    /// Two sub-cases share this variant:
    ///
    /// - **`limit > 0`** — maps to `tooManyChanges` in the JMAP response, with
    ///   `limit` as the suggested maximum. The client may retry with a smaller
    ///   window.
    ///
    /// - **`limit: 0`** — maps to `cannotCalculateChanges`. This signals a
    ///   **full state reset**: 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 — the server has no usable
    ///   change log for this state window. (Source: RFC 8620 §5.6; authoritative
    ///   behavior documented in jmapio/jmap-js `mail-model.js`.)
    TooManyChanges {
        /// Maximum window size the server can supply in a single
        /// `/changes` response. A value of `0` signals a full state
        /// reset is required per RFC 8620 §5.6; any non-zero value is
        /// 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::TooManyChanges { limit: 0 } => 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::TooManyChanges { limit: 0 } => {
                jmap_types::JmapError::cannot_calculate_changes()
            }
            BackendChangesError::TooManyChanges { limit } => {
                jmap_types::JmapError::too_many_changes_with_limit(limit)
            }
            BackendChangesError::Other(inner) => {
                jmap_types::JmapError::server_fail(inner.to_string())
            }
        }
    }
}

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

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,
        }
    }
}

/// 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.
    pub position: i64,
    /// 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: i64,
        total: Option<u64>,
        query_state: jmap_types::State,
        can_calculate_changes: bool,
    ) -> Self {
        Self {
            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,
        }
    }
}

// ---------------------------------------------------------------------------
// 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.
///
/// The `collapse_threads` parameter on `query_changes` is included for
/// `Email/queryChanges` (RFC 8621 §4.5). Non-mail backends should pass `false`
/// and may ignore the parameter.
///
/// 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.
    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.
    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.
    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 `since_state`, up to `max_changes` entries.
    fn get_changes<O: JmapObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        since_state: &jmap_types::State,
        max_changes: Option<u64>,
    ) -> impl std::future::Future<Output = Result<ChangesResult, BackendChangesError<Self::Error>>> + Send;

    /// Execute a `/query` and return a page of matching ids.
    ///
    /// `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).
    ///
    /// # 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.
    #[allow(clippy::too_many_arguments)]
    fn query_objects<O: QueryObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        filter: Option<&O::Filter>,
        sort: Option<&[O::Comparator]>,
        limit: Option<u64>,
        position: i64,
    ) -> impl std::future::Future<Output = Result<QueryResult, Self::Error>> + Send;

    /// Execute a `/queryChanges` and return deltas since `since_query_state`.
    ///
    /// `collapse_threads` is only meaningful for `Email/queryChanges`
    /// (RFC 8621 §4.5). Pass `false` for all other object types.
    #[allow(clippy::too_many_arguments)]
    fn query_changes<O: QueryObject + Send + Sync>(
        &self,
        caller: &Self::CallerCtx,
        account_id: &jmap_types::Id,
        since_query_state: &jmap_types::State,
        filter: Option<&O::Filter>,
        sort: Option<&[O::Comparator]>,
        max_changes: Option<u64>,
        up_to_id: Option<&jmap_types::Id>,
        collapse_threads: bool,
    ) -> 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, metadata isPrivate
    /// visibility scoping, 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`.
    fn principal_id(caller: &Self::CallerCtx) -> Option<&jmap_types::Id> {
        let _ = caller;
        None
    }
}

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

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

    /// Oracle: BackendChangesError::TooManyChanges { limit: 0 } must map to
    /// cannotCalculateChanges (RFC 8620 §5.6), not tooManyChanges with limit 0.
    ///
    /// limit=0 is the convention for "cannot calculate".
    #[test]
    fn backend_changes_error_limit_zero_maps_to_cannot_calculate() {
        let err = jmap_types::JmapError::from(
            BackendChangesError::<std::convert::Infallible>::TooManyChanges { limit: 0 },
        );
        assert_eq!(
            err.error_type.as_str(),
            "cannotCalculateChanges",
            "limit=0 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.as_str(),
            "tooManyChanges",
            "limit=50 must produce tooManyChanges; got: {:?}",
            err.error_type
        );
    }

    /// Oracle: SetErrorType::Custom("mdnAlreadySent") must serialize as the bare
    /// string "mdnAlreadySent" and deserialize back to Custom("mdnAlreadySent").
    /// Extension crates depend on this round-trip to emit domain-specific errors.
    #[test]
    fn set_error_type_custom_round_trips_as_bare_string() {
        let original = SetErrorType::custom("mdnAlreadySent");
        let serialized = serde_json::to_string(&original).expect("serialize");
        assert_eq!(
            serialized, r#""mdnAlreadySent""#,
            "Custom must serialize as bare string"
        );
        let deserialized: SetErrorType = serde_json::from_str(&serialized).expect("deserialize");
        assert_eq!(
            deserialized, original,
            "Custom must deserialize back to Custom"
        );
    }

    /// Oracle (bd:JMAP-dha0): SetError gains an `extra` map that captures
    /// extension-defined fields not covered by the typed `with_*` builders.
    /// A handler that emits `rateLimited` with `serverRetryAfter` must
    /// see the value round-trip through serialize / deserialize.
    #[test]
    fn set_error_extra_field_round_trips() {
        let original = SetError::new(SetErrorType::custom("rateLimited"))
            .with_description("Slow mode is active")
            .with_extra(
                "serverRetryAfter",
                serde_json::Value::String("2025-12-31T23:59:59Z".to_owned()),
            );

        let wire = serde_json::to_value(&original).expect("serialize");
        assert_eq!(wire["type"], "rateLimited");
        assert_eq!(wire["description"], "Slow mode is active");
        assert_eq!(
            wire["serverRetryAfter"], "2025-12-31T23:59:59Z",
            "extra field must flatten into the SetError wire shape"
        );

        let round: SetError = serde_json::from_value(wire).expect("deserialize");
        assert_eq!(round.error_type, original.error_type);
        assert_eq!(round.description, original.description);
        assert_eq!(
            round.extra.get("serverRetryAfter").and_then(|v| v.as_str()),
            Some("2025-12-31T23:59:59Z"),
            "extra field must survive deserialize"
        );
    }

    /// Oracle (bd:JMAP-dha0): a SetError with no extras serializes to a
    /// wire shape byte-identical to the pre-extras layout. The
    /// `skip_serializing_if` on `extra` collapses the empty map.
    #[test]
    fn set_error_empty_extra_is_invisible_on_the_wire() {
        let err = SetError::new(SetErrorType::Forbidden);
        let wire = serde_json::to_value(&err).expect("serialize");
        let obj = wire.as_object().expect("object");
        assert!(
            !obj.contains_key("extra"),
            "empty `extra` map must not appear on the wire (got {wire})"
        );
        // The only key on the wire for a bare SetError must be `type`.
        assert_eq!(
            obj.len(),
            1,
            "bare SetError must have exactly one key on the wire"
        );
        assert_eq!(obj["type"], "forbidden");
    }

    /// Oracle (bd:JMAP-dha0): unknown wire fields on a deserialized
    /// SetError land in `extra`. This means a future spec adding
    /// `someNewSetErrorField` will round-trip through current
    /// versions of the kit losslessly.
    #[test]
    fn set_error_unknown_field_lands_in_extra() {
        let wire = serde_json::json!({
            "type": "forbidden",
            "futureSpecField": "future-value",
            "anotherOne": 42
        });
        let err: SetError = serde_json::from_value(wire).expect("deserialize");
        assert_eq!(err.error_type, SetErrorType::Forbidden);
        assert_eq!(
            err.extra.get("futureSpecField").and_then(|v| v.as_str()),
            Some("future-value")
        );
        assert_eq!(
            err.extra.get("anotherOne").and_then(|v| v.as_u64()),
            Some(42)
        );
    }

    /// Oracle: known SetErrorType variants (e.g. Singleton) must still
    /// serialize as their camelCase wire strings and deserialize back correctly.
    #[test]
    fn set_error_type_known_variant_round_trips() {
        let original = SetErrorType::Singleton;
        let serialized = serde_json::to_string(&original).expect("serialize");
        assert_eq!(
            serialized, r#""singleton""#,
            "Singleton must serialize as \"singleton\""
        );
        let deserialized: SetErrorType = serde_json::from_str(&serialized).expect("deserialize");
        assert_eq!(
            deserialized, original,
            "Singleton must deserialize back to Singleton"
        );
    }

    /// 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() {
        // Minimal stub backend exercising only the default impl. All other
        // trait methods are stubbed with `unreachable!()` and never invoked.
        struct StubBackend;

        #[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 {}

        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!("only principal_id is exercised in this test")
            }

            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!("only principal_id is exercised in this test")
            }

            async fn get_state<O: JmapObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &jmap_types::Id,
            ) -> Result<jmap_types::State, Self::Error> {
                unreachable!("only principal_id is exercised in this test")
            }

            async fn get_changes<O: JmapObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &jmap_types::Id,
                _since_state: &jmap_types::State,
                _max_changes: Option<u64>,
            ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
                unreachable!("only principal_id is exercised in this test")
            }

            async fn query_objects<O: QueryObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &jmap_types::Id,
                _filter: Option<&O::Filter>,
                _sort: Option<&[O::Comparator]>,
                _limit: Option<u64>,
                _position: i64,
            ) -> Result<QueryResult, Self::Error> {
                unreachable!("only principal_id is exercised in this test")
            }

            async fn query_changes<O: QueryObject + Send + Sync>(
                &self,
                _caller: &(),
                _account_id: &jmap_types::Id,
                _since_query_state: &jmap_types::State,
                _filter: Option<&O::Filter>,
                _sort: Option<&[O::Comparator]>,
                _max_changes: Option<u64>,
                _up_to_id: Option<&jmap_types::Id>,
                _collapse_threads: bool,
            ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
                unreachable!("only principal_id is exercised in this test")
            }
        }

        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
        );
    }
}