Skip to main content

jmap_chat_server/
websocket.rs

1//! `ChatStreamEnable` / `ChatStreamDisable` and the ephemeral events they
2//! turn on, as a [`jmap_websocket`] extension (draft-atwood-jmap-chat-wss-00
3//! §Ephemeral Chat Events).
4//!
5//! - The deployment keeps one [`ChatEventHub`] and publishes every
6//!   `ChatTypingEvent` and `ChatPresenceEvent` to it, one per recipient
7//!   account (the event's `accountId`).
8//! - For each WebSocket connection it builds a [`ChatStreamHandler`] with
9//!   the connection's caller and accounts, and registers it with
10//!   [`Connection::with_extension`](jmap_websocket::server::Connection::with_extension)
11//!   next to advertising `urn:ietf:params:jmap:chat:websocket`.
12//!
13//! The handler keeps the connection's [`EphemeralSubscription`]. For each
14//! published event it checks, at delivery time, the subscription's
15//! `chatIds` / `contactIds` scope, [`should_deliver_typing`] or
16//! [`project_presence`], and the draft's rate limits
17//! ([`ChatStreamLimits`]), then queues the frame with
18//! [`ExtensionSender::try_send`], which drops it if the client is too
19//! slow ("events above this rate MAY be silently dropped").
20//!
21//! Credential expiry is the deployment's: "A server that does not close
22//! the connection when credentials expire SHOULD NOT deliver further
23//! ephemeral events on that connection" (§Authentication and Identity).
24//! The handler does not know when credentials expire; close the
25//! connection then.
26//!
27//! ```
28//! use std::sync::Arc;
29//! use jmap_chat_server::ChatBackend;
30//! use jmap_chat_server::websocket::{ChatEventHub, ChatStreamHandler};
31//! use jmap_types::Id;
32//! use jmap_websocket::server::{Connection, DispatcherHandler};
33//!
34//! /// Called once per accepted connection; `hub` is the server's.
35//! fn wire<B: ChatBackend<CallerCtx = ()>>(
36//!     backend: Arc<B>,
37//!     hub: &ChatEventHub,
38//!     connection: Connection<DispatcherHandler<()>>,
39//! ) -> Connection<DispatcherHandler<()>> {
40//!     let chat = ChatStreamHandler::new(backend, (), [Id::from("acct-owner")], hub);
41//!     connection.with_extension(chat)
42//! }
43//! ```
44
45mod limit;
46
47use std::collections::HashSet;
48use std::fmt;
49use std::sync::{Arc, Mutex, PoisonError};
50use std::time::Duration;
51
52use jmap_chat_types::{ChatPresenceEvent, ChatStreamEnable, ChatTypingEvent, EphemeralMessage};
53use jmap_types::{Id, JmapError};
54use jmap_websocket::server::{ExtensionHandler, ExtensionMessage, ExtensionSender};
55use tokio::sync::broadcast;
56use tokio::task::JoinHandle;
57use tokio::time::Instant;
58
59use crate::ChatBackend;
60use crate::ephemeral::{
61    CompanionStreams, EphemeralSubscription, project_presence, should_deliver_typing,
62};
63use limit::{Limiter, Window, sleep_until};
64
65/// The `@type` of the message that enables ephemeral Chat events.
66const ENABLE: &str = "ChatStreamEnable";
67/// The `@type` of the message that disables them.
68const DISABLE: &str = "ChatStreamDisable";
69
70/// One event published to a [`ChatEventHub`].
71#[derive(Debug, Clone)]
72enum ChatEvent {
73    Typing(ChatTypingEvent),
74    Presence(ChatPresenceEvent),
75}
76
77/// The server-wide source of ephemeral Chat events: the deployment
78/// publishes each event here once, and every connection's
79/// [`ChatStreamHandler`] decides whether its client receives it.
80///
81/// Publish one event per recipient account, with that account as
82/// `accountId`: for typing, the account holding the recipient's Chat
83/// record and `senderId` as the recipient sees it; for presence, the
84/// account holding the recipient's `ChatContact`. A connection takes the
85/// events whose `accountId` is one of its accounts.
86///
87/// The hub keeps the last `capacity` events for connections that fall
88/// behind; a connection that falls further behind skips the events it
89/// missed, which the draft allows for ephemeral events. Clones share the
90/// hub.
91#[derive(Clone)]
92pub struct ChatEventHub {
93    tx: broadcast::Sender<ChatEvent>,
94}
95
96impl fmt::Debug for ChatEventHub {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        f.debug_struct("ChatEventHub")
99            .field("connections", &self.tx.receiver_count())
100            .finish()
101    }
102}
103
104impl ChatEventHub {
105    /// A hub that buffers `capacity` events per slow connection.
106    ///
107    /// # Panics
108    ///
109    /// If `capacity` is 0.
110    pub fn new(capacity: usize) -> Self {
111        let (tx, _) = broadcast::channel(capacity);
112        Self { tx }
113    }
114
115    /// Offer a `ChatTypingEvent` to every connection. With none
116    /// connected it is dropped.
117    pub fn publish_typing(&self, event: ChatTypingEvent) {
118        let _ = self.tx.send(ChatEvent::Typing(event));
119    }
120
121    /// Offer a `ChatPresenceEvent` to every connection. With none
122    /// connected it is dropped.
123    pub fn publish_presence(&self, event: ChatPresenceEvent) {
124        let _ = self.tx.send(ChatEvent::Presence(event));
125    }
126}
127
128/// The outbound rate limits a [`ChatStreamHandler`] applies, per
129/// connection.
130///
131/// The default is the draft's:
132///
133/// - typing: "no more than one `ChatTypingEvent` per sender per chat per
134///   3 seconds SHOULD be delivered; events above this rate MAY be
135///   silently dropped" (draft-atwood-jmap-chat-wss-00 §`ChatTypingEvent`).
136///   Events over the limit are dropped, except `typing: false`, which is
137///   always delivered and does not count against the window, so a client
138///   never misses a stop (decision 66).
139/// - presence: "no more than one `ChatPresenceEvent` per contact per 30
140///   seconds SHOULD be delivered; events above this rate MAY be silently
141///   dropped, but the most recent presence state SHOULD be delivered when
142///   the rate window reopens" (§`ChatPresenceEvent`). The latest event over
143///   the limit is held and sent when the window reopens, after the
144///   delivery checks run again.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct ChatStreamLimits {
147    typing: Option<Duration>,
148    presence: Option<Duration>,
149}
150
151impl Default for ChatStreamLimits {
152    fn default() -> Self {
153        Self {
154            typing: Some(Duration::from_secs(3)),
155            presence: Some(Duration::from_secs(30)),
156        }
157    }
158}
159
160impl ChatStreamLimits {
161    /// The typing window: at most one event per sender per Chat in it;
162    /// `None` for no limit.
163    pub fn typing_window(mut self, window: Option<Duration>) -> Self {
164        self.typing = window;
165        self
166    }
167
168    /// The presence window: at most one event per contact in it, the
169    /// latest one over the limit sent when it reopens; `None` for no
170    /// limit.
171    pub fn presence_window(mut self, window: Option<Duration>) -> Self {
172        self.presence = window;
173        self
174    }
175
176    /// The typing window.
177    pub fn typing_window_value(&self) -> Option<Duration> {
178        self.typing
179    }
180
181    /// The presence window.
182    pub fn presence_window_value(&self) -> Option<Duration> {
183        self.presence
184    }
185}
186
187/// Called with the connection's subscription after it changes.
188type Observer = Box<dyn FnMut(&EphemeralSubscription) + Send>;
189
190/// What the forwarding task needs.
191struct Shared<B: ChatBackend> {
192    backend: Arc<B>,
193    caller: B::CallerCtx,
194    accounts: HashSet<Id>,
195    subscription: Mutex<EphemeralSubscription>,
196}
197
198impl<B: ChatBackend> Shared<B> {
199    fn subscription(&self) -> EphemeralSubscription {
200        self.subscription
201            .lock()
202            .unwrap_or_else(PoisonError::into_inner)
203            .clone()
204    }
205
206    /// Whether this connection receives `event` now. A backend error
207    /// drops it.
208    async fn typing(&self, event: &ChatTypingEvent) -> bool {
209        let covered = self
210            .subscription()
211            .typing()
212            .is_some_and(|scope| scope.covers(&event.chat_id));
213        covered
214            && self.accounts.contains(&event.account_id)
215            && should_deliver_typing(&*self.backend, &self.caller, &event.account_id, event)
216                .await
217                .unwrap_or(false)
218    }
219
220    /// The frame this connection receives for `event` now, if any. A
221    /// backend error drops it.
222    async fn presence(&self, event: &ChatPresenceEvent) -> Option<ChatPresenceEvent> {
223        let covered = self
224            .subscription()
225            .presence()
226            .is_some_and(|scope| scope.covers(&event.contact_id));
227        if !covered || !self.accounts.contains(&event.account_id) {
228            return None;
229        }
230        project_presence(&*self.backend, &self.caller, &event.account_id, event)
231            .await
232            .ok()
233            .flatten()
234    }
235}
236
237/// The `ChatStreamEnable` / `ChatStreamDisable` handler of one WebSocket
238/// connection; see the [module docs](self).
239///
240/// - `ChatStreamEnable` replaces the subscription through
241///   [`EphemeralSubscription::replace_with`] with the
242///   [`CompanionStreams`] given to
243///   [`with_companions`](Self::with_companions). Its error becomes the
244///   `RequestError` (`invalidArguments`, with the message's `id` as
245///   `requestId`) and leaves the subscription unchanged. A malformed
246///   message is `notRequest`.
247/// - `ChatStreamDisable` clears it, silently, whether or not one was
248///   active.
249/// - Closing the connection clears it and stops delivery.
250///
251/// The companion values `"vtc"` and `"scene"` only switch the companion
252/// handler's alias on: register
253/// [`on_subscription_change`](Self::on_subscription_change) observers for
254/// them (`jmap-chat-vtc-server` and `jmap-chat-scene-server` do).
255pub struct ChatStreamHandler<B: ChatBackend> {
256    shared: Arc<Shared<B>>,
257    hub: ChatEventHub,
258    companions: CompanionStreams,
259    limits: ChatStreamLimits,
260    observers: Vec<Observer>,
261    task: Option<JoinHandle<()>>,
262}
263
264impl<B: ChatBackend> fmt::Debug for ChatStreamHandler<B> {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        f.debug_struct("ChatStreamHandler")
267            .field("accounts", &self.shared.accounts)
268            .field("subscription", &self.shared.subscription())
269            .field("companions", &self.companions)
270            .field("limits", &self.limits)
271            .finish_non_exhaustive()
272    }
273}
274
275impl<B: ChatBackend> ChatStreamHandler<B> {
276    /// The handler of a connection authenticated as `caller`, receiving
277    /// the events of `accounts` (the accounts whose Chats and
278    /// `ChatContact`s the owner sees, usually the owner's own) from `hub`.
279    ///
280    /// No companion value is recognized and the default
281    /// [`ChatStreamLimits`] apply.
282    pub fn new(
283        backend: Arc<B>,
284        caller: B::CallerCtx,
285        accounts: impl IntoIterator<Item = Id>,
286        hub: &ChatEventHub,
287    ) -> Self {
288        Self {
289            shared: Arc::new(Shared {
290                backend,
291                caller,
292                accounts: accounts.into_iter().collect(),
293                subscription: Mutex::new(EphemeralSubscription::default()),
294            }),
295            hub: hub.clone(),
296            companions: CompanionStreams::default(),
297            limits: ChatStreamLimits::default(),
298            observers: Vec::new(),
299            task: None,
300        }
301    }
302
303    /// The companion WebSocket capabilities the server advertises, which
304    /// decide whether `"vtc"` and `"scene"` in `dataTypes` are recognized.
305    pub fn with_companions(mut self, companions: CompanionStreams) -> Self {
306        self.companions = companions;
307        self
308    }
309
310    /// The companion capabilities in effect.
311    pub fn companions(&self) -> CompanionStreams {
312        self.companions
313    }
314
315    /// Replace the outbound rate limits.
316    pub fn with_limits(mut self, limits: ChatStreamLimits) -> Self {
317        self.limits = limits;
318        self
319    }
320
321    /// Call `observer` with the subscription each time it changes: after
322    /// a successful `ChatStreamEnable`, after `ChatStreamDisable`, and
323    /// with the empty subscription when the connection closes. Observers
324    /// run in the order added, before the next client message is read.
325    pub fn on_subscription_change(
326        mut self,
327        observer: impl FnMut(&EphemeralSubscription) + Send + 'static,
328    ) -> Self {
329        self.observers.push(Box::new(observer));
330        self
331    }
332
333    /// The connection's current subscription.
334    pub fn subscription(&self) -> EphemeralSubscription {
335        self.shared.subscription()
336    }
337
338    /// Replace the subscription and tell the observers.
339    fn set(&mut self, subscription: EphemeralSubscription) {
340        *self
341            .shared
342            .subscription
343            .lock()
344            .unwrap_or_else(PoisonError::into_inner) = subscription.clone();
345        for observer in &mut self.observers {
346            observer(&subscription);
347        }
348    }
349
350    fn enable(&mut self, message: &ExtensionMessage) -> Result<(), JmapError> {
351        let enable: ChatStreamEnable = message.deserialize()?;
352        let mut next = self.subscription();
353        next.replace_with(&enable, self.companions)?;
354        self.set(next);
355        Ok(())
356    }
357}
358
359impl<B: ChatBackend> ExtensionHandler for ChatStreamHandler<B> {
360    fn message_types(&self) -> &[&str] {
361        &[ENABLE, DISABLE]
362    }
363
364    fn start(&mut self, events: ExtensionSender) {
365        let rx = self.hub.tx.subscribe();
366        self.task = Some(tokio::spawn(forward(
367            Arc::clone(&self.shared),
368            self.limits,
369            rx,
370            events,
371        )));
372    }
373
374    async fn handle(&mut self, message: ExtensionMessage) -> Result<(), JmapError> {
375        if message.message_type == ENABLE {
376            self.enable(&message)
377        } else {
378            self.set(EphemeralSubscription::default());
379            Ok(())
380        }
381    }
382
383    async fn close(&mut self) {
384        if let Some(task) = self.task.take() {
385            task.abort();
386        }
387        self.set(EphemeralSubscription::default());
388    }
389}
390
391impl<B: ChatBackend> Drop for ChatStreamHandler<B> {
392    fn drop(&mut self) {
393        if let Some(task) = self.task.take() {
394            task.abort();
395        }
396    }
397}
398
399/// Typing limiter key: (accountId, chatId, senderId).
400type TypingKey = (Id, Id, Id);
401/// Presence limiter key: (accountId, contactId).
402type PresenceKey = (Id, Id);
403
404/// Delivers the hub's events to one connection until it closes.
405async fn forward<B: ChatBackend>(
406    shared: Arc<Shared<B>>,
407    limits: ChatStreamLimits,
408    mut rx: broadcast::Receiver<ChatEvent>,
409    events: ExtensionSender,
410) {
411    let window = |per, keep_latest| {
412        Some(Window {
413            max: 1,
414            per,
415            keep_latest,
416        })
417    };
418    let mut typing: Limiter<TypingKey, ()> =
419        Limiter::new(limits.typing.and_then(|p| window(p, false)));
420    let mut presence: Limiter<PresenceKey, ChatPresenceEvent> =
421        Limiter::new(limits.presence.and_then(|p| window(p, true)));
422    loop {
423        tokio::select! {
424            () = events.closed() => return,
425            () = sleep_until(presence.next_due()) => {
426                for (_, held) in presence.take_due(Instant::now()) {
427                    if let Some(frame) = shared.presence(&held).await {
428                        send(&events, EphemeralMessage::Presence(frame));
429                    }
430                }
431            }
432            received = rx.recv() => match received {
433                Ok(ChatEvent::Typing(event)) => {
434                    if shared.typing(&event).await {
435                        let key = (
436                            event.account_id.clone(),
437                            event.chat_id.clone(),
438                            event.sender_id.clone(),
439                        );
440                        // decision 66: a `typing: false` is always delivered
441                        // and does not count against the window.
442                        if !event.typing || typing.offer(key, (), Instant::now()).is_some() {
443                            send(&events, EphemeralMessage::Typing(event));
444                        }
445                    }
446                }
447                Ok(ChatEvent::Presence(event)) => {
448                    if let Some(frame) = shared.presence(&event).await {
449                        let key = (event.account_id.clone(), event.contact_id.clone());
450                        if presence.offer(key, event, Instant::now()).is_some() {
451                            send(&events, EphemeralMessage::Presence(frame));
452                        }
453                    }
454                }
455                Err(broadcast::error::RecvError::Lagged(_)) => {}
456                Err(broadcast::error::RecvError::Closed) => return,
457            },
458        }
459    }
460}
461
462/// Queues `frame`, dropping it if the client is too slow.
463fn send(events: &ExtensionSender, frame: EphemeralMessage) {
464    let _ = events.try_send(&frame);
465}
466
467#[cfg(all(test, feature = "memory"))]
468mod tests {
469    use super::*;
470    use crate::ephemeral::IdScope;
471    use crate::memory::MemoryBackend;
472    use serde_json::{Value, json};
473
474    fn handler() -> ChatStreamHandler<MemoryBackend<()>> {
475        let hub = ChatEventHub::new(8);
476        ChatStreamHandler::new(
477            Arc::new(MemoryBackend::default()),
478            (),
479            [Id::from("a1")],
480            &hub,
481        )
482    }
483
484    fn message(ty: &str, body: Value) -> ExtensionMessage {
485        let Value::Object(body) = body else {
486            panic!("object")
487        };
488        ExtensionMessage::new(ty, body)
489    }
490
491    #[test]
492    fn registers_the_two_control_messages() {
493        assert_eq!(
494            handler().message_types(),
495            ["ChatStreamEnable", "ChatStreamDisable"]
496        );
497    }
498
499    /// §ChatStreamEnable: the subscription replaces the previous one in
500    /// its entirety; ChatStreamDisable clears it.
501    #[tokio::test]
502    async fn enable_replaces_and_disable_clears() {
503        let mut h = handler();
504        h.handle(message(
505            ENABLE,
506            json!({"dataTypes": ["typing"], "chatIds": ["c1"]}),
507        ))
508        .await
509        .unwrap();
510        assert_eq!(
511            h.subscription().typing(),
512            Some(&IdScope::Only(vec![Id::from("c1")]))
513        );
514        h.handle(message(ENABLE, json!({"dataTypes": ["presence"]})))
515            .await
516            .unwrap();
517        assert_eq!(h.subscription().typing(), None);
518        assert_eq!(h.subscription().presence(), Some(&IdScope::All));
519        h.handle(message(DISABLE, json!({}))).await.unwrap();
520        assert_eq!(h.subscription(), EphemeralSubscription::default());
521        // Silently succeeds with nothing active.
522        h.handle(message(DISABLE, json!({}))).await.unwrap();
523    }
524
525    /// §ChatStreamEnable: only unrecognized dataTypes is invalidArguments
526    /// and MUST NOT update the subscription; "vtc" is unrecognized unless
527    /// the companion capability is advertised.
528    #[tokio::test]
529    async fn unrecognized_data_types_leave_the_subscription_alone() {
530        let mut h = handler();
531        h.handle(message(ENABLE, json!({"dataTypes": ["typing"]})))
532            .await
533            .unwrap();
534        let err = h
535            .handle(message(ENABLE, json!({"id": "e1", "dataTypes": ["vtc"]})))
536            .await
537            .unwrap_err();
538        assert_eq!(err.error_type.as_str(), "invalidArguments");
539        assert_eq!(h.subscription().typing(), Some(&IdScope::All));
540    }
541
542    #[tokio::test]
543    async fn a_malformed_enable_is_not_request() {
544        let mut h = handler();
545        let err = h
546            .handle(message(ENABLE, json!({"dataTypes": "typing"})))
547            .await
548            .unwrap_err();
549        assert_eq!(err.error_type.as_str(), "notRequest");
550    }
551
552    #[tokio::test]
553    async fn observers_see_every_change_and_the_close() {
554        let seen = Arc::new(Mutex::new(Vec::new()));
555        let log = Arc::clone(&seen);
556        let mut h = handler()
557            .with_companions(CompanionStreams {
558                vtc: true,
559                ..CompanionStreams::default()
560            })
561            .on_subscription_change(move |s| log.lock().unwrap().push(s.vtc()));
562        h.handle(message(ENABLE, json!({"dataTypes": ["vtc"]})))
563            .await
564            .unwrap();
565        // A failed enable does not notify.
566        let _ = h.handle(message(ENABLE, json!({"dataTypes": []}))).await;
567        h.handle(message(DISABLE, json!({}))).await.unwrap();
568        h.handle(message(ENABLE, json!({"dataTypes": ["vtc"]})))
569            .await
570            .unwrap();
571        h.close().await;
572        assert_eq!(*seen.lock().unwrap(), [true, false, true, false]);
573    }
574
575    #[test]
576    fn default_limits_are_the_drafts() {
577        let l = ChatStreamLimits::default();
578        assert_eq!(l.typing_window_value(), Some(Duration::from_secs(3)));
579        assert_eq!(l.presence_window_value(), Some(Duration::from_secs(30)));
580        let l = l.typing_window(None);
581        assert_eq!(l.typing_window_value(), None);
582    }
583}