Skip to main content

jmap_types/
backend.rs

1//! Backend marker traits shared across all JMAP server crates.
2//!
3//! These traits are defined here in `jmap-types` so that implementations can
4//! go in the type crates (`jmap-mail-types`, `jmap-chat-types`) without
5//! violating the orphan rule.
6
7// ---------------------------------------------------------------------------
8// Marker traits
9// ---------------------------------------------------------------------------
10
11/// Marker trait for all JMAP object types.
12///
13/// Implement this in the *types* crate for each first-class JMAP object (e.g.
14/// `Mailbox`, `Email`, `Chat`). The [`TYPE_NAME`](JmapObject::TYPE_NAME) constant
15/// is used in error messages and capability checks in the server crates.
16pub trait JmapObject:
17    serde::Serialize + for<'de> serde::Deserialize<'de> + Send + Sync + 'static
18{
19    /// The JMAP type name string (e.g. `"Email"`, `"Mailbox"`, `"Chat"`).
20    const TYPE_NAME: &'static str;
21    /// The property selector enum for this type (server-side only, no serde).
22    type Property: Send + Sync + 'static;
23    /// The localizable properties of this type
24    /// (draft-atwood-jmap-updates-00 §5), as its defining specification
25    /// lists them; empty, the default, for a type that has none.
26    ///
27    /// A type with localizable properties gains `locale` and
28    /// `localizations` and takes the `language` argument on `/get`,
29    /// `/query` and `/queryChanges` when `urn:ietf:params:jmap:i18n` is in
30    /// `using`; a type without them rejects `language`. See
31    /// [`crate::i18n`].
32    const LOCALIZABLE: &'static [crate::i18n::LocalizableProperty] = &[];
33}
34
35/// Marker for object types that support `get` and `changes` operations.
36pub trait GetObject: JmapObject {}
37
38/// Marker for object types that support `set` (create/update/destroy) operations.
39pub trait SetObject: JmapObject {
40    /// The patch type for update operations.
41    ///
42    /// Typically [`serde_json::Value`] holding an RFC 8620 §5.3 PatchObject,
43    /// whose keys are JSON Pointer paths (RFC 6901) with an implicit leading
44    /// `/`. This is not an RFC 7396 JSON Merge Patch. A typed struct is also
45    /// allowed if it serializes to that PatchObject shape.
46    type Patch: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static;
47
48    /// Wire names of the properties the spec marks "server-set": "Only the
49    /// server can set the value for this property. The client MUST NOT send
50    /// this property when creating a new object of this type." (RFC 8620
51    /// §1.1). A property the type's `/set` method text never accepts from a
52    /// client, on create or update, is server-set too.
53    ///
54    /// A `/set` create that carries one, or an update patch that changes
55    /// one, is `invalidProperties` (RFC 8620 §5.3).
56    const SERVER_SET: &'static [&'static str];
57
58    /// Wire names of every property that is not [`SERVER_SET`]: the ones a
59    /// client may set through `/set`.
60    ///
61    /// Each property of the type is in exactly one of [`SERVER_SET`] and
62    /// `CLIENT_SETTABLE`; [`check_property_classification`] tests that.
63    ///
64    /// [`SERVER_SET`]: SetObject::SERVER_SET
65    const CLIENT_SETTABLE: &'static [&'static str];
66
67    /// The [`CLIENT_SETTABLE`] properties the spec marks "immutable": "The
68    /// value MUST NOT change after the object is created." (RFC 8620 §1.1).
69    /// A property the `/set` method text accepts on create but not on update
70    /// is immutable too.
71    ///
72    /// A client may set one in a `/set` create; an update patch that changes
73    /// one is `invalidProperties`.
74    ///
75    /// [`CLIENT_SETTABLE`]: SetObject::CLIENT_SETTABLE
76    const IMMUTABLE: &'static [&'static str];
77}
78
79/// Check the property classification of `T` against `obj`, a value with
80/// every field populated.
81///
82/// Every top-level property `obj` serializes MUST be in exactly one of
83/// [`SetObject::SERVER_SET`] and [`SetObject::CLIENT_SETTABLE`], and every
84/// [`SetObject::IMMUTABLE`] name MUST be in `CLIENT_SETTABLE`.
85///
86/// Types crates call this from a test that builds `obj` with a struct
87/// literal and no `..Default::default()`. A field added to the struct then
88/// fails to compile until the test sets it, and fails this check until it is
89/// classified.
90///
91/// # Errors
92///
93/// Returns every problem found, one per line, or a single line if `obj`
94/// does not serialize to a JSON object.
95pub fn check_property_classification<T: SetObject>(obj: &T) -> Result<(), String> {
96    let value = serde_json::to_value(obj).map_err(|e| format!("serialize: {e}"))?;
97    let serde_json::Value::Object(map) = value else {
98        return Err(format!("{} does not serialize to an object", T::TYPE_NAME));
99    };
100    let mut problems = Vec::new();
101    for key in map.keys() {
102        let k = key.as_str();
103        match (T::SERVER_SET.contains(&k), T::CLIENT_SETTABLE.contains(&k)) {
104            (false, false) => problems.push(format!("{}.{k} is unclassified", T::TYPE_NAME)),
105            (true, true) => problems.push(format!("{}.{k} is classified twice", T::TYPE_NAME)),
106            _ => {}
107        }
108    }
109    for name in T::IMMUTABLE {
110        if !T::CLIENT_SETTABLE.contains(name) {
111            problems.push(format!(
112                "{}.{name} is IMMUTABLE but not CLIENT_SETTABLE",
113                T::TYPE_NAME
114            ));
115        }
116    }
117    if problems.is_empty() {
118        Ok(())
119    } else {
120        Err(problems.join("\n"))
121    }
122}
123
124/// Marker for object types that support `query` and `queryChanges` operations.
125pub trait QueryObject: JmapObject {
126    /// The filter condition type.
127    ///
128    /// Must implement both `Serialize` and `DeserializeOwned` so that backends
129    /// can inspect or forward the filter.
130    type Filter: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static;
131    /// The comparator type for sort operations.
132    type Comparator: serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static;
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138
139    #[derive(serde::Serialize, serde::Deserialize)]
140    struct Probe {
141        id: String,
142        name: String,
143        email: String,
144    }
145
146    impl JmapObject for Probe {
147        const TYPE_NAME: &'static str = "Probe";
148        type Property = ();
149    }
150
151    impl SetObject for Probe {
152        type Patch = serde_json::Value;
153        const SERVER_SET: &'static [&'static str] = &["id"];
154        const CLIENT_SETTABLE: &'static [&'static str] = &["name", "email"];
155        const IMMUTABLE: &'static [&'static str] = &["email"];
156    }
157
158    /// The same shape with `email` left out of both lists, `name` in both,
159    /// and an IMMUTABLE name that is server-set.
160    #[derive(serde::Serialize, serde::Deserialize)]
161    struct BadProbe {
162        id: String,
163        name: String,
164        email: String,
165    }
166
167    impl JmapObject for BadProbe {
168        const TYPE_NAME: &'static str = "BadProbe";
169        type Property = ();
170    }
171
172    impl SetObject for BadProbe {
173        type Patch = serde_json::Value;
174        const SERVER_SET: &'static [&'static str] = &["id", "name"];
175        const CLIENT_SETTABLE: &'static [&'static str] = &["name"];
176        const IMMUTABLE: &'static [&'static str] = &["id"];
177    }
178
179    fn probe<T: SetObject>(make: fn(String, String, String) -> T) -> Result<(), String> {
180        check_property_classification(&make("i".into(), "n".into(), "e".into()))
181    }
182
183    #[test]
184    fn classification_accepts_a_partition() {
185        assert_eq!(probe(|id, name, email| Probe { id, name, email }), Ok(()));
186    }
187
188    #[test]
189    fn classification_reports_every_problem() {
190        let err = probe(|id, name, email| BadProbe { id, name, email }).unwrap_err();
191        let mut lines: Vec<&str> = err.lines().collect();
192        lines.sort_unstable();
193        assert_eq!(
194            lines,
195            [
196                "BadProbe.email is unclassified",
197                "BadProbe.id is IMMUTABLE but not CLIENT_SETTABLE",
198                "BadProbe.name is classified twice",
199            ]
200        );
201    }
202}