jmap_chat_server/ephemeral.rs
1//! Ephemeral-stream subscription state (draft-atwood-jmap-chat-wss-00
2//! §ChatStreamEnable).
3//!
4//! A WebSocket transport keeps one [`EphemeralSubscription`] per
5//! connection, starting from [`EphemeralSubscription::default`] (nothing
6//! subscribed). Each `ChatStreamEnable` frame goes through
7//! [`EphemeralSubscription::replace_with`], which validates the frame
8//! against the server's [`CompanionStreams`], normalizes it, and replaces
9//! the whole subscription. A `ChatStreamDisable` frame resets it to the
10//! default.
11//!
12//! Before sending a `ChatTypingEvent` to an owner's connections, the
13//! transport asks [`should_deliver_typing`] whether that owner may receive
14//! it. Before sending a `ChatPresenceEvent`, it asks [`project_presence`]
15//! for the frame that owner may see, if any.
16//!
17//! # Rate limits are the deployment's job
18//!
19//! This crate does not rate-limit ephemeral events, and neither predicate
20//! counts or times anything. The draft gives the outbound limits as SHOULD
21//! rules, and the transport or deployment applies them:
22//!
23//! - Typing: "no more than one `ChatTypingEvent` per sender per chat per 3
24//! seconds SHOULD be delivered; events above this rate MAY be silently
25//! dropped" (draft-atwood-jmap-chat-wss-00 §ChatTypingEvent, L251).
26//! - Presence: "no more than one `ChatPresenceEvent` per contact per 30
27//! seconds SHOULD be delivered; events above this rate MAY be silently
28//! dropped, but the most recent presence state SHOULD be delivered when
29//! the rate window reopens" (draft-atwood-jmap-chat-wss-00
30//! §ChatPresenceEvent, L298). A presence limiter therefore keeps the
31//! latest dropped event per contact and sends it, after passing it
32//! through [`project_presence`] again, when that contact's 30-second
33//! window reopens, so the recipient is not left with stale presence.
34//!
35//! # Credential expiry stops ephemeral delivery
36//!
37//! "A server that does not close the connection when credentials expire
38//! SHOULD NOT deliver further ephemeral events on that connection"
39//! (draft-atwood-jmap-chat-wss-00 §Authentication and Identity, L131).
40//! Neither predicate knows about credentials, so the transport checks
41//! expiry itself and sends no typing or presence frame on an expired
42//! connection.
43
44use jmap_chat_types::{
45 Chat, ChatKind, ChatPresenceEvent, ChatStreamEnable, ChatTypingEvent, Presence,
46};
47use jmap_types::{Id, JmapError};
48
49use crate::ChatBackend;
50use crate::push::owner_is_member;
51
52/// Which ids a subscribed data type covers.
53#[non_exhaustive]
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub enum IdScope {
56 /// Every id: the frame sent `null` or left the field out.
57 All,
58 /// Only the listed ids, in the order the frame sent them.
59 Only(Vec<Id>),
60}
61
62impl From<Option<&Vec<Id>>> for IdScope {
63 /// `None` (absent or JSON `null`) maps to [`IdScope::All`]: "An absent
64 /// `chatIds` or `contactIds` is equivalent to `null`"
65 /// (draft-atwood-jmap-chat-wss-00 §ChatStreamEnable).
66 fn from(ids: Option<&Vec<Id>>) -> Self {
67 ids.map_or(Self::All, |ids| Self::Only(ids.clone()))
68 }
69}
70
71/// The companion WebSocket capabilities the server advertises, which
72/// decide whether the companion `dataTypes` values `"vtc"` and `"scene"`
73/// are recognized in a `ChatStreamEnable` frame.
74///
75/// The default advertises neither. Per draft-atwood-jmap-chat-wss-00
76/// §Enabling Ephemeral Push (L175), `"vtc"` is "recognized only when the
77/// server advertises `urn:ietf:params:jmap:vtc:websocket`", and `"scene"`
78/// "only when the server advertises `urn:ietf:params:jmap:scene:websocket`".
79#[non_exhaustive]
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81pub struct CompanionStreams {
82 /// The server advertises `urn:ietf:params:jmap:vtc:websocket`.
83 pub vtc: bool,
84 /// The server advertises `urn:ietf:params:jmap:scene:websocket`.
85 pub scene: bool,
86}
87
88/// The ephemeral subscription of one WebSocket connection, normalized
89/// from a `ChatStreamEnable` frame.
90///
91/// The default value subscribes to nothing, which is the state before the
92/// first `ChatStreamEnable` and after a `ChatStreamDisable`.
93#[derive(Debug, Clone, PartialEq, Eq, Default)]
94pub struct EphemeralSubscription {
95 typing: Option<IdScope>,
96 presence: Option<IdScope>,
97 vtc: bool,
98 scene: bool,
99}
100
101impl EphemeralSubscription {
102 /// Validates and normalizes a `ChatStreamEnable` frame.
103 ///
104 /// `"typing"` and `"presence"` in `dataTypes` always take effect.
105 /// `"vtc"` and `"scene"` take effect only when `companions` says the
106 /// server advertises their capability; otherwise they are unrecognized
107 /// (draft-atwood-jmap-chat-wss-00 §Enabling Ephemeral Push, L196: the
108 /// value "is treated as unrecognized and silently ignored"). Other
109 /// values are ignored. `chatIds` applies only when `"typing"` is
110 /// present and `contactIds` only when `"presence"` is present.
111 ///
112 /// # Errors
113 ///
114 /// Returns an `invalidArguments` [`JmapError`] when `dataTypes` holds
115 /// no recognized value: "none of `"typing"`, `"presence"`, or a
116 /// companion value whose capability the server advertises"
117 /// (draft-atwood-jmap-chat-wss-00 §Enabling Ephemeral Push, L194). The
118 /// transport sends it to the client as an RFC 8887 §4.3.4
119 /// `RequestError` frame whose `type` is the full URN
120 /// `"urn:ietf:params:jmap:error:invalidArguments"`; the returned
121 /// [`JmapError`] carries the short method-level name. When `enable.id`
122 /// is set, the transport MUST put it in the frame's `requestId`: "A
123 /// `RequestError` caused by this message carries this value as its
124 /// `requestId`" (draft-atwood-jmap-chat-wss-00 §ChatStreamEnable, L186).
125 pub fn from_enable(
126 enable: &ChatStreamEnable,
127 companions: CompanionStreams,
128 ) -> Result<Self, JmapError> {
129 let has = |tag: &str| enable.data_types.iter().any(|t| t.as_str() == tag);
130 let subscription = Self {
131 typing: has("typing").then(|| IdScope::from(enable.chat_ids.as_ref())),
132 presence: has("presence").then(|| IdScope::from(enable.contact_ids.as_ref())),
133 vtc: companions.vtc && has("vtc"),
134 scene: companions.scene && has("scene"),
135 };
136 if subscription == Self::default() {
137 return Err(JmapError::invalid_arguments(
138 "dataTypes must contain \"typing\", \"presence\" or an advertised companion value",
139 ));
140 }
141 Ok(subscription)
142 }
143
144 /// Replaces this subscription with the one in `enable`.
145 ///
146 /// The new frame replaces the old subscription in full; nothing is
147 /// merged from it (draft-atwood-jmap-chat-wss-00 §ChatStreamEnable).
148 ///
149 /// # Errors
150 ///
151 /// Returns the same error as [`Self::from_enable`], which the transport
152 /// sends as a `RequestError` whose `requestId` is `enable.id`. On error
153 /// `self` is unchanged, as the draft requires.
154 pub fn replace_with(
155 &mut self,
156 enable: &ChatStreamEnable,
157 companions: CompanionStreams,
158 ) -> Result<(), JmapError> {
159 *self = Self::from_enable(enable, companions)?;
160 Ok(())
161 }
162
163 /// The Chats covered for typing events, or `None` when typing is not
164 /// subscribed. [`IdScope::All`] means every Chat of which the owner is
165 /// a current member.
166 pub fn typing(&self) -> Option<&IdScope> {
167 self.typing.as_ref()
168 }
169
170 /// The ChatContacts covered for presence events, or `None` when
171 /// presence is not subscribed. [`IdScope::All`] means every known
172 /// ChatContact.
173 pub fn presence(&self) -> Option<&IdScope> {
174 self.presence.as_ref()
175 }
176
177 /// Whether `"vtc"` is subscribed: it was in `dataTypes` and the server
178 /// advertises `urn:ietf:params:jmap:vtc:websocket`. This is the
179 /// `chat_vtc` flag that `jmap-chat-vtc-server` takes.
180 pub fn vtc(&self) -> bool {
181 self.vtc
182 }
183
184 /// Whether `"scene"` is subscribed: it was in `dataTypes` and the
185 /// server advertises `urn:ietf:params:jmap:scene:websocket`. This is
186 /// the `chat_scene` flag that `jmap-chat-scene-server` takes.
187 pub fn scene(&self) -> bool {
188 self.scene
189 }
190}
191
192/// Whether `event` may be delivered to the owner of `account_id`.
193///
194/// `account_id` is the recipient. `event.chat_id` names the recipient's
195/// Chat record, and `event.sender_id` is the typing user as the recipient
196/// sees it: a ChatContact id on the recipient's contact list. The
197/// transport calls this once per recipient, at delivery time, and sends
198/// the event to none of the recipient's connections when it returns
199/// `false`. The sender is never told. The connection's `chatIds` scope
200/// ([`EphemeralSubscription::typing`]) is a separate filter, checked by
201/// the transport on its own.
202///
203/// Delivery is allowed only when all of these hold:
204///
205/// - `event.account_id` is `account_id` (draft-atwood-jmap-chat-wss-00
206/// §ChatTypingEvent: `accountId` is "The id of the account that
207/// contains the Chat").
208/// - The sender is not the recipient (draft-atwood-jmap-chat-00
209/// §Chat/typing: delivery goes to "each local participant in the Chat
210/// other than the requesting account").
211/// - The Chat exists in the recipient's account and the recipient is
212/// still a member of it (draft-atwood-jmap-chat-wss-00
213/// §ChatTypingEvent, L255: "Servers SHOULD verify at delivery time that
214/// the owner remains a current member of the identified Chat").
215/// - For a direct or group Chat, its `receiveTypingIndicators` is `true`.
216/// Other kinds ignore it.
217/// - The sender's ChatContact is not blocked on the recipient's contact
218/// list, per [`ChatBackend::is_contact_blocked`].
219///
220/// # Errors
221///
222/// Returns the backend's error if reading the Chat, its Space or the
223/// sender's blocked status fails.
224pub async fn should_deliver_typing<B: ChatBackend>(
225 backend: &B,
226 caller: &B::CallerCtx,
227 account_id: &Id,
228 event: &ChatTypingEvent,
229) -> Result<bool, B::Error> {
230 if event.account_id != *account_id || event.sender_id == *account_id {
231 return Ok(false);
232 }
233 let (chats, _) = backend
234 .get_objects::<Chat>(
235 caller,
236 account_id,
237 Some(std::slice::from_ref(&event.chat_id)),
238 None,
239 )
240 .await?;
241 let Some(chat) = chats.into_iter().next() else {
242 return Ok(false);
243 };
244 if !owner_is_member(backend, caller, account_id, &chat).await? {
245 return Ok(false);
246 }
247 if matches!(chat.kind, ChatKind::Direct | ChatKind::Group) && !chat.receive_typing_indicators {
248 return Ok(false);
249 }
250 Ok(!backend
251 .is_contact_blocked(caller, account_id, &event.sender_id)
252 .await?)
253}
254
255/// The `ChatPresenceEvent` the owner of `account_id` may receive for
256/// `event`, or `None` if it must be dropped.
257///
258/// `account_id` is the recipient and `event.contact_id` is the contact
259/// whose presence changed, as a ChatContact id on the recipient's contact
260/// list. The transport calls this once per recipient, at delivery time,
261/// and sends the returned frame, or nothing, to that owner's connections.
262/// The contact is never told. The connection's `contactIds` scope
263/// ([`EphemeralSubscription::presence`]) is a separate filter, checked by
264/// the transport on its own.
265///
266/// - If `event.account_id` is not `account_id`, the result is `None`
267/// (same section: `accountId` is "The id of the account that contains
268/// the ChatContact").
269/// - If the contact is blocked on the recipient's contact list, per
270/// [`ChatBackend::is_contact_blocked`], the result is `None`
271/// (draft-atwood-jmap-chat-wss-00 §ChatPresenceEvent, L300: "a
272/// `ChatPresenceEvent` is not delivered for a contact whose `blocked`
273/// field is `true` on the owner's ChatContact record for that contact").
274/// - Otherwise the result is `event` with an `"invisible"` presence
275/// replaced by `"offline"` (same section, L275: "`"invisible"` is not a
276/// value of this field. The server reports a contact whose presence is
277/// `"invisible"` ... as `"offline"`"). Every other field is unchanged.
278///
279/// # Errors
280///
281/// Returns the backend's error if reading the contact's blocked status
282/// fails.
283pub async fn project_presence<B: ChatBackend>(
284 backend: &B,
285 caller: &B::CallerCtx,
286 account_id: &Id,
287 event: &ChatPresenceEvent,
288) -> Result<Option<ChatPresenceEvent>, B::Error> {
289 if event.account_id != *account_id {
290 return Ok(None);
291 }
292 if backend
293 .is_contact_blocked(caller, account_id, &event.contact_id)
294 .await?
295 {
296 return Ok(None);
297 }
298 let mut projected = event.clone();
299 if projected.presence == Presence::Invisible {
300 projected.presence = Presence::Offline;
301 }
302 Ok(Some(projected))
303}