zero-client 0.3.0

A native Rust client for Zero.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! The public client (`Zero` in `packages/zero-client/src/client/zero.ts`)
//! and its connection (`connection.ts`).

use super::connection_manager::ConnectionState;
use super::database::{ReplicaDatabase, replicache_name};
use super::engine::{
    Engine, MutationServerOutcome, MutatorFn, MutatorResult, UpdateNeededReason, ZeroOptions,
};
use super::inspector::{Inspector, InspectorHost};
use super::live_view::LiveView;
use super::mutation_tracker::OutcomeListeners;
use super::query_context::{MaterializedView, Preload, RunType, WeakView};
use super::storage::DroppedDatabases;
use super::transaction::Transaction;
use super::{ApplicationError, Deferred, Error, Scheduler, SocketFactory};
use crate::ivm::ViewValue;
use crate::json::Value;
use crate::query::{AnyQuery, ZeroQuery};
use crate::schema::Schema;
use crate::ttl::Ttl;
use crate::typed::TypedQuery;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;

type MutatorBody<C> = dyn Fn(&Transaction, Option<&Value>, &C) -> Result<Option<Value>, Error>;

/// A mutator the client can run and replay by name (`defineMutator` in
/// `packages/zql/src/mutate/mutator.ts`). The name must match the TS
/// registry entry the API server runs.
///
/// The body runs synchronously: once optimistically, and again on every
/// rebase over new server data while the mutation is pending, so it must
/// only depend on the transaction, the arguments, and the context. It
/// returns what the caller's `client` outcome carries.
pub struct Mutator<C> {
    /// The name the server runs it by: its path in the TS mutator registry.
    pub name: String,
    body: Rc<MutatorBody<C>>,
}

impl<C> Clone for Mutator<C> {
    fn clone(&self) -> Self {
        Mutator {
            name: self.name.clone(),
            body: self.body.clone(),
        }
    }
}

impl<C> Mutator<C> {
    /// A mutator over JSON arguments: `args` is `None` when the caller
    /// passed none (JS `undefined`).
    pub fn new(
        name: impl Into<String>,
        body: impl Fn(&Transaction, Option<&Value>, &C) -> Result<Option<Value>, Error> + 'static,
    ) -> Self {
        Mutator {
            name: name.into(),
            body: Rc::new(body),
        }
    }
}

/// A mutator applied to its arguments, ready for [`Zero::mutate_request`]
/// (`MutateRequest` in JS and Swift). A `define_mutator` definition makes
/// one with `with`.
#[derive(Clone, Debug, PartialEq)]
pub struct MutateRequest {
    /// The mutator's name.
    pub name: String,
    /// Its arguments as sent: `None` when it takes none (JS `undefined`).
    pub args: Option<Value>,
}

impl MutateRequest {
    /// A request with arguments already in their JSON form, for example to
    /// replay a mutation by name. Prefer a definition's `with`.
    pub fn new(name: impl Into<String>, args: Option<Value>) -> Self {
        MutateRequest {
            name: name.into(),
            args,
        }
    }
}

/// A Zero client: syncs the rows of named queries from zero-cache into a
/// local replica, keeps materialized views of them current, and runs
/// mutators optimistically before the server confirms them.
///
/// `C` is what mutators are given besides their arguments, such as the
/// logged-in user's auth data. Everything runs on the thread that made the
/// client, driven by the [`Scheduler`] and the socket events.
pub struct Zero<C = ()> {
    core: Rc<Core>,
    context: Rc<C>,
}

/// What the client keeps to replace its engine by a new one on the same
/// store when the server lost its state (`replaceClient` in zero-swift's
/// `ZeroClient`): the views and preloads move to the new engine.
struct Core {
    engine: RefCell<Rc<Engine>>,
    schema: Arc<Schema>,
    options: ZeroOptions,
    functions: Rc<HashMap<String, MutatorFn>>,
    scheduler: Rc<dyn Scheduler>,
    socket_factory: Option<Rc<dyn SocketFactory>>,
    connection: Connection,
    views: RefCell<Vec<(WeakView, AnyQuery, Ttl)>>,
    preloads: RefCell<Vec<Rc<PreloadRecord>>>,
    /// What the client's inspectors share, once there is one.
    inspector: RefCell<Option<Rc<InspectorHost>>>,
    /// The mutation outcome listeners, which every engine reports to.
    outcome_listeners: Rc<OutcomeListeners>,
}

/// A preload, which a replacement starts again on the new engine until
/// its cleanup.
struct PreloadRecord {
    query: AnyQuery,
    ttl: Ttl,
    cleanup: RefCell<Rc<dyn Fn()>>,
    active: Cell<bool>,
}

impl<C: 'static> Zero<C> {
    /// - `schema`: the app's schema.
    /// - `mutators`: every mutator the client may run. Pending mutations
    ///   are replayed by name, so each must be registered.
    /// - `scheduler`: the clock and timers, on the app's event loop; tests
    ///   pass a [`ManualScheduler`](crate::testing::ManualScheduler).
    /// - `socket_factory`: opens the sync socket. Without one the client
    ///   runs locally.
    ///
    /// When the server no longer has the client's state, such as after it
    /// closed the connection for a message over its size limit, and the
    /// app set no `on_client_state_not_found`, the client replaces itself
    /// by a new one on the same store, as JS reloads the page: a new client
    /// ID and client group, the views and preloads kept, and pending
    /// mutations of the old client group dropped.
    pub fn new(
        schema: Arc<Schema>,
        context: C,
        mutators: Vec<Mutator<C>>,
        options: ZeroOptions,
        scheduler: Rc<dyn Scheduler>,
        socket_factory: Option<Rc<dyn SocketFactory>>,
    ) -> Result<Self, Error> {
        let context = Rc::new(context);
        let mut functions: HashMap<String, MutatorFn> = HashMap::new();
        for m in mutators {
            if functions.contains_key(&m.name) {
                return Err(ApplicationError::new(format!(
                    "Mutator \"{}\" is registered twice",
                    m.name
                ))
                .into());
            }
            let (body, context) = (m.body.clone(), context.clone());
            functions.insert(m.name, Rc::new(move |tx, args| body(tx, args, &context)));
        }
        let functions = Rc::new(functions);
        let engine = Engine::new(
            schema.clone(),
            options.clone(),
            functions.clone(),
            scheduler.clone(),
            socket_factory.clone(),
            true,
        )?;
        let connection = Connection::new(engine.clone());
        let core = Rc::new(Core {
            engine: RefCell::new(engine.clone()),
            schema,
            options,
            functions,
            scheduler,
            socket_factory,
            connection,
            views: RefCell::default(),
            preloads: RefCell::default(),
            inspector: RefCell::default(),
            outcome_listeners: Rc::default(),
        });
        Core::attach(&core, &engine);
        Ok(Zero { core, context })
    }

    fn engine(&self) -> Rc<Engine> {
        self.core.engine()
    }

    /// The client's ID, which changes when it replaces itself.
    pub fn client_id(&self) -> String {
        self.engine().client_id.clone()
    }

    /// The client group's ID, which changes when the client replaces
    /// itself.
    pub fn client_group_id(&self) -> String {
        self.engine().client_group_id.clone()
    }

    /// The user the client syncs for.
    pub fn user_id(&self) -> Option<&str> {
        self.core.options.user_id.as_deref()
    }

    /// The app's schema.
    pub fn schema(&self) -> &Arc<Schema> {
        &self.core.schema
    }

    /// What the mutators are given besides their arguments.
    pub fn context(&self) -> &C {
        &self.context
    }

    /// Whether the client is closed.
    pub fn closed(&self) -> bool {
        self.engine().closed()
    }

    /// The client's connection to zero-cache.
    pub fn connection(&self) -> &Connection {
        &self.core.connection
    }

    /// A view of the query's rows that stays current. Named queries are
    /// synced from the server; an unnamed one only sees local data.
    pub fn materialize(
        &self,
        query: &(impl ZeroQuery<C> + ?Sized),
        ttl: &Ttl,
    ) -> Result<MaterializedView, Error> {
        let query = query.any_query(self.context());
        let e = self.engine();
        let view = e.event_loop.call(|| e.context.materialize(&query, ttl))?;
        let mut views = self.core.views.borrow_mut();
        views.retain(|(v, _, _)| v.upgrade().is_some_and(|v| !v.is_destroyed()));
        views.push((view.downgrade(), query.into_owned(), ttl.clone()));
        Ok(view)
    }

    /// The query's result read as its Rust type and kept current: its rows,
    /// the row of a `one()` query, or the value of an aggregate, from a
    /// typed [`Query`](crate::typed::Query) or a named query's
    /// `QueryRequest`. Fails when the query can't be materialized, or when
    /// its rows don't read as the type (an [`Error::Message`] saying why).
    pub fn live<Q>(&self, query: &Q, ttl: &Ttl) -> Result<LiveView<Q::Value>, Error>
    where
        Q: TypedQuery<C> + ?Sized,
        Q::Value: 'static,
    {
        LiveView::new(self.materialize(query, ttl)?)
    }

    /// The query's rows: what the replica holds now (`Unknown`), or once
    /// the server has confirmed them on this connection (`Complete`) or
    /// any (`Cached`). Await the result, or read it once settled.
    ///
    /// An unnamed query only sees local data: the server never confirms
    /// it, so waiting for `Complete` or `Cached` never settles.
    pub fn run(
        &self,
        query: &(impl ZeroQuery<C> + ?Sized),
        run_type: RunType,
        ttl: Option<&Ttl>,
    ) -> Deferred<ViewValue> {
        let query = query.any_query(self.context());
        let e = self.engine();
        e.event_loop.call(|| e.context.run(&query, run_type, ttl))
    }

    /// Keeps the query's rows synced without a view, until `cleanup`.
    /// Preloading an unnamed query does nothing. JS's default `ttl` for a
    /// preload is [`Ttl::DEFAULT_PRELOAD`], not `Ttl::default()`.
    pub fn preload(&self, query: &(impl ZeroQuery<C> + ?Sized), ttl: &Ttl) -> Preload {
        let query = query.any_query(self.context());
        let e = self.engine();
        let preload = e.event_loop.call(|| e.context.preload(&query, ttl));
        let record = Rc::new(PreloadRecord {
            query: query.into_owned(),
            ttl: ttl.clone(),
            cleanup: RefCell::new(preload.cleanup),
            active: Cell::new(true),
        });
        let mut preloads = self.core.preloads.borrow_mut();
        preloads.retain(|p| p.active.get());
        preloads.push(record.clone());
        Preload {
            cleanup: Rc::new(move || {
                record.active.set(false);
                let cleanup = record.cleanup.borrow().clone();
                cleanup();
            }),
            cached: preload.cached,
            complete: preload.complete,
        }
    }

    /// The inspector (`zero.inspector`): the client's queries and metrics
    /// and what zero-cache knows of them, for debugging and tooling.
    pub fn inspector(&self) -> Inspector<C> {
        let host = self
            .core
            .inspector
            .borrow_mut()
            .get_or_insert_with(|| {
                let core = Rc::downgrade(&self.core);
                Rc::new(InspectorHost {
                    engine: Box::new(move || core.upgrade().map(|c| c.engine())),
                    schema: self.core.schema.clone(),
                    admin_password: RefCell::new(None),
                })
            })
            .clone();
        // Evicted queries are kept for it from now on.
        self.engine().query_manager.keep_evicted();
        Inspector {
            host,
            context: self.context.clone(),
            client_id: self.client_id(),
            client_group_id: self.client_group_id(),
        }
    }

    /// Runs a mutator on the client now and sends it to the server. A
    /// mutator not registered with this client doesn't run: both outcomes
    /// are a `ZeroError` saying so. JS throws that error instead.
    pub fn mutate(&self, name: &str, args: Option<Value>) -> MutatorResult {
        let e = self.engine();
        e.event_loop.call(|| e.mutate(name, args))
    }

    /// [`mutate`](Zero::mutate) of a request, such as a `define_mutator`
    /// definition applied to its arguments: JS's and Swift's
    /// `zero.mutate(request)`.
    pub fn mutate_request(&self, request: MutateRequest) -> MutatorResult {
        self.mutate(&request.name, request.args)
    }

    /// Calls `listener` with the server's outcome of each mutation this
    /// client makes, once per mutation, as the server reports it. Returns
    /// the function that removes it.
    ///
    /// Unlike a mutation's `server` result, it hears the outcome of a
    /// mutation sent again after the connection came back: `server` settles
    /// with [`MutationOutcome::ZeroError`](super::MutationOutcome::ZeroError)
    /// when the client gives up connecting
    /// ([`disconnect_timeout_ms`](ZeroOptions::disconnect_timeout_ms)), and
    /// the mutation is replayed when it reconnects. A mutation still pending
    /// when the app quits is replayed when it next launches, but its outcome
    /// isn't reported, nor is a pending mutation's when the client replaces
    /// itself. The listeners stay with the client when it does.
    ///
    /// Use it for a single place that shows rejections, instead of each
    /// `server` result, so a rejection isn't shown twice. To read the
    /// outcomes elsewhere, such as from an async task, send them to a
    /// channel from the listener. Swift's `addMutationOutcomeListener`: the
    /// JS client has no counterpart.
    pub fn add_mutation_outcome_listener(
        &self,
        listener: impl Fn(&MutationServerOutcome) + 'static,
    ) -> Box<dyn Fn()> {
        let id = self.core.outcome_listeners.add(Rc::new(listener));
        let weak = Rc::downgrade(&self.core.outcome_listeners);
        Box::new(move || {
            if let Some(listeners) = weak.upgrade() {
                listeners.remove(id);
            }
        })
    }

    /// The app was shown, or hidden. Hidden for
    /// `ZeroOptions::hidden_disconnect_delay_ms`, the client disconnects
    /// until it is shown again.
    pub fn set_visible(&self, visible: bool) {
        let e = self.engine();
        e.event_loop.call(|| e.set_visible(visible));
    }

    /// The network may be back: reconnect without waiting for the backoff.
    pub fn reconnect_now(&self) {
        let e = self.engine();
        e.event_loop.call(|| e.reconnect_now());
    }

    /// Calls `done` once the server has confirmed every pending mutation,
    /// or when it can't.
    pub fn when_pending_settled(&self, done: impl FnOnce() + 'static) {
        let e = self.engine();
        e.event_loop.call(|| e.when_pending_settled(done));
    }

    /// Runs `body` as a task of the client's event loop: the work it
    /// queues runs before this returns, as after a timer or a socket event.
    #[doc(hidden)]
    pub fn dispatch<T>(&self, body: impl FnOnce() -> T) -> T {
        self.engine().event_loop.dispatch(body)
    }

    /// Closes the connection. Pending mutations and queries fail, and
    /// views stop updating.
    pub fn close(&self) {
        let e = self.engine();
        e.event_loop.call(|| e.close());
    }

    /// Waits for the local store's queued writes, such as before the app
    /// exits. A failure to write them is reported to
    /// `ZeroOptions::on_storage_failure`.
    pub fn flush_storage(&self) {
        self.engine().database.flush();
    }

    /// Closes the client and deletes its local data (`zero.delete()`): the
    /// replica and pending mutations of this user and storage key, under
    /// every schema version. Pending mutations the server hasn't confirmed
    /// are lost. Use it to log a user out.
    pub fn delete(&self) -> DroppedDatabases {
        self.close();
        let name = replicache_name(&self.engine().database.name);
        ReplicaDatabase::drop_matching(&self.core.options.storage, &|n| n == name)
    }
}

impl Core {
    fn engine(&self) -> Rc<Engine> {
        self.engine.borrow().clone()
    }

    /// Hooks `engine` up to the client: the connection hears it needs an
    /// update, the mutation outcome listeners hear its mutations' outcomes,
    /// and the client replaces it when it lost its state.
    fn attach(core: &Rc<Core>, engine: &Rc<Engine>) {
        engine.set_mutation_outcome_listeners(core.outcome_listeners.clone());
        let connection = Rc::downgrade(&core.connection.0);
        *engine.on_update_needed.borrow_mut() = Some(Rc::new(move |reason| {
            if let Some(c) = connection.upgrade() {
                *c.update_needed.borrow_mut() = Some(reason.clone());
            }
        }));
        if core.options.on_client_state_not_found.is_none() {
            let core = Rc::downgrade(core);
            *engine.on_client_state_not_found.borrow_mut() = Some(Rc::new(move || {
                if let Some(core) = core.upgrade() {
                    Core::replace(&core);
                }
            }));
        }
    }

    /// Replaces the engine, which can't sync any longer, by a new one on
    /// the same store, and moves the views and preloads to it.
    fn replace(core: &Rc<Core>) {
        let old = core.engine();
        if old.closed() {
            return;
        }
        // The new engine goes on with the token the app last gave, not the
        // one it started with.
        let mut options = core.options.clone();
        let auth = old.auth.borrow().clone();
        options.auth = (!auth.is_empty()).then_some(auth);
        let new = match Engine::new(
            core.schema.clone(),
            options,
            core.functions.clone(),
            core.scheduler.clone(),
            core.socket_factory.clone(),
            old.visible.get(),
        ) {
            Ok(new) => new,
            Err(e) => {
                old.log
                    .error(|| format!("Failed to replace the client: {e}"));
                return;
            }
        };
        *core.engine.borrow_mut() = new.clone();
        Core::attach(core, &new);
        core.connection.bind(new.clone());
        let views: Vec<_> = {
            let mut views = core.views.borrow_mut();
            views.retain(|(v, _, _)| v.upgrade().is_some_and(|v| !v.is_destroyed()));
            views
                .iter()
                .filter_map(|(v, q, t)| Some((v.upgrade()?, q.clone(), t.clone())))
                .collect()
        };
        for (view, query, ttl) in views {
            if let Ok(fresh) = new
                .event_loop
                .call(|| new.context.materialize(&query, &ttl))
            {
                view.rebind(fresh);
            }
        }
        let preloads: Vec<_> = {
            let mut preloads = core.preloads.borrow_mut();
            preloads.retain(|p| p.active.get());
            preloads.clone()
        };
        for record in preloads {
            let preload = new
                .event_loop
                .call(|| new.context.preload(&record.query, &record.ttl));
            *record.cleanup.borrow_mut() = preload.cleanup;
        }
        old.event_loop.call(|| old.close());
    }
}

impl<C> Drop for Zero<C> {
    /// Dropping the client closes it: otherwise its socket would stay
    /// open, and its timers run, with no client left to hear them.
    fn drop(&mut self) {
        let e = self.core.engine();
        e.event_loop.call(|| e.close());
    }
}

type StateListener = Rc<dyn Fn(&ConnectionState)>;

struct ConnectionInner {
    engine: RefCell<Rc<Engine>>,
    /// Counts the engines bound, so a replaced one isn't heard.
    generation: Cell<u64>,
    state: RefCell<ConnectionState>,
    update_needed: RefCell<Option<UpdateNeededReason>>,
    listeners: RefCell<Vec<(u64, StateListener)>>,
    next_id: Cell<u64>,
}

/// The connection to zero-cache (`Connection` in
/// `packages/zero-client/src/client/connection.ts`).
#[derive(Clone)]
pub struct Connection(Rc<ConnectionInner>);

impl Connection {
    fn new(engine: Rc<Engine>) -> Self {
        let inner = Rc::new(ConnectionInner {
            state: RefCell::new(ConnectionState::of(&engine.connection_manager.state())),
            engine: RefCell::new(engine.clone()),
            generation: Cell::new(0),
            update_needed: RefCell::new(None),
            listeners: RefCell::default(),
            next_id: Cell::new(0),
        });
        let connection = Connection(inner);
        connection.listen(&engine);
        connection
    }

    /// Follows `engine`'s state from now on, and reports it.
    fn bind(&self, engine: Rc<Engine>) {
        *self.0.engine.borrow_mut() = engine.clone();
        self.0.generation.set(self.0.generation.get() + 1);
        self.listen(&engine);
        self.0
            .changed(ConnectionState::of(&engine.connection_manager.state()));
    }

    fn listen(&self, engine: &Engine) {
        let weak = Rc::downgrade(&self.0);
        let generation = self.0.generation.get();
        // The manager lives as long as the engine, which the connection
        // keeps until it binds another.
        let _ = engine.connection_manager.subscribe(move |s| {
            let Some(inner) = weak.upgrade() else { return };
            if inner.generation.get() == generation {
                inner.changed(ConnectionState::of(s));
            }
        });
    }

    /// The state now.
    pub fn state(&self) -> ConnectionState {
        self.0.state.borrow().clone()
    }

    /// Why the app must be updated to sync, once the server said so
    /// (`onUpdateNeeded`). Reconnecting doesn't help.
    pub fn update_needed(&self) -> Option<UpdateNeededReason> {
        self.0.update_needed.borrow().clone()
    }

    /// Calls `listener` on every change of `state`. Returns the function
    /// that removes it.
    pub fn subscribe(&self, listener: impl Fn(&ConnectionState) + 'static) -> Box<dyn Fn()> {
        let id = self.0.next_id.get();
        self.0.next_id.set(id + 1);
        self.0.listeners.borrow_mut().push((id, Rc::new(listener)));
        let weak = Rc::downgrade(&self.0);
        Box::new(move || {
            if let Some(inner) = weak.upgrade() {
                inner.listeners.borrow_mut().retain(|(i, _)| *i != id);
            }
        })
    }

    /// Resumes connecting from `needs-auth` or `error` (`connect` in
    /// `connection.ts`). From any other state it only applies `auth`, and
    /// after a disconnect for a missing `cache_url` it never reconnects.
    ///
    /// `auth` first sets or clears the token, as `connect({auth})` does;
    /// when already connected, the server gets a new non-empty token in
    /// `updateAuth`. A token on a client without a `user_id` is an
    /// [`Error::Connection`] of kind `Internal` (JS's rejection), and
    /// nothing changes.
    ///
    /// It returns once the connection is asked to resume, not once it
    /// has: JS's promise waits for the next state, which
    /// [`subscribe`](Self::subscribe) follows here.
    pub fn connect(&self, auth: ConnectAuth) -> Result<(), Error> {
        let auth = match auth {
            ConnectAuth::Keep => None,
            ConnectAuth::Set(token) => Some(Some(token)),
            ConnectAuth::Clear => Some(None),
        };
        let e = self.0.engine.borrow().clone();
        e.event_loop.call(|| e.connect(auth))
    }
}

/// What [`Connection::connect`] does with the auth token first: the
/// `auth` of `connect({auth})` absent, a string, or `null`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum ConnectAuth {
    /// Keeps the token (no `auth`).
    Keep,
    /// Replaces the token.
    Set(String),
    /// Removes the token (`auth: null`).
    Clear,
}

impl ConnectionInner {
    fn changed(&self, state: ConnectionState) {
        *self.state.borrow_mut() = state.clone();
        let listeners: Vec<_> = self
            .listeners
            .borrow()
            .iter()
            .map(|(_, l)| l.clone())
            .collect();
        for l in listeners {
            l(&state);
        }
    }
}