tinystore 0.5.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
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
//! A node's link to the node it takes its files from: the first address of
//! its `from` that answers, its files followed from where each copy stands,
//! snapshots put together and entries applied as they come, the link made
//! again when it breaks, and the writes this node passes on over it.

use std::collections::{HashMap, HashSet};
use std::net::{TcpStream, ToSocketAddrs};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};

use super::copy::{self, Copy};
use super::entry::{self, Point};
use super::message::{Frames, Message, Refusal, plain_name, timed_out};
use super::node::State;
use super::serve::{Out, PING_EVERY, SILENT_AT_MOST};
use super::snapshot::Taking;
use crate::store::WeakStore;
use crate::sync::lock;
use crate::{Error, ErrorKind, Result, Store};

/// How often a node that copies every file asks for the files served.
const LIST_EVERY: Duration = Duration::from_secs(5);
/// How long a write passed on waits for a link to its home.
const LINK_WAIT: Duration = Duration::from_secs(10);

/// A write passed on toward the home and what came back.
pub(crate) struct Written {
    pub(crate) outcome: std::result::Result<Vec<u8>, Refusal>,
    pub(crate) waits: Vec<(String, u64)>,
}

/// What a write passed on is answered with, on the link's thread, so it must
/// not wait: none when the link broke before the answer came.
pub(crate) type Answered = Box<dyn FnOnce(Option<Written>) + Send>;

/// The link to the node this one takes its files from, as the threads that
/// pass writes on see it.
#[derive(Default)]
pub(crate) struct Upstream {
    out: Mutex<Option<Arc<Out>>>,
    linked: Condvar,
    next_id: AtomicU64,
    waiting: Mutex<HashMap<u64, Answered>>,
}

impl Upstream {
    /// Passes `op` on to the node this one takes its files from, and waits
    /// for what it answers.
    pub(crate) fn write(&self, op: Vec<u8>, at_most: Duration) -> Result<Written> {
        let out = self.wait_for_link()?;
        let (answer, answered): (Sender<Written>, Receiver<Written>) = mpsc::channel();
        let id = self.send(
            &out,
            op,
            Box::new(move |written| {
                if let Some(written) = written {
                    let _ = answer.send(written);
                }
            }),
        )?;
        answered.recv_timeout(at_most).map_err(|_| {
            lock(&self.waiting).remove(&id);
            Error::new(ErrorKind::OutcomeUnknown, "the link to the home broke or went silent before the write answered")
        })
    }

    /// Passes `op` on over the link up now, and hands what it answers to
    /// `answered`: it waits neither for a link, failing `unavailable` at once
    /// when none is up, nor for the answer.
    #[cfg(feature = "kv")]
    pub(crate) fn write_then(&self, op: Vec<u8>, answered: Answered) -> Result<()> {
        let out = lock(&self.out).clone();
        let out = out.ok_or_else(|| Error::new(ErrorKind::Unavailable, "no link reaches the home"))?;
        self.send(&out, op, answered).map(drop)
    }

    fn send(&self, out: &Out, op: Vec<u8>, answered: Answered) -> Result<u64> {
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        lock(&self.waiting).insert(id, answered);
        if let Err(error) = out.send(&Message::Write { id, op }) {
            lock(&self.waiting).remove(&id);
            return Err(Error::new(ErrorKind::Unavailable, "the link to the home broke before the write left")
                .with_source(error));
        }
        Ok(id)
    }

    fn wait_for_link(&self) -> Result<Arc<Out>> {
        let deadline = Instant::now() + LINK_WAIT;
        let mut out = lock(&self.out);
        loop {
            if let Some(out) = &*out {
                return Ok(Arc::clone(out));
            }
            let now = Instant::now();
            if now >= deadline {
                return Err(Error::new(ErrorKind::Unavailable, "no link reaches the home"));
            }
            out = self.linked.wait_timeout(out, deadline - now).unwrap_or_else(std::sync::PoisonError::into_inner).0;
        }
    }

    fn linked(&self, out: Option<Arc<Out>>) {
        let ended = out.is_none();
        *lock(&self.out) = out;
        self.linked.notify_all();
        if ended {
            // a write whose answer the broken link would have carried: its
            // caller hears the outcome unknown
            let unanswered: Vec<Answered> = lock(&self.waiting).drain().map(|(_, answered)| answered).collect();
            for answered in unanswered {
                answered(None);
            }
        }
    }

    fn answered(&self, id: u64, written: Written) {
        let answered = lock(&self.waiting).remove(&id);
        if let Some(answered) = answered {
            answered(Some(written));
        }
    }

    pub(crate) fn stop(&self) {
        self.linked(None);
    }
}

/// Starts the thread that keeps the link to the node's `from`.
pub(crate) fn start(state: &Arc<State>, store: &Store) {
    let (state, store) = (Arc::clone(state), store.downgrade());
    state.clone().spawn("tinystore node: from", move || keep_linked(&state, &store));
}

/// A link straight to a node the catalog names the home of files that the
/// nodes of `from` do not serve: it follows those files alone, and their
/// writes pass on through it.
pub(crate) struct Direct {
    pub(crate) address: String,
    pub(crate) upstream: Upstream,
    files: Mutex<HashSet<String>>,
}

impl Direct {
    pub(crate) fn new(address: &str) -> Direct {
        Direct { address: address.to_owned(), upstream: Upstream::default(), files: Mutex::default() }
    }

    pub(crate) fn add(&self, file: &str) {
        lock(&self.files).insert(file.to_owned());
    }

    pub(crate) fn follows(&self, file: &str) -> bool {
        lock(&self.files).contains(file)
    }

    pub(crate) fn remove(&self, file: &str) {
        lock(&self.files).remove(file);
    }

    fn files(&self) -> Vec<String> {
        let mut files: Vec<String> = lock(&self.files).iter().cloned().collect();
        files.sort_unstable();
        files
    }
}

/// What a link follows: every file the node takes, over the link to `from`,
/// or the files a direct link was opened for.
#[derive(Clone)]
enum Scope {
    From,
    Direct(Arc<Direct>),
}

/// Starts the thread that keeps a direct link, made again from each copy's
/// position whenever it breaks, until the node stops.
pub(crate) fn start_direct(state: &Arc<State>, store: &Store, direct: Arc<Direct>) {
    let (state, store) = (Arc::clone(state), store.downgrade());
    state.clone().spawn("tinystore node: direct", move || {
        let mut pause = Duration::from_millis(200);
        while !state.stopping() {
            let began = Instant::now();
            if let Err(error) = follow(&state, &store, &direct.address, Scope::Direct(Arc::clone(&direct)))
                && !state.stopping()
            {
                tracing::debug!(target: "tinystore", to = %direct.address, %error, "a node's direct link to a home");
            }
            direct.upstream.linked(None);
            pause = if began.elapsed() > Duration::from_secs(10) {
                Duration::from_millis(200)
            } else {
                (pause * 2).min(Duration::from_secs(5))
            };
            state.pause(pause);
        }
    });
}

fn keep_linked(state: &Arc<State>, store: &WeakStore) {
    let mut index = 0;
    let mut pause = Duration::from_millis(200);
    let mut said = None;
    while !state.stopping() {
        let address = state.options.from[index % state.options.from.len()].clone();
        let began = Instant::now();
        match follow(state, store, &address, Scope::From) {
            Ok(()) => {}
            Err(error) => {
                if said.as_deref() != Some(error.to_string().as_str()) && !state.stopping() {
                    tracing::warn!(target: "tinystore", from = %address, %error, "a node's link to the node it copies");
                    said = Some(error.to_string());
                }
            }
        }
        state.upstream.linked(None);
        *lock(&state.upstream_at) = None;
        if began.elapsed() > Duration::from_secs(10) {
            pause = Duration::from_millis(200);
        } else {
            index += 1;
            pause = (pause * 2).min(Duration::from_secs(5));
        }
        state.pause(pause);
    }
}

/// One file a link follows: a snapshot put together, or a copy whole.
enum Held {
    Taking(Box<Taking>),
    Whole(Arc<Copy>),
    /// Asked for, nothing come yet.
    Asked,
}

/// Follows the files over a link to `address` until it breaks.
fn follow(state: &Arc<State>, store: &WeakStore, address: &str, scope: Scope) -> Result<()> {
    let (mut reading, writing) = dial(state, address)?;
    reading.set_timeout(Duration::from_millis(250))?;
    writing.set_timeout(SILENT_AT_MOST)?;
    let out = Arc::new(Out::new(writing));
    out.send(&state.hello(state.address()))?;
    let mut link = Link::new(state, store, scope, Arc::clone(&out));
    let mut frames = Frames::default();
    let (mut heard, mut listed, mut welcomed) = (Instant::now(), Instant::now(), false);
    loop {
        if state.stopping() {
            return Ok(());
        }
        while let Some(message) = frames.next()? {
            heard = Instant::now();
            if welcomed {
                link.take(message)?;
                continue;
            }
            match message {
                Message::Welcome { node, files } => {
                    welcomed = true;
                    frames.unpack_from_here()?;
                    link.welcomed(address, node, &files)?;
                }
                Message::Refused { why } => return Err(Error::new(ErrorKind::Invalid, format!("refused: {why}"))),
                other => return Err(Error::invalid(format!("a link began with {other:?}, not a welcome"))),
            }
        }
        if welcomed {
            link.forget_copies_gone();
            link.say_applied()?;
            link.ask_to_verify()?;
        }
        match frames.fill(&mut reading) {
            Ok(true) => {}
            Ok(false) => return Err(Error::new(ErrorKind::Unavailable, "the node closed the link")),
            Err(error) if timed_out(&error) => {}
            Err(error) => return Err(Error::io("a link", error)),
        }
        if heard.elapsed() > SILENT_AT_MOST {
            return Err(Error::new(ErrorKind::Unavailable, "the node said nothing for too long"));
        }
        if welcomed {
            link.tend(&mut listed)?;
        }
    }
}

impl<'a> Link<'a> {
    fn new(state: &'a Arc<State>, store: &'a WeakStore, scope: Scope, out: Arc<Out>) -> Link<'a> {
        Link {
            state,
            store,
            scope,
            out,
            held: HashMap::new(),
            retries: Vec::new(),
            said: HashMap::new(),
            awaiting: HashMap::new(),
            peer: String::new(),
            refused: HashSet::new(),
            #[cfg(feature = "blobs")]
            fetching: Fetching::default(),
        }
    }

    /// Takes the node at `address` welcoming this one: what follows is
    /// packed, and the files it serves are followed.
    fn welcomed(&mut self, address: &str, node: String, files: &[String]) -> Result<()> {
        self.out.pack()?;
        self.peer = node;
        self.upstream().linked(Some(Arc::clone(&self.out)));
        if matches!(self.scope, Scope::From) {
            *lock(&self.state.upstream_at) = Some(address.to_owned());
            *lock(&self.state.served) = Some(files.to_vec());
        }
        tracing::info!(target: "tinystore", from = %address, "a node is linked to the node it copies");
        self.follow_new(files)
    }

    /// What a link does between messages: the retries and fetches due, the
    /// files to follow, and a list or a ping when the link was quiet.
    fn tend(&mut self, listed: &mut Instant) -> Result<()> {
        self.retry_due()?;
        #[cfg(feature = "blobs")]
        self.fetch_due()?;
        if matches!(self.scope, Scope::Direct(_)) {
            self.follow_new(&[])?;
        }
        let state = self.state;
        let wanted = matches!(self.scope, Scope::From) && state.wanted.swap(false, Ordering::SeqCst);
        if wanted || (state.options.files.is_none() && listed.elapsed() > LIST_EVERY) {
            self.out.send(&Message::List)?;
            *listed = Instant::now();
        } else if self.out.idle_for() >= PING_EVERY {
            self.out.send(&Message::Ping)?;
        }
        Ok(())
    }
}

/// Opens a link to the node at `address`, kept where a stop cuts it.
pub(crate) fn dial(state: &State, address: &str) -> Result<(super::transport::Reading, super::transport::Writing)> {
    let stream = connect(address)?;
    state.keep_link(&stream);
    super::transport::connect(state, address, stream)
}

pub(crate) fn connect(address: &str) -> Result<TcpStream> {
    let what = || format!("node: from {address}");
    let addresses = address.to_socket_addrs().map_err(|error| Error::io(what(), error))?;
    let mut last = None;
    for resolved in addresses {
        match TcpStream::connect_timeout(&resolved, Duration::from_secs(5)) {
            Ok(stream) => return Ok(stream),
            Err(error) => last = Some(error),
        }
    }
    Err(Error::io(what(), last.unwrap_or_else(|| std::io::Error::other("the address resolves to nothing"))))
}

/// One link's files and what it does with each message.
struct Link<'a> {
    state: &'a Arc<State>,
    store: &'a WeakStore,
    scope: Scope,
    out: Arc<Out>,
    held: HashMap<String, Held>,
    /// Files whose sending failed, asked for again once their time comes.
    retries: Vec<(String, Instant)>,
    /// The entry of each copy this link last said it holds.
    said: HashMap<String, u64>,
    /// The checks whose answer names a point the copy has not reached yet.
    awaiting: HashMap<String, (Point, Vec<u8>)>,
    /// The node at the other end, by the id its welcome said.
    peer: String,
    /// The files a direct link takes nothing of yet, the catalog naming
    /// another home of each than the node it reaches; each said once.
    refused: HashSet<String>,
    /// The files blobs keeps beside blobs.db, fetched once a copy names them.
    #[cfg(feature = "blobs")]
    fetching: Fetching,
}

/// The files of blobs a link fetches: those under way, each with the file
/// its pieces are written to, and when to look for missing ones next.
#[cfg(feature = "blobs")]
#[derive(Default)]
struct Fetching {
    under_way: HashMap<String, Option<std::fs::File>>,
    due: bool,
    not_before: Option<Instant>,
}

impl Link<'_> {
    /// The writes of the files this link follows pass on through it.
    fn upstream(&self) -> &Upstream {
        match &self.scope {
            Scope::From => &self.state.upstream,
            Scope::Direct(direct) => &direct.upstream,
        }
    }

    /// Follows each file served that this link takes and does not follow yet:
    /// over the link to `from`, those the node takes and no direct link
    /// follows; over a direct link, those it was opened for.
    fn follow_new(&mut self, served: &[String]) -> Result<()> {
        let mut wanted: HashSet<String> = match &self.scope {
            Scope::From => served
                .iter()
                .filter(|name| self.state.takes(name) && !self.state.follows_directly(name))
                .cloned()
                .collect(),
            Scope::Direct(direct) => direct.files().into_iter().collect(),
        };
        if let (Scope::From, Some(files)) = (&self.scope, &self.state.options.files) {
            wanted.extend(files.iter().filter(|name| !self.state.follows_directly(name)).cloned());
        }
        let mut wanted: Vec<String> = wanted.into_iter().filter(|name| plain_name(name)).collect();
        wanted.sort_unstable();
        for name in wanted {
            if !self.held.contains_key(&name) && self.reaches_its_home(&name)? {
                self.ask(&name)?;
            }
        }
        Ok(())
    }

    /// Whether this link reaches the home the catalog names of `name`: a
    /// direct link to a stale address, where another node listens now, takes
    /// nothing of it until the catalog names that node, and a route the
    /// catalog moved goes over a link to its new address.
    fn reaches_its_home(&mut self, name: &str) -> Result<bool> {
        let Scope::Direct(direct) = &self.scope else {
            return Ok(true);
        };
        let Some(store) = self.store.upgrade().filter(|_| self.state.uses_catalog()) else {
            return Ok(true);
        };
        let Some(home) = self.state.catalog(&store)?.home_of(name)?.filter(|home| home.node != self.peer) else {
            self.refused.remove(name);
            return Ok(true);
        };
        if !home.address.is_empty() && home.address != direct.address {
            direct.remove(name);
            self.refused.remove(name);
            self.state.take_directly(&store, name, &home.address)?;
        } else if self.refused.insert(name.to_owned()) {
            tracing::warn!(
                target: "tinystore",
                file = name,
                address = %direct.address,
                "the node at a file's address is not the home the catalog names: this node takes nothing of it there \
                 until the catalog names it"
            );
        }
        Ok(false)
    }

    /// Asks for `name` from where this node's copy of it stands.
    fn ask(&mut self, name: &str) -> Result<()> {
        let at = match self.state.copy(name) {
            Some(copy) => {
                let at = copy.point();
                self.held.insert(name.to_owned(), Held::Whole(copy));
                self.blobs_changed(name);
                at
            }
            None => {
                self.held.insert(name.to_owned(), Held::Asked);
                Point::default()
            }
        };
        self.out.send(&Message::Follow { file: name.to_owned(), at })
    }

    /// Looks for the files of blobs a copy of blobs.db names once it changed.
    fn blobs_changed(&mut self, file: &str) {
        #[cfg(feature = "blobs")]
        if file == crate::blobs::FILE_IN_STORE {
            self.fetching.due = true;
        }
        let _ = file;
    }

    /// Asks for each file of blobs the copy names and this node lacks.
    #[cfg(feature = "blobs")]
    fn fetch_due(&mut self) -> Result<()> {
        let now = Instant::now();
        if !self.fetching.due || self.fetching.not_before.is_some_and(|not_before| now < not_before) {
            return Ok(());
        }
        (self.fetching.due, self.fetching.not_before) = (false, Some(now + Duration::from_millis(300)));
        for path in crate::blobs::objects_missing(&self.state.dir)? {
            if !self.fetching.under_way.contains_key(&path) {
                self.out.send(&Message::Fetch { path: path.clone() })?;
                self.fetching.under_way.insert(path, None);
            }
        }
        Ok(())
    }

    /// Writes a piece of a file of blobs, and gives the file its name once
    /// whole: blobs never writes it again, so a name means its bytes.
    #[cfg(feature = "blobs")]
    fn object(&mut self, path: &str, offset: u64, bytes: &[u8], last: bool) -> Result<()> {
        use std::io::Write;
        let target = self.state.dir.join(path);
        // a file sent before the commit that names it comes unasked
        if offset == 0 && crate::blobs::is_object(path) && !target.exists() {
            self.fetching.under_way.entry(path.to_owned()).or_insert(None);
        }
        let Some(written) = self.fetching.under_way.get_mut(path) else {
            return Ok(());
        };
        let mut temp = target.as_os_str().to_owned();
        temp.push(".part");
        let temp = std::path::PathBuf::from(temp);
        let io = |error| Error::io(temp.display().to_string(), error);
        if offset == 0 {
            if let Some(parent) = target.parent() {
                std::fs::create_dir_all(parent).map_err(io)?;
            }
            *written = Some(std::fs::File::create(&temp).map_err(io)?);
        }
        let Some(file) = written.as_mut() else {
            return Err(Error::corrupt(format!("{path}: a piece of a file whose first never came")));
        };
        file.write_all(bytes).map_err(io)?;
        if last {
            file.sync_all().map_err(io)?;
            self.fetching.under_way.remove(path);
            std::fs::rename(&temp, &target).map_err(io)?;
        }
        Ok(())
    }

    /// Asks for the checks a program wants of the copies this link holds.
    fn ask_to_verify(&mut self) -> Result<()> {
        let held = &self.held;
        for file in self.state.to_verify(|file| matches!(held.get(file), Some(Held::Whole(_)))) {
            self.out.send(&Message::Verify { file })?;
        }
        Ok(())
    }

    /// Takes the point and hash its source answered for `file`: compared now
    /// when the copy stands there, once it reaches it otherwise.
    fn verified(&mut self, file: &str, at: Point, sum: Vec<u8>, why: &str) {
        let stands = match self.held.get(file) {
            Some(Held::Whole(copy)) => copy.point(),
            _ => return self.state.verification(file, Err(Error::new(ErrorKind::Unavailable, "no whole copy"))),
        };
        if sum.is_empty() {
            return self.state.verification(file, Err(Error::new(ErrorKind::Unavailable, why.to_owned())));
        }
        if stands.sequence < at.sequence {
            self.awaiting.insert(file.to_owned(), (at, sum));
            return;
        }
        self.compare(file, at, &sum, stands);
    }

    /// Compares the copy's hash with its source's, the copy standing at `stands`.
    /// An entry is named by its sequence and check: a home moved since names
    /// the same last entry at its own epoch.
    fn compare(&mut self, file: &str, at: Point, sum: &[u8], stands: Point) {
        let done = if stands.sequence != at.sequence {
            Err(Error::new(
                ErrorKind::Conflict,
                format!("the copy stands at entry {}, past those checked", stands.sequence),
            ))
        } else if stands.check != at.check {
            Err(Error::new(
                ErrorKind::Conflict,
                format!("the copy's entry {} is not its source's: another home wrote it", stands.sequence),
            ))
        } else {
            super::verify::of_copy(self.state, file)
                .and_then(|ours| super::verify::compare(file, at.sequence, ours, sum))
        };
        self.state.verification(file, done);
    }

    /// Lets go of each copy this node holds no longer, as one it became the
    /// home of, so that its applier closes.
    fn forget_copies_gone(&mut self) {
        let state = self.state;
        self.held.retain(|name, held| !matches!(held, Held::Whole(_)) || state.copy(name).is_some());
    }

    /// Tells the other node the entry each copy holds now, where it moved:
    /// what a synchronous home's commits wait for.
    fn say_applied(&mut self) -> Result<()> {
        for (file, held) in &self.held {
            if let Held::Whole(copy) = held {
                let applied = copy.applied();
                if self.said.get(file).is_none_or(|said| *said < applied) {
                    self.out.send(&Message::Applied { file: file.clone(), sequence: applied })?;
                    self.said.insert(file.clone(), applied);
                }
            }
        }
        Ok(())
    }

    fn retry_due(&mut self) -> Result<()> {
        let now = Instant::now();
        let due: Vec<String> = self.retries.iter().filter(|(_, at)| *at <= now).map(|(name, _)| name.clone()).collect();
        self.retries.retain(|(_, at)| *at > now);
        for name in due {
            self.ask(&name)?;
        }
        Ok(())
    }

    fn take(&mut self, message: Message) -> Result<()> {
        match message {
            Message::SnapshotBegin { file, page_size, at } => self.begin(&file, page_size, at),
            Message::SnapshotPages { file, pages } => match self.held.get_mut(&file) {
                Some(Held::Taking(taking)) => taking.pages(&pages),
                _ => Err(Error::invalid(format!("{file}: pages of no snapshot under way"))),
            },
            Message::SnapshotEnd { file, ready_at } => {
                if let Some(Held::Taking(taking)) = self.held.get_mut(&file) {
                    taking.end(ready_at);
                }
                self.finish_when_whole(&file)
            }
            Message::Entry { file, bytes } => self.apply(&file, &bytes),
            #[cfg(feature = "blobs")]
            Message::Failed { file, .. } if crate::blobs::is_object(&file) => {
                self.fetching.under_way.remove(&file);
                (self.fetching.due, self.fetching.not_before) = (true, Some(Instant::now() + Duration::from_secs(2)));
                Ok(())
            }
            #[cfg(feature = "blobs")]
            Message::Object { path, offset, bytes, last } => self.object(&path, offset, &bytes, last),
            // a node holding an old home's file: the link goes on to the next node
            Message::Failed { kind: ErrorKind::Conflict, why, .. } => Err(Error::new(ErrorKind::Conflict, why)),
            Message::Failed { file, kind, why } => {
                tracing::debug!(target: "tinystore", %file, %kind, %why, "a node's file could not be sent yet");
                self.held.remove(&file);
                self.retries.push((file, Instant::now() + Duration::from_secs(2)));
                Ok(())
            }
            Message::Written { id, outcome, waits } => {
                self.upstream().answered(id, Written { outcome, waits });
                Ok(())
            }
            Message::Verified { file, at, sum, why } => {
                self.verified(&file, at, sum, &why);
                Ok(())
            }
            Message::Listed { files } => {
                if matches!(self.scope, Scope::From) {
                    *lock(&self.state.served) = Some(files.clone());
                }
                self.follow_new(&files)
            }
            Message::Ping => Ok(()),
            other => Err(Error::invalid(format!("a link said {other:?}, which a follower is not sent"))),
        }
    }

    /// Starts putting a snapshot together beside the copy held before, which
    /// its readers read until the snapshot takes its place.
    fn begin(&mut self, file: &str, page_size: u32, at: Point) -> Result<()> {
        if !plain_name(file) {
            return Err(Error::invalid(format!("a link sent {file:?}, which is no file's name")));
        }
        let applied = self.epoch_applied(file)?;
        if at.epoch < applied {
            return Err(Error::new(
                ErrorKind::Conflict,
                format!(
                    "{file}: a snapshot at epoch {} from a node, and this copy applied epoch {applied}: an old home's file",
                    at.epoch
                ),
            ));
        }
        self.state.snapshots.fetch_add(1, Ordering::Relaxed);
        let dir = self.state.log_dir(file);
        let taking = Box::new(Taking::begin(&dir, &self.state.dir.join(file), page_size, at)?);
        self.held.insert(file.to_owned(), Held::Taking(taking));
        Ok(())
    }

    /// The epoch of the last entry this node's copy of `file` applied, kept
    /// until a snapshot replaces the copy.
    fn epoch_applied(&self, file: &str) -> Result<u64> {
        let kept = copy::Position::read_point(&self.state.log_dir(file).join(copy::Position::FILE))?;
        Ok(kept.map_or(0, |point| point.epoch))
    }

    fn apply(&mut self, file: &str, bytes: &[u8]) -> Result<()> {
        let Some((entry, _)) = entry::decode(bytes)? else {
            return Err(Error::corrupt(format!("{file}: an entry cut short")));
        };
        let applied = match self.held.get_mut(file) {
            Some(Held::Taking(taking)) => taking.apply(&entry),
            Some(Held::Whole(copy)) => copy.apply(&entry, Some(bytes)),
            Some(Held::Asked) | None => return Ok(()),
        };
        match applied {
            Ok(()) => {
                self.blobs_changed(file);
                if let (Some((at, _)), Some(Held::Whole(copy))) = (self.awaiting.get(file), self.held.get(file))
                    && copy.point().sequence >= at.sequence
                {
                    let stands = copy.point();
                    if let Some((at, sum)) = self.awaiting.remove(file) {
                        self.compare(file, at, &sum, stands);
                    }
                }
                self.finish_when_whole(file)
            }
            Err(error) if matches!(error.kind(), ErrorKind::Conflict | ErrorKind::Invalid) => {
                tracing::warn!(target: "tinystore", %file, %error, "a copy starts again from a snapshot");
                self.held.insert(file.to_owned(), Held::Asked);
                self.out.send(&Message::Follow { file: file.to_owned(), at: Point::default() })
            }
            Err(error) => Err(error),
        }
    }

    /// Gives a snapshot whose pages are all one commit's the copy's name,
    /// and opens it as the copy its engines read.
    fn finish_when_whole(&mut self, file: &str) -> Result<()> {
        let whole = matches!(self.held.get(file), Some(Held::Taking(taking)) if taking.whole());
        if !whole {
            return Ok(());
        }
        let store = self.store.upgrade().ok_or_else(|| Error::closed("the node's store"))?;
        // The opens that saw the copy held now end first, so that their files
        // pause too, and the opens after wait for the snapshot. A first copy
        // waits for none: its opens wait for it, holding theirs.
        let state = self.state;
        let _rerouting = state.copy(file).map(|_| state.wait_to_reroute(file)).transpose()?;
        // the engines reading the copy held before let go of its file, and the
        // copy its writer, so that the snapshot takes its name: an open file
        // keeps its name on Windows, and elsewhere a reader would go on
        // reading the file it replaced
        let paused = self.state.pause_readers(file)?;
        let Some(Held::Taking(taking)) = self.held.remove(file) else {
            return Ok(());
        };
        self.state.drop_copy(file);
        if let Err(error) = (*taking).finish() {
            if copy::is_ready(&self.state.log_dir(file), &self.state.dir.join(file)) {
                self.state.keep_copy(file, Arc::new(Copy::open(&store, file)?));
            }
            return Err(error);
        }
        let copy = Arc::new(Copy::open(&store, file)?);
        self.state.keep_copy(file, Arc::clone(&copy));
        drop(paused);
        // what an engine kept of a copy taken again is read again
        store.applied(file);
        drop(store);
        self.held.insert(file.to_owned(), Held::Whole(copy));
        // what it said of the copy held before, which may stand further on in
        // another home's entries, keeps it from saying what this one holds
        self.said.remove(file);
        tracing::info!(target: "tinystore", %file, "a node holds a whole copy of a file");
        self.blobs_changed(file);
        Ok(())
    }
}