stratum-node-cli 0.1.0-alpha.2

The `stratum` client for Stratum pod nodes: operator key files, bootstrap, config, backup, invitations and members over the loopback API; join, pod access and export for tenants through the gate
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
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
//! `stratum export`: a walk of the caller's own pod into a `.tar.zst`
//! archive and a manifest beside it.

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufWriter, Read as _, Seek as _, SeekFrom, Write};
use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
use std::path::{Path, PathBuf};

use serde_json::{json, Value as Json};
use sha2::{Digest as _, Sha256};
use stratum_node_core::{NostrSecretKey, PodPath, Sha256Digest, UnixTime};

use crate::client::{self, MAX_RESPONSE_BYTES};
use crate::error::CliError;
use crate::exit;
use crate::gate::{self, GateClient, Head, Request, Route, ANY, LD_JSON, MAX_LISTING_BYTES};
use crate::listing::{self, Child};
use crate::origin::GateTarget;
use crate::output::sanitize;
use crate::private_file;
use crate::session::Session;

/// The most entries an export holds before it stops: containers, resources
/// and ACLs together.
pub const MAX_EXPORT_ENTRIES: u64 = 100_000;

/// The most bytes of resource content an export holds before it stops:
/// 64 GiB.
pub const MAX_EXPORT_BYTES: u64 = 64 * 1024 * 1024 * 1024;

/// The `format` member of an export manifest.
pub const MANIFEST_FORMAT: &str = "stratum-pod-export";

/// The `format_version` member of an export manifest.
pub const MANIFEST_FORMAT_VERSION: u64 = 1;

/// The suffix appended to the archive's file name for the manifest.
pub const MANIFEST_SUFFIX: &str = ".manifest.json";

/// The zstd compression level: the library's default trade-off.
const ZSTD_LEVEL: i32 = 3;

/// Options for [`Session::export`].
#[derive(Debug, Clone, Default)]
pub struct ExportOptions {
    /// The archive to write (`-o`), conventionally `<name>.tar.zst`. The
    /// manifest is written beside it as `<archive>.manifest.json`.
    pub output: PathBuf,
    /// Replace an existing archive and manifest (`--force`).
    pub force: bool,
}

/// What an archived entry is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
    Container,
    Resource,
    Acl,
}

impl Kind {
    fn as_str(self) -> &'static str {
        match self {
            Self::Container => "container",
            Self::Resource => "resource",
            Self::Acl => "acl",
        }
    }
}

/// Why an entry is being fetched, which decides what a 404 means.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reason {
    /// It was named in a listing: a 404 means it vanished.
    Listed,
    /// It is the ACL beside a container or resource: a 404 means there is
    /// none.
    Beside,
}

/// One archived entry.
#[derive(Debug, Clone)]
struct Entry {
    path: PodPath,
    kind: Kind,
    size: u64,
    sha256: Option<Sha256Digest>,
    content_type: Option<String>,
    etag: Option<String>,
}

impl Entry {
    fn to_json(&self) -> Json {
        json!({
            "path": self.path,
            "archive_path": archive_path(&self.path),
            "kind": self.kind.as_str(),
            "size": self.size,
            "sha256": self.sha256,
            "content_type": self.content_type,
        })
    }
}

/// The archive path of a pod path: the path without its leading `/`, so
/// the archive unpacks to `pods/<pk>/…` and `pods/<pk>.acl`.
fn archive_path(path: &PodPath) -> &str {
    path.as_str().trim_start_matches('/')
}

/// The files an export writes, and the temporary names it writes them under.
#[derive(Debug)]
struct Targets {
    archive: PathBuf,
    manifest: PathBuf,
    directory: PathBuf,
    archive_temp: PathBuf,
    manifest_temp: PathBuf,
    /// Where `--force` sets the old manifest aside while the archive moves.
    manifest_aside: PathBuf,
    spool: PathBuf,
}

impl Targets {
    fn new(archive: &Path) -> Result<Self, CliError> {
        let name = archive
            .file_name()
            .and_then(|n| n.to_str())
            .filter(|n| !n.is_empty())
            .ok_or_else(|| CliError::Usage("-o must name an archive file".to_owned()))?;
        let directory = match archive.parent() {
            Some(parent) if !parent.as_os_str().is_empty() => parent.to_owned(),
            _ => PathBuf::from("."),
        };
        let tag = hex::encode(&client::random_32()?[..6]);
        let mut manifest = archive.as_os_str().to_owned();
        manifest.push(MANIFEST_SUFFIX);
        Ok(Self {
            archive: archive.to_owned(),
            manifest: PathBuf::from(manifest),
            archive_temp: directory.join(format!(".{name}.partial-{tag}")),
            manifest_temp: directory.join(format!(".{name}.manifest-{tag}")),
            manifest_aside: directory.join(format!(".{name}.manifest-old-{tag}")),
            spool: directory.join(format!(".{name}.spool-{tag}")),
            directory,
        })
    }
}

/// Removes the temporary files of an export that did not finish.
#[derive(Debug, Default)]
struct Cleanup(Vec<PathBuf>);

impl Drop for Cleanup {
    fn drop(&mut self) {
        for path in &self.0 {
            // Best effort: these are our own temporary files.
            let _removed = fs::remove_file(path);
        }
    }
}

/// How a temporary file is opened.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Access {
    /// Written only: the archive and the manifest.
    Write,
    /// Written and read back: the spool.
    ReadWrite,
}

/// Creates a new `0600` file; an existing one is never opened.
fn create_private(path: &Path, access: Access) -> Result<File, CliError> {
    OpenOptions::new()
        .read(access == Access::ReadWrite)
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)
        .map_err(|err| CliError::Local(format!("creating {} failed: {err}", path.display())))
}

/// A writer that hashes and counts what passes through it.
struct Hashing<W> {
    inner: W,
    hasher: Sha256,
    size: u64,
}

impl<W: Write> Write for Hashing<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let written = self.inner.write(buf)?;
        self.hasher.update(&buf[..written]);
        self.size = self
            .size
            .saturating_add(u64::try_from(written).unwrap_or(u64::MAX));
        Ok(written)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}

/// The archive being written.
type Archive = tar::Builder<zstd::stream::write::Encoder<'static, Hashing<BufWriter<File>>>>;

/// Something listed that the walk did not follow.
#[derive(Debug, Clone)]
struct Skipped {
    listed_in: Option<PodPath>,
    id: String,
    reason: String,
}

/// The state of one walk.
struct Walk<'a> {
    gate: GateClient,
    key: &'a NostrSecretKey,
    root: PodPath,
    archive: Archive,
    spool: File,
    created_at: UnixTime,
    entries: Vec<Entry>,
    visited: BTreeSet<PodPath>,
    listings: BTreeMap<PodPath, BTreeSet<PodPath>>,
    skipped: Vec<Skipped>,
    vanished: Vec<PodPath>,
    changed: Vec<(PodPath, String)>,
    unverified: Vec<(PodPath, u16)>,
    total_bytes: u64,
}

impl Walk<'_> {
    /// Walks the pod breadth first from its root.
    fn run(&mut self) -> Result<(), CliError> {
        let root = self.root.clone();
        let root_acl = root
            .acl_path()
            .ok_or_else(|| CliError::Local("the pod root has no ACL path".to_owned()))?;
        self.visited.insert(root.clone());
        self.visited.insert(root_acl.clone());
        self.fetch(&root_acl, Reason::Beside, None)?;
        let mut queue = VecDeque::from([root.clone()]);
        while let Some(container) = queue.pop_front() {
            let Some(children) = self.list(&container)? else {
                continue;
            };
            self.add_container(&container)?;
            if container != root {
                if let Some(acl) = container.acl_path() {
                    if self.visited.insert(acl.clone()) {
                        self.fetch(&acl, Reason::Beside, Some(&container))?;
                    }
                }
            }
            let mut accepted = BTreeSet::new();
            for child in children {
                let path = match child {
                    Child::Accepted(path) => path,
                    Child::Refused { id, reason } => {
                        self.skipped.push(Skipped {
                            listed_in: Some(container.clone()),
                            id,
                            reason,
                        });
                        continue;
                    }
                };
                accepted.insert(path.clone());
                if !self.visited.insert(path.clone()) {
                    continue;
                }
                if path.is_container() {
                    queue.push_back(path);
                    continue;
                }
                let present = self.fetch(&path, Reason::Listed, Some(&container))?;
                if present {
                    if let Some(acl) = path.acl_path() {
                        if self.visited.insert(acl.clone()) {
                            self.fetch(&acl, Reason::Beside, Some(&container))?;
                        }
                    }
                }
            }
            self.listings.insert(container, accepted);
        }
        Ok(())
    }

    /// Reads a container's listing; `None` when it vanished or redirected.
    fn list(&mut self, container: &PodPath) -> Result<Option<Vec<Child>>, CliError> {
        let response = self.gate.fetch(
            &Request::new("GET", container.as_str(), LD_JSON),
            Some(self.key),
            MAX_LISTING_BYTES,
        )?;
        let head = &response.head;
        if head.is_success() {
            let origin = self.gate.target().origin().clone();
            return listing::children(&origin, container, &response.body).map(Some);
        }
        if *container == self.root {
            return Err(response.into_error(Route::Pod));
        }
        if head.status == 404 {
            self.vanished.push(container.clone());
            return Ok(None);
        }
        if head.is_redirect() {
            self.skip_redirect(container, None);
            return Ok(None);
        }
        Err(response.into_error(Route::Pod))
    }

    /// Records a redirect, which is never followed.
    fn skip_redirect(&mut self, path: &PodPath, listed_in: Option<&PodPath>) {
        self.skipped.push(Skipped {
            listed_in: listed_in.cloned(),
            id: path.to_string(),
            reason: "answered with a redirect, which is not followed".to_owned(),
        });
    }

    /// Refuses one more entry when the archive already holds the most.
    fn count_entry(&self) -> Result<(), CliError> {
        check_entry_limit(u64::try_from(self.entries.len()).unwrap_or(u64::MAX))
    }

    /// Adds a container's directory entry.
    fn add_container(&mut self, container: &PodPath) -> Result<(), CliError> {
        self.count_entry()?;
        let mut header = tar::Header::new_gnu();
        header.set_entry_type(tar::EntryType::Directory);
        header.set_size(0);
        header.set_mode(0o700);
        header.set_mtime(self.created_at.as_secs());
        self.archive
            .append_data(&mut header, archive_path(container), io::empty())
            .map_err(|err| archive_error(&err))?;
        self.entries.push(Entry {
            path: container.clone(),
            kind: Kind::Container,
            size: 0,
            sha256: None,
            content_type: None,
            etag: None,
        });
        Ok(())
    }

    /// Fetches a resource or ACL into the archive. Returns `false` when it
    /// is absent (a 404) or was skipped.
    fn fetch(
        &mut self,
        path: &PodPath,
        reason: Reason,
        listed_in: Option<&PodPath>,
    ) -> Result<bool, CliError> {
        self.count_entry()?;
        self.spool
            .set_len(0)
            .and_then(|()| self.spool.seek(SeekFrom::Start(0)).map(drop))
            .map_err(|err| spool_error(&err))?;
        let request = Request::new("GET", path.as_str(), ANY);
        let (head, outcome) = {
            let mut sink = BufWriter::new(&self.spool);
            let result =
                self.gate
                    .stream(&request, self.key, &mut sink, gate::MAX_RESOURCE_BYTES)?;
            sink.flush().map_err(|err| spool_error(&err))?;
            result
        };
        let streamed = match outcome {
            Ok(streamed) => streamed,
            Err(body) => {
                if head.status == 404 {
                    if reason == Reason::Listed {
                        self.vanished.push(path.clone());
                    }
                    return Ok(false);
                }
                if head.is_redirect() {
                    self.skip_redirect(path, listed_in);
                    return Ok(false);
                }
                return Err(gate::error_from(&head, &body, Route::Pod));
            }
        };
        self.total_bytes = self.total_bytes.saturating_add(streamed.size);
        check_byte_limit(self.total_bytes)?;
        if let Some(tag) = head.etag.as_deref().and_then(sha256_tag) {
            if tag != streamed.sha256 {
                self.changed.push((
                    path.clone(),
                    "the bytes received do not match the entity tag sent with them".to_owned(),
                ));
            }
        }
        self.spool
            .seek(SeekFrom::Start(0))
            .map_err(|err| spool_error(&err))?;
        let mut header = tar::Header::new_gnu();
        header.set_entry_type(tar::EntryType::Regular);
        header.set_size(streamed.size);
        header.set_mode(0o600);
        header.set_mtime(self.created_at.as_secs());
        self.archive
            .append_data(
                &mut header,
                archive_path(path),
                (&self.spool).take(streamed.size),
            )
            .map_err(|err| archive_error(&err))?;
        let kind = if path.acl_path().is_none() {
            Kind::Acl
        } else {
            Kind::Resource
        };
        self.entries.push(Entry {
            path: path.clone(),
            kind,
            size: streamed.size,
            sha256: Some(streamed.sha256),
            content_type: head.content_type.as_deref().map(sanitize),
            etag: head.etag,
        });
        Ok(true)
    }

    /// After the walk: asks again for every resource's entity tag and every
    /// container's listing, and records what changed or vanished meanwhile.
    fn verify(&mut self) -> Result<(), CliError> {
        let files: Vec<Entry> = self
            .entries
            .iter()
            .filter(|entry| entry.kind != Kind::Container)
            .cloned()
            .collect();
        for entry in files {
            let response = self.gate.fetch(
                &Request::new("HEAD", entry.path.as_str(), ANY),
                Some(self.key),
                MAX_RESPONSE_BYTES,
            )?;
            let head: &Head = &response.head;
            if head.status == 404 {
                self.vanished.push(entry.path);
            } else if head.is_success() {
                if let Some(now) = &head.etag {
                    let before = entry.etag.as_deref().and_then(sha256_tag).or(entry.sha256);
                    let differs = match (sha256_tag(now), before) {
                        (Some(now), Some(before)) => now != before,
                        _ => entry.etag.as_deref() != Some(now.as_str()),
                    };
                    if differs {
                        self.changed.push((
                            entry.path,
                            "its entity tag changed during the export".to_owned(),
                        ));
                    }
                }
            } else {
                self.unverified.push((entry.path, head.status));
            }
        }
        let listings = std::mem::take(&mut self.listings);
        for (container, before) in &listings {
            let response = self.gate.fetch(
                &Request::new("GET", container.as_str(), LD_JSON),
                Some(self.key),
                MAX_LISTING_BYTES,
            )?;
            if response.head.status == 404 {
                self.vanished.push(container.clone());
                continue;
            }
            if !response.head.is_success() {
                self.unverified
                    .push((container.clone(), response.head.status));
                continue;
            }
            let origin = self.gate.target().origin().clone();
            let now: BTreeSet<PodPath> = listing::children(&origin, container, &response.body)?
                .into_iter()
                .filter_map(|child| match child {
                    Child::Accepted(path) => Some(path),
                    Child::Refused { .. } => None,
                })
                .collect();
            if now != *before {
                self.changed.push((
                    container.clone(),
                    "its listing changed during the export".to_owned(),
                ));
            }
        }
        self.listings = listings;
        Ok(())
    }
}

/// Refuses another entry when `held` entries are already archived.
fn check_entry_limit(held: u64) -> Result<(), CliError> {
    if held >= MAX_EXPORT_ENTRIES {
        return Err(CliError::Local(format!(
            "export stopped: the pod holds more than {MAX_EXPORT_ENTRIES} entries; \
             nothing was written"
        )));
    }
    Ok(())
}

/// Refuses a walk whose content has grown to `total` bytes, past the limit.
fn check_byte_limit(total: u64) -> Result<(), CliError> {
    if total > MAX_EXPORT_BYTES {
        return Err(CliError::Local(format!(
            "export stopped: the pod holds more than {MAX_EXPORT_BYTES} bytes (64 GiB); \
             nothing was written"
        )));
    }
    Ok(())
}

/// Reads an entity tag that is the quoted SHA-256 of the body, as the pod
/// server sends; `None` for any other tag.
fn sha256_tag(etag: &str) -> Option<Sha256Digest> {
    let tag = etag.strip_prefix("W/").unwrap_or(etag);
    tag.strip_prefix('"')?.strip_suffix('"')?.parse().ok()
}

/// Maps a failure to write the archive.
fn archive_error(err: &io::Error) -> CliError {
    CliError::Local(format!("writing the archive failed: {err}"))
}

/// Maps a failure of the spool file.
fn spool_error(err: &io::Error) -> CliError {
    CliError::Local(format!("the export's temporary file failed: {err}"))
}

/// Refuses an existing file before any work is done. This is an early,
/// friendly refusal only: [`place`] is what guarantees that nothing that
/// appears later is replaced.
fn check_absent(path: &Path) -> Result<(), CliError> {
    if fs::symlink_metadata(path).is_ok() {
        return Err(CliError::Local(format!(
            "{} already exists; pass --force to replace it",
            path.display()
        )));
    }
    Ok(())
}

/// What a finished walk found, for the manifest and the report.
#[derive(Debug)]
struct Findings {
    root: PodPath,
    entries: Vec<Entry>,
    skipped: Vec<Skipped>,
    vanished: Vec<PodPath>,
    changed: Vec<(PodPath, String)>,
    unverified: Vec<(PodPath, u16)>,
    total_bytes: u64,
}

impl Findings {
    /// Splits a finished walk into the archive and what it found.
    fn from_walk(walk: Walk<'_>) -> (Archive, Self) {
        let findings = Self {
            root: walk.root,
            entries: walk.entries,
            skipped: walk.skipped,
            vanished: walk.vanished,
            changed: walk.changed,
            unverified: walk.unverified,
            total_bytes: walk.total_bytes,
        };
        (walk.archive, findings)
    }

    /// The ACLs that exist.
    fn acls(&self) -> Vec<&PodPath> {
        self.entries
            .iter()
            .filter(|entry| entry.kind == Kind::Acl)
            .map(|entry| &entry.path)
            .collect()
    }

    /// Returns `true` when nothing changed, vanished or was skipped.
    fn is_complete(&self) -> bool {
        self.changed.is_empty() && self.vanished.is_empty() && self.skipped.is_empty()
    }

    /// The members the manifest and the report share.
    fn json_members(&self) -> serde_json::Map<String, Json> {
        let mut map = serde_json::Map::new();
        map.insert("total_bytes".to_owned(), json!(self.total_bytes));
        map.insert("acls".to_owned(), json!(self.acls()));
        map.insert(
            "changed".to_owned(),
            self.changed
                .iter()
                .map(|(path, why)| json!({"path": path, "reason": why}))
                .collect(),
        );
        map.insert("vanished".to_owned(), json!(self.vanished));
        map.insert(
            "skipped".to_owned(),
            self.skipped
                .iter()
                .map(|s| json!({"listed_in": s.listed_in, "id": s.id, "reason": s.reason}))
                .collect(),
        );
        map.insert(
            "unverified".to_owned(),
            self.unverified
                .iter()
                .map(|(path, status)| json!({"path": path, "status": status}))
                .collect(),
        );
        map
    }
}

/// Finishes the tar stream and the zstd frame, syncs the file, and returns
/// the archive's size and SHA-256.
fn finish_archive(archive: Archive) -> Result<(u64, Sha256Digest), CliError> {
    let encoder = archive.into_inner().map_err(|err| archive_error(&err))?;
    let mut hashing = encoder.finish().map_err(|err| archive_error(&err))?;
    hashing.flush().map_err(|err| archive_error(&err))?;
    let size = hashing.size;
    let digest: [u8; 32] = hashing.hasher.finalize().into();
    let file = hashing
        .inner
        .into_inner()
        .map_err(|err| archive_error(err.error()))?;
    file.sync_all().map_err(|err| archive_error(&err))?;
    Ok((size, Sha256Digest::from_bytes(digest)))
}

/// What an export does with files already at its final names.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Existing {
    /// Never replace them (the default).
    Keep,
    /// Replace them (`--force`).
    Replace,
}

/// Writes the manifest under its temporary name, then puts both files in
/// place with [`place`].
fn install(
    targets: &Targets,
    manifest: &Json,
    existing: Existing,
    cleanup: &mut Cleanup,
) -> Result<(), CliError> {
    let mut text = serde_json::to_vec_pretty(manifest)
        .map_err(|err| CliError::Local(format!("encoding the manifest failed: {err}")))?;
    text.push(b'\n');
    let mut file = create_private(&targets.manifest_temp, Access::Write)?;
    cleanup.0.push(targets.manifest_temp.clone());
    file.write_all(&text)
        .and_then(|()| file.sync_all())
        .map_err(|err| CliError::Local(format!("writing the manifest failed: {err}")))?;
    drop(file);
    place(targets, existing)
}

/// Puts the archive and then its manifest in place and syncs the directory.
///
/// The manifest is the commit point: it is always placed last, so a
/// manifest under the final name always describes the archive beside it.
/// An archive with no manifest is an export that did not finish.
///
/// With [`Existing::Keep`], both files are placed with [`private_file::place_new`],
/// which never replaces anything: a file that appeared at either name after
/// the absence check (another export, say) is kept, and the export fails.
/// If the manifest's name is taken, the archive placed a moment before is
/// withdrawn again.
///
/// With [`Existing::Replace`] (`--force`), two files cannot be replaced in
/// one atomic step, so the old manifest is first moved aside (and the directory synced), then the
/// archive and the manifest are renamed over the old files. If the archive
/// cannot be moved, the old manifest is moved back and the old pair is as
/// it was. If the manifest cannot be moved, the old one is discarded, as it
/// describes an archive that is gone, and the new archive stays with no
/// manifest. A crash between the steps leaves either the old archive or the
/// new one with no manifest, and at most a hidden `.<name>.manifest-old-…`
/// file. Concurrent forced exports to the same name are not coordinated.
fn place(targets: &Targets, existing: Existing) -> Result<(), CliError> {
    match existing {
        Existing::Keep => place_new(targets)?,
        Existing::Replace => place_replacing(targets)?,
    }
    sync_directory(targets, "the archive and its manifest are in place")
}

/// [`place`] with [`Existing::Keep`].
fn place_new(targets: &Targets) -> Result<(), CliError> {
    let refused = |path: &Path, err: &io::Error| {
        if err.kind() == io::ErrorKind::AlreadyExists {
            CliError::Local(format!(
                "{} already exists; pass --force to replace it",
                path.display()
            ))
        } else {
            CliError::Local(format!(
                "moving {} into place failed: {err}",
                path.display()
            ))
        }
    };
    let ours = fs::symlink_metadata(&targets.archive_temp)
        .map_err(|err| refused(&targets.archive, &err))?;
    private_file::place_new(&targets.archive_temp, &targets.archive)
        .map_err(|err| refused(&targets.archive, &err))?;
    if let Err(err) = private_file::place_new(&targets.manifest_temp, &targets.manifest) {
        // Withdraw the archive, but only if the name still holds our file.
        if let Ok(now) = fs::symlink_metadata(&targets.archive) {
            if (now.dev(), now.ino()) == (ours.dev(), ours.ino()) {
                let _removed = fs::remove_file(&targets.archive);
            }
        }
        return Err(refused(&targets.manifest, &err));
    }
    Ok(())
}

/// [`place`] with [`Existing::Replace`].
fn place_replacing(targets: &Targets) -> Result<(), CliError> {
    let aside = match fs::rename(&targets.manifest, &targets.manifest_aside) {
        Ok(()) => {
            sync_directory(targets, "the old manifest is set aside")?;
            Some(&targets.manifest_aside)
        }
        Err(err) if err.kind() == io::ErrorKind::NotFound => None,
        Err(err) => {
            return Err(CliError::Local(format!(
                "moving the old manifest {} aside failed: {err}",
                targets.manifest.display()
            )))
        }
    };
    if let Err(err) = fs::rename(&targets.archive_temp, &targets.archive) {
        let restored = aside.map_or(Ok(()), |old| fs::rename(old, &targets.manifest));
        let note = match restored {
            Ok(()) => String::new(),
            Err(restore) => format!(
                "; restoring the old manifest from {} failed: {restore}",
                targets.manifest_aside.display()
            ),
        };
        return Err(CliError::Local(format!(
            "moving the archive into place at {} failed: {err}{note}",
            targets.archive.display()
        )));
    }
    if let Some(old) = aside {
        // Best effort: it describes an archive that has just been replaced.
        let _removed = fs::remove_file(old);
    }
    fs::rename(&targets.manifest_temp, &targets.manifest).map_err(|err| {
        CliError::Local(format!(
            "the archive is in place at {}, but moving its manifest into place at {} failed: \
             {err}; no manifest is beside it",
            targets.archive.display(),
            targets.manifest.display()
        ))
    })
}

/// Syncs the target directory, so the renames so far are durable.
fn sync_directory(targets: &Targets, done: &str) -> Result<(), CliError> {
    File::open(&targets.directory)
        .and_then(|dir| dir.sync_all())
        .map_err(|err| {
            CliError::Local(format!(
                "{done}, but syncing {} failed: {err}",
                targets.directory.display()
            ))
        })
}

impl Session {
    /// `stratum export -o <archive.tar.zst> [--force]`: walks the caller's
    /// own pod over signed requests and writes it as a tar archive
    /// compressed with zstd, with a manifest beside it.
    ///
    /// The walk starts at the pod root `/pods/<pk>/` and fetches the root
    /// ACL `/pods/<pk>.acl`. Each child a listing names under `ldp:contains`
    /// is resolved against the listing's own address and followed only if
    /// the result is on the canonical origin, parses as a pod path under the
    /// Step 2 rules, is in the caller's own pod and lies under the container
    /// listed; anything else is skipped and reported. Redirects are never
    /// followed. For every container and resource the ACL beside it is
    /// asked for (a 404 means none). No entry is fetched twice.
    ///
    /// The archive holds `pods/<pk>/…` (containers as directories) and
    /// `pods/<pk>.acl`, so it unpacks to the bytes that were written. The
    /// manifest, `<archive>.manifest.json`, lists every entry's path, kind,
    /// size, SHA-256 and content type, which ACLs exist, the archive's own
    /// size and SHA-256, and what was skipped. The export is not a snapshot:
    /// after the walk each resource's entity tag and each container's
    /// listing is asked for again, and entries that changed or vanished are
    /// reported. The walk stops with an error at 100,000 entries or 64 GiB.
    ///
    /// Both files are written under temporary names in the target directory
    /// (mode `0600`) and moved into place only once complete, the archive
    /// first and the manifest last. A manifest present beside the archive
    /// therefore always describes that archive; an archive with no manifest
    /// is an export that did not finish and should not be trusted. Without
    /// `force`, nothing is ever replaced, including a file that appears at
    /// either name while the export runs: the export fails instead, and an
    /// archive it had already placed is withdrawn. With `force`, the old
    /// manifest is set aside before the archive is replaced, and put back if
    /// the archive cannot be moved; the limit is that a failure or crash
    /// between the two moves leaves the new (or old) archive with no
    /// manifest, never with a mismatched one. Concurrent forced exports to
    /// the same name are not coordinated.
    ///
    /// # Errors
    ///
    /// [`CliError::Local`] when a target exists without `force` (checked
    /// before the walk and again when the files are placed), a limit is
    /// reached or a file cannot be written; [`CliError::ExportIncomplete`]
    /// (after both files are written) when anything changed, vanished or
    /// was skipped; and key, transport and server errors.
    pub fn export(&self, target: &GateTarget, options: &ExportOptions) -> Result<u8, CliError> {
        let key = self.key()?;
        let me = key.public();
        let targets = Targets::new(&options.output)?;
        if !options.force {
            check_absent(&targets.archive)?;
            check_absent(&targets.manifest)?;
        }

        let mut cleanup = Cleanup::default();
        let archive_file = create_private(&targets.archive_temp, Access::Write)?;
        cleanup.0.push(targets.archive_temp.clone());
        let spool = create_private(&targets.spool, Access::ReadWrite)?;
        cleanup.0.push(targets.spool.clone());
        let encoder = zstd::stream::write::Encoder::new(
            Hashing {
                inner: BufWriter::new(archive_file),
                hasher: Sha256::new(),
                size: 0,
            },
            ZSTD_LEVEL,
        )
        .map_err(|err| archive_error(&err))?;
        let created_at = client::now()?;
        let mut walk = Walk {
            gate: GateClient::new(target.clone()).with_busy_retries(*self.output()),
            key: &key,
            root: PodPath::pod_root(&me),
            archive: tar::Builder::new(encoder),
            spool,
            created_at,
            entries: Vec::new(),
            visited: BTreeSet::new(),
            listings: BTreeMap::new(),
            skipped: Vec::new(),
            vanished: Vec::new(),
            changed: Vec::new(),
            unverified: Vec::new(),
            total_bytes: 0,
        };
        self.output()
            .note(&format!("exporting {} from {}", walk.root, target.origin()))?;
        walk.run()?;
        walk.verify()?;
        let (archive, findings) = Findings::from_walk(walk);
        let (archive_size, archive_sha256) = finish_archive(archive)?;

        let archive_name = targets
            .archive
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_default();
        let mut manifest = json!({
            "format": MANIFEST_FORMAT,
            "format_version": MANIFEST_FORMAT_VERSION,
            "origin": target.origin().as_str(),
            "owner": me,
            "pod_root": findings.root,
            "created_at": created_at,
            "archive": {"name": archive_name, "size": archive_size, "sha256": archive_sha256},
            "entries": findings.entries.iter().map(Entry::to_json).collect::<Vec<_>>(),
        });
        if let Json::Object(map) = &mut manifest {
            map.extend(findings.json_members());
        }
        let existing = if options.force {
            Existing::Replace
        } else {
            Existing::Keep
        };
        install(&targets, &manifest, existing, &mut cleanup)?;
        drop(cleanup);
        self.report_export(&targets, archive_size, archive_sha256, &findings)
    }

    /// Prints what an export wrote and found.
    fn report_export(
        &self,
        targets: &Targets,
        archive_size: u64,
        archive_sha256: Sha256Digest,
        findings: &Findings,
    ) -> Result<u8, CliError> {
        let mut report = json!({
            "archive": targets.archive.display().to_string(),
            "manifest": targets.manifest.display().to_string(),
            "archive_size": archive_size,
            "archive_sha256": archive_sha256,
            "entries": findings.entries.len(),
        });
        if let Json::Object(map) = &mut report {
            map.extend(findings.json_members());
        }
        self.output().json(&report)?;
        self.output().line(&format!(
            "archive: {} ({archive_size} bytes, sha256 {archive_sha256})",
            targets.archive.display()
        ))?;
        self.output()
            .line(&format!("manifest: {}", targets.manifest.display()))?;
        self.output().line(&format!(
            "entries: {} ({} bytes of content, {} ACLs)",
            findings.entries.len(),
            findings.total_bytes,
            findings.acls().len()
        ))?;
        for (path, why) in &findings.changed {
            self.output().line(&format!("changed: {path}: {why}"))?;
        }
        for path in &findings.vanished {
            self.output().line(&format!("vanished: {path}"))?;
        }
        for s in &findings.skipped {
            let place = s
                .listed_in
                .as_ref()
                .map(|p| format!(" (listed in {p})"))
                .unwrap_or_default();
            self.output()
                .line(&format!("skipped: {:?}{place}: {}", s.id, s.reason))?;
        }
        for (path, status) in &findings.unverified {
            self.output()
                .line(&format!("not rechecked: {path}: HTTP {status}"))?;
        }
        if findings.is_complete() {
            return Ok(exit::OK);
        }
        Err(CliError::ExportIncomplete(format!(
            "the archive is written, but {} entries changed, {} vanished and {} listed children \
             were skipped during the walk; the manifest lists them",
            findings.changed.len(),
            findings.vanished.len(),
            findings.skipped.len()
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn entity_tags_are_read_as_quoted_digests() {
        let hex = "ab".repeat(32);
        let digest: Sha256Digest = hex.parse().expect("digest");
        assert_eq!(sha256_tag(&format!("\"{hex}\"")), Some(digest));
        assert_eq!(sha256_tag(&format!("W/\"{hex}\"")), Some(digest));
        assert_eq!(sha256_tag(&hex), None);
        assert_eq!(sha256_tag("\"abc\""), None);
    }

    #[test]
    fn the_walk_stops_at_the_limits() {
        assert!(check_entry_limit(MAX_EXPORT_ENTRIES - 1).is_ok());
        let err = check_entry_limit(MAX_EXPORT_ENTRIES).expect_err("the 100,001st entry");
        assert!(err.to_string().contains("100000 entries"), "{err}");
        assert!(check_byte_limit(MAX_EXPORT_BYTES).is_ok());
        let err = check_byte_limit(MAX_EXPORT_BYTES + 1).expect_err("one byte over 64 GiB");
        assert!(err.to_string().contains("64 GiB"), "{err}");
        assert_eq!(err.exit_code(), exit::FAILURE);
    }

    #[test]
    fn targets_sit_beside_the_archive() {
        let targets = Targets::new(Path::new("out/pod.tar.zst")).expect("targets");
        assert_eq!(targets.manifest, Path::new("out/pod.tar.zst.manifest.json"));
        assert_eq!(targets.directory, Path::new("out"));
        assert!(targets
            .archive_temp
            .to_string_lossy()
            .starts_with("out/.pod.tar.zst.partial-"));
        let bare = Targets::new(Path::new("pod.tar.zst")).expect("targets");
        assert_eq!(bare.directory, Path::new("."));
    }
    /// An export's targets in a fresh directory, with both temporary files
    /// written: an archive holding `archive` and a manifest naming its
    /// SHA-256.
    fn staged(archive: &[u8]) -> (tempfile::TempDir, Targets) {
        let dir = tempfile::tempdir().expect("tempdir");
        let targets = Targets::new(&dir.path().join("pod.tar.zst")).expect("targets");
        fs::write(&targets.archive_temp, archive).expect("archive");
        fs::write(&targets.manifest_temp, manifest_for(archive)).expect("manifest");
        (dir, targets)
    }

    /// A manifest that describes `archive`.
    fn manifest_for(archive: &[u8]) -> Vec<u8> {
        json!({"archive": {"sha256": Sha256Digest::of(archive)}})
            .to_string()
            .into_bytes()
    }

    /// Whether the manifest beside the archive, if any, describes it.
    fn pair_is_consistent(targets: &Targets) -> bool {
        let Ok(manifest) = fs::read(&targets.manifest) else {
            return true;
        };
        let Ok(archive) = fs::read(&targets.archive) else {
            return false;
        };
        let manifest: Json = serde_json::from_slice(&manifest).expect("manifest json");
        manifest["archive"]["sha256"] == json!(Sha256Digest::of(&archive))
    }

    /// The names in `dir`, sorted.
    fn names(dir: &Path) -> Vec<String> {
        let mut names: Vec<String> = fs::read_dir(dir)
            .expect("read dir")
            .map(|entry| {
                entry
                    .expect("entry")
                    .file_name()
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();
        names.sort();
        names
    }

    #[test]
    fn an_archive_appearing_after_the_check_is_never_replaced() {
        let (_dir, targets) = staged(b"new");
        fs::write(&targets.archive, b"theirs").expect("theirs");
        let err = place(&targets, Existing::Keep).expect_err("refused");
        assert!(err.to_string().contains("already exists"), "{err}");
        assert_eq!(
            fs::read(&targets.archive).expect("archive"),
            b"theirs",
            "kept"
        );
        assert!(
            fs::metadata(&targets.manifest).is_err(),
            "no manifest beside it"
        );
    }

    #[test]
    fn a_manifest_appearing_after_the_check_is_never_replaced() {
        let (_dir, targets) = staged(b"new");
        fs::write(&targets.manifest, b"theirs").expect("theirs");
        let err = place(&targets, Existing::Keep).expect_err("refused");
        assert!(err.to_string().contains("already exists"), "{err}");
        assert_eq!(
            fs::read(&targets.manifest).expect("manifest"),
            b"theirs",
            "kept"
        );
        assert!(
            fs::metadata(&targets.archive).is_err(),
            "the archive placed a moment earlier is withdrawn"
        );
    }

    #[test]
    fn a_failed_manifest_step_never_leaves_a_new_archive_beside_an_old_manifest() {
        let (dir, targets) = staged(b"new");
        fs::write(&targets.archive, b"old").expect("old archive");
        fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
        fs::remove_file(&targets.manifest_temp).expect("make the manifest step fail");
        let err = place(&targets, Existing::Replace).expect_err("the manifest step fails");
        assert!(err.to_string().contains("no manifest"), "{err}");
        assert!(pair_is_consistent(&targets), "{:?}", names(dir.path()));
        let visible: Vec<String> = names(dir.path())
            .into_iter()
            .filter(|name| !name.starts_with('.'))
            .collect();
        assert_eq!(
            visible,
            ["pod.tar.zst"],
            "the archive alone, with no manifest"
        );
    }

    #[test]
    fn a_failed_archive_step_keeps_the_old_pair() {
        let (dir, targets) = staged(b"new");
        // A non-empty directory at the archive's name makes its rename fail.
        fs::create_dir(&targets.archive).expect("dir");
        fs::write(targets.archive.join("x"), b"x").expect("x");
        fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
        let err = place(&targets, Existing::Replace).expect_err("the archive step fails");
        assert!(err.to_string().contains("moving the archive"), "{err}");
        assert_eq!(
            fs::read(&targets.manifest).expect("manifest"),
            manifest_for(b"old"),
            "the old manifest is back: {:?}",
            names(dir.path())
        );
    }

    #[test]
    fn a_forced_export_replaces_the_pair() {
        let (dir, targets) = staged(b"new");
        fs::write(&targets.archive, b"old").expect("old archive");
        fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
        place(&targets, Existing::Replace).expect("placed");
        assert_eq!(fs::read(&targets.archive).expect("archive"), b"new", "new");
        assert!(pair_is_consistent(&targets), "the manifest describes it");
        assert_eq!(
            names(dir.path()),
            ["pod.tar.zst", "pod.tar.zst.manifest.json"],
            "nothing else is left"
        );
    }
}