store-io-engine 0.6.0

The store-io engine: volumes, regions, barriers with flush sharing, receipts, provisioning and A/B slot objects over any store-io platform.
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
//! Streaming export (PLANNING R5.6, D-148): a store's regions, their
//! attributes and their bytes, pushed in order to a caller's [`ExportSink`],
//! for backup, restore and replication shipping. How the stream travels is
//! the caller's: store-io does not frame it.
//!
//! **One plan, then each region at its turn.** Export shares `copy_store`'s
//! plan (`copy.rs`): every refusal and every volume fact is decided once,
//! before the sink is called, so the two cannot drift. Each region is then
//! looked up again at its turn: it must still be the planned (id,
//! generation), else the export fails (`StaleGeneration` if recycled,
//! `NotReady` if released), the region named. Sizes are fixed at the plan:
//! a page region grown since is exported at its planned size, a positioned
//! append region's durable prefix is clamped to its planned data size, and
//! a slot's object is read at its turn and refused `TooLarge` as the plan
//! refuses one.
//!
//! **What each kind exports.** A positioned append region its durable
//! prefix; an unpositioned one (any reopened store) its whole data area, as
//! read, with no durable length; a page region its data area, as read (a
//! writable store's pages may hold bytes not yet durable: the header says
//! the store was writable); a slot its committed object, as one chunk; a
//! region of a stale page (read-only opens only) its whole capacity and the
//! extra extent its header lists, by container offset.
//!
//! **Bytes.** One background read stream for the whole call, paced by the
//! call's record on the store's device group, its buffers taken before the
//! sink's `begin` (so the header carries its `lend`), each region added to
//! it at its turn. Chunks are owned: a sink may hold up to `lend - 1` of
//! them and drop them later. When the stream needs a buffer and every one
//! is lent, the sink's `settle` is called once; if it still holds them all,
//! the export fails `TooManyInFlight`. A media error fails the export at
//! once (a backup never has a silent hole).
//!
//! **What the report says.** The offset reached in the region being
//! exported counts only bytes the sink's `data` accepted, and with a
//! reference sink (`FileSink`, `StoreSink`) only bytes it wrote (a chunk it
//! holds in a piece not yet written counts none); a region counts as
//! exported only once `end_region` returned `Ok`; the export is `complete`
//! only once `finish` returned `Ok`.

use std::sync::Arc;
use std::sync::atomic::Ordering;

use store_io_core::error::{Error, ErrorContext, NotWrittenCause, Op, OsError};
use store_io_core::id::RegionId;
use store_io_format::exportinfo::{self, InfoHeader, RECORD_LEN, RegionRecord};
use store_io_format::meta::{FillPattern, RegionKind, RegionName};
use store_io_format::meta2::max_object;
use store_io_platform::Platform;

use crate::call::{self, CallState};
use crate::copy::{CopyPlan, Facts};
use crate::io::{ctx_range, not_written};
use crate::lifecycle::retired_error;
use crate::slot_handle::committed_object;
use crate::store::{LiveRegion, Store, StoreOptions};
use crate::stream::{Chunk, Locator, ReadStream};

/// How [`Store::export_with`] exports.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct ExportOptions {
    /// The regions to export, by name, each once (`None`: every region, in
    /// the store's order). A subset is exported in the store's order; the
    /// volume-wide refusals (a frozen store, lost or stale pages,
    /// unavailable entries) stand whatever it names.
    pub regions: Option<Vec<String>>,
    /// The export stream's reads in flight, 1 to
    /// [`MAX_DEPTH`](crate::MAX_DEPTH) (`None`: the stream's default, as
    /// [`StreamOptions`](crate::StreamOptions)).
    pub depth: Option<usize>,
    /// Export a store with stale or lost table pages or unavailable
    /// entries as far as it can be, as
    /// [`CopyOptions::accept_stale_pages`](crate::CopyOptions::accept_stale_pages):
    /// what is left out is in the header's [`VolumeFacts`]. A region of a
    /// stale page is exported in full, and only from a read-only open.
    pub accept_stale_pages: bool,
}

/// What the plan found about the volume as a whole (the facts
/// [`CopyReport`](crate::CopyReport) carries), so a restore never hides a
/// loss.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct VolumeFacts {
    /// Entries left out (unavailable, or of a kind this version does not
    /// know), in id order.
    pub omitted: Vec<RegionId>,
    /// Table pages lost: their regions are unknown.
    pub lost_pages: Vec<u32>,
    /// Table pages stale: their regions exported in full.
    pub stale_pages: Vec<u32>,
    /// Each region exported in full, with the data size its entry records
    /// (the bytes past it are its capacity's, as read).
    pub verified_up_to: Vec<(String, u64)>,
    /// Regions possibly superseded (another region's newer footprint may
    /// cover their bytes).
    pub superseded: Vec<String>,
}

/// What a sink's [`ExportSink::begin`] is told before the first region.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExportHeader {
    /// Regions that follow, exactly.
    pub region_count: u32,
    /// The store's block size: every region's data size is a multiple.
    pub block_size: u64,
    /// The volume's facts.
    pub facts: VolumeFacts,
    /// Whether the store was open for writing: a page region's bytes are
    /// then as read, possibly not yet durable.
    pub writable: bool,
    /// Chunks the export's stream lends at once: a sink holding `lend - 1`
    /// at most never meets `TooManyInFlight` by its own counting.
    pub lend: usize,
    /// An upper bound on the bytes a restore into a new store of the
    /// default geometry takes: its metadata, two header blocks per region,
    /// each region's data size (a capped region's cap when larger), each
    /// slot at the largest object a format-2 slot holds.
    pub total: u64,
}

/// One region, as a sink's [`ExportSink::region`] is told before its bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct RegionInfo {
    /// Its name.
    pub name: String,
    /// Its kind.
    pub kind: RegionKind,
    /// Its generation (a format-1 slot's: 1).
    pub generation: u64,
    /// Its space tag.
    pub tag: u32,
    /// Its growth cap, if capped.
    pub cap: Option<u64>,
    /// How its blocks were filled at provisioning.
    pub fill: FillPattern,
    /// The keyed fill's key.
    pub fill_key: [u8; 16],
    /// The store's block size.
    pub block_size: u64,
    /// Its data size as planned (a region exported in full: the length of
    /// what it exports).
    pub data_size: u64,
    /// A positioned append region's durable length as exported, at most
    /// `data_size` (`None`: an unpositioned append region's whole data
    /// area, as read, or another kind).
    pub durable_len: Option<u64>,
    /// A slot's committed object's length, `Some(0)` for an empty one
    /// (`None`: none committed, or another kind).
    pub object_len: Option<u64>,
    /// Exported in full (a region of a stale page).
    pub full_copy: bool,
    /// Possibly superseded.
    pub superseded: bool,
}

impl RegionInfo {
    /// The bytes its region's data in the stream holds: a slot's object's
    /// length, an append region's durable length when it has one, else its
    /// data size.
    #[must_use]
    pub fn stream_len(&self) -> u64 {
        match self.kind {
            RegionKind::Slot => self.object_len.unwrap_or(0),
            _ => self.durable_len.unwrap_or(self.data_size),
        }
    }

    /// Whether a restore into a store of blocks of `block_size` can take
    /// it as it says, checked as untrusted input: a valid name, a non-zero
    /// generation, the block size the target's (a power of two from 512 to
    /// 65,536), a data size and cap in whole blocks with the cap at least
    /// the data size, a durable length only on an append region not
    /// exported in full and at most its data size, an object length only
    /// on a slot and at most what a slot holds, no slot exported in full,
    /// and its restored footprint (two header blocks and its data) within
    /// `u64`.
    ///
    /// # Errors
    ///
    /// `NotWritten(InvalidOptions)` at the first check that fails.
    pub fn validate(&self, block_size: u64) -> Result<(), Error> {
        let bad = || not_written(NotWrittenCause::InvalidOptions, ErrorContext::default());
        if RegionName::new(&self.name).is_err() || self.generation == 0 {
            return Err(bad());
        }
        let block = self.block_size;
        if block != block_size || !block.is_power_of_two() || !(512..=1 << 16).contains(&block) {
            return Err(bad());
        }
        if self.data_size % block != 0 {
            return Err(bad());
        }
        if let Some(cap) = self.cap {
            if cap < self.data_size || cap % block != 0 {
                return Err(bad());
            }
        }
        let slot = self.kind == RegionKind::Slot;
        if let Some(d) = self.durable_len {
            if self.kind != RegionKind::Append || self.full_copy || d > self.data_size {
                return Err(bad());
            }
        }
        if let Some(n) = self.object_len {
            let most = max_object(block.trailing_zeros() as u8) as u64;
            if !slot || n > most {
                return Err(bad());
            }
        }
        if self.full_copy && slot {
            return Err(bad());
        }
        let footprint = block
            .checked_mul(2)
            .and_then(|h| h.checked_add(self.cap.unwrap_or(0).max(self.data_size)));
        if footprint.is_none() {
            return Err(bad());
        }
        Ok(())
    }

    /// The format's record of it (`None` if its name is not a region name
    /// or its object length does not fit the record).
    pub(crate) fn to_record(&self) -> Option<RegionRecord> {
        Some(RegionRecord {
            name: RegionName::new(&self.name).ok()?,
            kind: self.kind,
            fill: self.fill,
            fill_key: self.fill_key,
            tag: self.tag,
            generation: self.generation,
            cap: self.cap,
            data_size: self.data_size,
            durable_len: self.durable_len,
            object_len: match self.object_len {
                Some(n) => Some(u32::try_from(n).ok()?),
                None => None,
            },
            stream_len: self.stream_len(),
            full_copy: self.full_copy,
            superseded: self.superseded,
        })
    }

    /// The region a record describes, in a stream of blocks of
    /// `block_size`.
    pub(crate) fn from_record(rec: &RegionRecord, block_size: u64) -> Self {
        Self {
            name: rec.name.as_str().to_owned(),
            kind: rec.kind,
            generation: rec.generation,
            tag: rec.tag,
            cap: rec.cap,
            fill: rec.fill,
            fill_key: rec.fill_key,
            block_size,
            data_size: rec.data_size,
            durable_len: rec.durable_len,
            object_len: rec.object_len.map(u64::from),
            full_copy: rec.full_copy,
            superseded: rec.superseded,
        }
    }

    /// Its bytes in format `exportinfo`'s region record ([`RECORD_LEN`],
    /// versioned with the record), for a caller's own framing; the block
    /// size travels in the header ([`ExportHeader::to_bytes`]).
    ///
    /// # Errors
    ///
    /// `NotWritten(InvalidOptions)` if its fields cannot be a record (a
    /// name not a region name, an object length past `u32`, fields that
    /// disagree with its kind).
    pub fn to_bytes(&self) -> Result<[u8; RECORD_LEN], Error> {
        let bad = || not_written(NotWrittenCause::InvalidOptions, ErrorContext::default());
        let rec = self.to_record().ok_or_else(bad)?;
        rec.check().map_err(|_| bad())?;
        Ok(rec.encode())
    }

    /// A region from bytes [`Self::to_bytes`] wrote, in a stream of blocks
    /// of `block_size`, decoded and then [`Self::validate`]d (the bytes are
    /// untrusted).
    ///
    /// # Errors
    ///
    /// `NotWritten(InvalidOptions)` if the bytes are not a record or the
    /// region fails [`Self::validate`].
    pub fn from_bytes(bytes: &[u8], block_size: u64) -> Result<Self, Error> {
        let rec = RegionRecord::decode(bytes)
            .map_err(|_| not_written(NotWrittenCause::InvalidOptions, ErrorContext::default()))?;
        let info = Self::from_record(&rec, block_size);
        info.validate(block_size)?;
        Ok(info)
    }
}

impl ExportHeader {
    /// Its bytes: format `exportinfo`'s header and lists, sealed by a
    /// CRC-32C, for a caller's own framing (the regions follow as
    /// [`RegionInfo::to_bytes`] records).
    ///
    /// # Errors
    ///
    /// `NotWritten(InvalidOptions)` if it cannot be encoded: a block size
    /// out of range, a verified name not a region name, a list holding an
    /// item twice, or a count past `u32`.
    pub fn to_bytes(&self) -> Result<Vec<u8>, Error> {
        let bad = || not_written(NotWrittenCause::InvalidOptions, ErrorContext::default());
        // A power of two (its range the codec's to check).
        let block = self.block_size;
        if !block.is_power_of_two() {
            return Err(bad());
        }
        let mut omitted: Vec<u64> = self.facts.omitted.iter().map(|id| id.get()).collect();
        omitted.sort_unstable();
        let mut lost = self.facts.lost_pages.clone();
        lost.sort_unstable();
        let mut stale = self.facts.stale_pages.clone();
        stale.sort_unstable();
        let mut verified = Vec::with_capacity(self.facts.verified_up_to.len());
        for (name, len) in &self.facts.verified_up_to {
            verified.push((RegionName::new(name).map_err(|_| bad())?, *len));
        }
        verified.sort_by_key(|(n, _)| n.as_padded());
        let h = InfoHeader {
            writable: self.writable,
            block_log2: block.trailing_zeros() as u8,
            region_count: self.region_count,
            lend: u32::try_from(self.lend).unwrap_or(u32::MAX),
            total: self.total,
            omitted_count: 0,
            lost_count: 0,
            stale_count: 0,
            verified_count: 0,
        };
        let counted = InfoHeader {
            omitted_count: u32::try_from(omitted.len()).map_err(|_| bad())?,
            lost_count: u32::try_from(lost.len()).map_err(|_| bad())?,
            stale_count: u32::try_from(stale.len()).map_err(|_| bad())?,
            verified_count: u32::try_from(verified.len()).map_err(|_| bad())?,
            ..h
        };
        let len = exportinfo::head_len(&counted)
            .and_then(|n| n.checked_add(4))
            .ok_or_else(bad)?;
        let mut out = vec![0u8; len];
        let n = exportinfo::encode_head(&h, &omitted, &lost, &stale, &verified, &mut out)
            .map_err(|_| bad())?;
        out.truncate(n);
        Ok(out)
    }

    /// A header from bytes [`Self::to_bytes`] wrote (or a `regions.info`'s
    /// header and lists, sealed), decoded and checked: the CRC-32C, the
    /// block size in range, each list in its order. Its `superseded` facts
    /// are not carried (each region's record says it).
    ///
    /// # Errors
    ///
    /// `NotWritten(InvalidOptions)` if the bytes are not a sealed header.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        let info = exportinfo::decode_head(bytes)
            .map_err(|_| not_written(NotWrittenCause::InvalidOptions, ErrorContext::default()))?;
        Ok(Self::from_view(&info))
    }

    /// The header a decoded view holds (its lists the volume's facts).
    pub(crate) fn from_view(info: &exportinfo::ExportInfo<'_>) -> Self {
        let h = info.header;
        Self {
            region_count: h.region_count,
            block_size: 1u64 << h.block_log2,
            facts: VolumeFacts {
                omitted: info.omitted().map(RegionId::from_raw).collect(),
                lost_pages: info.lost_pages().collect(),
                stale_pages: info.stale_pages().collect(),
                verified_up_to: info
                    .verified()
                    .map(|(n, len)| (n.as_str().to_owned(), len))
                    .collect(),
                superseded: Vec::new(),
            },
            writable: h.writable,
            lend: h.lend as usize,
            total: h.total,
        }
    }
}

/// Where an import pulls a store from: the header an export's sink was
/// given, then each region's info and its bytes, in order. A caller's own
/// source (its framing carried by [`ExportHeader::to_bytes`] and
/// [`RegionInfo::to_bytes`]) or a [`FileSource`](crate::FileSource).
/// Everything it yields is untrusted: the import checks it.
pub trait ImportSource {
    /// The export's header (first, once).
    ///
    /// # Errors
    ///
    /// The source's: the import stops, nothing renamed.
    fn header(&mut self) -> Result<ExportHeader, SinkError>;

    /// The next region's info, or `None` after the last.
    ///
    /// # Errors
    ///
    /// The source's: the import stops, nothing renamed.
    fn next_region(&mut self) -> Result<Option<RegionInfo>, SinkError>;

    /// The current region's next bytes into `buf` (at most `buf.len()`):
    /// how many, 0 at the region's end.
    ///
    /// # Errors
    ///
    /// The source's: the import stops, nothing renamed.
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, SinkError>;
}

/// How far an export got.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ExportReport {
    /// Regions exported: each counted once its `end_region` returned `Ok`.
    pub regions: usize,
    /// Bytes the sink's `data` accepted.
    pub bytes: u64,
    /// The region being exported when the export stopped (`None` once
    /// every region ended, or before the first).
    pub region: Option<String>,
    /// The offset in that region's stream the sink accepted bytes up to.
    pub offset: u64,
    /// Whether the store was open for writing.
    pub writable: bool,
    /// Every region ended and the sink's `finish` returned `Ok`.
    pub complete: bool,
    /// The volume's facts (empty if the plan refused).
    pub facts: VolumeFacts,
}

/// A sink's refusal, without payload: an I/O error, a refusal, or the
/// caller's own code.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SinkError {
    /// An I/O error, as the operating system reported it.
    Io(OsError),
    /// The sink refused the call (out of order, or past what it was told).
    Refused,
    /// The caller's own code.
    Other(u32),
}

impl core::fmt::Display for SinkError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Io(raw) => write!(f, "sink I/O error {}", raw.code),
            Self::Refused => f.write_str("sink refused the call"),
            Self::Other(code) => write!(f, "sink error {code}"),
        }
    }
}

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

/// An export that stopped: why, the sink's own error if it was the sink's
/// (`error` is then `Io` for [`SinkError::Io`], `NotWritten(Interrupted)`
/// otherwise), and how far it got (`complete` false).
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ExportError {
    /// Why it stopped (the region in its context when one was being
    /// exported).
    pub error: Error,
    /// The sink's error, if the sink stopped it.
    pub sink: Option<SinkError>,
    /// How far it got.
    pub report: ExportReport,
}

impl core::fmt::Display for ExportError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "export stopped: {}", self.error)
    }
}

impl std::error::Error for ExportError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.error)
    }
}

/// Where an export pushes a store: its header, then each region's info,
/// its bytes in order and its end, then the finish. Pacing is invisible to
/// it: the export's reads are paced by its own call.
pub trait ExportSink {
    /// Before the first region.
    ///
    /// # Errors
    ///
    /// The sink's: the export stops.
    fn begin(&mut self, header: &ExportHeader) -> Result<(), SinkError>;

    /// Before a region's bytes.
    ///
    /// # Errors
    ///
    /// The sink's: the export stops.
    fn region(&mut self, info: &RegionInfo) -> Result<(), SinkError>;

    /// The region's next bytes, contiguous from offset 0 of its stream
    /// ([`Chunk::offset`]). The sink owns the chunk: it may keep up to the
    /// header's `lend - 1` and drop them later.
    ///
    /// # Errors
    ///
    /// The sink's: the export stops; the report's offset is where this
    /// chunk began.
    fn data(&mut self, chunk: Chunk) -> Result<(), SinkError>;

    /// Called when the export needs a buffer and the sink holds every one
    /// lent: drop the chunks no longer needed. If it still holds them all
    /// the export fails `TooManyInFlight`. By default, nothing.
    ///
    /// # Errors
    ///
    /// The sink's: the export stops.
    fn settle(&mut self) -> Result<(), SinkError> {
        Ok(())
    }

    /// After a region's last bytes: the region counts as exported once
    /// this returns `Ok`.
    ///
    /// # Errors
    ///
    /// The sink's: the export stops.
    fn end_region(&mut self) -> Result<(), SinkError>;

    /// After the last region (right after `begin` with none): the export is
    /// complete once this returns `Ok`.
    ///
    /// # Errors
    ///
    /// The sink's: the export stops, incomplete.
    fn finish(&mut self) -> Result<(), SinkError>;
}

/// Why an export stopped, before the report is attached.
struct Stop {
    error: Error,
    sink: Option<SinkError>,
}

impl From<Error> for Stop {
    fn from(error: Error) -> Self {
        Self { error, sink: None }
    }
}

/// A refusal naming `region`.
fn refused(cause: NotWrittenCause, region: Option<RegionId>) -> Error {
    Error::NotWritten {
        cause,
        ctx: ErrorContext {
            region,
            ..ErrorContext::default()
        },
    }
}

/// The sink's error as the export's, naming `region`.
fn sunk(region: Option<RegionId>) -> impl Fn(SinkError) -> Stop {
    move |e| {
        let ctx = ErrorContext {
            region,
            ..ErrorContext::default()
        };
        let error = match e {
            SinkError::Io(raw) => Error::Io {
                op: Op::Write,
                raw,
                ctx,
            },
            SinkError::Refused | SinkError::Other(_) => Error::NotWritten {
                cause: NotWrittenCause::Interrupted,
                ctx,
            },
        };
        Stop {
            error,
            sink: Some(e),
        }
    }
}

fn too_many(e: &Error) -> bool {
    matches!(
        e,
        Error::NotWritten {
            cause: NotWrittenCause::TooManyInFlight,
            ..
        }
    )
}

impl<P: Platform> Store<P>
where
    P::Queue: Send,
{
    /// Exports every region to `sink`, in the store's order: see the
    /// module docs and [`Self::export_with`].
    ///
    /// # Errors
    ///
    /// As [`Self::export_with`].
    pub fn export(&self, sink: &mut dyn ExportSink) -> Result<ExportReport, Box<ExportError>> {
        self.export_with(sink, ExportOptions::default())
    }

    /// Exports the regions `opts` names (all by default) to `sink`: its
    /// `begin` with the header, then for each region its `region`, its
    /// bytes through `data` and its `end_region`, then its `finish`.
    ///
    /// # Errors
    ///
    /// An [`ExportError`] (boxed: it holds the report) with how far it got. Before the sink is
    /// called: `NotWritten(InvalidOptions)` for a region named twice, a
    /// name no region has, a depth out of range, or on a writable open a
    /// region that only a read-only open exports (one of a stale page,
    /// possibly superseded, or at risk: open the store read-only to export
    /// it); `NotWritten(NotReady)` for an unavailable region or an entry
    /// that does not decode, `NotWritten(Frozen)` for a stale or lost table
    /// page (both unless [`ExportOptions::accept_stale_pages`]);
    /// `NotWritten(TooLarge)` for a slot object a format-2 slot cannot
    /// hold; `NotWritten(StaleGeneration)` for a region that changed while
    /// the plan read it; `NotWritten(PoolExhausted)` with too few buffers
    /// free for the stream; `Io` if its queue could not be made. At a
    /// region's turn: `NotWritten(StaleGeneration)` (recycled) or
    /// `NotWritten(NotReady)` (released) since the plan or while it
    /// streams, `NotWritten(TooLarge)` for a slot object committed since
    /// that a format-2 slot cannot hold; a read's errors as a
    /// [`ReadStream`]'s, a media error (`Corruption(MediaError)`, the
    /// range named) among them; `NotWritten(TooManyInFlight)` if the sink
    /// still holds every lent chunk after `settle`. Any error of the sink
    /// (in `sink`).
    pub fn export_with(
        &self,
        sink: &mut dyn ExportSink,
        opts: ExportOptions,
    ) -> Result<ExportReport, Box<ExportError>> {
        let mut report = ExportReport {
            writable: !self.inner.read_only,
            ..ExportReport::default()
        };
        match self.export_run(sink, &opts, &mut report) {
            Ok(()) => {
                report.region = None;
                report.offset = 0;
                report.complete = true;
                Ok(report)
            }
            Err(Stop { error, sink }) => Err(Box::new(ExportError {
                error,
                sink,
                report,
            })),
        }
    }

    /// The export's plan: the options checked, `copy_store`'s plan of the
    /// regions named, and on a writable open the regions only a read-only
    /// open exports refused.
    fn export_plan(&self, opts: &ExportOptions) -> Result<CopyPlan, Error> {
        // A name no region has is refused by the plan; the depth by the
        // stream, before the sink's `begin`.
        if let Some(names) = &opts.regions {
            if (1..names.len()).any(|i| names[..i].contains(&names[i])) {
                return Err(not_written(
                    NotWrittenCause::InvalidOptions,
                    ErrorContext::default(),
                ));
            }
        }
        let plan = self.plan_of(opts.accept_stale_pages, opts.regions.as_deref())?;
        // A region of a stale page is read by container offset: on a
        // writable open an accepted rollback may free its extra extent
        // under it. A superseded or at-risk region may be made writable
        // and stream newer bytes. Only a read-only open exports them.
        if !self.inner.read_only {
            if let Some(f) = plan.facts.iter().find(|f| f.full.is_some() || f.superseded) {
                return Err(refused(NotWrittenCause::InvalidOptions, Some(f.source.id)));
            }
        }
        Ok(plan)
    }

    /// An upper bound on what a restore of `facts` takes in a new store of
    /// the default geometry with blocks of `block` (saturating).
    fn export_total(facts: &[Facts], block: u64) -> u64 {
        let defaults = StoreOptions::default();
        let log2_block = block.trailing_zeros() as u8;
        let log2_table = defaults.log2_table_slot.clamp(log2_block, 16);
        let count = u32::try_from(facts.len()).unwrap_or(u32::MAX);
        let table =
            crate::v2::layout_for(log2_block, log2_table, defaults.region_capacity.max(count))
                .data_start();
        facts.iter().fold(table, |total, f| {
            let data = match f.kind {
                RegionKind::Slot => max_object(log2_block) as u64,
                _ => f.cap.unwrap_or(0).max(f.data_size),
            };
            total.saturating_add(2 * block).saturating_add(data)
        })
    }

    fn export_run(
        &self,
        sink: &mut dyn ExportSink,
        opts: &ExportOptions,
        report: &mut ExportReport,
    ) -> Result<(), Stop> {
        let plan = self.export_plan(opts)?;
        // The call's record on this store's device group: the stream's
        // reads are its pieces; a reference sink joins it at `begin`.
        let pace = self.inner.domain.new_pace();
        let call = CallState::new(Arc::clone(&self.inner.qos), pace.clone());
        let _bound = call::bind(&call);
        let ran = self.export_body(sink, opts, report, &plan, pace, &call);
        // A part's failure (a reference sink's write, even one a caller's
        // wrapper swallowed) is the export's: its error, and the report
        // clamped to where the failed write began.
        let failure = call.failure();
        // To where the failure was in the export's own order of regions:
        // the regions ended before it, the region and offset when inside
        // one, and the bytes up to there.
        let clamp = |report: &mut ExportReport| {
            if let Some(f) = &failure {
                // The regions ended before it (a backstop beside the count
                // of regions every bound sink ended, below: a part that
                // records a failure without binding as a sink).
                report.regions = report.regions.min(f.region as usize);
                let base = call.base(f.region);
                match plan.facts.get(f.region as usize).filter(|_| f.inside) {
                    Some(r) => {
                        // Never past the bytes `data` accepted when the
                        // export stopped in the failure's region (a write
                        // that failed inside a later chunk's call began
                        // past that chunk's start); a region the export
                        // went past was accepted whole.
                        let same = report.region.as_deref() == Some(r.name.as_str());
                        report.region = Some(r.name.clone());
                        report.offset = if same {
                            report.offset.min(f.offset)
                        } else {
                            f.offset
                        };
                    }
                    None => {
                        report.region = None;
                        report.offset = 0;
                        if let Some(b) = base {
                            report.bytes = report.bytes.min(b);
                        }
                    }
                }
            }
            // Stopped inside a region, whatever stopped it: no further than
            // every bound reference sink's writes done (a sink holding
            // accepted bytes not yet written counts none of them), and the
            // bytes no further than that offset.
            let inside = match &failure {
                Some(f) => f.inside.then_some(f.region),
                None => call.inside_region(),
            };
            if let (Some(i), Some(_)) = (inside, report.region.as_ref()) {
                if let Some(w) = call.written_up_to(i) {
                    report.offset = report.offset.min(w);
                }
                if let Some(b) = call.base(i) {
                    report.bytes = report.bytes.min(b.saturating_add(report.offset));
                }
            }
            // A region counts only once every bound reference sink ended
            // it (a wrapper may have swallowed a sink's failure no part
            // recorded).
            if let Some(n) = call.regions_ended() {
                // Short of where the report stands (the region it names,
                // else past the regions it counts): it stands at region
                // `n` instead, the first a sink never ended, with that
                // region's writes done, and nothing past it.
                let i = n as usize;
                let named = report
                    .region
                    .as_ref()
                    .and_then(|name| plan.facts.iter().position(|f| &f.name == name));
                if i < named.unwrap_or(report.regions) {
                    report.regions = i;
                    report.region = plan.facts.get(i).map(|f| f.name.clone());
                    report.offset = call.written_up_to(n).unwrap_or(0);
                    if let Some(b) = call.base(n) {
                        report.bytes = report.bytes.min(b.saturating_add(report.offset));
                    }
                }
            }
        };
        match ran {
            Err(mut stop) => {
                if let Some(f) = &failure {
                    stop.error = f.error.clone();
                }
                clamp(report);
                Err(stop)
            }
            Ok(()) => {
                if let Some(f) = &failure {
                    clamp(report);
                    return Err(Stop {
                        error: f.error.clone(),
                        sink: None,
                    });
                }
                // A bound reference sink that never finished (a wrapper
                // that dropped it, or fell back to another).
                if !call.all_finished() {
                    clamp(report);
                    return Err(Stop::from(not_written(
                        NotWrittenCause::Interrupted,
                        ErrorContext::default(),
                    )));
                }
                Ok(())
            }
        }
    }

    /// The export's sink calls, bound to its call.
    fn export_body(
        &self,
        sink: &mut dyn ExportSink,
        opts: &ExportOptions,
        report: &mut ExportReport,
        plan: &CopyPlan,
        pace: Option<crate::pace::Pace>,
        call: &CallState,
    ) -> Result<(), Stop> {
        report.facts = VolumeFacts {
            omitted: plan.omitted.clone(),
            lost_pages: plan.lost_pages.clone(),
            stale_pages: plan.stale_pages.clone(),
            verified_up_to: plan.verified_up_to.clone(),
            superseded: plan.superseded.clone(),
        };
        let stream = self.export_stream(opts.depth, pace)?;
        let header = ExportHeader {
            region_count: u32::try_from(plan.facts.len()).unwrap_or(u32::MAX),
            block_size: plan.block,
            facts: report.facts.clone(),
            writable: report.writable,
            lend: stream.lend(),
            total: Self::export_total(&plan.facts, plan.block),
        };
        sink.begin(&header).map_err(sunk(None))?;
        // A sink that joined the source's record shares its pieces.
        if call.shares_source() {
            stream.make_second();
        }
        for (i, f) in plan.facts.iter().enumerate() {
            report.region = Some(f.name.clone());
            report.offset = 0;
            let index = u32::try_from(i).unwrap_or(u32::MAX);
            call.enter(index, report.bytes);
            self.export_region(f, plan.block, &stream, sink, report)
                .map_err(|stop| Self::part_error(&stream, stop))?;
            report.regions += 1;
            call.leave(index.saturating_add(1));
        }
        report.region = None;
        report.offset = 0;
        // Every part asked before the export reports anything: a read the
        // stream lost while a sink's wait collected it is its failure.
        if let Some(e) = stream.failure() {
            return Err(Stop::from(e));
        }
        // Nothing is in flight: every part was read to its end.
        stream.cancel()?;
        sink.finish().map_err(sunk(None))
    }

    /// The stream's own failure, if a collection for another part of the
    /// call lost its reads (the sink then only saw its wait end), else
    /// `stop` as it was.
    fn part_error(stream: &ReadStream<P>, stop: Stop) -> Stop {
        match stream.failure() {
            Some(error) => Stop {
                error,
                sink: stop.sink,
            },
            None => stop,
        }
    }

    /// Slot `r`'s committed object at its turn, read under its header lock
    /// (a slot is never recycled or released: its gate stays live), refused
    /// as the plan refuses one a format-2 slot cannot hold.
    fn object_at_turn(&self, r: &LiveRegion, block: u64) -> Result<Option<Vec<u8>>, Error> {
        let header = r
            .header
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        let object = committed_object(&header, &self.inner.layout);
        if object
            .as_ref()
            .is_some_and(|o| o.len() > max_object(block.trailing_zeros() as u8))
        {
            return Err(refused(NotWrittenCause::TooLarge, Some(r.id)));
        }
        Ok(object)
    }

    /// Exports region `f` (of the plan) at its turn.
    fn export_region(
        &self,
        f: &Facts,
        block: u64,
        stream: &ReadStream<P>,
        sink: &mut dyn ExportSink,
        report: &mut ExportReport,
    ) -> Result<(), Stop> {
        // Still the planned (id, generation): a recycle or release closes
        // the planned region's gate for good (a recycle's new generation is
        // a region of its own), so a gate still live is the plan's region.
        let r = &f.source;
        r.gate.live().map_err(|why| retired_error(why, r))?;
        let id = Some(r.id);
        let (durable_len, object, part) = match (f.kind, &f.full) {
            (RegionKind::Slot, _) => (None, self.object_at_turn(r, block)?, None),
            // By container offset: its capacity's runs, then its extra
            // extent.
            (_, Some((ranges, _))) => (
                None,
                None,
                Some((f.data_size, Locator::Ranges(ranges.clone()))),
            ),
            (kind, None) => {
                // A positioned append region's durable prefix, clamped to
                // its planned data size (still a valid prefix).
                let durable = (kind == RegionKind::Append && r.positioned.load(Ordering::Acquire))
                    .then(|| {
                        r.frontier
                            .as_ref()
                            .map_or(0, crate::frontier::AppendFrontier::durable)
                            .min(f.data_size)
                    });
                (
                    durable,
                    None,
                    Some((durable.unwrap_or(f.data_size), Locator::Map)),
                )
            }
        };
        let info = RegionInfo {
            name: f.name.clone(),
            kind: f.kind,
            generation: f.attrs.generation,
            tag: f.attrs.tag,
            cap: f.cap,
            fill: f.attrs.fill,
            fill_key: f.attrs.fill_key,
            block_size: block,
            data_size: f.data_size,
            durable_len,
            object_len: object.as_ref().map(|o| o.len() as u64),
            full_copy: f.full.is_some(),
            superseded: f.superseded,
        };
        sink.region(&info).map_err(sunk(id))?;
        if let Some(o) = object.filter(|o| !o.is_empty()) {
            let mut settled = false;
            let chunk = loop {
                match stream.lend_bytes(r, 0, &o) {
                    Ok(c) => break c,
                    Err(e) if too_many(&e) && !settled => {
                        sink.settle().map_err(sunk(id))?;
                        settled = true;
                    }
                    Err(e) => return Err(e.into()),
                }
            };
            sink.data(chunk).map_err(sunk(id))?;
            report.offset = o.len() as u64;
            report.bytes += o.len() as u64;
        }
        if let Some((len, loc)) = part {
            self.export_bytes(r, len, loc, stream, sink, report)?;
        }
        sink.end_region().map_err(sunk(id))
    }

    /// Streams `[0, len)` of `r` (read as `loc` places it) to the sink.
    fn export_bytes(
        &self,
        r: &Arc<LiveRegion>,
        len: u64,
        loc: Locator,
        stream: &ReadStream<P>,
        sink: &mut dyn ExportSink,
        report: &mut ExportReport,
    ) -> Result<(), Stop> {
        let id = Some(r.id);
        stream.add_part(r, 0..len, loc)?;
        let mut got = 0u64;
        let mut settled = false;
        while got < len {
            match stream.pull() {
                Some(Ok(c)) => {
                    let n = c.bytes().len() as u64;
                    // In order from the region's start, with no gap and
                    // nothing past its end.
                    if n == 0 || c.offset() != got || n > len - got {
                        let mut e = crate::store::corrupt();
                        if let Error::Corruption { ctx, .. } = &mut e {
                            *ctx = ctx_range(r, got, len);
                        }
                        return Err(e.into());
                    }
                    settled = false;
                    sink.data(c).map_err(sunk(id))?;
                    got += n;
                    report.offset = got;
                    report.bytes += n;
                }
                Some(Err(e)) if too_many(&e) && !settled => {
                    sink.settle().map_err(sunk(id))?;
                    settled = true;
                }
                Some(Err(e)) => return Err(e.into()),
                // Ended before the region's bytes did.
                None => {
                    return Err(
                        not_written(NotWrittenCause::Interrupted, ctx_range(r, got, len)).into(),
                    );
                }
            }
        }
        Ok(())
    }
}