Skip to main content

jmap_websocket/server/
extension.rs

1//! Extension message types: [`ExtensionHandler`] and its parts.
2//!
3//! RFC 8887 §4.3 closes the set of message types. The JMAP Chat, VTC and
4//! Scene WebSocket drafts update it: "A JMAP capability advertised in the
5//! Session object ... MAY define additional WebSocket message types, each
6//! identified by its `@type` value", and "A server MUST NOT send an
7//! additional server-to-client message type unless the client has enabled
8//! it using a control message defined by the same capability"
9//! (draft-atwood-jmap-chat-wss-00 §Update to RFC 8887; the VTC and Scene
10//! drafts restate it). This module is that hook, with no knowledge of any
11//! one extension.
12
13use std::collections::HashMap;
14use std::fmt;
15use std::future::Future;
16use std::pin::Pin;
17
18use futures::future::BoxFuture;
19use jmap_types::JmapError;
20use serde::Serialize;
21use serde::de::DeserializeOwned;
22use serde_json::{Map, Value};
23use tokio::sync::mpsc;
24
25/// The `@type` values RFC 8887 §4.3 defines. The driver handles the
26/// client-to-server ones itself, and an extension may not send the
27/// server-to-client ones.
28const CORE_TYPES: [&str; 6] = [
29    "Request",
30    "WebSocketPushEnable",
31    "WebSocketPushDisable",
32    "Response",
33    "RequestError",
34    "StateChange",
35];
36
37/// Problem-details members the driver writes itself; an
38/// [`ExtensionHandler`] error's `extra` members with these names are
39/// dropped so they cannot appear twice.
40const RESERVED_PROBLEM_MEMBERS: [&str; 8] = [
41    "@type",
42    "requestId",
43    "type",
44    "status",
45    "title",
46    "detail",
47    "instance",
48    "limit",
49];
50
51/// One client message whose `@type` an [`ExtensionHandler`] registered.
52///
53/// ```
54/// use jmap_websocket::server::ExtensionMessage;
55///
56/// #[derive(serde::Deserialize)]
57/// #[serde(rename_all = "camelCase")]
58/// struct ToyEnable {
59///     topics: Vec<String>,
60/// }
61///
62/// let m = ExtensionMessage::new(
63///     "ToyStreamEnable",
64///     serde_json::from_str(r#"{"id":"e1","topics":["a"]}"#).unwrap(),
65/// );
66/// assert_eq!(m.id.as_deref(), Some("e1"));
67/// let enable: ToyEnable = m.deserialize().unwrap();
68/// assert_eq!(enable.topics, ["a"]);
69/// ```
70#[non_exhaustive]
71#[derive(Debug, Clone, PartialEq)]
72pub struct ExtensionMessage {
73    /// The message's `@type`.
74    pub message_type: String,
75    /// The message's `id` when it is a string: the `requestId` of a
76    /// `RequestError` the message causes (RFC 8887 §4.3.4). It also stays
77    /// in [`body`](Self::body).
78    pub id: Option<String>,
79    /// Every member of the message except `@type`.
80    pub body: Map<String, Value>,
81}
82
83impl ExtensionMessage {
84    /// A message of type `message_type` with the members `body` (without
85    /// `@type`); [`id`](Self::id) is taken from `body`.
86    pub fn new(message_type: impl Into<String>, body: Map<String, Value>) -> Self {
87        let id = body.get("id").and_then(Value::as_str).map(str::to_owned);
88        Self {
89            message_type: message_type.into(),
90            id,
91            body,
92        }
93    }
94
95    /// The body as a `T`, typically the extension's own frame type.
96    ///
97    /// # Errors
98    ///
99    /// A `notRequest` error when the body does not deserialize, as the
100    /// driver answers a malformed `WebSocketPushEnable`. Return it from
101    /// [`ExtensionHandler::handle`] to send it to the client.
102    pub fn deserialize<T: DeserializeOwned>(&self) -> Result<T, JmapError> {
103        serde_json::from_value(Value::Object(self.body.clone())).map_err(|e| {
104            let mut err = JmapError::not_request();
105            err.description = Some(format!("Malformed {}: {e}", self.message_type));
106            err
107        })
108    }
109}
110
111/// Why an [`ExtensionSender`] did not queue a message.
112#[non_exhaustive]
113#[derive(Debug, thiserror::Error)]
114pub enum ExtensionSendError {
115    /// The queue is full ([`ExtensionSender::try_send`] only). The
116    /// message was dropped.
117    #[error("the connection's extension message queue is full")]
118    Full,
119    /// The connection has ended. The message was dropped.
120    #[error("the connection has ended")]
121    Closed,
122    /// The message is not a JSON object with a string `@type`, or its
123    /// `@type` is one RFC 8887 §4.3 defines (`Response`, `RequestError`,
124    /// `StateChange`, and the client-to-server types).
125    #[error("an extension message must be a JSON object whose @type is not an RFC 8887 type")]
126    NotAnExtensionMessage,
127    /// The message did not serialize.
128    #[error("serializing an extension message failed")]
129    Serialize(#[source] serde_json::Error),
130}
131
132/// Queues server-to-client messages of one connection's extensions.
133///
134/// The driver writes them in the order they were queued, interleaved
135/// with Responses and `StateChange`s in no set order (the drafts guarantee
136/// none: "No ordering relationship is guaranteed between ephemeral event
137/// frames and `Response` or `StateChange` frames",
138/// draft-atwood-jmap-chat-wss-00 §Ephemeral Chat Events). The queue is
139/// bounded by [`ConnectionConfig::extension_queue_capacity`](super::ConnectionConfig::extension_queue_capacity).
140///
141/// Clone it freely, for example into a task that forwards events from a
142/// broadcast channel. Once the connection ends every send fails with
143/// [`ExtensionSendError::Closed`], and [`closed`](Self::closed)
144/// resolves, so such a task can stop; messages still queued then are
145/// dropped.
146#[derive(Debug, Clone)]
147pub struct ExtensionSender {
148    tx: mpsc::Sender<String>,
149}
150
151impl ExtensionSender {
152    pub(super) fn new(tx: mpsc::Sender<String>) -> Self {
153        Self { tx }
154    }
155
156    /// Queue `message`, waiting while the queue is full.
157    ///
158    /// Awaiting it in [`ExtensionHandler::handle`] cannot deadlock (the
159    /// driver keeps writing while `handle` runs), but with a full queue
160    /// `handle`, and so the next client message, waits on a slow client.
161    ///
162    /// # Errors
163    ///
164    /// [`ExtensionSendError`] other than `Full`.
165    pub async fn send<T: Serialize + ?Sized>(&self, message: &T) -> Result<(), ExtensionSendError> {
166        let text = extension_text(message)?;
167        self.tx
168            .send(text)
169            .await
170            .map_err(|_| ExtensionSendError::Closed)
171    }
172
173    /// Queue `message` now, or drop it if the queue is full. Suits
174    /// ephemeral events, which the drafts let a server drop under load
175    /// ("events above this rate MAY be silently dropped").
176    ///
177    /// # Errors
178    ///
179    /// [`ExtensionSendError`].
180    pub fn try_send<T: Serialize + ?Sized>(&self, message: &T) -> Result<(), ExtensionSendError> {
181        let text = extension_text(message)?;
182        self.tx.try_send(text).map_err(|e| match e {
183            mpsc::error::TrySendError::Full(_) => ExtensionSendError::Full,
184            mpsc::error::TrySendError::Closed(_) => ExtensionSendError::Closed,
185        })
186    }
187
188    /// Whether the connection has ended.
189    pub fn is_closed(&self) -> bool {
190        self.tx.is_closed()
191    }
192
193    /// Resolves when the connection has ended.
194    pub async fn closed(&self) {
195        self.tx.closed().await;
196    }
197}
198
199/// Serializes `message` after checking it is an extension message.
200fn extension_text<T: Serialize + ?Sized>(message: &T) -> Result<String, ExtensionSendError> {
201    let value = serde_json::to_value(message).map_err(ExtensionSendError::Serialize)?;
202    match value.get("@type").and_then(Value::as_str) {
203        Some(ty) if !CORE_TYPES.contains(&ty) => {}
204        _ => return Err(ExtensionSendError::NotAnExtensionMessage),
205    }
206    serde_json::to_string(&value).map_err(ExtensionSendError::Serialize)
207}
208
209/// Handles the client messages of one or more extension `@type`s on one
210/// connection, and sends that extension's server-to-client messages.
211///
212/// Register it with
213/// [`Connection::with_extension`](super::Connection::with_extension), one
214/// value per connection, when the Session advertises the capability that
215/// defines the types (for example `urn:ietf:params:jmap:chat:websocket`
216/// for `ChatStreamEnable` and `ChatStreamDisable`). The drafts tie the
217/// types to the advertised capability, not to a Request's `using`, so the
218/// driver does no capability check of its own. A message whose `@type` no
219/// handler registered is answered with `notRequest`, as before
220/// ("A client-to-server message with an unrecognized `@type` value is a
221/// request-level error", draft-atwood-jmap-chat-wss-00 §Handling Unknown
222/// Message Types).
223///
224/// The value is the connection's extension state: build it with the
225/// connection's authenticated caller, keep the subscription in it, and
226/// use `&mut self` freely. The driver calls, in order:
227///
228/// 1. [`start`](Self::start) once, before reading any message, with the
229///    [`ExtensionSender`] for server-to-client messages.
230/// 2. [`handle`](Self::handle) for each registered message, one at a
231///    time in the order the client sent them. Until `handle` returns the
232///    driver reads no further client message, so a Request sent after a
233///    `…StreamEnable` runs after the subscription is in place; Responses,
234///    `StateChange`s and queued extension messages keep flowing meanwhile.
235///    Keep it short: start long work on a task of your own.
236/// 3. [`close`](Self::close) once when [`Connection::run`](super::Connection::run)
237///    ends, however it ends, after the connection's queue is closed and
238///    any running `handle` finished. Release per-connection resources
239///    here (the drafts cancel the subscription "immediately" when the
240///    connection closes; a Scene observer stops counting toward
241///    `observerCount`). It is not called if the `run` future itself is
242///    dropped; put cleanup that must run then in `Drop`.
243///
244/// To let one extension's control message turn on another's events (a
245/// `ChatStreamEnable` with `"vtc"` in `dataTypes`), register one handler
246/// for all the types involved.
247///
248/// ```
249/// use jmap_websocket::jmap_types::JmapError;
250/// use jmap_websocket::server::{ExtensionHandler, ExtensionMessage, ExtensionSender};
251/// use serde_json::json;
252///
253/// /// `ToyStreamEnable` turns on `ToyEvent`s; `ToyStreamDisable` turns
254/// /// them off.
255/// #[derive(Default)]
256/// struct Toy {
257///     events: Option<ExtensionSender>,
258///     enabled: bool,
259/// }
260///
261/// impl ExtensionHandler for Toy {
262///     fn message_types(&self) -> &[&str] {
263///         &["ToyStreamEnable", "ToyStreamDisable"]
264///     }
265///
266///     fn start(&mut self, events: ExtensionSender) {
267///         self.events = Some(events);
268///     }
269///
270///     async fn handle(&mut self, message: ExtensionMessage) -> Result<(), JmapError> {
271///         match message.message_type.as_str() {
272///             "ToyStreamEnable" => self.enabled = true,
273///             _ => self.enabled = false,
274///         }
275///         if self.enabled
276///             && let Some(events) = &self.events
277///         {
278///             // An ephemeral event: drop it rather than wait if the
279///             // client is slow.
280///             let _ = events.try_send(&json!({"@type": "ToyEvent", "hello": true}));
281///         }
282///         Ok(())
283///     }
284/// }
285/// ```
286pub trait ExtensionHandler: Send + 'static {
287    /// The client-to-server `@type`s this handler takes. Read once, by
288    /// [`Connection::with_extension`](super::Connection::with_extension).
289    fn message_types(&self) -> &[&str];
290
291    /// Called once before the first message, with the queue for this
292    /// connection's server-to-client extension messages. The default
293    /// drops it.
294    fn start(&mut self, events: ExtensionSender) {
295        let _ = events;
296    }
297
298    /// Process one message. Success sends nothing (the drafts' control
299    /// messages are not acknowledged: "success is silent and failure
300    /// produces a `RequestError`"). `Err` is sent as an RFC 8887 §4.3.4
301    /// `RequestError` with the message's [`id`](ExtensionMessage::id) as
302    /// `requestId`, through
303    /// [`RequestHandler::prepare_problem`](super::RequestHandler::prepare_problem);
304    /// its `extra` members become problem-details members (for example
305    /// the Scene draft's `regionIds` on a `forbidden` error).
306    fn handle(
307        &mut self,
308        message: ExtensionMessage,
309    ) -> impl Future<Output = Result<(), JmapError>> + Send;
310
311    /// Called once when the connection ends. The default does nothing.
312    fn close(&mut self) -> impl Future<Output = ()> + Send {
313        async {}
314    }
315}
316
317/// [`ExtensionHandler`] made object safe, so a connection can hold
318/// handlers of different types.
319trait ErasedHandler: Send {
320    fn start(&mut self, events: ExtensionSender);
321    fn handle(&mut self, message: ExtensionMessage) -> BoxFuture<'_, Result<(), JmapError>>;
322    fn close(&mut self) -> BoxFuture<'_, ()>;
323}
324
325impl<T: ExtensionHandler> ErasedHandler for T {
326    fn start(&mut self, events: ExtensionSender) {
327        ExtensionHandler::start(self, events);
328    }
329
330    fn handle(&mut self, message: ExtensionMessage) -> BoxFuture<'_, Result<(), JmapError>> {
331        Box::pin(ExtensionHandler::handle(self, message))
332    }
333
334    fn close(&mut self) -> BoxFuture<'_, ()> {
335        Box::pin(ExtensionHandler::close(self))
336    }
337}
338
339/// What a finished [`ExtensionHandler::handle`] gives back: the handler's
340/// slot, the handler, the message id, the result.
341type Handled = (
342    usize,
343    Box<dyn ErasedHandler>,
344    Option<String>,
345    Result<(), JmapError>,
346);
347
348/// The extension handlers of one connection, and the one message being
349/// handled.
350#[derive(Default)]
351pub(super) struct Extensions {
352    /// `None` while that handler's `handle` runs.
353    handlers: Vec<Option<Box<dyn ErasedHandler>>>,
354    by_type: HashMap<String, usize>,
355    in_flight: Option<Pin<Box<dyn Future<Output = Handled> + Send>>>,
356}
357
358impl fmt::Debug for Extensions {
359    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
360        let mut types: Vec<&str> = self.by_type.keys().map(String::as_str).collect();
361        types.sort_unstable();
362        f.debug_list().entries(types).finish()
363    }
364}
365
366impl Extensions {
367    /// Adds `handler` under its message types.
368    ///
369    /// # Panics
370    ///
371    /// If a type is an RFC 8887 type or another handler's.
372    pub(super) fn register<X: ExtensionHandler>(&mut self, handler: X) {
373        let index = self.handlers.len();
374        for &ty in handler.message_types() {
375            assert!(
376                !CORE_TYPES.contains(&ty),
377                "extension message type {ty:?} is an RFC 8887 type"
378            );
379            let previous = self.by_type.insert(ty.to_owned(), index);
380            assert!(
381                previous.is_none_or(|p| p == index),
382                "extension message type {ty:?} is registered twice"
383            );
384        }
385        self.handlers.push(Some(Box::new(handler)));
386    }
387
388    /// Whether a handler takes messages of type `ty`.
389    pub(super) fn handles(&self, ty: &str) -> bool {
390        self.by_type.contains_key(ty)
391    }
392
393    /// Whether a message is being handled.
394    pub(super) fn is_busy(&self) -> bool {
395        self.in_flight.is_some()
396    }
397
398    /// Calls every handler's `start` with a sender on a new queue of
399    /// `capacity` messages, and returns its receiver; `None` when there
400    /// are no handlers.
401    pub(super) fn start(&mut self, capacity: usize) -> Option<mpsc::Receiver<String>> {
402        if self.handlers.is_empty() {
403            return None;
404        }
405        let (tx, rx) = mpsc::channel(capacity);
406        for handler in self.handlers.iter_mut().flatten() {
407            handler.start(ExtensionSender::new(tx.clone()));
408        }
409        Some(rx)
410    }
411
412    /// Starts handling `message`. The driver calls this only when not
413    /// [`is_busy`](Self::is_busy) and for a type [`handles`](Self::handles)
414    /// accepts.
415    pub(super) fn dispatch(&mut self, message: ExtensionMessage) {
416        let index = self.by_type[&message.message_type];
417        let mut handler = self.handlers[index]
418            .take()
419            .expect("handlers run one message at a time");
420        let id = message.id.clone();
421        self.in_flight = Some(Box::pin(async move {
422            let result = handler.handle(message).await;
423            (index, handler, id, result)
424        }));
425    }
426
427    /// The outcome of the message being handled, `(id, result)`; pending
428    /// forever when none is. Cancel safe: dropping it leaves the message
429    /// running.
430    pub(super) async fn next_done(&mut self) -> (Option<String>, Result<(), JmapError>) {
431        let Some(in_flight) = self.in_flight.as_mut() else {
432            return std::future::pending().await;
433        };
434        let (index, handler, id, result) = in_flight.await;
435        self.in_flight = None;
436        self.handlers[index] = Some(handler);
437        (id, result)
438    }
439
440    /// Finishes the message being handled, then calls every handler's
441    /// `close`. Close the queue first, so a `send` waiting in it returns.
442    pub(super) async fn close(&mut self) {
443        if self.in_flight.is_some() {
444            let _ = self.next_done().await;
445        }
446        for handler in self.handlers.iter_mut().flatten() {
447            handler.close().await;
448        }
449    }
450}
451
452/// The problem details for an [`ExtensionHandler`] error: as for a
453/// Request ([`request_error`](super::request_error)), plus the error's
454/// `extra` members.
455pub(super) fn extension_error(
456    err: &JmapError,
457    request_id: Option<String>,
458) -> crate::WsRequestError {
459    let mut error = super::request_error(err, request_id);
460    for (name, value) in &err.extra {
461        if !RESERVED_PROBLEM_MEMBERS.contains(&name.as_str()) {
462            error.problem.extra.insert(name.clone(), value.clone());
463        }
464    }
465    error
466}