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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! The cache against protocol/contract/CACHE-SEMANTICS.md, behaviour by
//! behaviour: each test names the clause it holds. The service is a script,
//! so a test decides what each fetch is answered and when.
//!
//! An observer here is read as a watcher reads it: its state now, then each
//! state after. A run of changes nobody read between is its last, so a test
//! that must see a state reads the observer before it causes the next.

use futures_core::Stream;
use semiont::cache::{Cache, CachePersister, CacheState, StoragePersister};
use semiont::errors::{BusRequestError, BusRequestErrorCode, SemiontError};
use semiont::state_unit::StateUnit;
use semiont::storage::{InMemorySessionStorage, SessionStorage};
use semiont::testing::axioms::{
    AxiomSubject, Fresh, StreamSurface, Surface, assert_state_unit_axioms,
};
use semiont::timing::{MAX_STORED_BYTES_COUNT, SAVE_DEBOUNCE};
use semiont::transport::BoxFuture;
use serde_json::{Value, json};
use std::collections::{HashMap, VecDeque};
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::oneshot;
use tokio_stream::wrappers::WatchStream;

type Answer = Result<String, SemiontError>;

fn refused(why: &str) -> SemiontError {
    BusRequestError::new(BusRequestErrorCode::Rejected, why).into()
}

enum Scripted {
    Now(Answer),
    When(oneshot::Receiver<Answer>),
}

/// What the cache fetches from: it answers what was scripted, in order, and
/// once the script is spent answers `<key>-v<n>`, the n-th ask of all.
#[derive(Clone, Default)]
struct Service {
    asked: Arc<Mutex<Vec<String>>>,
    script: Arc<Mutex<VecDeque<Scripted>>>,
}

impl Service {
    fn fetching(
        &self,
    ) -> impl Fn(
        String,
    ) -> BoxFuture<'static, Result<String, Box<dyn std::error::Error + Send + Sync>>>
    + Send
    + Sync
    + 'static {
        let service = self.clone();
        move |key: String| {
            let number = {
                let mut asked = service.asked.lock().expect("asked");
                asked.push(key.clone());
                asked.len()
            };
            let scripted = service.script.lock().expect("script").pop_front();
            Box::pin(async move {
                let answer = match scripted {
                    None => Ok(format!("{key}-v{number}")),
                    Some(Scripted::Now(answer)) => answer,
                    Some(Scripted::When(answer)) => answer
                        .await
                        .unwrap_or_else(|_| Err(refused("never answered"))),
                };
                answer.map_err(Into::into)
            })
        }
    }

    fn cache(&self) -> Cache<String, String> {
        Cache::new(self.fetching())
    }

    /// The next ask is answered this.
    fn then(&self, answer: Answer) {
        self.script
            .lock()
            .expect("script")
            .push_back(Scripted::Now(answer));
    }

    /// The next ask waits for what is sent here.
    fn hold(&self) -> oneshot::Sender<Answer> {
        let (answer, answered) = oneshot::channel();
        self.script
            .lock()
            .expect("script")
            .push_back(Scripted::When(answered));
        answer
    }

    fn asked(&self) -> usize {
        self.asked.lock().expect("asked").len()
    }

    fn asked_for(&self, key: &str) -> usize {
        self.asked
            .lock()
            .expect("asked")
            .iter()
            .filter(|asked| *asked == key)
            .count()
    }
}

fn key(name: &str) -> String {
    name.to_owned()
}

fn ready(value: &str) -> CacheState<String> {
    CacheState::Ready(value.to_owned())
}

/// A one-shot read's value, or what its failure says.
fn read(
    fetched: Result<String, Arc<dyn std::error::Error + Send + Sync>>,
) -> Result<String, String> {
    fetched.map_err(|failure| failure.to_string())
}

/// What a failed state says failed; none for a state that has not failed.
fn failure<T>(state: &CacheState<T>) -> Option<String> {
    match state {
        CacheState::Failed(failure) => Some(failure.to_string()),
        CacheState::Pending | CacheState::Ready(_) => None,
    }
}

/// Let what is ready run: fetches are answered and their states written.
async fn settle() {
    tokio::time::sleep(Duration::from_millis(1)).await;
}

/// The observer's next state, or `None` at its end. An observer that is
/// given neither is a failure, not a wait: an hour of the test's clock is
/// longer than anything here takes.
async fn next<T>(stream: &mut (impl Stream<Item = T> + Unpin)) -> Option<T> {
    tokio::time::timeout(
        Duration::from_secs(3600),
        std::future::poll_fn(|cx| Pin::new(&mut *stream).poll_next(cx)),
    )
    .await
    .expect("the observer is given a state")
}

/// The state the observer holds once what is ready has run.
async fn holds(observer: &mut WatchStream<CacheState<String>>) -> CacheState<String> {
    settle().await;
    let mut held = None;
    while let Ok(Some(state)) = tokio::time::timeout(Duration::from_millis(1), next(observer)).await
    {
        held = Some(state);
    }
    held.expect("an observer always holds a state")
}

/// Whether the observer's stream has ended.
async fn ended(observer: &mut WatchStream<CacheState<String>>) -> bool {
    loop {
        match tokio::time::timeout(Duration::from_millis(5), next(observer)).await {
            Ok(None) => return true,
            Ok(Some(_)) => {}
            Err(_) => return false,
        }
    }
}

// ── B1–B3: observing ────────────────────────────────────────────────────

#[tokio::test(start_paused = true)]
async fn b1_the_first_observation_fetches_and_is_pending_until_it_is_answered() {
    let service = Service::default();
    let answer = service.hold();
    let cache = service.cache();

    let mut observer = cache.observe(&key("a"));
    assert_eq!(holds(&mut observer).await, CacheState::Pending);
    assert_eq!(service.asked(), 1);

    answer.send(Ok(key("one"))).expect("the fetch is waiting");
    assert_eq!(holds(&mut observer).await, ready("one"));
    assert_eq!(service.asked(), 1);
}

#[tokio::test(start_paused = true)]
async fn b2_a_later_observation_is_given_the_value_and_fetches_nothing() {
    let service = Service::default();
    let cache = service.cache();
    let mut first = cache.observe(&key("a"));
    assert_eq!(holds(&mut first).await, ready("a-v1"));

    let mut later = cache.observe(&key("a"));
    assert_eq!(next(&mut later).await, Some(ready("a-v1")));
    settle().await;
    assert_eq!(service.asked(), 1);
}

#[tokio::test(start_paused = true)]
async fn b3_observers_arriving_together_share_one_fetch() {
    let service = Service::default();
    let answer = service.hold();
    let cache = service.cache();
    let mut one = cache.observe(&key("a"));
    let mut other = cache.observe(&key("a"));
    settle().await;
    assert_eq!(service.asked(), 1);

    answer
        .send(Ok(key("shared")))
        .expect("the fetch is waiting");
    assert_eq!(holds(&mut one).await, ready("shared"));
    assert_eq!(holds(&mut other).await, ready("shared"));
}

// ── B5–B10: values, failures, invalidation ──────────────────────────────

#[tokio::test(start_paused = true)]
async fn b5_b7_an_invalidated_key_shows_its_value_until_the_new_one_arrives_and_is_never_pending() {
    let service = Service::default();
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    assert_eq!(holds(&mut observer).await, ready("a-v1"));

    let answer = service.hold();
    cache.invalidate(&key("a"));
    // The refetch is in flight, and the observer was given nothing new.
    settle().await;
    assert_eq!(service.asked(), 2);
    assert!(
        tokio::time::timeout(Duration::from_millis(1), next(&mut observer))
            .await
            .is_err()
    );
    assert_eq!(cache.get(&key("a")), Some(key("a-v1")));

    answer
        .send(Ok(key("newer")))
        .expect("the refetch is waiting");
    assert_eq!(next(&mut observer).await, Some(ready("newer")));
}

#[tokio::test(start_paused = true)]
async fn b6_a_failed_refetch_leaves_the_value_there_was() {
    let service = Service::default();
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    assert_eq!(holds(&mut observer).await, ready("a-v1"));

    service.then(Err(refused("down")));
    service.then(Err(refused("still down")));
    cache.invalidate(&key("a"));
    settle().await;
    // Tried, and tried once more (B14), and the value is still what is shown.
    assert_eq!(service.asked(), 3);
    assert_eq!(cache.get(&key("a")), Some(key("a-v1")));
    assert_eq!(holds(&mut cache.observe(&key("a"))).await, ready("a-v1"));
}

#[tokio::test(start_paused = true)]
async fn b8_invalidating_a_key_nothing_asked_for_fetches_it() {
    let service = Service::default();
    let cache = service.cache();
    cache.invalidate(&key("a"));
    settle().await;
    assert_eq!(service.asked(), 1);
    assert_eq!(cache.get(&key("a")), Some(key("a-v1")));
}

#[tokio::test(start_paused = true)]
async fn b9_an_invalidate_does_not_wait_on_the_fetch_in_flight_and_the_last_answer_stands() {
    let service = Service::default();
    let orphaned = service.hold();
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    settle().await;
    assert_eq!(service.asked(), 1);

    // The fetch in flight may never be answered: the invalidate asks anyway.
    let second = service.hold();
    cache.invalidate(&key("a"));
    settle().await;
    assert_eq!(service.asked(), 2);

    second
        .send(Ok(key("second")))
        .expect("the second fetch is waiting");
    assert_eq!(holds(&mut observer).await, ready("second"));
    // The first, answered after all, is written too: either is at least as
    // new as what was there before.
    orphaned
        .send(Ok(key("first, late")))
        .expect("the first fetch is waiting");
    assert_eq!(holds(&mut observer).await, ready("first, late"));
}

#[tokio::test(start_paused = true)]
async fn b10_keys_are_independent() {
    let service = Service::default();
    let cache = service.cache();
    let mut a = cache.observe(&key("a"));
    let mut b = cache.observe(&key("b"));
    assert_eq!(holds(&mut a).await, ready("a-v1"));
    assert_eq!(holds(&mut b).await, ready("b-v2"));

    service.then(Err(refused("a is down")));
    service.then(Err(refused("a is down")));
    cache.invalidate(&key("a"));
    settle().await;
    assert_eq!(service.asked_for("b"), 1);
    assert_eq!(cache.get(&key("b")), Some(key("b-v2")));
}

// ── B13a, B13b: remove and set ──────────────────────────────────────────

#[tokio::test(start_paused = true)]
async fn b13a_a_removed_key_fails_at_once_with_what_it_was_given_and_nothing_is_asked() {
    let service = Service::default();
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    assert_eq!(holds(&mut observer).await, ready("a-v1"));

    cache.remove(&key("a"), refused("gone").into());
    // Straight from ready: no pending with no request behind it.
    assert_eq!(
        next(&mut observer).await.as_ref().and_then(failure),
        Some("gone".to_owned())
    );
    settle().await;
    assert_eq!(service.asked(), 1);
    assert_eq!(cache.get(&key("a")), None);
    assert!(cache.known(&key("a")));
}

#[tokio::test(start_paused = true)]
async fn b13a_an_observer_arriving_at_a_removed_key_asks_the_service() {
    let service = Service::default();
    let cache = service.cache();
    let mut present = cache.observe(&key("a"));
    holds(&mut present).await;
    cache.remove(&key("a"), refused("gone").into());

    let mut arriving = cache.observe(&key("a"));
    assert_eq!(next(&mut arriving).await, Some(CacheState::Pending));
    assert_eq!(holds(&mut arriving).await, ready("a-v2"));
    assert_eq!(service.asked(), 2);
}

#[tokio::test(start_paused = true)]
async fn b13b_a_written_value_is_shown_and_nothing_is_asked() {
    let service = Service::default();
    let cache = service.cache();
    cache.set(&key("a"), key("written"));
    assert_eq!(cache.get(&key("a")), Some(key("written")));

    let mut observer = cache.observe(&key("a"));
    assert_eq!(next(&mut observer).await, Some(ready("written")));
    settle().await;
    assert_eq!(service.asked(), 0);
}

// ── keys, invalidate_all ────────────────────────────────────────────────

#[tokio::test(start_paused = true)]
async fn b20_a_key_is_known_from_the_moment_it_is_asked_for_and_a_failed_key_is_known() {
    let service = Service::default();
    let answer = service.hold();
    let cache = service.cache();
    assert!(!cache.known(&key("a")));
    assert!(cache.keys().is_empty());

    let _observer = cache.observe(&key("a"));
    assert!(cache.known(&key("a")));
    assert_eq!(cache.keys(), [key("a")]);
    answer
        .send(Err(refused("down")))
        .expect("the fetch is waiting");
    service.then(Err(refused("down")));
    settle().await;
    assert_eq!(cache.keys(), [key("a")]);
    assert_eq!(cache.get(&key("a")), None);
}

#[tokio::test(start_paused = true)]
async fn invalidate_all_asks_again_for_each_key_it_knows_a_failed_one_included() {
    let service = Service::default();
    let cache = service.cache();
    holds(&mut cache.observe(&key("a"))).await;
    service.then(Err(refused("down")));
    service.then(Err(refused("down")));
    let mut failed = cache.observe(&key("b"));
    assert!(matches!(holds(&mut failed).await, CacheState::Failed(_)));
    let before = service.asked();

    cache.invalidate_all();
    settle().await;
    assert_eq!(service.asked(), before + 2);
    assert_eq!(service.asked_for("never-asked"), 0);
    assert!(holds(&mut failed).await.is_ready());
}

// ── fetch: the one-shot read ────────────────────────────────────────────

#[tokio::test(start_paused = true)]
async fn a_one_shot_read_always_asks_and_its_observers_are_given_the_answer() {
    let service = Service::default();
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    assert_eq!(holds(&mut observer).await, ready("a-v1"));

    assert_eq!(read(cache.fetch(&key("a")).await), Ok(key("a-v2")));
    assert_eq!(holds(&mut observer).await, ready("a-v2"));
}

#[tokio::test(start_paused = true)]
async fn one_shot_reads_made_together_share_one_fetch() {
    let service = Service::default();
    let answer = service.hold();
    let cache = service.cache();
    let one = tokio::spawn(cache.fetch(&key("a")));
    let other = tokio::spawn(cache.fetch(&key("a")));
    settle().await;
    assert_eq!(service.asked(), 1);
    answer
        .send(Ok(key("shared")))
        .expect("the fetch is waiting");
    assert_eq!(read(one.await.expect("the read ran")), Ok(key("shared")));
    assert_eq!(read(other.await.expect("the read ran")), Ok(key("shared")));
}

#[tokio::test(start_paused = true)]
async fn b14_a_one_shot_read_that_fails_is_not_tried_again_and_fails_only_its_caller() {
    let service = Service::default();
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    assert_eq!(holds(&mut observer).await, ready("a-v1"));

    service.then(Err(refused("down")));
    assert_eq!(read(cache.fetch(&key("a")).await), Err("down".to_owned()));
    settle().await;
    assert_eq!(service.asked(), 2);
    assert_eq!(cache.get(&key("a")), Some(key("a-v1")));
}

// ── B14, B15: the retry, and the failure of a key with no value ─────────

#[tokio::test(start_paused = true)]
async fn b14_a_failed_fetch_is_tried_once_more_and_its_observers_recover() {
    let service = Service::default();
    service.then(Err(refused("a blip")));
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    assert_eq!(holds(&mut observer).await, ready("a-v2"));
    assert_eq!(service.asked(), 2);
}

#[tokio::test(start_paused = true)]
async fn b14_b15_a_key_that_keeps_failing_is_failed_after_one_retry_and_no_more_is_asked() {
    let service = Service::default();
    service.then(Err(refused("down")));
    service.then(Err(refused("still down")));
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    assert_eq!(
        failure(&holds(&mut observer).await),
        Some("still down".to_owned())
    );
    tokio::time::sleep(Duration::from_secs(60)).await;
    assert_eq!(service.asked(), 2);
    // The stream lives through the failure.
    assert!(!ended(&mut observer).await);
}

/// A failure of the host's own: no `SemiontError`.
#[derive(Debug)]
struct Unreadable;

impl std::fmt::Display for Unreadable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("the disk could not be read")
    }
}

impl std::error::Error for Unreadable {}

#[tokio::test(start_paused = true)]
async fn b14_b15_any_failure_of_a_fetch_is_the_keys_after_one_retry() {
    let asked = Arc::new(Mutex::new(0));
    let counting = asked.clone();
    let cache: Cache<String, String> = Cache::new(move |_| {
        *counting.lock().expect("asked") += 1;
        async { Err(Unreadable.into()) }
    });
    let mut observer = cache.observe(&key("a"));

    match holds(&mut observer).await {
        CacheState::Failed(failure) => assert!(failure.downcast_ref::<Unreadable>().is_some()),
        other => panic!("the key was to fail, not be {other:?}"),
    }
    assert_eq!(*asked.lock().expect("asked"), 2);
    // A one-shot read is given it too, as it is.
    let fetched = cache.fetch(&key("a")).await;
    assert!(
        fetched
            .err()
            .is_some_and(|failure| failure.downcast_ref::<Unreadable>().is_some())
    );
}

#[tokio::test(start_paused = true)]
async fn b15_an_observer_arriving_at_a_failed_key_starts_over_and_the_one_present_is_pending_too() {
    let service = Service::default();
    service.then(Err(refused("down")));
    service.then(Err(refused("down")));
    let cache = service.cache();
    let mut present = cache.observe(&key("a"));
    assert!(matches!(holds(&mut present).await, CacheState::Failed(_)));

    let answer = service.hold();
    let mut arriving = cache.observe(&key("a"));
    assert_eq!(next(&mut arriving).await, Some(CacheState::Pending));
    assert_eq!(next(&mut present).await, Some(CacheState::Pending));

    answer
        .send(Ok(key("recovered")))
        .expect("the fetch is waiting");
    assert_eq!(holds(&mut arriving).await, ready("recovered"));
    assert_eq!(holds(&mut present).await, ready("recovered"));
}

#[tokio::test(start_paused = true)]
async fn b15_a_recovery_that_fails_again_gives_every_observer_its_own_failure() {
    let service = Service::default();
    for why in ["first", "first again", "second", "second again"] {
        service.then(Err(refused(why)));
    }
    let cache = service.cache();
    let mut present = cache.observe(&key("a"));
    assert_eq!(
        failure(&holds(&mut present).await),
        Some("first again".to_owned())
    );
    let mut arriving = cache.observe(&key("a"));
    assert_eq!(
        failure(&holds(&mut arriving).await),
        Some("second again".to_owned())
    );
    assert_eq!(
        failure(&holds(&mut present).await),
        Some("second again".to_owned())
    );
}

#[tokio::test(start_paused = true)]
async fn b15_invalidate_returns_a_failed_key_to_pending_and_a_value_moves_it_straight_to_ready() {
    let service = Service::default();
    service.then(Err(refused("down")));
    service.then(Err(refused("down")));
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    assert!(matches!(holds(&mut observer).await, CacheState::Failed(_)));

    let answer = service.hold();
    cache.invalidate(&key("a"));
    assert_eq!(next(&mut observer).await, Some(CacheState::Pending));
    answer
        .send(Err(refused("down")))
        .expect("the fetch is waiting");
    service.then(Err(refused("down")));
    assert!(matches!(holds(&mut observer).await, CacheState::Failed(_)));

    // A value written to a failed key: ready, with no pending between.
    cache.set(&key("a"), key("written"));
    assert_eq!(next(&mut observer).await, Some(ready("written")));
}

#[tokio::test(start_paused = true)]
async fn b15_a_one_shot_read_that_succeeds_ends_the_failure_for_everyone() {
    let service = Service::default();
    service.then(Err(refused("down")));
    service.then(Err(refused("down")));
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    assert!(matches!(holds(&mut observer).await, CacheState::Failed(_)));

    assert_eq!(read(cache.fetch(&key("a")).await), Ok(key("a-v3")));
    assert_eq!(next(&mut observer).await, Some(ready("a-v3")));
    // And a later observer is given the value, asking nothing.
    assert_eq!(
        next(&mut cache.observe(&key("a"))).await,
        Some(ready("a-v3"))
    );
    settle().await;
    assert_eq!(service.asked(), 3);
}

// ── B16: disposal ───────────────────────────────────────────────────────

#[tokio::test(start_paused = true)]
async fn b16_disposal_ends_every_observer_and_a_fetch_that_straddles_it_goes_quiet() {
    let service = Service::default();
    let straddling = service.hold();
    let cache = service.cache();
    let mut observer = cache.observe(&key("a"));
    assert_eq!(holds(&mut observer).await, CacheState::Pending);

    cache.dispose();
    cache.dispose();
    assert!(ended(&mut observer).await);

    // The fetch in flight fails after disposal: not tried again, and no
    // failure is given to anyone.
    straddling
        .send(Err(refused("closed under it")))
        .expect("the fetch is waiting");
    tokio::time::sleep(Duration::from_secs(1)).await;
    assert_eq!(service.asked(), 1);
}

#[tokio::test(start_paused = true)]
async fn b16_a_disposed_cache_asks_nothing_and_a_one_shot_read_of_it_fails_as_closed() {
    let service = Service::default();
    let cache = service.cache();
    holds(&mut cache.observe(&key("a"))).await;
    cache.dispose();

    assert!(ended(&mut cache.observe(&key("a"))).await);
    cache.invalidate(&key("a"));
    cache.invalidate_all();
    cache.set(&key("a"), key("written"));
    cache.remove(&key("a"), refused("gone").into());
    let refusal = cache.fetch(&key("a")).await.expect_err("it is closed");
    assert_eq!(
        refusal
            .downcast_ref::<SemiontError>()
            .map(SemiontError::code),
        Some("bus.closed")
    );
    settle().await;
    assert_eq!(service.asked(), 1);
    assert_eq!(cache.get(&key("a")), None);
    assert!(cache.keys().is_empty());
}

// ── B17, B18: persistence ───────────────────────────────────────────────

/// A persister that keeps what it is given, and counts; while it is full, it
/// counts each save and keeps none.
#[derive(Default)]
struct Kept {
    stored: Mutex<Option<HashMap<String, String>>>,
    saves: Mutex<Vec<HashMap<String, String>>>,
    full: AtomicBool,
}

impl Kept {
    fn with(entries: &[(&str, &str)]) -> Arc<Kept> {
        Arc::new(Kept {
            stored: Mutex::new(Some(
                entries
                    .iter()
                    .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
                    .collect(),
            )),
            ..Kept::default()
        })
    }

    fn saves(&self) -> Vec<HashMap<String, String>> {
        self.saves.lock().expect("saves").clone()
    }
}

impl CachePersister<String, String> for Kept {
    fn load(&self) -> Option<HashMap<String, String>> {
        self.stored.lock().expect("stored").clone()
    }

    fn save(
        &self,
        entries: &HashMap<String, String>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        self.saves.lock().expect("saves").push(entries.clone());
        if self.full.load(Ordering::SeqCst) {
            return Err("the storage is full".into());
        }
        Ok(())
    }
}

fn persisted(service: &Service, kept: &Arc<Kept>) -> Cache<String, String> {
    Cache::persisted(service.fetching(), kept.clone(), SAVE_DEBOUNCE)
}

#[tokio::test(start_paused = true)]
async fn b17_b18_a_kept_value_is_shown_at_once_and_asked_for_again_once() {
    let service = Service::default();
    let kept = Kept::with(&[("a", "from before"), ("b", "also kept")]);
    let cache = persisted(&service, &kept);
    assert_eq!(cache.get(&key("a")), Some(key("from before")));
    assert_eq!(service.asked(), 0);

    let answer = service.hold();
    let mut observer = cache.observe(&key("a"));
    // At once, and never pending.
    assert_eq!(next(&mut observer).await, Some(ready("from before")));
    settle().await;
    assert_eq!(service.asked(), 1);
    answer
        .send(Ok(key("as it is now")))
        .expect("the revalidation is waiting");
    assert_eq!(holds(&mut observer).await, ready("as it is now"));

    // Once: a later observer asks nothing, and a key nobody looks at is
    // never asked for.
    holds(&mut cache.observe(&key("a"))).await;
    assert_eq!(service.asked(), 1);
    assert_eq!(service.asked_for("b"), 0);
}

#[tokio::test(start_paused = true)]
async fn b18_a_kept_value_whose_revalidation_fails_is_still_shown() {
    let service = Service::default();
    service.then(Err(refused("down")));
    service.then(Err(refused("down")));
    let kept = Kept::with(&[("a", "from before")]);
    let cache = persisted(&service, &kept);
    let mut observer = cache.observe(&key("a"));
    assert_eq!(holds(&mut observer).await, ready("from before"));
    assert_eq!(service.asked(), 2);
}

#[tokio::test(start_paused = true)]
async fn b17_a_burst_of_changes_is_one_save_and_failures_are_never_saved() {
    let service = Service::default();
    let kept = Arc::new(Kept::default());
    let cache = persisted(&service, &kept);
    cache.set(&key("a"), key("one"));
    cache.set(&key("a"), key("two"));
    cache.set(&key("b"), key("three"));
    assert!(cache.persistence_pending());
    assert!(kept.saves().is_empty());

    tokio::time::sleep(SAVE_DEBOUNCE * 2).await;
    assert!(!cache.persistence_pending());
    let expected: HashMap<String, String> =
        [(key("a"), key("two")), (key("b"), key("three"))].into();
    assert_eq!(kept.saves(), std::slice::from_ref(&expected));

    // A key that failed holds no value, so there is nothing of it to save.
    service.then(Err(refused("down")));
    service.then(Err(refused("down")));
    holds(&mut cache.observe(&key("failed"))).await;
    tokio::time::sleep(SAVE_DEBOUNCE * 2).await;
    assert_eq!(kept.saves(), [expected]);
}

#[tokio::test(start_paused = true)]
async fn b17_a_save_that_fails_leaves_the_cache_as_it_was_and_the_next_save_tries_again() {
    let service = Service::default();
    let kept = Arc::new(Kept::default());
    kept.full.store(true, Ordering::SeqCst);
    let cache = persisted(&service, &kept);
    cache.set(&key("a"), key("one"));
    tokio::time::sleep(SAVE_DEBOUNCE * 2).await;
    assert_eq!(kept.saves().len(), 1);
    assert!(!cache.persistence_pending());
    assert_eq!(cache.get(&key("a")), Some(key("one")));

    kept.full.store(false, Ordering::SeqCst);
    cache.set(&key("b"), key("two"));
    tokio::time::sleep(SAVE_DEBOUNCE * 2).await;
    let expected: HashMap<String, String> = [(key("a"), key("one")), (key("b"), key("two"))].into();
    assert_eq!(kept.saves().last(), Some(&expected));
}

#[tokio::test(start_paused = true)]
async fn b17_disposal_makes_the_save_that_was_owed_and_nothing_is_saved_after() {
    let service = Service::default();
    let kept = Arc::new(Kept::default());
    let cache = persisted(&service, &kept);
    cache.set(&key("a"), key("last write"));
    cache.dispose();
    assert_eq!(kept.saves(), [[(key("a"), key("last write"))].into()]);

    cache.set(&key("a"), key("after"));
    tokio::time::sleep(SAVE_DEBOUNCE * 2).await;
    assert_eq!(kept.saves().len(), 1);
}

// ── The persister over a storage ────────────────────────────────────────

fn stored(
    storage: &Arc<InMemorySessionStorage>,
    version: u64,
    max_bytes: usize,
) -> StoragePersister<String, String> {
    StoragePersister::new(storage.clone(), "semiont.cache.kb.test", version, max_bytes)
}

fn entries(of: &[(&str, &str)]) -> HashMap<String, String> {
    of.iter()
        .map(|(key, value)| ((*key).to_owned(), (*value).to_owned()))
        .collect()
}

#[test]
fn a_stored_cache_is_one_document_and_is_read_back_as_it_was_written() {
    let storage = Arc::new(InMemorySessionStorage::new());
    let persister = stored(&storage, 1, MAX_STORED_BYTES_COUNT);
    assert_eq!(persister.load(), None);
    persister
        .save(&entries(&[("a", "one"), ("b", "two")]))
        .expect("stored");

    let document: Value =
        serde_json::from_str(&storage.get("semiont.cache.kb.test").expect("a document"))
            .expect("it is JSON");
    assert_eq!(document["version"], json!(1));
    assert_eq!(document["entries"].as_array().map(Vec::len), Some(2));

    assert_eq!(
        stored(&storage, 1, MAX_STORED_BYTES_COUNT).load(),
        Some(entries(&[("a", "one"), ("b", "two")]))
    );
}

#[test]
fn a_document_of_another_version_or_one_that_is_not_a_document_reads_as_nothing_kept() {
    let storage = Arc::new(InMemorySessionStorage::new());
    stored(&storage, 1, MAX_STORED_BYTES_COUNT)
        .save(&entries(&[("a", "one")]))
        .expect("stored");
    assert_eq!(stored(&storage, 2, MAX_STORED_BYTES_COUNT).load(), None);

    storage
        .set("semiont.cache.kb.test", "{ not a document")
        .expect("stored");
    assert_eq!(stored(&storage, 1, MAX_STORED_BYTES_COUNT).load(), None);
    storage
        .set("semiont.cache.kb.test", "[1, 2, 3]")
        .expect("stored");
    assert_eq!(stored(&storage, 1, MAX_STORED_BYTES_COUNT).load(), None);
}

#[test]
fn a_document_over_its_size_loses_the_entries_longest_unwritten() {
    let storage = Arc::new(InMemorySessionStorage::new());
    let value = "x".repeat(100);
    let persister = stored(&storage, 1, 400);
    persister
        .save(&entries(&[("oldest", &value)]))
        .expect("stored");
    std::thread::sleep(Duration::from_millis(5));
    persister
        .save(&entries(&[("oldest", &value), ("older", &value)]))
        .expect("stored");
    std::thread::sleep(Duration::from_millis(5));
    // An entry whose value did not change keeps the time it was written, so
    // the newest is the one that stays.
    persister
        .save(&entries(&[
            ("oldest", &value),
            ("older", &value),
            ("newest", &value),
        ]))
        .expect("stored");

    let kept = stored(&storage, 1, 400).load().expect("a document");
    assert!(kept.contains_key("newest"), "{kept:?}");
    assert!(!kept.contains_key("oldest"), "{kept:?}");
    assert!(
        storage
            .get("semiont.cache.kb.test")
            .expect("a document")
            .len()
            <= 400
    );
}

// ── The cache as a state unit ───────────────────────────────────────────

struct Caches;

impl AxiomSubject for Caches {
    type Unit = Cache<String, String>;

    fn setup(&self) -> Fresh<Cache<String, String>> {
        Fresh::of(Service::default().cache())
    }

    fn surfaces(&self, cache: &Cache<String, String>) -> Vec<Box<dyn Surface>> {
        vec![
            Box::new(StreamSurface(cache.observe(&"a".to_owned()))),
            Box::new(StreamSurface(cache.observe(&"b".to_owned()))),
        ]
    }

    fn invocations<'a>(&self, cache: &'a Cache<String, String>) -> Vec<Box<dyn Fn() + 'a>> {
        let a = || "a".to_owned();
        vec![
            Box::new(move || cache.invalidate(&a())),
            Box::new(move || cache.invalidate_all()),
            Box::new(move || cache.set(&a(), "written".to_owned())),
            Box::new(move || cache.remove(&a(), refused("gone").into())),
            Box::new(move || drop(tokio::spawn(cache.fetch(&a())))),
        ]
    }
}

#[test]
fn the_cache_keeps_the_state_unit_axioms() {
    assert_eq!(assert_state_unit_axioms(&Caches), Ok(()));
}