Skip to main content

wse_client/
handler.rs

1//! What the application hears: its messages through a [`Handler`], and
2//! [`Event`]s about the connection.
3
4use std::future::Future;
5use std::time::Duration;
6
7use crate::delivery::{Continuity, StreamPosition};
8use crate::error::Error;
9use crate::message::{Message, Position};
10
11/// `Send`, except in the browser: a handler there may hold what the page
12/// has, and runs on its one thread.
13#[cfg(not(target_arch = "wasm32"))]
14pub trait MaybeSend: Send {}
15#[cfg(not(target_arch = "wasm32"))]
16impl<T: Send> MaybeSend for T {}
17
18/// `Send`, except in the browser: a handler there may hold what the page
19/// has, and runs on its one thread.
20#[cfg(target_arch = "wasm32")]
21pub trait MaybeSend {}
22#[cfg(target_arch = "wasm32")]
23impl<T> MaybeSend for T {}
24
25/// What the application does with what the server sends.
26///
27/// The client calls it from the connection's own task, in the order the
28/// messages came, with each message read in place from its frame. It holds
29/// the connection while it runs: hand long work to a task of its own.
30///
31/// A closure taking `&Message` is a handler too.
32pub trait Handler: MaybeSend + 'static {
33    /// A message for the application: everything the server sends but its
34    /// own protocol messages, duplicates dropped and topic messages in
35    /// order.
36    fn message(&mut self, message: &Message<'_>);
37
38    /// Something happened to the connection.
39    fn event(&mut self, event: Event) {
40        let _ = event;
41    }
42
43    /// Bytes the server application sent as they are (`send_bytes`).
44    fn binary(&mut self, data: &[u8]) {
45        let _ = data;
46    }
47
48    /// Called before each frame is read once the server took the
49    /// connection. Waiting here holds the server back while the application
50    /// catches up; the heartbeat and sends go on meanwhile, and the wait may
51    /// be dropped for them and begun again: it must lose nothing when
52    /// dropped. Not called in the browser, which cannot hold a WebSocket
53    /// back: there the frames wait in memory.
54    fn ready(&mut self) -> impl Future<Output = ()> + MaybeSend {
55        std::future::ready(())
56    }
57}
58
59impl<F> Handler for F
60where
61    F: FnMut(&Message<'_>) + MaybeSend + 'static,
62{
63    fn message(&mut self, message: &Message<'_>) {
64        self(message)
65    }
66}
67
68/// Something that happened to the connection.
69#[derive(Clone, Debug)]
70#[non_exhaustive]
71pub enum Event {
72    /// The server took the connection (`server_ready`). Topics are
73    /// subscribed again from where the client left off.
74    Connected(Connected),
75    /// The connection was lost, or an attempt to make it again failed; the
76    /// next attempt comes after `retry_in`.
77    Disconnected(Disconnected),
78    /// The application paused the client ([`Client::pause`]): the
79    /// connection ended and no attempt is made until the last reason is
80    /// cleared; topics and positions stay.
81    ///
82    /// [`Client::pause`]: crate::Client::pause
83    Paused(Paused),
84    /// The server's answer to a subscription request.
85    Subscribed(Subscribed),
86    /// Messages of a topic that will not come: reload what depends on them.
87    Gap(Gap),
88    /// An `error` message from the server.
89    ServerError(ServerError),
90    /// recover-or-resync ([`Config::delivery`]): the topics wait for the
91    /// application to bring its state of them up to date;
92    /// [`Client::resynced`] with the round then hands on what they held.
93    ///
94    /// [`Config::delivery`]: crate::Config::delivery
95    /// [`Client::resynced`]: crate::Client::resynced
96    Resync(Resync),
97    /// A topic's continuity changed: its messages run without a break, or
98    /// they broke off and the application's state of it is to be brought up
99    /// to date.
100    Continuity(TopicContinuity),
101    /// The checkpoint the delivery was given is not this client's (its
102    /// realm, user, consumer or schema differs), or not one at all: recovery
103    /// starts without it.
104    CheckpointRejected(CheckpointRejected),
105    /// The server took these messages of the outbox (their ids): it
106    /// confirmed them, or, a server older than 3.2, they were written.
107    Delivered(Vec<String>),
108    /// These messages of the outbox will not be delivered: the server
109    /// refused them, they waited too long, or the user changed or signed
110    /// out.
111    NotDelivered(NotDelivered),
112    /// The outbox's file ([`Config::offline`]) could not be opened or
113    /// written: what is kept stays in memory, and may not outlive the
114    /// application.
115    ///
116    /// [`Config::offline`]: crate::Config::offline
117    StorageFailed(StorageFailed),
118    /// The client stopped for good: closed by the application (`None`), or
119    /// the reason.
120    Closed(Option<Error>),
121}
122
123/// Topics waiting for the application to bring its state of them up to date.
124#[derive(Clone, Debug, PartialEq, Eq)]
125#[non_exhaustive]
126pub struct Resync {
127    /// What to give [`Client::resynced`](crate::Client::resynced) once the
128    /// application's state of the topics is up to date.
129    pub round: u64,
130    pub topics: Vec<String>,
131    /// Why, for each topic in order: `cold_start`, `reconnected`,
132    /// `requested`, `overflow`, or the reason of the gap.
133    pub reasons: Vec<String>,
134    /// Where the consumer stands in each stream of the topics: what it
135    /// committed it applied.
136    pub committed: Vec<StreamPosition>,
137}
138
139/// A topic's continuity, as it changed.
140#[derive(Clone, Debug, PartialEq, Eq)]
141#[non_exhaustive]
142pub struct TopicContinuity {
143    pub topic: String,
144    pub continuity: Continuity,
145    /// Why it is not continuous.
146    pub reason: Option<String>,
147}
148
149/// Messages of the outbox that will not be delivered, and why: the
150/// server's refusal (`busy`, `rate_limited`, `missing`, `not_ready`), or
151/// `expired`, `user_changed`, `cleared`.
152#[derive(Clone, Debug, PartialEq, Eq)]
153#[non_exhaustive]
154pub struct NotDelivered {
155    pub reason: String,
156    pub ids: Vec<String>,
157}
158
159/// What failed in the outbox's file (`operation`: `open` or `write`), and
160/// why.
161#[derive(Clone, Debug, PartialEq, Eq)]
162#[non_exhaustive]
163pub struct StorageFailed {
164    pub operation: String,
165    pub message: String,
166}
167
168/// Why the delivery's checkpoint was not taken: `malformed`, `version`,
169/// `realm`, `user`, `consumer` or `schema`.
170#[derive(Clone, Debug, PartialEq, Eq)]
171#[non_exhaustive]
172pub struct CheckpointRejected {
173    pub reason: String,
174}
175
176#[derive(Clone, Debug, PartialEq, Eq)]
177#[non_exhaustive]
178pub struct Connected {
179    pub connection_id: String,
180    pub user_id: Option<String>,
181    /// A connection made again after one was lost.
182    pub reconnected: bool,
183    /// The server keeps topic histories: missed messages are replayed.
184    pub recovery: bool,
185}
186
187#[derive(Clone, Debug, PartialEq, Eq)]
188#[non_exhaustive]
189pub struct Disconnected {
190    /// The close code; `None` when the connection was cut or never made.
191    pub code: Option<u16>,
192    pub reason: String,
193    /// When the next attempt is made.
194    pub retry_in: Duration,
195    /// Attempts made since the last connection the server took.
196    pub attempt: u32,
197}
198
199#[derive(Clone, Debug, PartialEq, Eq)]
200#[non_exhaustive]
201pub struct Paused {
202    /// The reasons the client is paused for.
203    pub reasons: Vec<String>,
204}
205
206#[derive(Clone, Debug, PartialEq, Eq)]
207#[non_exhaustive]
208pub struct Subscribed {
209    pub topics: Vec<String>,
210    /// Refused: by the topic rights, an invalid name, or over a limit.
211    pub failed: Vec<String>,
212    /// Per topic asked for with a position: what was replayed.
213    pub recovery: Vec<Recovery>,
214}
215
216/// What a subscription replayed of a topic.
217#[derive(Clone, Debug, PartialEq, Eq)]
218#[non_exhaustive]
219pub struct Recovery {
220    pub topic: String,
221    /// Every missed message was replayed.
222    pub recovered: bool,
223    /// Messages replayed.
224    pub count: u64,
225    /// The topic's position on the server now.
226    pub position: Option<Position>,
227}
228
229/// Messages of a topic that will not come.
230#[derive(Clone, Debug, PartialEq, Eq)]
231#[non_exhaustive]
232pub struct Gap {
233    pub topic: String,
234    pub epoch: u32,
235    /// The first and last offsets missing, when known.
236    pub first: Option<u64>,
237    pub last: Option<u64>,
238    pub reason: GapReason,
239}
240
241impl Gap {
242    /// How many messages are missing, when known.
243    pub fn missed(&self) -> Option<u64> {
244        Some(self.last?.checked_sub(self.first?)? + 1)
245    }
246}
247
248/// Why a gap was not filled.
249#[derive(Clone, Copy, Debug, PartialEq, Eq)]
250#[non_exhaustive]
251pub enum GapReason {
252    /// The replay did not come within `recovery_timeout`.
253    Timeout,
254    /// Too many messages came past the gap while waiting.
255    Overflow,
256    /// The server no longer has the messages.
257    NotRecovered,
258    /// The server keeps no history, or does not answer recovery requests.
259    Unavailable,
260    /// The replay stopped short.
261    Incomplete,
262    /// The server restarted: the topic's history began again.
263    EpochChanged,
264    /// The client stopped while waiting.
265    Closed,
266}
267
268impl GapReason {
269    /// The reason as the other clients name it.
270    pub fn as_str(self) -> &'static str {
271        match self {
272            Self::Timeout => "timeout",
273            Self::Overflow => "overflow",
274            Self::NotRecovered => "not_recovered",
275            Self::Unavailable => "unavailable",
276            Self::Incomplete => "incomplete",
277            Self::EpochChanged => "epoch_changed",
278            Self::Closed => "closed",
279        }
280    }
281}
282
283/// An `error` message from the server.
284#[derive(Clone, Debug, PartialEq)]
285#[non_exhaustive]
286pub struct ServerError {
287    /// `RATE_LIMITED`, `SIGNATURE_REFUSED`, the application's own codes...
288    pub code: String,
289    pub message: String,
290    /// The whole payload.
291    pub details: serde_json::Value,
292}