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