Skip to main content

wse_client/
client.rs

1//! The application's handle on a connection.
2
3use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::{Arc, Mutex};
5
6use serde::Serialize;
7use tokio::sync::{mpsc, oneshot, watch};
8
9#[cfg(target_arch = "wasm32")]
10use crate::browser::Driver;
11use crate::config::Config;
12#[cfg(not(target_arch = "wasm32"))]
13use crate::connection::Driver;
14use crate::delivery::{self, Gate, TopicState};
15use crate::error::Error;
16use crate::handler::{Event, Handler, StorageFailed};
17use crate::message::Message;
18use crate::outbox::{Outbox, Room};
19use crate::security::Keys;
20
21/// Where the client stands.
22#[derive(Clone, Debug, PartialEq, Eq)]
23#[non_exhaustive]
24pub enum Status {
25    /// Making the first connection.
26    Connecting,
27    /// The server took the connection.
28    Connected,
29    /// The connection was lost; making it again.
30    Reconnecting,
31    /// Paused by the application: no connection until it resumes.
32    Paused,
33    /// Stopped for good: closed by the application (`None`), or the reason.
34    Closed(Option<Error>),
35}
36
37/// What the application asks of the connection, besides its messages.
38pub(crate) enum Control {
39    Subscribe(Vec<String>),
40    Unsubscribe(Vec<String>),
41    Reconnect,
42    Pause(String),
43    Resume(String),
44    /// The delivery's gate made something for the handler (held messages
45    /// handed on): it goes to the handler now.
46    Drain,
47    /// The user signed out: the outbox is emptied.
48    Clear,
49    Close,
50}
51
52/// Where what the delivery's gate makes outside the messages goes to the
53/// application.
54#[derive(Clone)]
55pub(crate) enum Wake {
56    /// The handler, from the connection's task.
57    Session,
58    /// The [`Events`](crate::Events) stream, at its next read.
59    Reader(mpsc::UnboundedSender<()>),
60}
61
62/// A message the application sent, on its way to the connection's task.
63pub(crate) struct Queued {
64    pub(crate) text: String,
65    /// The user it was sent as ([`Shared::users`]): it goes nowhere once the
66    /// server took a connection for another user.
67    pub(crate) user: u64,
68    /// A signed or live message goes on the connection it was sent on
69    /// ([`Shared::connections`]), or not at all.
70    pub(crate) only_on: Option<u64>,
71    /// Topics that must each be continuous when it goes: until then it
72    /// waits, in order with the others that wait.
73    pub(crate) requires: Option<Box<[String]>>,
74    /// Its id: the application's own, or a random one; what its outcome
75    /// names.
76    pub(crate) id: Box<str>,
77    /// Until when it may wait before it is first sent, in milliseconds
78    /// since the Unix epoch, from its send on (waiting for its topics
79    /// included); None: the outbox's `max_age`.
80    pub(crate) until: Option<u64>,
81    /// It took a place in the outbox's room, given back when it goes.
82    pub(crate) counted: bool,
83    /// The outbox's clears before it ([`Shared::clears`]): it goes nowhere
84    /// once the application cleared the outbox after it.
85    pub(crate) clears: u64,
86    /// The bridge owner's window that sent it ([`crate::outbox::Tags`]): 0
87    /// for the application's own.
88    pub(crate) tag: u64,
89}
90
91impl Queued {
92    /// Its size as the application sent it: its place in the outbox's room
93    /// (the room for its number, before it, not counted).
94    pub(crate) fn size(&self) -> usize {
95        if self.counted {
96            self.text.len().saturating_sub(crate::outbox::HEADROOM)
97        } else {
98            self.text.len()
99        }
100    }
101}
102
103/// The user and connection a message was sent for.
104struct SentFor {
105    user: u64,
106    /// What a signed or live message goes on.
107    connection: u64,
108    /// The server took the current connection.
109    ready: bool,
110    clears: u64,
111}
112
113impl SentFor {
114    fn frame(&self, id: Box<str>, text: String) -> Queued {
115        Queued {
116            text,
117            user: self.user,
118            only_on: None,
119            requires: None,
120            id,
121            until: None,
122            counted: false,
123            clears: self.clears,
124            tag: 0,
125        }
126    }
127
128    /// For this connection only.
129    fn live(&self, text: String) -> Queued {
130        Queued {
131            only_on: Some(self.connection),
132            ..self.frame(Box::default(), text)
133        }
134    }
135}
136
137/// How a message goes ([`Client::send_with`]).
138#[derive(Clone, Debug, Default)]
139#[non_exhaustive]
140pub struct SendOptions {
141    /// Its id: the application's own (one it keeps in its own outbox, say),
142    /// or a random UUID. The outcome events name it.
143    pub id: Option<String>,
144    /// How long it may wait before it is first sent: past it, it is dropped
145    /// and the application told ([`Event::NotDelivered`](crate::Event),
146    /// `expired`). Once written it waits for the server's answer whatever
147    /// its age. None: the outbox's `max_age`.
148    pub ttl: Option<std::time::Duration>,
149    /// Topics that must each be continuous when it goes (see
150    /// [`Client::send_requiring`]).
151    pub requires: Vec<String>,
152    /// The id the application's reply names (`cid`): its request and its
153    /// response.
154    pub correlation_id: Option<String>,
155    /// How urgent the application says it is (`pri`; the other clients
156    /// name 10 critical, 8 high, 5 normal, 3 low, 1 background). It is for
157    /// the server's application: the outbox keeps the order messages were
158    /// sent in.
159    pub priority: Option<u8>,
160    /// On the connection that is ready now, or not at all, as
161    /// [`Client::try_send_live`]: never kept in the outbox. It waits for
162    /// nothing, so it takes no `ttl` and requires no topics.
163    pub live: bool,
164}
165
166/// What a message carries besides its type, payload and id.
167#[derive(Clone, Copy, Default)]
168struct Extra<'a> {
169    cid: Option<&'a str>,
170    pri: Option<u8>,
171}
172
173impl<'a> Extra<'a> {
174    fn of(options: &'a SendOptions) -> Self {
175        Self {
176            cid: options.correlation_id.as_deref(),
177            pri: options.priority,
178        }
179    }
180}
181
182/// A message as it goes: `{"t", "p", "id"}`, and its `cid` and `pri` when
183/// it has them.
184#[derive(Serialize)]
185struct Out<'a, P: ?Sized> {
186    t: &'a str,
187    p: &'a P,
188    id: &'a str,
189    #[serde(skip_serializing_if = "Option::is_none")]
190    cid: Option<&'a str>,
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pri: Option<u8>,
193}
194
195/// What the handles and the connection's task share.
196pub(crate) struct Shared {
197    /// The server took the current connection: messages may go.
198    pub(crate) ready: AtomicBool,
199    /// Counts the times the server took a connection for another user than
200    /// the one before.
201    pub(crate) users: AtomicU64,
202    /// Counts the connections the server took.
203    pub(crate) connections: AtomicU64,
204    /// The current connection's id and user.
205    pub(crate) connection: Mutex<Option<(String, Option<String>)>>,
206    /// The token for the next connection attempt.
207    pub(crate) token: Mutex<Option<String>>,
208    /// The server's signing key: what signed messages are for.
209    pub(crate) server_kid: Mutex<Option<String>>,
210    /// Stops the connection's task where it stands: a close past its
211    /// deadline.
212    stop: Mutex<Option<futures_util::future::AbortHandle>>,
213    /// The outbox's room ([`Config::offline`]): a send takes a place in it
214    /// before it is queued.
215    pub(crate) room: Option<Arc<Room>>,
216    /// Counts the times the application cleared the outbox.
217    pub(crate) clears: AtomicU64,
218    /// A bridge owner of this crate: its windows' sends' outcomes, and
219    /// whether a window holds one back.
220    pub(crate) tags: Option<Arc<dyn crate::outbox::Tags>>,
221}
222
223impl Shared {
224    pub(crate) fn new(token: Option<String>, room: Option<Arc<Room>>) -> Self {
225        Self {
226            ready: AtomicBool::new(false),
227            users: AtomicU64::new(0),
228            connections: AtomicU64::new(0),
229            connection: Mutex::new(None),
230            token: Mutex::new(token),
231            server_kid: Mutex::new(None),
232            stop: Mutex::new(None),
233            room,
234            clears: AtomicU64::new(0),
235            tags: None,
236        }
237    }
238}
239
240/// A connection to a WSE server, made again when it is lost.
241///
242/// Clones share the connection, which lives as long as the application
243/// holds a handle (or until [`close`](Self::close)); the client a handler
244/// is given by [`connect_with`](Self::connect_with) does not keep it.
245/// Sends go out in the order they were made; what the server sends goes to
246/// the [`Handler`] the client was made with, or to the
247/// [`Events`](crate::Events) of [`connect`](crate::connect).
248///
249/// A message still queued when the connection is lost goes out on the next
250/// one, unless the server takes that one for another user: then it goes
251/// nowhere, and the topics start over. A signed message goes out on the
252/// connection it was signed on, or not at all.
253#[derive(Clone)]
254pub struct Client {
255    shared: Arc<Shared>,
256    #[cfg_attr(not(feature = "aws-lc"), allow(dead_code))]
257    keys: Arc<Keys>,
258    frames: mpsc::Sender<Queued>,
259    control: mpsc::UnboundedSender<Control>,
260    status: watch::Receiver<Status>,
261    /// The delivery: the topics' states, what was held and committed.
262    gate: delivery::Shared,
263    wake: Wake,
264    /// The application's hold on the connection; none for a handler's.
265    _owner: Option<Arc<Owner>>,
266}
267
268/// The application's handles hold one of these: when the last goes, the
269/// connection is closed.
270struct Owner(mpsc::UnboundedSender<Control>);
271
272impl Drop for Owner {
273    fn drop(&mut self) {
274        let _ = self.0.send(Control::Close);
275    }
276}
277
278impl Client {
279    /// Connects, and returns once the server took the connection. What it
280    /// sends goes to `handler`.
281    ///
282    /// The first connection is not made again when it fails: the error is
283    /// returned. Later ones are, as [`Config::reconnect`] says.
284    pub async fn connect<H: Handler>(config: Config, handler: H) -> Result<Self, Error> {
285        Self::connect_with(config, |_| handler).await
286    }
287
288    /// [`connect`](Self::connect) with a handler that is given the client,
289    /// to send from it.
290    pub async fn connect_with<H, F>(config: Config, make: F) -> Result<Self, Error>
291    where
292        H: Handler,
293        F: FnOnce(Client) -> H,
294    {
295        Self::launch(config, make, None, true)
296            .await
297            .map(|(client, _)| client)
298    }
299
300    /// Starts, and returns at once: the connection is made in the
301    /// background, a failed first attempt made again as any later one
302    /// ([`Config::reconnect`]). What is sent meanwhile waits in the outbox.
303    /// For an application that may start without a network; a client that
304    /// gives up says so in [`Client::closed`].
305    pub async fn start<H: Handler>(config: Config, handler: H) -> Result<Self, Error> {
306        Self::start_with(config, |_| handler).await
307    }
308
309    /// [`start`](Self::start) with a handler that is given the client, to
310    /// send from it.
311    pub async fn start_with<H, F>(config: Config, make: F) -> Result<Self, Error>
312    where
313        H: Handler,
314        F: FnOnce(Client) -> H,
315    {
316        Self::launch(config, make, None, false)
317            .await
318            .map(|(client, _)| client)
319    }
320
321    /// Starts the client, and returns once the server took the first
322    /// connection (`wait`) or at once. The delivery's gate stands before the
323    /// handler, or, with `reader` (the [`Events`](crate::Events) stream's
324    /// wake), where the stream is read: it is returned for it.
325    pub(crate) async fn launch<H, F>(
326        mut config: Config,
327        make: F,
328        reader: Option<mpsc::UnboundedSender<()>>,
329        wait: bool,
330    ) -> Result<(Self, delivery::Shared), Error>
331    where
332        H: Handler,
333        F: FnOnce(Client) -> H,
334    {
335        config.check()?;
336        let gate = Gate::new(config.delivery.clone(), &config.url, &config.topics)?;
337        let gate = Arc::new(std::sync::Mutex::new(gate));
338        // Recovery starts from what the application committed.
339        let committed = Arc::clone(&gate);
340        config.committed = Some(Arc::new(move |user| {
341            delivery::lock(&committed).committed(user)
342        }));
343        let before_handler = reader.is_none();
344        let (control_tx, control_rx) = mpsc::unbounded_channel();
345        let (room, outbox) = match &config.offline {
346            Some(offline) => {
347                let room = Arc::new(Room::new(offline));
348                let report = storage_report(&gate, &control_tx, reader.clone());
349                let outbox =
350                    Outbox::open(offline, Arc::clone(&room), report, outbox_wake(&control_tx));
351                (Some(room), Some(outbox))
352            }
353            None => (None, None),
354        };
355        let wake = match reader {
356            Some(reader) => Wake::Reader(reader),
357            None => Wake::Session,
358        };
359        let keys = Arc::new(Keys::from_config(&config)?);
360        // Read into the keys: the bytes of this copy go.
361        #[cfg(feature = "aws-lc")]
362        if let Some(mut key) = config.signing_key.take() {
363            zeroize::Zeroize::zeroize(&mut key);
364        }
365        let mut shared = Shared::new(config.token.clone(), room);
366        shared.tags = config.tags.take();
367        let shared = Arc::new(shared);
368        let (frames_tx, frames_rx) = mpsc::channel(config.send_queue);
369        let (status_tx, status_rx) = watch::channel(Status::Connecting);
370        let for_handler = Client {
371            shared: Arc::clone(&shared),
372            keys: Arc::clone(&keys),
373            frames: frames_tx,
374            control: control_tx.clone(),
375            status: status_rx,
376            gate: Arc::clone(&gate),
377            wake,
378            _owner: None,
379        };
380        let client = Client {
381            _owner: Some(Arc::new(Owner(control_tx))),
382            ..for_handler.clone()
383        };
384        let handler = make(for_handler);
385        // Connect waits for the first connection's answer; start retries it.
386        let (first_tx, first_rx) = oneshot::channel();
387        let first = wait.then_some(first_tx);
388        let ended = (Arc::clone(&shared), status_tx.clone());
389        let (stop, stopped) = futures_util::future::AbortHandle::new_pair();
390        if let Ok(mut slot) = shared.stop.lock() {
391            *slot = Some(stop);
392        }
393        let handler = crate::delivery::Delivered::new(handler, Arc::clone(&gate), before_handler);
394        let driver = Driver::new(
395            config, handler, shared, keys, frames_rx, control_rx, status_tx,
396        )
397        .with_outbox(outbox);
398        let run = async move {
399            use futures_util::FutureExt;
400            let driven = futures_util::future::Abortable::new(
401                std::panic::AssertUnwindSafe(driver.run(first)).catch_unwind(),
402                stopped,
403            )
404            .await;
405            let (shared, status) = ended;
406            // A send that waits for a place in the outbox waits no longer,
407            // however the client ended (a handler that panicked, a close
408            // past its deadline).
409            if let Some(room) = &shared.room {
410                room.close();
411            }
412            match driven {
413                Ok(Ok(())) => {}
414                // A handler that panics ends the client, which says so.
415                Ok(Err(_)) => {
416                    shared.ready.store(false, Ordering::Release);
417                    status.send_replace(Status::Closed(Some(Error::Panicked)));
418                }
419                // Stopped by a close past its deadline: the connection went
420                // with the task.
421                Err(_) => {
422                    shared.ready.store(false, Ordering::Release);
423                    status.send_replace(Status::Closed(None));
424                }
425            }
426        };
427        #[cfg(not(target_arch = "wasm32"))]
428        tokio::spawn(run);
429        #[cfg(target_arch = "wasm32")]
430        wasm_bindgen_futures::spawn_local(run);
431        if !wait {
432            return Ok((client, gate));
433        }
434        match first_rx.await {
435            Ok(Ok(())) => Ok((client, gate)),
436            Ok(Err(error)) => Err(error),
437            Err(_) => Err(Error::Closed),
438        }
439    }
440
441    /// Sends a message `{"t": kind, "p": payload}`; fails at once when the
442    /// outbox or the queue is full.
443    pub fn try_send<P: Serialize + ?Sized>(&self, kind: &str, payload: &P) -> Result<(), Error> {
444        let frame = self.outgoing(kind, payload, &SendOptions::default())?;
445        self.try_put(frame)
446    }
447
448    /// Sends a message `{"t": kind, "p": payload}`, waiting for room in the
449    /// queue. It waits in the outbox ([`Config::offline`], in memory by
450    /// default) until the server answers for it, and goes again after a
451    /// reconnect; with no outbox, a send with no connection fails with
452    /// [`Error::NotConnected`].
453    pub async fn send<P: Serialize + ?Sized>(&self, kind: &str, payload: &P) -> Result<(), Error> {
454        let frame = self.outgoing(kind, payload, &SendOptions::default())?;
455        self.put(frame).await
456    }
457
458    /// [`Client::send`] with its `options`: its own id, how long it may
459    /// wait, the topics it requires, its correlation id and priority, or
460    /// live. Returns its id, which its outcome names
461    /// ([`Event::Delivered`](crate::Event::Delivered),
462    /// [`Event::NotDelivered`](crate::Event::NotDelivered)).
463    pub async fn send_with<P: Serialize + ?Sized>(
464        &self,
465        kind: &str,
466        payload: &P,
467        options: &SendOptions,
468    ) -> Result<String, Error> {
469        if options.live {
470            let (id, frame) = self.live_frame(kind, payload, options)?;
471            self.frames.send(frame).await.map_err(|_| Error::Closed)?;
472            return Ok(id);
473        }
474        let frame = self.outgoing(kind, payload, options)?;
475        let id = frame.id.to_string();
476        self.put(frame).await?;
477        Ok(id)
478    }
479
480    /// [`Client::send_with`], failing at once when the outbox or the queue
481    /// is full.
482    pub fn try_send_with<P: Serialize + ?Sized>(
483        &self,
484        kind: &str,
485        payload: &P,
486        options: &SendOptions,
487    ) -> Result<String, Error> {
488        if options.live {
489            let (id, frame) = self.live_frame(kind, payload, options)?;
490            self.frames.try_send(frame).map_err(|e| match e {
491                mpsc::error::TrySendError::Full(_) => Error::Full,
492                mpsc::error::TrySendError::Closed(_) => Error::Closed,
493            })?;
494            return Ok(id);
495        }
496        let frame = self.outgoing(kind, payload, options)?;
497        let id = frame.id.to_string();
498        self.try_put(frame)?;
499        Ok(id)
500    }
501
502    /// [`Client::try_send_with`] for window `tag` of a bridge owner: the
503    /// message carries it in the outbox, and what became of it goes to the
504    /// owner ([`crate::outbox::Tags`]) with it, not to the handler.
505    #[cfg(all(feature = "bridge", not(target_arch = "wasm32")))]
506    pub(crate) fn try_send_tagged<P: Serialize + ?Sized>(
507        &self,
508        kind: &str,
509        payload: &P,
510        options: &SendOptions,
511        tag: u64,
512    ) -> Result<String, Error> {
513        let mut frame = self.outgoing(kind, payload, options)?;
514        frame.tag = tag;
515        let id = frame.id.to_string();
516        self.try_put(frame)?;
517        Ok(id)
518    }
519
520    /// Sends a message `{"t": kind, "p": payload}` on the connection that is
521    /// ready now, or not at all: one this connection did not write is
522    /// dropped, never sent on a later connection, and it never waits in the
523    /// outbox. For commands that must not run late (a valve, a door, an
524    /// order). Fails at once when the queue is full.
525    pub fn try_send_live<P: Serialize + ?Sized>(
526        &self,
527        kind: &str,
528        payload: &P,
529    ) -> Result<(), Error> {
530        let for_now = self.ready()?;
531        let text = encode(kind, payload, &message_id(), Extra::default())?;
532        self.frames
533            .try_send(for_now.live(text))
534            .map_err(|e| match e {
535                mpsc::error::TrySendError::Full(_) => Error::Full,
536                mpsc::error::TrySendError::Closed(_) => Error::Closed,
537            })
538    }
539
540    /// [`Client::try_send_live`], waiting for room in the queue.
541    pub async fn send_live<P: Serialize + ?Sized>(
542        &self,
543        kind: &str,
544        payload: &P,
545    ) -> Result<(), Error> {
546        let for_now = self.ready()?;
547        let text = encode(kind, payload, &message_id(), Extra::default())?;
548        self.frames
549            .send(for_now.live(text))
550            .await
551            .map_err(|_| Error::Closed)
552    }
553
554    /// Sends a message `{"t": kind, "p": payload}` once each of `topics` is
555    /// continuous on the connection (the delivery's
556    /// [`TopicState`](crate::TopicState)): until then it waits, in order with
557    /// the others that wait, while sends that require nothing go past it.
558    /// It is checked as it is taken to go out, so one waiting does not go
559    /// after a reconnect before the resync; it is the user's who made it, and
560    /// goes nowhere once the server takes a connection for another. Waits
561    /// for room in the queue.
562    pub async fn send_requiring<P, I, T>(
563        &self,
564        kind: &str,
565        payload: &P,
566        topics: I,
567    ) -> Result<(), Error>
568    where
569        P: Serialize + ?Sized,
570        I: IntoIterator<Item = T>,
571        T: Into<String>,
572    {
573        let options = SendOptions {
574            requires: topics.into_iter().map(Into::into).collect(),
575            ..SendOptions::default()
576        };
577        self.send_with(kind, payload, &options).await.map(drop)
578    }
579
580    /// [`Client::send_requiring`], failing at once when the outbox or the
581    /// queue is full.
582    pub fn try_send_requiring<P, I, T>(
583        &self,
584        kind: &str,
585        payload: &P,
586        topics: I,
587    ) -> Result<(), Error>
588    where
589        P: Serialize + ?Sized,
590        I: IntoIterator<Item = T>,
591        T: Into<String>,
592    {
593        let options = SendOptions {
594            requires: topics.into_iter().map(Into::into).collect(),
595            ..SendOptions::default()
596        };
597        self.try_send_with(kind, payload, &options).map(drop)
598    }
599
600    /// Sends JSON text as it is: a message the application built itself, a
601    /// JSON object. It waits in the outbox as [`Client::send`] does.
602    pub async fn send_raw(&self, json: impl Into<String>) -> Result<(), Error> {
603        let json = json.into();
604        let body = json.trim_start();
605        if !body.starts_with('{') {
606            return Err(Error::Encode("a message is a JSON object".to_owned()));
607        }
608        // Whole: the outbox keeps it, and its file holds it as it is.
609        serde_json::from_str::<serde::de::IgnoredAny>(body)
610            .map_err(|e| Error::Encode(format!("not JSON: {e}")))?;
611        let text = if self.shared.room.is_some() {
612            let mut text = String::with_capacity(crate::outbox::HEADROOM + body.len());
613            text.extend(std::iter::repeat_n(' ', crate::outbox::HEADROOM));
614            text.push_str(body);
615            text
616        } else {
617            json
618        };
619        let frame = self.queued(message_id().into_boxed_str(), text)?;
620        self.put(frame).await
621    }
622
623    /// Sends a signed message `{"t": kind, "p": payload}`: signed with
624    /// [`Config::signing_key`] for the server's signing key, so whoever
625    /// keeps it can show who sent it. `n` names it once, 1 to 128
626    /// characters (an order id, say; a random one when `None`). Returns the
627    /// `n` it went with: the server's signed `receipt`, or its error
628    /// `SIGNATURE_REFUSED`, names it.
629    #[cfg(feature = "aws-lc")]
630    pub async fn send_signed<P: Serialize + ?Sized>(
631        &self,
632        kind: &str,
633        payload: &P,
634        n: Option<&str>,
635    ) -> Result<String, Error> {
636        let for_now = self.ready()?;
637        let audience = self
638            .shared
639            .server_kid
640            .lock()
641            .ok()
642            .and_then(|kid| kid.clone())
643            .ok_or_else(|| Error::Signing("the server named no signing key".to_owned()))?;
644        let payload =
645            serde_json::value::to_raw_value(payload).map_err(|e| Error::Encode(e.to_string()))?;
646        let n = match n {
647            Some(n)
648                if n.is_empty() || n.chars().count() > wse::protocol::signing::MAX_NONCE_LEN =>
649            {
650                return Err(Error::Signing(format!(
651                    "n must be 1 to {} characters",
652                    wse::protocol::signing::MAX_NONCE_LEN
653                )));
654            }
655            Some(n) => n.to_owned(),
656            None => {
657                let mut bytes = [0u8; 16];
658                wse::protocol::crypto::fill_random(&mut bytes)
659                    .map_err(|_| Error::Signing("no random bytes".to_owned()))?;
660                bytes.iter().map(|b| format!("{b:02x}")).collect::<String>()
661            }
662        };
663        let text = self
664            .keys
665            .sign(kind, &payload, &audience, &n, crate::session::now_ms())?;
666        // Signed for this connection: it goes on it or not at all.
667        self.frames
668            .send(for_now.live(text))
669            .await
670            .map_err(|_| Error::Closed)?;
671        Ok(n)
672    }
673
674    /// Ends the connection for `reason` (`"background"`, `"offline"`,
675    /// ...) and makes no attempt while any reason holds: topics and
676    /// positions stay, and what is queued goes out first. The last reason
677    /// cleared with [`resume`](Self::resume), the client connects at once
678    /// and recovers what it missed.
679    pub fn pause(&self, reason: impl Into<String>) -> Result<(), Error> {
680        self.control(Control::Pause(reason.into()))
681    }
682
683    /// Clears `reason`; once none is left the client connects again.
684    pub fn resume(&self, reason: impl Into<String>) -> Result<(), Error> {
685        self.control(Control::Resume(reason.into()))
686    }
687
688    /// Subscribes to topics, on this connection and every later one; after
689    /// a reconnect the client asks for them from where it left off.
690    pub fn subscribe<I, T>(&self, topics: I) -> Result<(), Error>
691    where
692        I: IntoIterator<Item = T>,
693        T: Into<String>,
694    {
695        let topics: Vec<String> = topics.into_iter().map(Into::into).collect();
696        delivery::lock(&self.gate).track(&topics);
697        self.control(Control::Subscribe(topics))
698    }
699
700    /// Unsubscribes, and forgets where the client stood in the topics.
701    pub fn unsubscribe<I, T>(&self, topics: I) -> Result<(), Error>
702    where
703        I: IntoIterator<Item = T>,
704        T: Into<String>,
705    {
706        let topics: Vec<String> = topics.into_iter().map(Into::into).collect();
707        delivery::lock(&self.gate).untrack(&topics);
708        self.control(Control::Unsubscribe(topics))
709    }
710
711    /// How many messages wait in the outbox for the server's answer
712    /// ([`Config::offline`]).
713    pub fn kept(&self) -> usize {
714        self.shared.room.as_ref().map_or(0, |room| room.count())
715    }
716
717    /// The user signs out: every message in the outbox, and every one sent
718    /// before this call, goes ([`Event::NotDelivered`](crate::Event),
719    /// `cleared`), and the user is forgotten, so nothing of theirs is sent as
720    /// the next one. One the server has in hand already is delivered if it
721    /// confirms it on the current connection.
722    pub fn clear(&self) -> Result<(), Error> {
723        self.shared.clears.fetch_add(1, Ordering::AcqRel);
724        self.control(Control::Clear)
725    }
726
727    /// Each topic held: whether the server took it, and whether its
728    /// messages run without a break.
729    pub fn topic_states(&self) -> Vec<TopicState> {
730        delivery::lock(&self.gate).topic_states()
731    }
732
733    /// The consumer applied `message` (a topic message): the checkpoint
734    /// moves on through what was applied without a hole. A message handed
735    /// out before the events showed another user counts for nobody. An
736    /// [`OwnedMessage`](crate::OwnedMessage) commits as `owned.as_message()`.
737    pub fn commit(&self, message: &Message<'_>) {
738        if let (Some(topic), Some(at)) = (message.topic(), message.position()) {
739            self.commit_at(topic, at.epoch, at.offset, message.generation);
740        }
741    }
742
743    pub(crate) fn commit_at(&self, topic: &str, epoch: u32, offset: u64, generation: u32) {
744        delivery::lock(&self.gate).commit(topic, epoch, offset, generation);
745    }
746
747    /// What the consumer committed, bound to the realm, the user, the
748    /// consumer and the schema: to save with the application's own state and
749    /// give back as [`Delivery::checkpoint`](crate::Delivery::checkpoint).
750    pub fn checkpoint(&self) -> String {
751        delivery::lock(&self.gate).checkpoint()
752    }
753
754    /// recover-or-resync: the application brought the topics of `round`
755    /// ([`Event::Resync`](crate::Event::Resync)) up to date; what they held
756    /// comes next.
757    pub fn resynced(&self, round: u64) -> Result<(), Error> {
758        delivery::lock(&self.gate).resynced(round);
759        self.wake()
760    }
761
762    /// Bring `topics` up to date: in recover-or-resync a resync round asks
763    /// for it; in best effort the application did so itself, and they read
764    /// continuous again.
765    pub fn resync<I, T>(&self, topics: I) -> Result<(), Error>
766    where
767        I: IntoIterator<Item = T>,
768        T: Into<String>,
769    {
770        let topics: Vec<String> = topics.into_iter().map(Into::into).collect();
771        delivery::lock(&self.gate).resync(&topics);
772        self.wake()
773    }
774
775    /// What the gate made goes to the application, and the sends that wait
776    /// for their topics are looked at again.
777    pub(crate) fn wake(&self) -> Result<(), Error> {
778        if let Wake::Reader(reader) = &self.wake {
779            // A stream nobody reads any more has nobody to tell.
780            let _ = reader.send(());
781        }
782        self.control(Control::Drain)
783    }
784
785    /// Drops the connection and makes it again at once.
786    pub fn reconnect(&self) -> Result<(), Error> {
787        self.control(Control::Reconnect)
788    }
789
790    /// The token for the next connection attempt.
791    pub fn set_token(&self, token: impl Into<String>) {
792        if let Ok(mut current) = self.shared.token.lock() {
793            *current = Some(token.into());
794        }
795    }
796
797    /// Closes the connection for good, and waits until it is.
798    pub async fn close(&self) {
799        let _ = self.control.send(Control::Close);
800        self.closed().await;
801    }
802
803    /// Closes the client, giving what is queued `deadline` to go out: past
804    /// it the connection is dropped where it stands (a link that takes
805    /// nothing holds a close for as long as the system keeps the
806    /// connection).
807    #[cfg(not(target_arch = "wasm32"))]
808    pub async fn close_within(&self, deadline: std::time::Duration) {
809        let _ = self.control.send(Control::Close);
810        if tokio::time::timeout(deadline, self.closed()).await.is_err() {
811            if let Some(stop) = self.shared.stop.lock().ok().and_then(|slot| slot.clone()) {
812                stop.abort();
813            }
814            self.closed().await;
815        }
816    }
817
818    /// Waits until the client stops for good; the reason, unless the
819    /// application closed it.
820    pub async fn closed(&self) -> Option<Error> {
821        let mut status = self.status.clone();
822        let closed = status
823            .wait_for(|s| matches!(s, Status::Closed(_)))
824            .await
825            .map(|s| s.clone());
826        match closed {
827            Ok(Status::Closed(error)) => error,
828            _ => None,
829        }
830    }
831
832    pub fn status(&self) -> Status {
833        self.status.borrow().clone()
834    }
835
836    /// The server took the current connection: messages go out.
837    pub fn is_connected(&self) -> bool {
838        self.shared.ready.load(Ordering::Acquire)
839    }
840
841    /// The current connection's id, as the server named it.
842    pub fn connection_id(&self) -> Option<String> {
843        let connection = self.shared.connection.lock().ok()?;
844        connection.as_ref().map(|(id, _)| id.clone())
845    }
846
847    /// The user the server took the connection for.
848    pub fn user_id(&self) -> Option<String> {
849        let connection = self.shared.connection.lock().ok()?;
850        connection.as_ref().and_then(|(_, user)| user.clone())
851    }
852
853    /// The user and connection a message is sent for, read before the flag:
854    /// one taken in between leaves the message with those before it, which
855    /// it does not go out for.
856    /// Who and what a message is sent for now; the client is not closed.
857    fn sent_for(&self) -> Result<SentFor, Error> {
858        let sent_for = SentFor {
859            user: self.shared.users.load(Ordering::Acquire),
860            connection: self.shared.connections.load(Ordering::Acquire),
861            ready: self.shared.ready.load(Ordering::Acquire),
862            clears: self.shared.clears.load(Ordering::Acquire),
863        };
864        if !sent_for.ready && matches!(*self.status.borrow(), Status::Closed(_)) {
865            return Err(Error::Closed);
866        }
867        Ok(sent_for)
868    }
869
870    /// [`Client::sent_for`] on a connection the server took.
871    fn ready(&self) -> Result<SentFor, Error> {
872        let sent_for = self.sent_for()?;
873        if sent_for.ready {
874            Ok(sent_for)
875        } else {
876            Err(Error::NotConnected)
877        }
878    }
879
880    /// A message to send: its id and its frame.
881    fn outgoing<P: Serialize + ?Sized>(
882        &self,
883        kind: &str,
884        payload: &P,
885        options: &SendOptions,
886    ) -> Result<Queued, Error> {
887        let id = options.id.clone().unwrap_or_else(message_id);
888        // For the outbox: after the room for the message's number.
889        let room = if self.shared.room.is_some() {
890            crate::outbox::HEADROOM
891        } else {
892            0
893        };
894        let extra = Extra::of(options);
895        let text = if room == 0 {
896            encode(kind, payload, &id, extra)?
897        } else {
898            encode_after(room, kind, payload, &id, extra)?
899        };
900        let mut frame = self.queued(id.into_boxed_str(), text)?;
901        frame.until = options.ttl.map(|ttl| {
902            crate::outbox::now_ms()
903                .saturating_add(u64::try_from(ttl.as_millis()).unwrap_or(u64::MAX))
904        });
905        if !options.requires.is_empty() {
906            frame.requires = Some(options.requires.iter().cloned().collect());
907        }
908        Ok(frame)
909    }
910
911    /// A live message as `options` say, for the connection that is ready
912    /// now; and its id.
913    fn live_frame<P: Serialize + ?Sized>(
914        &self,
915        kind: &str,
916        payload: &P,
917        options: &SendOptions,
918    ) -> Result<(String, Queued), Error> {
919        if !options.requires.is_empty() || options.ttl.is_some() {
920            return Err(Error::Config(
921                "a live message waits for nothing: it takes no ttl and requires no topics"
922                    .to_owned(),
923            ));
924        }
925        let for_now = self.ready()?;
926        let id = options.id.clone().unwrap_or_else(message_id);
927        let text = encode(kind, payload, &id, Extra::of(options))?;
928        Ok((id, for_now.live(text)))
929    }
930
931    /// A message for the outbox (its place in the room taken as it is put;
932    /// its text after the room for its number); without an outbox, for the
933    /// connection that is ready now.
934    fn queued(&self, id: Box<str>, text: String) -> Result<Queued, Error> {
935        let for_now = self.sent_for()?;
936        match &self.shared.room {
937            Some(_) => Ok(Queued {
938                counted: true,
939                ..for_now.frame(id, text)
940            }),
941            None if for_now.ready => Ok(for_now.frame(id, text)),
942            None => Err(Error::NotConnected),
943        }
944    }
945
946    /// Queues `frame`, waiting for a place in the outbox and room in the
947    /// queue. A send dropped while it waits (its future cancelled) gives its
948    /// place back.
949    async fn put(&self, frame: Queued) -> Result<(), Error> {
950        /// A place taken in the room, given back unless the frame got into
951        /// the queue.
952        struct Taken<'a> {
953            room: Option<&'a crate::outbox::Room>,
954            size: usize,
955        }
956        impl Drop for Taken<'_> {
957            fn drop(&mut self) {
958                if let Some(room) = self.room {
959                    room.give_back(self.size);
960                }
961            }
962        }
963        let room = self.shared.room.as_deref().filter(|_| frame.counted);
964        let size = frame.size();
965        if let Some(room) = room {
966            room.wait_take(size).await?;
967        }
968        let mut taken = Taken { room, size };
969        let sent = self.frames.send(frame).await;
970        if sent.is_ok() {
971            // The session gives it back when the message goes.
972            taken.room = None;
973        }
974        sent.map_err(|_| Error::Closed)
975    }
976
977    /// Queues `frame`, or fails at once when the outbox or the queue is full.
978    fn try_put(&self, frame: Queued) -> Result<(), Error> {
979        let room = self.shared.room.as_ref().filter(|_| frame.counted);
980        if let Some(room) = room
981            && !room.take(frame.size())
982        {
983            return Err(Error::Full);
984        }
985        self.frames.try_send(frame).map_err(|e| {
986            let (frame, error) = match e {
987                mpsc::error::TrySendError::Full(frame) => (frame, Error::Full),
988                mpsc::error::TrySendError::Closed(frame) => (frame, Error::Closed),
989            };
990            if let Some(room) = room {
991                room.give_back(frame.size());
992            }
993            error
994        })
995    }
996
997    fn control(&self, control: Control) -> Result<(), Error> {
998        self.control.send(control).map_err(|_| Error::Closed)
999    }
1000}
1001
1002impl std::fmt::Debug for Client {
1003    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1004        f.debug_struct("Client")
1005            .field("status", &self.status())
1006            .field("connection_id", &self.connection_id())
1007            .finish()
1008    }
1009}
1010
1011/// `{"t": kind, "p": payload, "id": id}` and its extras, in one pass.
1012fn encode<P: Serialize + ?Sized>(
1013    kind: &str,
1014    payload: &P,
1015    id: &str,
1016    extra: Extra<'_>,
1017) -> Result<String, Error> {
1018    serde_json::to_string(&Out {
1019        t: kind,
1020        p: payload,
1021        id,
1022        cid: extra.cid,
1023        pri: extra.pri,
1024    })
1025    .map_err(|e| Error::Encode(e.to_string()))
1026}
1027
1028/// [`encode`] after `room` spaces, in one buffer: the outbox writes the
1029/// message's number in them.
1030fn encode_after<P: Serialize + ?Sized>(
1031    room: usize,
1032    kind: &str,
1033    payload: &P,
1034    id: &str,
1035    extra: Extra<'_>,
1036) -> Result<String, Error> {
1037    let mut out =
1038        Vec::with_capacity(room + 80 + kind.len() + id.len() + extra.cid.map_or(0, str::len));
1039    out.resize(room, b' ');
1040    serde_json::to_writer(
1041        &mut out,
1042        &Out {
1043            t: kind,
1044            p: payload,
1045            id,
1046            cid: extra.cid,
1047            pri: extra.pri,
1048        },
1049    )
1050    .map_err(|e| Error::Encode(e.to_string()))?;
1051    // SAFETY: spaces, then what serde_json wrote, which is UTF-8 (its own
1052    // `to_string` takes it so).
1053    Ok(unsafe { String::from_utf8_unchecked(out) })
1054}
1055
1056/// A message's id: a random UUID (version 4), as the TypeScript and Python
1057/// clients give theirs.
1058pub(crate) fn message_id() -> String {
1059    const HEX: &[u8; 16] = b"0123456789abcdef";
1060    let (hi, lo) = random_pair();
1061    // Version 4, variant 10.
1062    let hi = (hi & 0xffff_ffff_ffff_0fff) | 0x0000_0000_0000_4000;
1063    let lo = (lo & 0x3fff_ffff_ffff_ffff) | 0x8000_0000_0000_0000;
1064    let bytes = ((u128::from(hi) << 64) | u128::from(lo)).to_be_bytes();
1065    let mut out = [0u8; 36];
1066    let mut at = 0;
1067    for (i, byte) in bytes.iter().enumerate() {
1068        if matches!(i, 4 | 6 | 8 | 10) {
1069            out[at] = b'-';
1070            at += 1;
1071        }
1072        out[at] = HEX[usize::from(byte >> 4)];
1073        out[at + 1] = HEX[usize::from(byte & 0x0f)];
1074        at += 2;
1075    }
1076    String::from_utf8_lossy(&out).into_owned()
1077}
1078
1079#[cfg(not(target_arch = "wasm32"))]
1080pub(crate) fn random_pair() -> (u64, u64) {
1081    (fastrand::u64(..), fastrand::u64(..))
1082}
1083
1084#[cfg(target_arch = "wasm32")]
1085pub(crate) fn random_pair() -> (u64, u64) {
1086    // 52 random bits a call: four calls fill both.
1087    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1088    let bits = || (js_sys::Math::random() * (1u64 << 52) as f64) as u64;
1089    (bits() << 32 ^ bits(), bits() << 32 ^ bits())
1090}
1091
1092/// What the offline queue's file says goes to the application as an
1093/// [`Event::StorageFailed`], with what the delivery's gate makes.
1094/// Wakes the connection's task once the outbox's store wrote what messages
1095/// waited for: they go.
1096fn outbox_wake(control: &mpsc::UnboundedSender<Control>) -> crate::outbox::Wake {
1097    let control = control.downgrade();
1098    Arc::new(move || {
1099        if let Some(control) = control.upgrade() {
1100            let _ = control.send(Control::Drain);
1101        }
1102    })
1103}
1104
1105fn storage_report(
1106    gate: &delivery::Shared,
1107    control: &mpsc::UnboundedSender<Control>,
1108    reader: Option<mpsc::UnboundedSender<()>>,
1109) -> crate::outbox::Report {
1110    let gate = Arc::clone(gate);
1111    let control = control.downgrade();
1112    Arc::new(move |operation, message| {
1113        tracing::error!("[WSE] the outbox's file: {operation} failed: {message}");
1114        delivery::lock(&gate).tell(Event::StorageFailed(StorageFailed {
1115            operation: operation.to_owned(),
1116            message,
1117        }));
1118        if let Some(reader) = &reader {
1119            let _ = reader.send(());
1120        }
1121        if let Some(control) = control.upgrade() {
1122            let _ = control.send(Control::Drain);
1123        }
1124    })
1125}