semiont 0.7.2

Semiont's Rust SDK: the protocol's types, the transport contract and a client of the bus over it, and what a client needs to name its principals and hold its roles, as protocol/specs/ states it.
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
655
656
657
658
659
660
661
662
663
664
665
666
//! A session with one knowledge base: its client, the token the client's
//! transport sends, and who is signed in.
//!
//! Headless: it runs in an application, a script, a daemon and a test alike,
//! and shows nobody anything. What it needs of its environment it is given:
//!
//! - `refresh` renews the token: after it expires, and when the gateway
//!   refuses it. It is given the token the session holds, and answers the
//!   new token, nothing when there is nothing to renew with, or why it
//!   failed.
//! - `validate` asks the gateway who a token is: when the session starts,
//!   and of a token renewed because the gateway refused the one before. A
//!   session of a service has none: there is nobody to ask about.
//! - `on_auth_failed` is told when the session is over, and why: its issuer
//!   refused to renew it (`Expired`), or the gateway refused a token the
//!   issuer had just issued (`Refused`). What a person reads of it is the host's.
//!   `on_error` is told of every failure that makes the session unusable.
//!
//! A session whose issuer refuses to renew it clears its token and what it
//! stored, so a dead credential is never used again. One that never had a credential is
//! only signed out: there is nothing to end, and nothing is said. Whenever a
//! token is renewed, what is stored is forgotten only when the issuer
//! refuses: a renewal that got no answer leaves the session no usable token
//! and keeps what is stored, and the next refusal renews again, and so does
//! the session on its own, on the reconnect backoff.
//!
//! The token is renewed before it expires, by the schedule every Semiont
//! client keeps (`super::refresh_delay`). What another context writes under
//! this knowledge base's key is taken up: a token it renewed, or a sign-out.
//!
//! A session is a state unit: it writes its token and its user, so `dispose`
//! ends them, and stops its renewal. It only uses its client, so it never
//! closes it: whoever built the client and the session closes the client
//! after ending the session. A session that is only dropped ends the same
//! things. A session is built inside a Tokio runtime.

use super::signals::SessionEndReason;
use super::stored::{
    StoredSession, clear_stored_session, is_token_expired, session_key, stored_session,
};
use super::{renew_when_due, token_expiry};
use crate::client::SemiontClient;
use crate::errors::{
    SemiontError, SessionError, SessionErrorCode, SignInError, SignInErrorCode, TransportErrorCode,
};
use crate::locked;
use crate::retry::{REFRESH, RetryFacts, equal_jitter};
use crate::state::{Held, Tasks};
use crate::state_unit::StateUnit;
use crate::storage::{SessionStorage, StorageSubscription};
use crate::timing::{MAX_RECONNECT, RECONNECT};
use crate::transport::{BoxFuture, ConnectionState, Failures};
use crate::types::{KbTarget, UserResponse};
use rand_core::Rng;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};
use std::time::SystemTime;
use tokio::sync::watch;

/// Renew the token the session holds, which it is given (none when it holds
/// none): the new one, `None` when there is nothing to renew with, or why
/// the renewal failed: a `SignInError` of the issuer's answer, or of its
/// absence, or the failure of whatever else the renewal needed.
pub type Refresh = Arc<
    dyn Fn(
            Option<String>,
        )
            -> BoxFuture<'static, Result<Option<String>, Arc<dyn std::error::Error + Send + Sync>>>
        + Send
        + Sync,
>;

/// Ask the gateway who `token` is.
pub type Validate =
    Arc<dyn Fn(String) -> BoxFuture<'static, Result<UserResponse, SemiontError>> + Send + Sync>;

/// Told that the session is over, and why.
pub type OnAuthFailed = Arc<dyn Fn(SessionEndReason) + Send + Sync>;

/// Told of a failure that makes the session unusable.
pub type OnSessionError = Arc<dyn Fn(SessionError) + Send + Sync>;

/// Why a renewal gave no token, for whoever reads the error.
fn not_renewed(failure: Option<&(dyn std::error::Error + Send + Sync)>) -> String {
    match failure {
        Some(failure) => format!("Token refresh failed: {failure}"),
        None => "Token refresh failed".to_owned(),
    }
}

/// Whether a renewal failed because the issuer refused it: an answer the
/// `refresh` rule does not try again. No answer, and one it tries again
/// until the budget is spent, is no refusal.
fn refused(failure: &(dyn std::error::Error + Send + Sync + 'static)) -> bool {
    failure
        .downcast_ref::<SignInError>()
        .is_some_and(|failure| {
            failure.code == SignInErrorCode::Exchange
                && failure.status.is_some()
                && !REFRESH.retryable(&RetryFacts {
                    status: failure.status,
                    method: Some("POST"),
                    keyed: false,
                })
        })
}

/// Why a session failed, and why its credential could not be forgotten.
fn not_forgotten(why: String, forgotten: &(dyn std::error::Error + Send + Sync)) -> String {
    format!("{why}; and the sign-in could not be forgotten: {forgotten}")
}

pub struct SemiontSessionConfig {
    pub kb: KbTarget,
    /// Where the session's tokens are kept.
    pub storage: Arc<dyn SessionStorage>,
    /// The client, already built over its transport.
    pub client: Arc<SemiontClient>,
    /// The token the client's transport sends: the transport holds a
    /// receiver of this sender, and the session writes each renewed token
    /// into it.
    pub token: watch::Sender<Option<String>>,
    pub refresh: Option<Refresh>,
    pub validate: Option<Validate>,
    pub on_auth_failed: Option<OnAuthFailed>,
    pub on_error: Option<OnSessionError>,
    /// What the renewal retry's jitter is drawn from; the system's source
    /// when none is given.
    pub random: Option<Arc<Mutex<dyn Rng + Send>>>,
}

struct Shared {
    id: String,
    kb: KbTarget,
    client: Arc<SemiontClient>,
    storage: Arc<dyn SessionStorage>,
    token: Held<Option<String>>,
    user: Held<Option<UserResponse>>,
    ready: Held<bool>,
    /// Holds while a renewal that got no answer is owed another attempt.
    unanswered: Held<bool>,
    refresh: Option<Refresh>,
    validate: Option<Validate>,
    on_auth_failed: Option<OnAuthFailed>,
    on_error: Option<OnSessionError>,
    random: Option<Arc<Mutex<dyn Rng + Send>>>,
    tasks: Tasks,
    storage_changes: Mutex<Option<StorageSubscription>>,
    closed: AtomicBool,
    /// Held while a refusal is being answered, so that the refusals that
    /// arrive during it are answered by it.
    answering: tokio::sync::Mutex<()>,
}

/// See the module's documentation.
pub struct SemiontSession {
    shared: Arc<Shared>,
}

impl SemiontSession {
    pub fn new(config: SemiontSessionConfig) -> SemiontSession {
        let shared = Arc::new(Shared {
            id: format!("session-{}", uuid::Uuid::new_v4()),
            kb: config.kb,
            client: config.client,
            storage: config.storage,
            token: Held::of(config.token),
            user: Held::new(None),
            ready: Held::new(false),
            unanswered: Held::new(false),
            refresh: config.refresh,
            validate: config.validate,
            on_auth_failed: config.on_auth_failed,
            on_error: config.on_error,
            random: config.random,
            tasks: Tasks::new(),
            storage_changes: Mutex::new(None),
            closed: AtomicBool::new(false),
            answering: tokio::sync::Mutex::new(()),
        });

        // A stored token that is still good is what the transport sends
        // first, unless it was given one already.
        let stored = stored_session(shared.storage.as_ref(), &shared.kb.id);
        if let Some(stored) = &stored
            && !is_token_expired(&stored.access, SystemTime::now())
            && shared.token.now().is_none()
        {
            shared.token.set(Some(stored.access.clone()));
        }

        let renewing = shared.clone();
        shared
            .tasks
            .spawn(renew_when_due(shared.token.read(), move || {
                let shared = renewing.clone();
                async move {
                    shared.renew().await;
                }
            }));

        let retrying = shared.clone();
        shared
            .tasks
            .spawn(async move { retrying.renew_when_unanswered().await });

        let heard = Arc::downgrade(&shared);
        *locked(&shared.storage_changes) = shared.storage.subscribe(Arc::new(move |key, value| {
            if let Some(shared) = heard.upgrade() {
                shared.written_elsewhere(key, value);
            }
        }));

        let starting = shared.clone();
        shared.tasks.spawn(async move {
            starting.validate(stored).await;
            starting.ready.set(true);
        });
        SemiontSession { shared }
    }

    /// Which live session this is: a new one for the same knowledge base has
    /// another. What is derived from a session is kept by this, so it is not
    /// kept past the session it was derived from.
    pub fn id(&self) -> &str {
        &self.shared.id
    }

    pub fn kb(&self) -> &KbTarget {
        &self.shared.kb
    }

    pub fn client(&self) -> &Arc<SemiontClient> {
        &self.shared.client
    }

    /// The token the transport sends: the current one, and each after it.
    pub fn token(&self) -> watch::Receiver<Option<String>> {
        self.shared.token.read()
    }

    /// Who is signed in, once the gateway has said; none for a service.
    pub fn user(&self) -> watch::Receiver<Option<UserResponse>> {
        self.shared.user.read()
    }

    /// The state of the client's connection.
    pub fn stream_state(&self) -> watch::Receiver<ConnectionState> {
        self.shared.client.state()
    }

    /// The failures the client's transport meets, from now on. A host routes
    /// them: a refusal for want of a valid token is a reason to `refresh`.
    pub fn errors(&self) -> Failures {
        self.shared.client.transport().failures()
    }

    /// Resolves when the session has done what it does at its start: renewed
    /// a stored token that had expired, and asked who the token is. It
    /// resolves whatever that came to.
    pub async fn ready(&self) {
        let mut ready = self.shared.ready.read();
        // An ended session is as ready as it will be.
        let _ = ready.wait_for(|ready| *ready).await;
    }

    /// When the token the session holds expires.
    pub fn expires_at(&self) -> Option<SystemTime> {
        token_expiry(&self.shared.token.now()?)
    }

    /// The gateway refused `refused`, the token a request carried (`None`
    /// when it carried none): renew it, and ask the gateway who the new one
    /// is. The token the session then holds, or none: it holds no token, and
    /// if the issuer refused to renew a stored credential it is over. A token
    /// the session no longer holds was answered already, however late the
    /// refusal arrives: the token it holds is given, and nothing is renewed
    /// or asked. See `SessionRenewer`, through which a transport asks.
    pub async fn refresh(&self, refused: Option<&str>) -> Option<String> {
        self.shared.refused(refused).await
    }

    /// A handle that renews this session's token, for the transport under
    /// the session's client: a transport is built before the session that
    /// holds it, and asks through this when the gateway refuses a token.
    pub fn renewer(&self) -> SessionRenewer {
        SessionRenewer {
            shared: Arc::downgrade(&self.shared),
        }
    }
}

impl StateUnit for SemiontSession {
    /// End the session: its renewal stops, it follows its storage no more,
    /// and its token, its user and its readiness end. Its client is left to
    /// whoever built it. Ending twice is ending once.
    fn dispose(&self) {
        self.shared.end();
    }
}

/// A session and the client it was built with, which whoever holds this
/// ends together: what a script's sign-in gives. The session only uses its
/// client, so ending the session alone would leave the client open.
pub struct OpenedSession {
    session: SemiontSession,
}

impl OpenedSession {
    /// The session, over the client it was built with.
    pub fn new(session: SemiontSession) -> OpenedSession {
        OpenedSession { session }
    }

    pub fn session(&self) -> &SemiontSession {
        &self.session
    }

    /// End the session, then close its client. Closing twice is closing
    /// once.
    pub async fn close(&self) {
        self.session.dispose();
        self.session.client().close().await;
    }
}

/// See `SemiontSession::renewer`. It does not keep the session alive: one
/// that has ended renews nothing.
#[derive(Clone)]
pub struct SessionRenewer {
    shared: Weak<Shared>,
}

impl SessionRenewer {
    /// As `SemiontSession::refresh`.
    pub async fn refresh(&self, refused: Option<&str>) -> Option<String> {
        match self.shared.upgrade() {
            Some(shared) => shared.refused(refused).await,
            None => None,
        }
    }
}

impl Drop for SemiontSession {
    fn drop(&mut self) {
        self.shared.end();
    }
}

impl Shared {
    fn closed(&self) -> bool {
        self.closed.load(Ordering::SeqCst)
    }

    /// Stop everything the session runs and end what it holds.
    fn end(&self) {
        if self.closed.swap(true, Ordering::SeqCst) {
            return;
        }
        self.tasks.stop();
        *locked(&self.storage_changes) = None;
        self.token.end();
        self.user.end();
        self.ready.end();
        self.unanswered.end();
    }

    /// Ask `refresh`, with a failure to ask read as there being no token:
    /// a renewal that could not be made and one that was refused both leave
    /// the session without one. The reason is kept for whoever reads why.
    async fn try_refresh(
        &self,
    ) -> (
        Option<String>,
        Option<Arc<dyn std::error::Error + Send + Sync>>,
    ) {
        match &self.refresh {
            None => (None, None),
            Some(refresh) => match refresh(self.token.now()).await {
                Ok(token) => (token, None),
                Err(failure) => (None, Some(failure)),
            },
        }
    }

    /// Renew the token at the issuer, with nobody asked afterwards: what
    /// the session does on its own schedule, where no refusal came first.
    async fn renew(&self) -> Option<String> {
        if self.closed() || self.refresh.is_none() {
            return None;
        }
        let (renewed, failure) = self.try_refresh().await;
        if self.closed() {
            return None;
        }
        if let Some(token) = renewed {
            self.unanswered.set(false);
            self.token.set(Some(token.clone()));
            return Some(token);
        }
        self.token.set(None);
        // A session that never had a credential cannot expire: it is signed
        // out, which is no failure. Ending the session below also clears the
        // credential, so the refusals that follow it are quiet too.
        if stored_session(self.storage.as_ref(), &self.kb.id).is_none() {
            self.unanswered.set(false);
            return None;
        }
        self.unrenewed(failure);
        None
    }

    /// After a renewal that got no answer, renew again on the reconnect
    /// backoff: each wait is the equal jitter of its step, the step
    /// `RECONNECT` doubling to `MAX_RECONNECT`. It stops when a renewal is
    /// made or refused, when a token arrives some other way, and when the
    /// session ends. A renewal made while nobody has said who the session's
    /// token is asks the gateway once, as the start would have.
    async fn renew_when_unanswered(&self) {
        let mut owed = self.unanswered.read();
        loop {
            if owed.wait_for(|owed| *owed).await.is_err() {
                return;
            }
            let mut step = RECONNECT;
            while self.unanswered.now() {
                tokio::time::sleep(equal_jitter(step, self.random.as_deref())).await;
                if self.token.now().is_some() {
                    self.unanswered.set(false);
                } else if self.unanswered.now() {
                    if self.user.now().is_none() {
                        self.refused(None).await;
                    } else {
                        self.renew().await;
                    }
                }
                step = (step * 2).min(MAX_RECONNECT);
            }
        }
    }

    /// A renewal of what is stored gave no token, and the session holds
    /// none. The issuer's refusal, or nothing left to renew with, ends the
    /// session; any other failure keeps what is stored, and says why: the
    /// next refusal renews again, and so does the reconnect backoff.
    fn unrenewed(&self, failure: Option<Arc<dyn std::error::Error + Send + Sync>>) {
        self.token.set(None);
        let why = not_renewed(failure.as_deref());
        match failure {
            Some(failure) if !refused(failure.as_ref()) => {
                self.unanswered.set(true);
                self.failed(SessionErrorCode::RefreshExhausted, why);
            }
            _ => self.signed_out(
                SessionEndReason::Expired,
                SessionErrorCode::RefreshExhausted,
                why,
            ),
        }
    }

    /// The gateway refused the session's token: renew it, and ask the
    /// gateway who the new one is. The rule is the start's
    /// (protocol/specs/src/session/cases.json, `refusal`): a token the issuer has
    /// just issued and the gateway refuses is final, and the session ends as
    /// `CredentialRefused`. So one refusal costs at most one renewal and one
    /// ask, and a gateway that refuses whatever its issuer issues is not
    /// asked again for every request that follows. Who the gateway says the
    /// renewed token is, is who is signed in. A gateway that cannot be asked
    /// refuses nothing: the renewed token is given. A session of a service,
    /// which has nobody to ask about, only renews.
    ///
    /// One refusal is answered at a time, so however many requests were
    /// refused at once, they cost one renewal and one ask. A refusal of a
    /// token the session no longer holds was answered already: the token it
    /// holds is given.
    async fn refused(&self, refused: Option<&str>) -> Option<String> {
        let _answering = self.answering.lock().await;
        let held = self.token.now();
        if held.as_deref() != refused {
            return held;
        }
        let renewed = self.renew().await?;
        let Some(validate) = &self.validate else {
            return Some(renewed);
        };
        // While the session is starting, its start is what asks: it finds
        // the token renewed here and takes it up as the just-issued one.
        // Asking here too would be a second ask about one renewal.
        if !self.ready.now() {
            return Some(renewed);
        }
        let answer = validate(renewed.clone()).await;
        if self.closed() {
            return None;
        }
        // Only a token the session still holds is its to be refused, or to say
        // who it is: one replaced while the gateway was being asked (another
        // context signed in, or renewed) is not.
        if self.token.now().as_deref() == Some(renewed.as_str()) {
            match answer {
                Ok(user) => self.user.set(Some(user)),
                Err(SemiontError::Transport(refusal))
                    if refusal.code == TransportErrorCode::Unauthorized =>
                {
                    self.signed_out(
                        SessionEndReason::Refused,
                        SessionErrorCode::CredentialRefused,
                        "The gateway refused a token its issuer had just issued".to_owned(),
                    );
                }
                Err(_) => {}
            }
        }
        self.token.now()
    }

    /// The session is over: its credential is forgotten, and the person and
    /// the application are each told why. The one teardown, whichever way
    /// the session ended.
    fn signed_out(&self, told: SessionEndReason, code: SessionErrorCode, why: String) {
        self.unanswered.set(false);
        self.token.set(None);
        let why = match clear_stored_session(self.storage.as_ref(), &self.kb.id) {
            Ok(()) => why,
            Err(forgotten) => not_forgotten(why, forgotten.as_ref()),
        };
        if let Some(on_auth_failed) = &self.on_auth_failed {
            on_auth_failed(told);
        }
        self.failed(code, why);
    }

    fn failed(&self, code: SessionErrorCode, message: String) {
        if let Some(on_error) = &self.on_error {
            on_error(SessionError::new(code, message, &self.kb.id));
        }
    }

    /// What a session does at its start, with the credential it found
    /// stored: renew it if it has expired, then ask the gateway who it is.
    /// A token the gateway refuses is renewed once and asked about once
    /// more. A token the issuer has just issued and the gateway refuses is
    /// final: renewing again cannot change the answer, and asking for as
    /// long as the issuer goes on issuing is a loop with no end. So the
    /// gateway is asked at most twice and the issuer at most once
    /// (protocol/specs/src/session/cases.json, `startup`).
    async fn validate(&self, stored: Option<StoredSession>) {
        let Some(stored) = stored else { return };
        let expired = is_token_expired(&stored.access, SystemTime::now());
        let mut token = if expired {
            match self.try_refresh().await {
                (Some(renewed), _) => renewed,
                (None, Some(failure)) if !refused(failure.as_ref()) => {
                    // The issuer did not refuse it: the credential is kept,
                    // and renewed on the reconnect backoff or when a request
                    // is refused.
                    self.unanswered.set(true);
                    self.failed(
                        SessionErrorCode::AuthFailed,
                        not_renewed(Some(failure.as_ref())),
                    );
                    return;
                }
                (None, failure) => {
                    // There was no session to end: the credential is
                    // forgotten, and nothing is said unless it could not be.
                    if let Err(forgotten) = clear_stored_session(self.storage.as_ref(), &self.kb.id)
                    {
                        self.failed(
                            SessionErrorCode::RefreshExhausted,
                            not_forgotten(not_renewed(failure.as_deref()), forgotten.as_ref()),
                        );
                    }
                    return;
                }
            }
        } else {
            stored.access.clone()
        };
        if token != stored.access {
            self.token.set(Some(token.clone()));
        }
        let Some(validate) = &self.validate else {
            return;
        };
        let mut just_issued = expired;
        loop {
            if self.closed() {
                return;
            }
            let answer = validate(token.clone()).await;
            if self.closed() {
                return;
            }
            match answer {
                Ok(user) => {
                    self.user.set(Some(user));
                    return;
                }
                Err(SemiontError::Transport(refusal))
                    if refusal.code == TransportErrorCode::Unauthorized =>
                {
                    if just_issued {
                        self.signed_out(
                            SessionEndReason::Refused,
                            SessionErrorCode::CredentialRefused,
                            "The gateway refused a token its issuer had just issued".to_owned(),
                        );
                        return;
                    }
                    // The session's token is no longer the one asked about:
                    // the stream was refused with it too, and `refused` has
                    // renewed it meanwhile. That token is the just-issued
                    // one, and is not renewed again.
                    let current = self.token.now();
                    if current.as_deref() != Some(token.as_str()) {
                        let Some(current) = current else { return };
                        token = current;
                        just_issued = true;
                        continue;
                    }
                    let (renewed, failure) = self.try_refresh().await;
                    if self.closed() {
                        return;
                    }
                    match renewed {
                        Some(renewed) => {
                            self.token.set(Some(renewed.clone()));
                            token = renewed;
                            just_issued = true;
                        }
                        None => {
                            self.unrenewed(failure);
                            return;
                        }
                    }
                }
                Err(other) => {
                    self.failed(SessionErrorCode::AuthFailed, other.to_string());
                    return;
                }
            }
        }
    }

    /// Another context wrote this knowledge base's session: it renewed the
    /// token, or signed out.
    fn written_elsewhere(&self, key: &str, value: Option<&str>) {
        if self.closed() || key != session_key(&self.kb.id) {
            return;
        }
        match value {
            None => {
                self.token.set(None);
                self.user.set(None);
            }
            Some(written) => {
                // What is not a session is nobody's news.
                if let Some(session) = StoredSession::read(written) {
                    self.token.set(Some(session.access));
                }
            }
        }
    }
}