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 IdScope {
63 /// Whether `id` is in scope: always for [`IdScope::All`], otherwise
64 /// when it is listed.
65 pub fn covers(&self, id: &Id) -> bool {
66 match self {
67 Self::All => true,
68 Self::Only(ids) => ids.contains(id),
69 }
70 }
71}
72
73impl From<Option<&Vec<Id>>> for IdScope {
74 /// `None` (absent or JSON `null`) maps to [`IdScope::All`]: "An absent
75 /// `chatIds` or `contactIds` is equivalent to `null`"
76 /// (draft-atwood-jmap-chat-wss-00 §`ChatStreamEnable`).
77 fn from(ids: Option<&Vec<Id>>) -> Self {
78 ids.map_or(Self::All, |ids| Self::Only(ids.clone()))
79 }
80}
81
82/// The companion WebSocket capabilities the server advertises, which
83/// decide whether the companion `dataTypes` values `"vtc"` and `"scene"`
84/// are recognized in a `ChatStreamEnable` frame.
85///
86/// The default advertises neither. Per draft-atwood-jmap-chat-wss-00
87/// §Enabling Ephemeral Push (L175), `"vtc"` is "recognized only when the
88/// server advertises `urn:ietf:params:jmap:vtc:websocket`", and `"scene"`
89/// "only when the server advertises `urn:ietf:params:jmap:scene:websocket`".
90#[non_exhaustive]
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
92pub struct CompanionStreams {
93 /// The server advertises `urn:ietf:params:jmap:vtc:websocket`.
94 pub vtc: bool,
95 /// The server advertises `urn:ietf:params:jmap:scene:websocket`.
96 pub scene: bool,
97}
98
99/// The ephemeral subscription of one WebSocket connection, normalized
100/// from a `ChatStreamEnable` frame.
101///
102/// The default value subscribes to nothing, which is the state before the
103/// first `ChatStreamEnable` and after a `ChatStreamDisable`.
104#[derive(Debug, Clone, PartialEq, Eq, Default)]
105pub struct EphemeralSubscription {
106 typing: Option<IdScope>,
107 presence: Option<IdScope>,
108 vtc: bool,
109 scene: bool,
110}
111
112impl EphemeralSubscription {
113 /// Validates and normalizes a `ChatStreamEnable` frame.
114 ///
115 /// `"typing"` and `"presence"` in `dataTypes` always take effect.
116 /// `"vtc"` and `"scene"` take effect only when `companions` says the
117 /// server advertises their capability; otherwise they are unrecognized
118 /// (draft-atwood-jmap-chat-wss-00 §Enabling Ephemeral Push, L196: the
119 /// value "is treated as unrecognized and silently ignored"). Other
120 /// values are ignored. `chatIds` applies only when `"typing"` is
121 /// present and `contactIds` only when `"presence"` is present.
122 ///
123 /// # Errors
124 ///
125 /// Returns an `invalidArguments` [`JmapError`] when `dataTypes` holds
126 /// no recognized value: "none of `"typing"`, `"presence"`, or a
127 /// companion value whose capability the server advertises"
128 /// (draft-atwood-jmap-chat-wss-00 §Enabling Ephemeral Push, L194). The
129 /// transport sends it to the client as an RFC 8887 §4.3.4
130 /// `RequestError` frame whose `type` is the full URN
131 /// `"urn:ietf:params:jmap:error:invalidArguments"`; the returned
132 /// [`JmapError`] carries the short method-level name. When `enable.id`
133 /// is set, the transport MUST put it in the frame's `requestId`: "A
134 /// `RequestError` caused by this message carries this value as its
135 /// `requestId`" (draft-atwood-jmap-chat-wss-00 §`ChatStreamEnable`, L186).
136 pub fn from_enable(
137 enable: &ChatStreamEnable,
138 companions: CompanionStreams,
139 ) -> Result<Self, JmapError> {
140 let has = |tag: &str| enable.data_types.iter().any(|t| t.as_str() == tag);
141 let subscription = Self {
142 typing: has("typing").then(|| IdScope::from(enable.chat_ids.as_ref())),
143 presence: has("presence").then(|| IdScope::from(enable.contact_ids.as_ref())),
144 vtc: companions.vtc && has("vtc"),
145 scene: companions.scene && has("scene"),
146 };
147 if subscription == Self::default() {
148 return Err(JmapError::invalid_arguments(
149 "dataTypes must contain \"typing\", \"presence\" or an advertised companion value",
150 ));
151 }
152 Ok(subscription)
153 }
154
155 /// Replaces this subscription with the one in `enable`.
156 ///
157 /// The new frame replaces the old subscription in full; nothing is
158 /// merged from it (draft-atwood-jmap-chat-wss-00 §`ChatStreamEnable`).
159 ///
160 /// # Errors
161 ///
162 /// Returns the same error as [`Self::from_enable`], which the transport
163 /// sends as a `RequestError` whose `requestId` is `enable.id`. On error
164 /// `self` is unchanged, as the draft requires.
165 pub fn replace_with(
166 &mut self,
167 enable: &ChatStreamEnable,
168 companions: CompanionStreams,
169 ) -> Result<(), JmapError> {
170 *self = Self::from_enable(enable, companions)?;
171 Ok(())
172 }
173
174 /// The Chats covered for typing events, or `None` when typing is not
175 /// subscribed. [`IdScope::All`] means every Chat of which the owner is
176 /// a current member.
177 pub fn typing(&self) -> Option<&IdScope> {
178 self.typing.as_ref()
179 }
180
181 /// The `ChatContact`s covered for presence events, or `None` when
182 /// presence is not subscribed. [`IdScope::All`] means every known
183 /// `ChatContact`.
184 pub fn presence(&self) -> Option<&IdScope> {
185 self.presence.as_ref()
186 }
187
188 /// Whether `"vtc"` is subscribed: it was in `dataTypes` and the server
189 /// advertises `urn:ietf:params:jmap:vtc:websocket`. This is the
190 /// `chat_vtc` flag that `jmap-chat-vtc-server` takes.
191 pub fn vtc(&self) -> bool {
192 self.vtc
193 }
194
195 /// Whether `"scene"` is subscribed: it was in `dataTypes` and the
196 /// server advertises `urn:ietf:params:jmap:scene:websocket`. This is
197 /// the `chat_scene` flag that `jmap-chat-scene-server` takes.
198 pub fn scene(&self) -> bool {
199 self.scene
200 }
201}
202
203/// Whether `event` may be delivered to the owner of `account_id`.
204///
205/// `account_id` is the recipient. `event.chat_id` names the recipient's
206/// Chat record, and `event.sender_id` is the typing user as the recipient
207/// sees it: a `ChatContact` id on the recipient's contact list. The
208/// transport calls this once per recipient, at delivery time, and sends
209/// the event to none of the recipient's connections when it returns
210/// `false`. The sender is never told. The connection's `chatIds` scope
211/// ([`EphemeralSubscription::typing`]) is a separate filter, checked by
212/// the transport on its own.
213///
214/// Delivery is allowed only when all of these hold:
215///
216/// - `event.account_id` is `account_id` (draft-atwood-jmap-chat-wss-00
217/// §`ChatTypingEvent`: `accountId` is "The id of the account that
218/// contains the Chat").
219/// - The sender is not the recipient (draft-atwood-jmap-chat-00
220/// §Chat/typing: delivery goes to "each local participant in the Chat
221/// other than the requesting account").
222/// - The Chat exists in the recipient's account and the recipient is
223/// still a member of it (draft-atwood-jmap-chat-wss-00
224/// §`ChatTypingEvent`, L255: "Servers SHOULD verify at delivery time that
225/// the owner remains a current member of the identified Chat").
226/// - For a direct or group Chat, its `receiveTypingIndicators` is `true`.
227/// Other kinds ignore it.
228/// - The sender's `ChatContact` is not blocked on the recipient's contact
229/// list, per [`ChatAccessPolicy::is_contact_blocked`](crate::ChatAccessPolicy::is_contact_blocked).
230///
231/// # Errors
232///
233/// Returns the backend's error if reading the Chat, its Space or the
234/// sender's blocked status fails.
235pub async fn should_deliver_typing<B: ChatBackend>(
236 backend: &B,
237 caller: &B::CallerCtx,
238 account_id: &Id,
239 event: &ChatTypingEvent,
240) -> Result<bool, B::Error> {
241 if event.account_id != *account_id || event.sender_id == *account_id {
242 return Ok(false);
243 }
244 let (chats, _) = backend
245 .get_objects::<Chat>(
246 caller,
247 account_id,
248 Some(std::slice::from_ref(&event.chat_id)),
249 None,
250 )
251 .await?;
252 let Some(chat) = chats.into_iter().next() else {
253 return Ok(false);
254 };
255 if !owner_is_member(backend, caller, account_id, &chat).await? {
256 return Ok(false);
257 }
258 if matches!(chat.kind, ChatKind::Direct | ChatKind::Group) && !chat.receive_typing_indicators {
259 return Ok(false);
260 }
261 Ok(!backend
262 .is_contact_blocked(caller, account_id, &event.sender_id)
263 .await?)
264}
265
266/// The `ChatPresenceEvent` the owner of `account_id` may receive for
267/// `event`, or `None` if it must be dropped.
268///
269/// `account_id` is the recipient and `event.contact_id` is the contact
270/// whose presence changed, as a `ChatContact` id on the recipient's contact
271/// list. The transport calls this once per recipient, at delivery time,
272/// and sends the returned frame, or nothing, to that owner's connections.
273/// The contact is never told. The connection's `contactIds` scope
274/// ([`EphemeralSubscription::presence`]) is a separate filter, checked by
275/// the transport on its own.
276///
277/// - If `event.account_id` is not `account_id`, the result is `None`
278/// (same section: `accountId` is "The id of the account that contains
279/// the `ChatContact`").
280/// - If the contact is blocked on the recipient's contact list, per
281/// [`ChatAccessPolicy::is_contact_blocked`](crate::ChatAccessPolicy::is_contact_blocked), the result is `None`
282/// (draft-atwood-jmap-chat-wss-00 §`ChatPresenceEvent`, L300: "a
283/// `ChatPresenceEvent` is not delivered for a contact whose `blocked`
284/// field is `true` on the owner's `ChatContact` record for that contact").
285/// - Otherwise the result is `event` with an `"invisible"` presence
286/// replaced by `"offline"` (same section, L275: "`"invisible"` is not a
287/// value of this field. The server reports a contact whose presence is
288/// `"invisible"` ... as `"offline"`"). Every other field is unchanged.
289///
290/// # Errors
291///
292/// Returns the backend's error if reading the contact's blocked status
293/// fails.
294pub async fn project_presence<B: ChatBackend>(
295 backend: &B,
296 caller: &B::CallerCtx,
297 account_id: &Id,
298 event: &ChatPresenceEvent,
299) -> Result<Option<ChatPresenceEvent>, B::Error> {
300 if event.account_id != *account_id {
301 return Ok(None);
302 }
303 if backend
304 .is_contact_blocked(caller, account_id, &event.contact_id)
305 .await?
306 {
307 return Ok(None);
308 }
309 let mut projected = event.clone();
310 if projected.presence == Presence::Invisible {
311 projected.presence = Presence::Offline;
312 }
313 Ok(Some(projected))
314}