Skip to main content

jmap_websocket/
frame.rs

1//! The RFC 8887 §4.3 WebSocket messages.
2//!
3//! Every message is one JSON object whose `@type` names it. Serialize
4//! always writes `@type`; deserializing one message type directly rejects
5//! any other `@type` value and accepts its absence (the jmap-types
6//! `StateChange` convention). [`ClientMessage`] and [`ServerMessage`]
7//! pick the type from `@type`, so there it is required.
8
9use serde::de::{self, DeserializeOwned};
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11use serde_json::{Map, Value};
12
13use jmap_types::problem::ProblemDetails;
14use jmap_types::{JmapRequest, JmapResponse, StateChange};
15
16const REQUEST: &str = "Request";
17const RESPONSE: &str = "Response";
18const REQUEST_ERROR: &str = "RequestError";
19const STATE_CHANGE: &str = "StateChange";
20const PUSH_ENABLE: &str = "WebSocketPushEnable";
21const PUSH_DISABLE: &str = "WebSocketPushDisable";
22
23/// Checks a deserialized `@type`: absent is accepted, any value other
24/// than `expected` is an error.
25fn check_type<E: de::Error>(found: Option<String>, expected: &'static str) -> Result<(), E> {
26    match found {
27        None => Ok(()),
28        Some(t) if t == expected => Ok(()),
29        Some(t) => Err(E::invalid_value(de::Unexpected::Str(&t), &expected)),
30    }
31}
32
33// ---------------------------------------------------------------------------
34// Request
35// ---------------------------------------------------------------------------
36
37/// A JMAP Request sent over the WebSocket (RFC 8887 §4.3.2): an RFC 8620
38/// §3.3 Request plus `@type: "Request"` and an optional client `id`.
39///
40/// Unknown members land in the inner [`JmapRequest::extra`].
41#[non_exhaustive]
42#[derive(Debug, Clone, PartialEq)]
43pub struct WsRequest {
44    /// `id`: "A client-specified identifier for the request to be echoed
45    /// back in the response to this request."
46    pub id: Option<String>,
47    /// The RFC 8620 Request (`using`, `methodCalls`, `createdIds`).
48    pub request: JmapRequest,
49}
50
51impl WsRequest {
52    /// A request frame for `request` with correlation id `id`.
53    pub fn new(request: JmapRequest, id: Option<String>) -> Self {
54        Self { id, request }
55    }
56}
57
58#[derive(Serialize)]
59struct RequestOut<'a> {
60    #[serde(rename = "@type")]
61    ty: &'static str,
62    #[serde(skip_serializing_if = "Option::is_none")]
63    id: Option<&'a str>,
64    #[serde(flatten)]
65    request: &'a JmapRequest,
66}
67
68#[derive(Deserialize)]
69struct RequestIn {
70    #[serde(rename = "@type", default)]
71    ty: Option<String>,
72    #[serde(default)]
73    id: Option<String>,
74    #[serde(flatten)]
75    request: JmapRequest,
76}
77
78impl Serialize for WsRequest {
79    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
80        RequestOut {
81            ty: REQUEST,
82            id: self.id.as_deref(),
83            request: &self.request,
84        }
85        .serialize(s)
86    }
87}
88
89impl<'de> Deserialize<'de> for WsRequest {
90    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
91        let r = RequestIn::deserialize(d)?;
92        check_type(r.ty, REQUEST)?;
93        Ok(Self {
94            id: r.id,
95            request: r.request,
96        })
97    }
98}
99
100// ---------------------------------------------------------------------------
101// Response
102// ---------------------------------------------------------------------------
103
104/// A JMAP Response sent over the WebSocket (RFC 8887 §4.3.3): an RFC 8620
105/// §3.4 Response plus `@type: "Response"` and `requestId`.
106///
107/// `requestId` "MUST be returned if an identifier is included in the
108/// request"; it is omitted on the wire when `None`.
109#[non_exhaustive]
110#[derive(Debug, Clone, PartialEq)]
111pub struct WsResponse {
112    /// `requestId`: the `id` of the [`WsRequest`] this answers.
113    pub request_id: Option<String>,
114    /// The RFC 8620 Response.
115    pub response: JmapResponse,
116}
117
118impl WsResponse {
119    /// A response frame answering the request with id `request_id`.
120    pub fn new(response: JmapResponse, request_id: Option<String>) -> Self {
121        Self {
122            request_id,
123            response,
124        }
125    }
126}
127
128#[derive(Serialize)]
129struct ResponseOut<'a> {
130    #[serde(rename = "@type")]
131    ty: &'static str,
132    #[serde(rename = "requestId", skip_serializing_if = "Option::is_none")]
133    request_id: Option<&'a str>,
134    #[serde(flatten)]
135    response: &'a JmapResponse,
136}
137
138#[derive(Deserialize)]
139struct ResponseIn {
140    #[serde(rename = "@type", default)]
141    ty: Option<String>,
142    #[serde(rename = "requestId", default)]
143    request_id: Option<String>,
144    #[serde(flatten)]
145    response: JmapResponse,
146}
147
148impl Serialize for WsResponse {
149    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
150        ResponseOut {
151            ty: RESPONSE,
152            request_id: self.request_id.as_deref(),
153            response: &self.response,
154        }
155        .serialize(s)
156    }
157}
158
159impl<'de> Deserialize<'de> for WsResponse {
160    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
161        let r = ResponseIn::deserialize(d)?;
162        check_type(r.ty, RESPONSE)?;
163        Ok(Self {
164            request_id: r.request_id,
165            response: r.response,
166        })
167    }
168}
169
170// ---------------------------------------------------------------------------
171// RequestError
172// ---------------------------------------------------------------------------
173
174/// A request-level error sent over the WebSocket (RFC 8887 §4.3.4): an
175/// RFC 8620 §3.6.1 problem details object plus `@type: "RequestError"`
176/// and `requestId`.
177///
178/// `requestId` is always written, as `null` when `None`, the way the
179/// RFC 8887 §4.4 `notJSON` example writes it for a message the server
180/// could not read an id from. It "MUST be returned if given in the
181/// request".
182///
183/// ```
184/// use jmap_websocket::WsRequestError;
185/// use jmap_websocket::jmap_types::problem::ProblemDetails;
186///
187/// let e = WsRequestError::new(
188///     ProblemDetails::new("urn:ietf:params:jmap:error:notJSON", 400),
189///     None,
190/// );
191/// let v = serde_json::to_value(&e).unwrap();
192/// assert_eq!(v["@type"], "RequestError");
193/// assert!(v["requestId"].is_null());
194/// ```
195#[non_exhaustive]
196#[derive(Debug, Clone, PartialEq)]
197pub struct WsRequestError {
198    /// `requestId`: the `id` of the request this error answers.
199    pub request_id: Option<String>,
200    /// The problem details (`type`, `status`, `title`, `detail`, `limit`,
201    /// extension members).
202    pub problem: ProblemDetails,
203}
204
205impl WsRequestError {
206    /// An error frame carrying `problem` for the request with id
207    /// `request_id`.
208    pub fn new(problem: ProblemDetails, request_id: Option<String>) -> Self {
209        Self {
210            request_id,
211            problem,
212        }
213    }
214}
215
216#[derive(Serialize)]
217struct RequestErrorOut<'a> {
218    #[serde(rename = "@type")]
219    ty: &'static str,
220    #[serde(rename = "requestId")]
221    request_id: Option<&'a str>,
222    #[serde(flatten)]
223    problem: &'a ProblemDetails,
224}
225
226#[derive(Deserialize)]
227struct RequestErrorIn {
228    #[serde(rename = "@type", default)]
229    ty: Option<String>,
230    #[serde(rename = "requestId", default)]
231    request_id: Option<String>,
232    #[serde(flatten)]
233    problem: ProblemDetails,
234}
235
236impl Serialize for WsRequestError {
237    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
238        RequestErrorOut {
239            ty: REQUEST_ERROR,
240            request_id: self.request_id.as_deref(),
241            problem: &self.problem,
242        }
243        .serialize(s)
244    }
245}
246
247impl<'de> Deserialize<'de> for WsRequestError {
248    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
249        let r = RequestErrorIn::deserialize(d)?;
250        check_type(r.ty, REQUEST_ERROR)?;
251        Ok(Self {
252            request_id: r.request_id,
253            problem: r.problem,
254        })
255    }
256}
257
258// ---------------------------------------------------------------------------
259// StateChange
260// ---------------------------------------------------------------------------
261
262/// A push notification sent over the WebSocket (RFC 8887 §4.3.5.1): an
263/// RFC 8620 §7.1 StateChange plus an optional `pushState`.
264///
265/// `pushState` "encodes the entire server state visible to the user"; a
266/// client echoes the last one it got in [`WebSocketPushEnable`] after a
267/// reconnect. Omitted on the wire when `None`.
268#[non_exhaustive]
269#[derive(Debug, Clone, PartialEq, Eq)]
270pub struct WsStateChange {
271    /// `pushState`.
272    pub push_state: Option<String>,
273    /// The RFC 8620 StateChange (`changed` and extension members).
274    pub state_change: StateChange,
275}
276
277impl WsStateChange {
278    /// A push frame for `state_change` with token `push_state`.
279    pub fn new(state_change: StateChange, push_state: Option<String>) -> Self {
280        Self {
281            push_state,
282            state_change,
283        }
284    }
285}
286
287#[derive(Serialize)]
288struct StateChangeOut<'a> {
289    // StateChange's own Serialize writes `@type` first.
290    #[serde(flatten)]
291    state_change: &'a StateChange,
292    #[serde(rename = "pushState", skip_serializing_if = "Option::is_none")]
293    push_state: Option<&'a str>,
294}
295
296#[derive(Deserialize)]
297struct StateChangeIn {
298    #[serde(rename = "pushState", default)]
299    push_state: Option<String>,
300    // StateChange's own Deserialize checks and drops `@type`.
301    #[serde(flatten)]
302    state_change: StateChange,
303}
304
305impl Serialize for WsStateChange {
306    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
307        StateChangeOut {
308            state_change: &self.state_change,
309            push_state: self.push_state.as_deref(),
310        }
311        .serialize(s)
312    }
313}
314
315impl<'de> Deserialize<'de> for WsStateChange {
316    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
317        let r = StateChangeIn::deserialize(d)?;
318        Ok(Self {
319            push_state: r.push_state,
320            state_change: r.state_change,
321        })
322    }
323}
324
325// ---------------------------------------------------------------------------
326// WebSocketPushEnable / WebSocketPushDisable
327// ---------------------------------------------------------------------------
328
329/// Turns on push notifications for the connection (RFC 8887 §4.3.5.2).
330///
331/// `dataTypes` is `String[]|null` and always written; `null` asks for
332/// every supported data type. A missing `dataTypes` reads as `null`.
333/// Sending it again replaces the earlier subscription.
334#[non_exhaustive]
335#[derive(Debug, Clone, PartialEq, Eq, Default)]
336pub struct WebSocketPushEnable {
337    /// `dataTypes`: the data type names whose changes the client wants;
338    /// "Other types are omitted from the TypeState object." `None` is
339    /// every type.
340    pub data_types: Option<Vec<String>>,
341    /// `pushState`: the last token the client got; "the server SHOULD
342    /// immediately send all changes since that state token".
343    pub push_state: Option<String>,
344    /// Vendor, site and future-spec members.
345    pub extra: Map<String, Value>,
346}
347
348impl WebSocketPushEnable {
349    /// A push-enable message for `data_types` (`None`: all types),
350    /// resuming from `push_state`.
351    pub fn new(data_types: Option<Vec<String>>, push_state: Option<String>) -> Self {
352        Self {
353            data_types,
354            push_state,
355            extra: Map::new(),
356        }
357    }
358}
359
360#[derive(Serialize)]
361struct PushEnableOut<'a> {
362    #[serde(rename = "@type")]
363    ty: &'static str,
364    #[serde(rename = "dataTypes")]
365    data_types: Option<&'a [String]>,
366    #[serde(rename = "pushState", skip_serializing_if = "Option::is_none")]
367    push_state: Option<&'a str>,
368    #[serde(flatten)]
369    extra: &'a Map<String, Value>,
370}
371
372#[derive(Deserialize)]
373struct PushEnableIn {
374    #[serde(rename = "@type", default)]
375    ty: Option<String>,
376    #[serde(rename = "dataTypes", default)]
377    data_types: Option<Vec<String>>,
378    #[serde(rename = "pushState", default)]
379    push_state: Option<String>,
380    #[serde(flatten)]
381    extra: Map<String, Value>,
382}
383
384impl Serialize for WebSocketPushEnable {
385    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
386        PushEnableOut {
387            ty: PUSH_ENABLE,
388            data_types: self.data_types.as_deref(),
389            push_state: self.push_state.as_deref(),
390            extra: &self.extra,
391        }
392        .serialize(s)
393    }
394}
395
396impl<'de> Deserialize<'de> for WebSocketPushEnable {
397    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
398        let r = PushEnableIn::deserialize(d)?;
399        check_type(r.ty, PUSH_ENABLE)?;
400        Ok(Self {
401            data_types: r.data_types,
402            push_state: r.push_state,
403            extra: r.extra,
404        })
405    }
406}
407
408/// Turns off push notifications for the connection (RFC 8887 §4.3.5.3).
409/// Its only RFC property is `@type`.
410#[non_exhaustive]
411#[derive(Debug, Clone, PartialEq, Eq, Default)]
412pub struct WebSocketPushDisable {
413    /// Vendor, site and future-spec members.
414    pub extra: Map<String, Value>,
415}
416
417impl WebSocketPushDisable {
418    /// A push-disable message with no extension members.
419    pub fn new() -> Self {
420        Self::default()
421    }
422}
423
424#[derive(Serialize)]
425struct PushDisableOut<'a> {
426    #[serde(rename = "@type")]
427    ty: &'static str,
428    #[serde(flatten)]
429    extra: &'a Map<String, Value>,
430}
431
432#[derive(Deserialize)]
433struct PushDisableIn {
434    #[serde(rename = "@type", default)]
435    ty: Option<String>,
436    #[serde(flatten)]
437    extra: Map<String, Value>,
438}
439
440impl Serialize for WebSocketPushDisable {
441    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
442        PushDisableOut {
443            ty: PUSH_DISABLE,
444            extra: &self.extra,
445        }
446        .serialize(s)
447    }
448}
449
450impl<'de> Deserialize<'de> for WebSocketPushDisable {
451    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
452        let r = PushDisableIn::deserialize(d)?;
453        check_type(r.ty, PUSH_DISABLE)?;
454        Ok(Self { extra: r.extra })
455    }
456}
457
458// ---------------------------------------------------------------------------
459// Message enums
460// ---------------------------------------------------------------------------
461
462/// Reads `@type` from a message object and deserializes the whole object
463/// as `T`.
464fn from_object<T: DeserializeOwned, E: de::Error>(obj: Map<String, Value>) -> Result<T, E> {
465    serde_json::from_value(Value::Object(obj)).map_err(E::custom)
466}
467
468fn take_tag<E: de::Error>(obj: &Map<String, Value>) -> Result<String, E> {
469    match obj.get("@type") {
470        Some(Value::String(s)) => Ok(s.clone()),
471        Some(_) => Err(E::custom("`@type` is not a string")),
472        None => Err(E::missing_field("@type")),
473    }
474}
475
476/// A message a client sends (RFC 8887 §4.3): "a single JMAP Request
477/// object ..., JMAP WebSocketPushEnable object ..., or JMAP
478/// WebSocketPushDisable object".
479///
480/// Deserialize requires `@type` and fails on any other value; a server
481/// that must answer bad input with the right problem type uses
482/// `server::parse_client_message` (feature `server`) instead.
483#[non_exhaustive]
484#[derive(Debug, Clone, PartialEq)]
485pub enum ClientMessage {
486    /// `@type: "Request"`.
487    Request(WsRequest),
488    /// `@type: "WebSocketPushEnable"`.
489    PushEnable(WebSocketPushEnable),
490    /// `@type: "WebSocketPushDisable"`.
491    PushDisable(WebSocketPushDisable),
492}
493
494impl Serialize for ClientMessage {
495    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
496        match self {
497            Self::Request(m) => m.serialize(s),
498            Self::PushEnable(m) => m.serialize(s),
499            Self::PushDisable(m) => m.serialize(s),
500        }
501    }
502}
503
504impl<'de> Deserialize<'de> for ClientMessage {
505    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
506        let obj = Map::deserialize(d)?;
507        match take_tag::<D::Error>(&obj)?.as_str() {
508            REQUEST => from_object(obj).map(Self::Request),
509            PUSH_ENABLE => from_object(obj).map(Self::PushEnable),
510            PUSH_DISABLE => from_object(obj).map(Self::PushDisable),
511            other => Err(de::Error::unknown_variant(
512                other,
513                &[REQUEST, PUSH_ENABLE, PUSH_DISABLE],
514            )),
515        }
516    }
517}
518
519/// A message a server sends (RFC 8887 §4.3): "a single JMAP Response
520/// object, JSON Problem Details object, or JMAP StateChange object".
521///
522/// Deserialize requires `@type` and fails on any other value; RFC 8887
523/// §4.3.1 lets a client ignore such a message or close the connection.
524#[non_exhaustive]
525#[derive(Debug, Clone, PartialEq)]
526pub enum ServerMessage {
527    /// `@type: "Response"`.
528    Response(WsResponse),
529    /// `@type: "RequestError"`.
530    RequestError(WsRequestError),
531    /// `@type: "StateChange"`.
532    StateChange(WsStateChange),
533}
534
535impl Serialize for ServerMessage {
536    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
537        match self {
538            Self::Response(m) => m.serialize(s),
539            Self::RequestError(m) => m.serialize(s),
540            Self::StateChange(m) => m.serialize(s),
541        }
542    }
543}
544
545impl<'de> Deserialize<'de> for ServerMessage {
546    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
547        let obj = Map::deserialize(d)?;
548        match take_tag::<D::Error>(&obj)?.as_str() {
549            RESPONSE => from_object(obj).map(Self::Response),
550            REQUEST_ERROR => from_object(obj).map(Self::RequestError),
551            STATE_CHANGE => from_object(obj).map(Self::StateChange),
552            other => Err(de::Error::unknown_variant(
553                other,
554                &[RESPONSE, REQUEST_ERROR, STATE_CHANGE],
555            )),
556        }
557    }
558}
559
560#[cfg(test)]
561mod tests;