Skip to main content

jmap_websocket/server/
mod.rs

1//! The server side of RFC 8887: a per-connection session driver.
2//!
3//! [`Connection::run`] reads [`Inbound`] messages from any `Stream` and
4//! writes [`Outbound`] messages to any `Sink`, so it is independent of
5//! the WebSocket library. The deployment does the opening handshake
6//! (authentication, RFC 8887 §4.1; the `jmap` subprotocol, §4.2, see
7//! [`offers_jmap`](crate::offers_jmap)), maps its library's messages to
8//! [`Inbound`] / [`Outbound`] (feature `tungstenite` does this for
9//! tokio-tungstenite), and calls `run` once per connection.
10//!
11//! - Each text message goes through [`parse_client_message`]. A
12//!   [`WsRequest`] is handed to the [`RequestHandler`]
13//!   ([`DispatcherHandler`] wraps a [`jmap_server::Dispatcher`]); its
14//!   [`WsResponse`] or
15//!   [`WsRequestError`] carries the request's `id`
16//!   back as `requestId` (§4.3.3, §4.3.4).
17//! - Requests run concurrently, up to
18//!   [`ConnectionConfig::max_concurrent_requests`], and answer in the
19//!   order they finish: "JMAP over WebSocket allows the server to process
20//!   requests out of order" (§4.3.2). A request over the limit gets a
21//!   `limit` error naming `maxConcurrentRequests`, which "also applies to
22//!   requests made on the WebSocket connection". [`Connection::with_shared_limit`]
23//!   shares the limit with the deployment's HTTP API endpoint.
24//! - A [`WebSocketPushEnable`] subscribes to the [`PushSource`]; each
25//!   [`WsStateChange`] it yields is cut to the requested `dataTypes`
26//!   ([`filter_state_change`]) and sent, in the order the source yields
27//!   them. Enabling again replaces the subscription;
28//!   [`WebSocketPushDisable`] drops it (§4.3.5). [`PushHub`] is a ready
29//!   source.
30//! - A binary message closes the connection with status 1003, or is
31//!   ignored ([`BinaryFrames`], §4.3.1).
32//! - A message the WebSocket library refused for its size
33//!   ([`Inbound::TooBig`]) closes the connection with status 1009
34//!   ([`CLOSE_MESSAGE_TOO_BIG`]).
35//! - A message whose `@type` an [`ExtensionHandler`] registered
36//!   ([`Connection::with_extension`]) goes to that handler, for the
37//!   extension message types the JMAP Chat, VTC and Scene WebSocket
38//!   drafts define (`ChatStreamEnable`, `VTCStreamEnable`,
39//!   `SceneStreamEnable`, ...). The handler sends its server-to-client
40//!   messages through an [`ExtensionSender`]. Any other `@type` is
41//!   answered with `notRequest`.
42//! - A [`CloseHandle`] ([`Connection::close_handle`]) lets the deployment
43//!   end the connection with a Close frame of its choosing, such as 1008
44//!   ([`CloseCode::POLICY_VIOLATION`]) when the credentials of the
45//!   opening handshake expire (§4.2).
46
47mod close;
48mod extension;
49mod hub;
50
51pub use close::{CloseCode, CloseHandle, MAX_CLOSE_REASON_LEN};
52pub use extension::{ExtensionHandler, ExtensionMessage, ExtensionSendError, ExtensionSender};
53pub use hub::PushHub;
54
55use std::fmt;
56use std::future::Future;
57use std::sync::Arc;
58
59use futures::stream::{BoxStream, FuturesUnordered};
60use futures::{Sink, SinkExt as _, Stream, StreamExt as _};
61use jmap_server::Dispatcher;
62use jmap_types::problem::ProblemDetails;
63use jmap_types::{JmapError, JmapRequest, JmapResponse, State};
64use serde_json::Value;
65use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc};
66
67use extension::Extensions;
68
69use crate::{
70    ClientMessage, WebSocketPushDisable, WebSocketPushEnable, WsRequest, WsRequestError,
71    WsResponse, WsStateChange,
72};
73
74/// The WebSocket close status for a binary message (RFC 8887 §4.3.1,
75/// RFC 6455 §7.4.1: 1003 Unsupported Data).
76pub const CLOSE_UNSUPPORTED_DATA: u16 = 1003;
77
78/// The WebSocket close status for a message over the WebSocket library's
79/// size cap ([`Inbound::TooBig`]; RFC 6455 §7.4.1: 1009, "a message that
80/// is too big for it to process").
81pub const CLOSE_MESSAGE_TOO_BIG: u16 = 1009;
82
83// ---------------------------------------------------------------------------
84// Messages in and out
85// ---------------------------------------------------------------------------
86
87/// A WebSocket message received from the client, as the driver needs it.
88///
89/// Fragmented messages must already be coalesced (RFC 8887 §4.3); every
90/// WebSocket library does this. Map Ping and Pong to nothing: the
91/// library answers Pings itself.
92#[non_exhaustive]
93#[derive(Debug, Clone, PartialEq, Eq)]
94pub enum Inbound {
95    /// A text message (UTF-8, checked by the WebSocket library).
96    Text(String),
97    /// A binary message; its payload is not needed.
98    Binary,
99    /// A Close frame: the client is ending the connection.
100    Close,
101    /// The WebSocket library refused a message over its size cap while
102    /// reading it (tokio-tungstenite: `Error::Capacity`). The driver
103    /// closes the connection with [`CLOSE_MESSAGE_TOO_BIG`].
104    ///
105    /// Cap the library at `maxSizeRequest`
106    /// ([`ConnectionConfig::max_size_request`]), so that an oversized
107    /// message is refused before it is buffered whole.
108    TooBig,
109}
110
111/// A WebSocket message the driver sends.
112#[non_exhaustive]
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub enum Outbound {
115    /// A text message: one serialized RFC 8887 server message.
116    Text(String),
117    /// A Close frame with a status code and reason.
118    Close {
119        /// The RFC 6455 §7.4 status code.
120        code: u16,
121        /// The reason text.
122        reason: String,
123    },
124}
125
126// ---------------------------------------------------------------------------
127// Configuration
128// ---------------------------------------------------------------------------
129
130/// What the driver does with a binary message (RFC 8887 §4.3.1: "the
131/// endpoint can either ignore the frame or close the WebSocket
132/// connection").
133#[non_exhaustive]
134#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
135pub enum BinaryFrames {
136    /// Send a Close with [`CLOSE_UNSUPPORTED_DATA`] and end the connection.
137    #[default]
138    Close,
139    /// Drop the message and keep reading.
140    Ignore,
141}
142
143/// Per-connection limits and policies.
144///
145/// Set the limits to the values the Session's
146/// `urn:ietf:params:jmap:core` capability advertises (RFC 8620 §2).
147///
148/// ```
149/// use jmap_websocket::server::ConnectionConfig;
150///
151/// let config = ConnectionConfig::default()
152///     .max_calls_in_request(32)
153///     .max_size_request(Some(10_000_000))
154///     .max_concurrent_requests(4);
155/// assert_eq!(config.max_calls_in_request_value(), 32);
156/// ```
157#[non_exhaustive]
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub struct ConnectionConfig {
160    max_calls_in_request: usize,
161    max_size_request: Option<usize>,
162    max_concurrent_requests: usize,
163    binary_frames: BinaryFrames,
164    extension_queue_capacity: usize,
165}
166
167impl Default for ConnectionConfig {
168    /// 16 calls per request, 10 000 000 octets per request, 4 concurrent
169    /// requests (the RFC 8620 §2 suggested minimums), binary messages
170    /// close the connection, 64 queued extension messages.
171    fn default() -> Self {
172        Self {
173            max_calls_in_request: 16,
174            max_size_request: Some(10_000_000),
175            max_concurrent_requests: 4,
176            binary_frames: BinaryFrames::Close,
177            extension_queue_capacity: 64,
178        }
179    }
180}
181
182impl ConnectionConfig {
183    /// `maxCallsInRequest`: a Request with more method calls gets a
184    /// `limit` error naming it.
185    #[must_use]
186    pub fn max_calls_in_request(mut self, max: usize) -> Self {
187        self.max_calls_in_request = max;
188        self
189    }
190
191    /// `maxSizeRequest` in octets, or `None` for no check here: a longer
192    /// text message gets a `limit` error naming it, unparsed, so with
193    /// `requestId: null`.
194    ///
195    /// Also cap the message size in the WebSocket library, which reads the
196    /// whole message before the driver sees it. With feature `tungstenite`,
197    /// `tungstenite::accept_with_config` and `tungstenite::websocket_config`
198    /// set its cap to this value. A message over the library's cap closes
199    /// the connection with 1009 ([`Inbound::TooBig`]) instead of getting
200    /// the `limit` error; the error then answers only messages under the
201    /// library's cap and over this one.
202    #[must_use]
203    pub fn max_size_request(mut self, max: Option<usize>) -> Self {
204        self.max_size_request = max;
205        self
206    }
207
208    /// `maxConcurrentRequests` on this connection. Values below 1 are
209    /// treated as 1.
210    #[must_use]
211    pub fn max_concurrent_requests(mut self, max: usize) -> Self {
212        self.max_concurrent_requests = max.max(1);
213        self
214    }
215
216    /// The binary-message policy.
217    #[must_use]
218    pub fn binary_frames(mut self, policy: BinaryFrames) -> Self {
219        self.binary_frames = policy;
220        self
221    }
222
223    /// How many server-to-client messages the connection's
224    /// [`ExtensionHandler`]s may queue ([`ExtensionSender`]) before
225    /// [`ExtensionSender::try_send`] fails with
226    /// [`ExtensionSendError::Full`] and [`ExtensionSender::send`] waits.
227    /// Values below 1 are treated as 1.
228    #[must_use]
229    pub fn extension_queue_capacity(mut self, capacity: usize) -> Self {
230        self.extension_queue_capacity = capacity.max(1);
231        self
232    }
233
234    /// The `maxCallsInRequest` limit.
235    pub fn max_calls_in_request_value(&self) -> usize {
236        self.max_calls_in_request
237    }
238
239    /// The `maxSizeRequest` limit.
240    pub fn max_size_request_value(&self) -> Option<usize> {
241        self.max_size_request
242    }
243
244    /// The per-connection `maxConcurrentRequests` limit.
245    pub fn max_concurrent_requests_value(&self) -> usize {
246        self.max_concurrent_requests
247    }
248
249    /// The binary-message policy.
250    pub fn binary_frames_value(&self) -> BinaryFrames {
251        self.binary_frames
252    }
253
254    /// The extension message queue capacity.
255    pub fn extension_queue_capacity_value(&self) -> usize {
256        self.extension_queue_capacity
257    }
258}
259
260// ---------------------------------------------------------------------------
261// Parsing client messages
262// ---------------------------------------------------------------------------
263
264/// The RFC 8887 §4.3.4 `RequestError` for a request-level `err`: its RFC
265/// 8620 §3.6.1 problem details (status from [`jmap_server::error_status`])
266/// with `requestId` set to `request_id`.
267pub fn request_error(err: &JmapError, request_id: Option<String>) -> WsRequestError {
268    let status = jmap_server::error_status(err).as_u16();
269    WsRequestError::new(ProblemDetails::for_jmap_error(err, status), request_id)
270}
271
272/// Reads one text message from the client (RFC 8887 §4.3).
273///
274/// In order:
275///
276/// 1. Longer than `maxSizeRequest`: `limit` (`maxSizeRequest`).
277/// 2. Not JSON: `notJSON`, with the detail text of the RFC 8887 §4.4
278///    example.
279/// 3. Not an object, or `@type` missing or not one of `Request`,
280///    `WebSocketPushEnable`, `WebSocketPushDisable`: `notRequest`.
281/// 4. `Request`: `id`, when present, must be a string (§4.3.2), else
282///    `notRequest`; the rest must be an RFC 8620 §3.3 Request
283///    ([`jmap_server::parse_request`]: `notRequest`, or `limit` for
284///    `maxCallsInRequest`).
285/// 5. `WebSocketPushEnable` / `WebSocketPushDisable` with members of the
286///    wrong type: `notRequest`.
287///
288/// Every error carries the message's `id` as `requestId` when the message
289/// is an object with a string `id`, and `null` otherwise, so the client
290/// can correlate it (§4.3.4: "MUST be returned if given in the request").
291///
292/// ```
293/// use jmap_websocket::ClientMessage;
294/// use jmap_websocket::server::{ConnectionConfig, parse_client_message};
295///
296/// let config = ConnectionConfig::default();
297/// let m = parse_client_message(r#"{"@type":"WebSocketPushDisable"}"#, &config).unwrap();
298/// assert!(matches!(m, ClientMessage::PushDisable(_)));
299///
300/// let e = parse_client_message("The quick brown fox", &config).unwrap_err();
301/// assert_eq!(e.problem.problem_type, "urn:ietf:params:jmap:error:notJSON");
302/// assert_eq!(e.request_id, None);
303/// ```
304///
305/// # Errors
306///
307/// The [`WsRequestError`] to send back, as listed above.
308// The error is the message to send back, built once per bad message;
309// boxing it would only add an allocation and a deref for the caller.
310#[allow(clippy::result_large_err)]
311pub fn parse_client_message(
312    text: &str,
313    config: &ConnectionConfig,
314) -> Result<ClientMessage, WsRequestError> {
315    match parse_message(text, config, |_| false)? {
316        Parsed::Core(message) => Ok(message),
317        Parsed::Extension(_) => unreachable!("no extension types were given"),
318    }
319}
320
321/// A client message: an RFC 8887 one, or one for an [`ExtensionHandler`].
322enum Parsed {
323    Core(ClientMessage),
324    Extension(ExtensionMessage),
325}
326
327/// [`parse_client_message`], also accepting the `@type`s for which
328/// `is_extension` is true.
329#[allow(clippy::result_large_err)] // as parse_client_message
330fn parse_message(
331    text: &str,
332    config: &ConnectionConfig,
333    is_extension: impl Fn(&str) -> bool,
334) -> Result<Parsed, WsRequestError> {
335    if let Some(max) = config.max_size_request
336        && text.len() > max
337    {
338        let mut err = JmapError::limit("maxSizeRequest");
339        err.description = Some(format!(
340            "The request is {} octets, more than maxSizeRequest {max}.",
341            text.len()
342        ));
343        return Err(request_error(&err, None));
344    }
345    let value: Value = serde_json::from_str(text).map_err(|_| {
346        let mut err = JmapError::not_json();
347        err.description = Some("The request did not parse as I-JSON.".to_owned());
348        request_error(&err, None)
349    })?;
350    let Value::Object(mut obj) = value else {
351        return Err(not_request("The message is not a JSON object.", None));
352    };
353    let request_id = obj.get("id").and_then(Value::as_str).map(str::to_owned);
354    let Some(Value::String(ty)) = obj.remove("@type") else {
355        return Err(not_request("The message has no string @type.", request_id));
356    };
357    match ty.as_str() {
358        "Request" => {
359            let id = match obj.remove("id") {
360                None | Some(Value::Null) => None,
361                Some(Value::String(s)) => Some(s),
362                Some(_) => return Err(not_request("The request id is not a String.", None)),
363            };
364            match jmap_server::parse_request(Value::Object(obj), config.max_calls_in_request) {
365                Ok(request) => Ok(Parsed::Core(ClientMessage::Request(WsRequest::new(
366                    request, id,
367                )))),
368                Err(err) => Err(request_error(&err, id)),
369            }
370        }
371        "WebSocketPushEnable" => serde_json::from_value::<WebSocketPushEnable>(Value::Object(obj))
372            .map(|m| Parsed::Core(ClientMessage::PushEnable(m)))
373            .map_err(|_| not_request("Malformed WebSocketPushEnable.", request_id)),
374        "WebSocketPushDisable" => {
375            serde_json::from_value::<WebSocketPushDisable>(Value::Object(obj))
376                .map(|m| Parsed::Core(ClientMessage::PushDisable(m)))
377                .map_err(|_| not_request("Malformed WebSocketPushDisable.", request_id))
378        }
379        ty if is_extension(ty) => Ok(Parsed::Extension(ExtensionMessage::new(ty, obj))),
380        _ => Err(not_request(
381            "The @type is not one a client may send.",
382            request_id,
383        )),
384    }
385}
386
387fn not_request(detail: &str, request_id: Option<String>) -> WsRequestError {
388    let mut err = JmapError::not_request();
389    err.description = Some(detail.to_owned());
390    request_error(&err, request_id)
391}
392
393// ---------------------------------------------------------------------------
394// Request handling
395// ---------------------------------------------------------------------------
396
397/// Answers the Requests of one connection.
398///
399/// Implement it to add work around each dispatch (a `using` check, state
400/// change notification, metrics), or use [`DispatcherHandler`].
401pub trait RequestHandler: Send + Sync + 'static {
402    /// Process one parsed Request. `Err` is a request-level error (RFC
403    /// 8620 §3.6.1, e.g. `unknownCapability`) and is sent as a
404    /// `RequestError`; method-level errors belong in the Response.
405    fn handle(
406        &self,
407        request: JmapRequest,
408    ) -> impl Future<Output = Result<JmapResponse, JmapError>> + Send;
409
410    /// Called on every `RequestError` before it is sent, including those
411    /// the driver makes itself. Set a localized `title` here (RFC 9457
412    /// §3.1.3); the default leaves the problem as it is.
413    fn prepare_problem(&self, problem: &mut ProblemDetails) {
414        let _ = problem;
415    }
416}
417
418type SessionStateFn = dyn Fn() -> State + Send + Sync;
419
420/// A [`RequestHandler`] that dispatches every Request on a
421/// [`Dispatcher`] for one caller.
422///
423/// ```
424/// use std::sync::Arc;
425/// use jmap_websocket::server::DispatcherHandler;
426/// use jmap_websocket::jmap_server::Dispatcher;
427/// use jmap_websocket::jmap_types::State;
428///
429/// let dispatcher: Arc<Dispatcher<()>> = Arc::new(Dispatcher::new());
430/// let handler = DispatcherHandler::new(dispatcher, (), || State::from("s0"))
431///     .with_known_capabilities(["urn:ietf:params:jmap:core"]);
432/// # let _ = handler;
433/// ```
434pub struct DispatcherHandler<C> {
435    dispatcher: Arc<Dispatcher<C>>,
436    caller: C,
437    session_state: Arc<SessionStateFn>,
438    known_capabilities: Option<Vec<String>>,
439}
440
441impl<C: Clone + Send + Sync + 'static> DispatcherHandler<C> {
442    /// Dispatch on `dispatcher` as `caller` (the authenticated principal
443    /// of the opening handshake, RFC 8887 §4.1). `session_state` gives
444    /// the Response's `sessionState` (RFC 8620 §3.4) at each dispatch.
445    pub fn new(
446        dispatcher: Arc<Dispatcher<C>>,
447        caller: C,
448        session_state: impl Fn() -> State + Send + Sync + 'static,
449    ) -> Self {
450        Self {
451            dispatcher,
452            caller,
453            session_state: Arc::new(session_state),
454            known_capabilities: None,
455        }
456    }
457
458    /// Answer a Request whose `using` names a capability not in
459    /// `capabilities` with `unknownCapability` (RFC 8620 §3.3) through
460    /// [`jmap_server::check_known_capabilities`]. Without this every
461    /// `using` is accepted.
462    #[must_use]
463    pub fn with_known_capabilities<I, S>(mut self, capabilities: I) -> Self
464    where
465        I: IntoIterator<Item = S>,
466        S: Into<String>,
467    {
468        self.known_capabilities = Some(capabilities.into_iter().map(Into::into).collect());
469        self
470    }
471}
472
473impl<C> fmt::Debug for DispatcherHandler<C> {
474    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475        f.debug_struct("DispatcherHandler")
476            .field("known_capabilities", &self.known_capabilities)
477            .finish_non_exhaustive()
478    }
479}
480
481impl<C: Clone + Send + Sync + 'static> RequestHandler for DispatcherHandler<C> {
482    async fn handle(&self, request: JmapRequest) -> Result<JmapResponse, JmapError> {
483        if let Some(known) = &self.known_capabilities {
484            jmap_server::check_known_capabilities(&request, known)?;
485        }
486        let state = (self.session_state)();
487        Ok(self
488            .dispatcher
489            .dispatch(request, self.caller.clone(), state)
490            .await)
491    }
492}
493
494/// The [`StateChange`](jmap_types::StateChange) a Response implies: the
495/// `newState` of every `Foo/set` response whose state changed
496/// (`oldState` differs, RFC 8620 §5.3), keyed by its `accountId` and the
497/// data type `Foo`. `None` when nothing changed.
498///
499/// A deployment that learns of changes from its store instead (for
500/// example changes other connections or other protocols make) publishes
501/// those itself; this covers the writes made through this dispatcher.
502pub fn state_change_for_response(response: &JmapResponse) -> Option<jmap_types::StateChange> {
503    let mut changed: std::collections::BTreeMap<
504        jmap_types::Id,
505        std::collections::BTreeMap<String, State>,
506    > = std::collections::BTreeMap::new();
507    for call in &response.method_responses {
508        let Some(type_name) = call.name.strip_suffix("/set") else {
509            continue;
510        };
511        let args = &call.arguments;
512        let (Some(account), Some(new)) = (
513            args.get("accountId").and_then(serde_json::Value::as_str),
514            args.get("newState").and_then(serde_json::Value::as_str),
515        ) else {
516            continue;
517        };
518        if args.get("oldState").and_then(serde_json::Value::as_str) == Some(new) {
519            continue;
520        }
521        changed
522            .entry(jmap_types::Id::from(account))
523            .or_default()
524            .insert(type_name.to_owned(), State::from(new));
525    }
526    (!changed.is_empty()).then(|| jmap_types::StateChange::new(changed))
527}
528
529/// A [`RequestHandler`] that runs `inner`, then publishes the state
530/// changes of its `/set` responses ([`state_change_for_response`]) to a
531/// [`PushHub`], so connections with push enabled hear about writes made
532/// over the WebSocket without the deployment wiring it by hand.
533///
534/// ```
535/// use std::sync::Arc;
536/// use jmap_websocket::server::{DispatcherHandler, PublishingHandler, PushHub};
537/// use jmap_websocket::jmap_server::Dispatcher;
538/// use jmap_websocket::jmap_types::State;
539///
540/// let dispatcher: Arc<Dispatcher<()>> = Arc::new(Dispatcher::new());
541/// let hub = PushHub::new(64);
542/// let handler = PublishingHandler::new(
543///     DispatcherHandler::new(dispatcher, (), || State::from("s0")),
544///     hub.clone(),
545/// );
546/// # let _ = handler;
547/// ```
548#[derive(Debug)]
549pub struct PublishingHandler<H> {
550    inner: H,
551    hub: PushHub,
552}
553
554impl<H: RequestHandler> PublishingHandler<H> {
555    /// Publish `inner`'s `/set` state changes to `hub`.
556    pub fn new(inner: H, hub: PushHub) -> Self {
557        Self { inner, hub }
558    }
559}
560
561impl<H: RequestHandler> RequestHandler for PublishingHandler<H> {
562    async fn handle(&self, request: JmapRequest) -> Result<JmapResponse, JmapError> {
563        let response = self.inner.handle(request).await?;
564        if let Some(change) = state_change_for_response(&response) {
565            self.hub.publish(change);
566        }
567        Ok(response)
568    }
569
570    fn prepare_problem(&self, problem: &mut ProblemDetails) {
571        self.inner.prepare_problem(problem);
572    }
573}
574
575// ---------------------------------------------------------------------------
576// Push
577// ---------------------------------------------------------------------------
578
579/// Where a connection's push notifications come from (RFC 8887 §4.3.5).
580///
581/// One value serves one connection, so it may be scoped to the
582/// connection's caller: it must yield only changes that caller may see.
583pub trait PushSource: Send + 'static {
584    /// Start a subscription for `enable`: yield every later state change,
585    /// and first, when `enable.push_state` is a token this source issued,
586    /// the changes since it ("the server SHOULD immediately send all
587    /// changes since that state token", §4.3.5.2).
588    ///
589    /// The source may skip types outside `enable.data_types`; the driver
590    /// cuts every notification to them anyway. A stream that ends turns
591    /// push off for the connection.
592    fn subscribe(&mut self, enable: &WebSocketPushEnable) -> BoxStream<'static, WsStateChange>;
593}
594
595/// A [`PushSource`] that never pushes, for a server whose capability says
596/// `supportsPush: false`. A [`WebSocketPushEnable`] is accepted and
597/// yields nothing.
598#[non_exhaustive]
599#[derive(Debug, Clone, Copy, Default)]
600pub struct NoPush;
601
602impl PushSource for NoPush {
603    fn subscribe(&mut self, _enable: &WebSocketPushEnable) -> BoxStream<'static, WsStateChange> {
604        futures::stream::empty().boxed()
605    }
606}
607
608/// Cuts `change` to `data_types` (RFC 8887 §4.3.5.2: "A `StateChange`
609/// notification will only be sent if the data for one of these types
610/// changes. Other types are omitted from the `TypeState` object.").
611///
612/// `None` keeps every type. Accounts left with no types are dropped;
613/// `None` is returned when nothing is left. An empty list therefore
614/// matches nothing.
615pub fn filter_state_change(
616    mut change: WsStateChange,
617    data_types: Option<&[String]>,
618) -> Option<WsStateChange> {
619    if let Some(types) = data_types {
620        change.state_change.changed.retain(|_, by_type| {
621            by_type.retain(|name, _| types.iter().any(|t| t == name));
622            !by_type.is_empty()
623        });
624    }
625    if change.state_change.changed.is_empty() {
626        None
627    } else {
628        Some(change)
629    }
630}
631
632// ---------------------------------------------------------------------------
633// The driver
634// ---------------------------------------------------------------------------
635
636/// Why [`Connection::run`] stopped early.
637#[non_exhaustive]
638#[derive(Debug, thiserror::Error)]
639pub enum ConnectionError {
640    /// The incoming stream returned an error.
641    #[error("receiving a WebSocket message failed")]
642    Receive(#[source] Box<dyn std::error::Error + Send + Sync>),
643    /// The outgoing sink returned an error.
644    #[error("sending a WebSocket message failed")]
645    Send(#[source] Box<dyn std::error::Error + Send + Sync>),
646    /// A server message did not serialize.
647    #[error("serializing a server message failed")]
648    Serialize(#[source] serde_json::Error),
649}
650
651/// One JMAP-over-WebSocket connection: a [`RequestHandler`], a
652/// [`PushSource`] and limits. See the [module docs](self).
653pub struct Connection<H, P = NoPush> {
654    handler: Arc<H>,
655    push: P,
656    config: ConnectionConfig,
657    shared_limit: Option<Arc<Semaphore>>,
658    extensions: Extensions,
659    close: Arc<close::Shared>,
660}
661
662impl<H, P> fmt::Debug for Connection<H, P> {
663    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
664        f.debug_struct("Connection")
665            .field("config", &self.config)
666            .field("shared_limit", &self.shared_limit.is_some())
667            .field("extensions", &self.extensions)
668            .finish_non_exhaustive()
669    }
670}
671
672impl<H: RequestHandler> Connection<H, NoPush> {
673    /// A connection answering with `handler`, with no push
674    /// ([`NoPush`]) and the default [`ConnectionConfig`].
675    pub fn new(handler: Arc<H>) -> Self {
676        Self {
677            handler,
678            push: NoPush,
679            config: ConnectionConfig::default(),
680            shared_limit: None,
681            extensions: Extensions::default(),
682            close: close::Shared::new(),
683        }
684    }
685}
686
687type InFlight = std::pin::Pin<
688    Box<
689        dyn Future<
690                Output = (
691                    Option<String>,
692                    Result<JmapResponse, JmapError>,
693                    Option<OwnedSemaphorePermit>,
694                ),
695            > + Send,
696    >,
697>;
698
699impl<H: RequestHandler, P: PushSource> Connection<H, P> {
700    /// Push notifications from `push`.
701    pub fn with_push<Q: PushSource>(self, push: Q) -> Connection<H, Q> {
702        Connection {
703            handler: self.handler,
704            push,
705            config: self.config,
706            shared_limit: self.shared_limit,
707            extensions: self.extensions,
708            close: self.close,
709        }
710    }
711
712    /// Use `config`.
713    #[must_use]
714    pub fn with_config(mut self, config: ConnectionConfig) -> Self {
715        self.config = config;
716        self
717    }
718
719    /// Also hold a permit of `limit` while each Request runs, failing the
720    /// Request with `maxConcurrentRequests` when none is free. Share one
721    /// semaphore with the HTTP API endpoint to apply the limit to "the sum
722    /// of requests made on both" (RFC 8887 §4.3.2).
723    #[must_use]
724    pub fn with_shared_limit(mut self, limit: Arc<Semaphore>) -> Self {
725        self.shared_limit = Some(limit);
726        self
727    }
728
729    /// Route client messages of `handler`'s
730    /// [`message_types`](ExtensionHandler::message_types) to `handler`
731    /// instead of answering them with `notRequest`. Call it once per
732    /// extension capability the Session advertises; see
733    /// [`ExtensionHandler`] for the order of calls.
734    ///
735    /// # Panics
736    ///
737    /// If one of the types is an RFC 8887 type (`Request`,
738    /// `WebSocketPushEnable`, `WebSocketPushDisable`, `Response`,
739    /// `RequestError`, `StateChange`) or was registered by an earlier
740    /// handler: both are programming errors.
741    #[must_use]
742    pub fn with_extension<X: ExtensionHandler>(mut self, handler: X) -> Self {
743        self.extensions.register(handler);
744        self
745    }
746
747    /// A handle that closes this connection while it runs, with a Close
748    /// frame code and reason of the deployment's choosing (for expired
749    /// credentials, RFC 8887 §4.2). Take it before calling
750    /// [`run`](Self::run); see [`CloseHandle`] for what closing does.
751    pub fn close_handle(&self) -> CloseHandle {
752        CloseHandle::new(Arc::clone(&self.close))
753    }
754
755    /// Serve the connection until the client closes it, the incoming
756    /// stream ends, or the deployment closes it.
757    ///
758    /// Returns `Ok` after a Close, the end of `incoming`, a binary
759    /// message under [`BinaryFrames::Close`] (after sending the Close), an
760    /// [`Inbound::TooBig`] (after sending a Close with
761    /// [`CLOSE_MESSAGE_TOO_BIG`]), or a [`CloseHandle::close`] (after
762    /// sending its Close).
763    /// Requests still running then are dropped; method calls the
764    /// [`Dispatcher`] already started still finish (see
765    /// [`Dispatcher::dispatch`], Cancellation). Before returning, by any
766    /// path, it closes the extension message queue, waits for an
767    /// [`ExtensionHandler::handle`] that is running, and calls every
768    /// [`ExtensionHandler::close`].
769    ///
770    /// # Errors
771    ///
772    /// [`ConnectionError`] if `incoming` or `outgoing` fails, or a message
773    /// does not serialize.
774    pub async fn run<S, K, E>(self, mut incoming: S, mut outgoing: K) -> Result<(), ConnectionError>
775    where
776        S: Stream<Item = Result<Inbound, E>> + Unpin,
777        E: std::error::Error + Send + Sync + 'static,
778        K: Sink<Outbound> + Unpin,
779        K::Error: std::error::Error + Send + Sync + 'static,
780    {
781        let Self {
782            handler,
783            mut push,
784            config,
785            shared_limit,
786            mut extensions,
787            close,
788        } = self;
789        let mut in_flight: FuturesUnordered<InFlight> = FuturesUnordered::new();
790        let mut subscription: Option<(BoxStream<'static, WsStateChange>, Option<Vec<String>>)> =
791            None;
792        let mut extension_queue = extensions.start(config.extension_queue_capacity);
793
794        let result: Result<(), ConnectionError> = async {
795            loop {
796                // Checked first so that, once a Close is requested, no
797                // other ready branch writes ahead of it.
798                if let Some((code, reason)) = close.requested_now() {
799                    let frame = Outbound::Close { code: code.as_u16(), reason };
800                    send(&mut outgoing, frame).await?;
801                    return Ok(());
802                }
803                tokio::select! {
804                    // Polled in order, close first: when the loop was
805                    // already waiting here and a Close request and another
806                    // branch become ready together, the Close must win.
807                    biased;
808                    // Only wakes the loop; the check above sends the Close.
809                    _ = close.requested() => {}
810                    done = in_flight.next(), if !in_flight.is_empty() => {
811                        let Some((request_id, result, permit)) = done else { continue };
812                        drop(permit);
813                        let text = match result {
814                            Ok(response) => to_text(&WsResponse::new(response, request_id))?,
815                            Err(err) => error_text(&*handler, request_error(&err, request_id))?,
816                        };
817                        send(&mut outgoing, Outbound::Text(text)).await?;
818                    }
819                    change = next_change(&mut subscription) => {
820                        match change {
821                            Some(change) => {
822                                let types = subscription.as_ref().and_then(|(_, t)| t.as_deref());
823                                if let Some(change) = filter_state_change(change, types) {
824                                    send(&mut outgoing, Outbound::Text(to_text(&change)?)).await?;
825                                }
826                            }
827                            None => subscription = None,
828                        }
829                    }
830                    (id, result) = extensions.next_done() => {
831                        if let Err(err) = result {
832                            let text = error_text(&*handler, extension::extension_error(&err, id))?;
833                            send(&mut outgoing, Outbound::Text(text)).await?;
834                        }
835                    }
836                    queued = next_queued(&mut extension_queue) => {
837                        match queued {
838                            Some(text) => send(&mut outgoing, Outbound::Text(text)).await?,
839                            // Every handler dropped its sender.
840                            None => extension_queue = None,
841                        }
842                    }
843                    // While an extension message is handled, later messages
844                    // wait, so they see its effect.
845                    message = incoming.next(), if !extensions.is_busy() => {
846                        let message = match message {
847                            None | Some(Ok(Inbound::Close)) => return Ok(()),
848                            Some(Err(e)) => return Err(ConnectionError::Receive(Box::new(e))),
849                            Some(Ok(m)) => m,
850                        };
851                        let text = match message {
852                            Inbound::Text(text) => text,
853                            Inbound::Binary => match config.binary_frames {
854                                BinaryFrames::Ignore => continue,
855                                BinaryFrames::Close => {
856                                    let close = Outbound::Close {
857                                        code: CLOSE_UNSUPPORTED_DATA,
858                                        reason: "binary messages are not supported".to_owned(),
859                                    };
860                                    send(&mut outgoing, close).await?;
861                                    return Ok(());
862                                }
863                            },
864                            Inbound::TooBig => {
865                                let close = Outbound::Close {
866                                    code: CLOSE_MESSAGE_TOO_BIG,
867                                    reason: "message too big".to_owned(),
868                                };
869                                send(&mut outgoing, close).await?;
870                                return Ok(());
871                            }
872                            Inbound::Close => return Ok(()),
873                        };
874                        let parsed = parse_message(&text, &config, |ty| extensions.handles(ty));
875                        let message = match parsed {
876                            Ok(Parsed::Extension(message)) => {
877                                extensions.dispatch(message);
878                                continue;
879                            }
880                            Ok(Parsed::Core(message)) => Ok(message),
881                            Err(e) => Err(e),
882                        };
883                        match message {
884                            Err(e) => {
885                                send(&mut outgoing, Outbound::Text(error_text(&*handler, e)?)).await?;
886                            }
887                            Ok(ClientMessage::Request(WsRequest { id, request })) => {
888                                match admit(&in_flight, &config, shared_limit.as_ref()) {
889                                    Ok(permit) => {
890                                        let h = Arc::clone(&handler);
891                                        in_flight.push(Box::pin(async move {
892                                            let result = h.handle(request).await;
893                                            (id, result, permit)
894                                        }));
895                                    }
896                                    Err(()) => {
897                                        let err = JmapError::limit("maxConcurrentRequests");
898                                        let text = error_text(&*handler, request_error(&err, id))?;
899                                        send(&mut outgoing, Outbound::Text(text)).await?;
900                                    }
901                                }
902                            }
903                            Ok(ClientMessage::PushEnable(enable)) => {
904                                let stream = push.subscribe(&enable);
905                                subscription = Some((stream, enable.data_types));
906                            }
907                            Ok(ClientMessage::PushDisable(_)) => subscription = None,
908                        }
909                    }
910                }
911            }
912        }
913        .await;
914
915        close.end();
916        // Close the queue first, so a handler waiting to send returns.
917        drop(extension_queue);
918        extensions.close().await;
919        result
920    }
921}
922
923/// The next queued extension message; pending forever without a queue.
924async fn next_queued(queue: &mut Option<mpsc::Receiver<String>>) -> Option<String> {
925    match queue {
926        Some(rx) => rx.recv().await,
927        None => std::future::pending().await,
928    }
929}
930
931/// A slot for one more Request, or `Err` at the limit.
932fn admit(
933    in_flight: &FuturesUnordered<InFlight>,
934    config: &ConnectionConfig,
935    shared: Option<&Arc<Semaphore>>,
936) -> Result<Option<OwnedSemaphorePermit>, ()> {
937    if in_flight.len() >= config.max_concurrent_requests {
938        return Err(());
939    }
940    match shared {
941        None => Ok(None),
942        Some(s) => Arc::clone(s).try_acquire_owned().map(Some).map_err(|_| ()),
943    }
944}
945
946/// The next push from the subscription; pending forever without one.
947async fn next_change(
948    subscription: &mut Option<(BoxStream<'static, WsStateChange>, Option<Vec<String>>)>,
949) -> Option<WsStateChange> {
950    match subscription {
951        Some((stream, _)) => stream.next().await,
952        None => std::future::pending().await,
953    }
954}
955
956fn to_text<T: serde::Serialize>(message: &T) -> Result<String, ConnectionError> {
957    serde_json::to_string(message).map_err(ConnectionError::Serialize)
958}
959
960fn error_text<H: RequestHandler>(
961    handler: &H,
962    mut error: WsRequestError,
963) -> Result<String, ConnectionError> {
964    handler.prepare_problem(&mut error.problem);
965    to_text(&error)
966}
967
968async fn send<K>(outgoing: &mut K, message: Outbound) -> Result<(), ConnectionError>
969where
970    K: Sink<Outbound> + Unpin,
971    K::Error: std::error::Error + Send + Sync + 'static,
972{
973    outgoing
974        .send(message)
975        .await
976        .map_err(|e| ConnectionError::Send(Box::new(e)))
977}
978
979#[cfg(test)]
980mod tests;