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