Skip to main content

stratum_node_cli/
export.rs

1//! `stratum export`: a walk of the caller's own pod into a `.tar.zst`
2//! archive and a manifest beside it.
3
4use std::collections::{BTreeMap, BTreeSet, VecDeque};
5use std::fs::{self, File, OpenOptions};
6use std::io::{self, BufWriter, Read as _, Seek as _, SeekFrom, Write};
7use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
8use std::path::{Path, PathBuf};
9
10use serde_json::{json, Value as Json};
11use sha2::{Digest as _, Sha256};
12use stratum_node_core::{NostrSecretKey, PodPath, Sha256Digest, UnixTime};
13
14use crate::client::{self, MAX_RESPONSE_BYTES};
15use crate::error::CliError;
16use crate::exit;
17use crate::gate::{
18    self, GateClient, Head, Request, Route, ANY, LD_JSON, MAX_LISTING_BYTES, SUSPENDED,
19};
20use crate::listing::{self, Child};
21use crate::origin::GateTarget;
22use crate::output::sanitize;
23use crate::private_file;
24use crate::session::Session;
25
26/// The most entries an export holds before it stops: containers, resources
27/// and ACLs together.
28pub const MAX_EXPORT_ENTRIES: u64 = 100_000;
29
30/// The most bytes of resource content an export holds before it stops:
31/// 64 GiB.
32pub const MAX_EXPORT_BYTES: u64 = 64 * 1024 * 1024 * 1024;
33
34/// The `format` member of an export manifest.
35pub const MANIFEST_FORMAT: &str = "stratum-pod-export";
36
37/// The `format_version` member of an export manifest.
38pub const MANIFEST_FORMAT_VERSION: u64 = 1;
39
40/// The suffix appended to the archive's file name for the manifest.
41pub const MANIFEST_SUFFIX: &str = ".manifest.json";
42
43/// The zstd compression level: the library's default trade-off.
44const ZSTD_LEVEL: i32 = 3;
45
46/// Options for [`Session::export`].
47#[derive(Debug, Clone, Default)]
48pub struct ExportOptions {
49    /// The archive to write (`-o`), conventionally `<name>.tar.zst`. The
50    /// manifest is written beside it as `<archive>.manifest.json`.
51    pub output: PathBuf,
52    /// Replace an existing archive and manifest (`--force`).
53    pub force: bool,
54}
55
56/// What an archived entry is.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58enum Kind {
59    Container,
60    Resource,
61    Acl,
62}
63
64impl Kind {
65    fn as_str(self) -> &'static str {
66        match self {
67            Self::Container => "container",
68            Self::Resource => "resource",
69            Self::Acl => "acl",
70        }
71    }
72}
73
74/// Why an entry is being fetched, which decides what a 404 means.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76enum Reason {
77    /// It was named in a listing: a 404 means it vanished.
78    Listed,
79    /// It is the ACL beside a container or resource: a 404 means there is
80    /// none.
81    Beside,
82}
83
84/// One archived entry.
85#[derive(Debug, Clone)]
86struct Entry {
87    path: PodPath,
88    kind: Kind,
89    size: u64,
90    sha256: Option<Sha256Digest>,
91    content_type: Option<String>,
92    etag: Option<String>,
93}
94
95impl Entry {
96    fn to_json(&self) -> Json {
97        json!({
98            "path": self.path,
99            "archive_path": archive_path(&self.path),
100            "kind": self.kind.as_str(),
101            "size": self.size,
102            "sha256": self.sha256,
103            "content_type": self.content_type,
104        })
105    }
106}
107
108/// The archive path of a pod path: the path without its leading `/`, so
109/// the archive unpacks to `pods/<pk>/…` and `pods/<pk>.acl`.
110fn archive_path(path: &PodPath) -> &str {
111    path.as_str().trim_start_matches('/')
112}
113
114/// The files an export writes, and the temporary names it writes them under.
115#[derive(Debug)]
116struct Targets {
117    archive: PathBuf,
118    manifest: PathBuf,
119    directory: PathBuf,
120    archive_temp: PathBuf,
121    manifest_temp: PathBuf,
122    /// Where `--force` sets the old manifest aside while the archive moves.
123    manifest_aside: PathBuf,
124    spool: PathBuf,
125}
126
127impl Targets {
128    fn new(archive: &Path) -> Result<Self, CliError> {
129        let name = archive
130            .file_name()
131            .and_then(|n| n.to_str())
132            .filter(|n| !n.is_empty())
133            .ok_or_else(|| CliError::Usage("-o must name an archive file".to_owned()))?;
134        let directory = match archive.parent() {
135            Some(parent) if !parent.as_os_str().is_empty() => parent.to_owned(),
136            _ => PathBuf::from("."),
137        };
138        let tag = hex::encode(&client::random_32()?[..6]);
139        let mut manifest = archive.as_os_str().to_owned();
140        manifest.push(MANIFEST_SUFFIX);
141        Ok(Self {
142            archive: archive.to_owned(),
143            manifest: PathBuf::from(manifest),
144            archive_temp: directory.join(format!(".{name}.partial-{tag}")),
145            manifest_temp: directory.join(format!(".{name}.manifest-{tag}")),
146            manifest_aside: directory.join(format!(".{name}.manifest-old-{tag}")),
147            spool: directory.join(format!(".{name}.spool-{tag}")),
148            directory,
149        })
150    }
151}
152
153/// Removes the temporary files of an export that did not finish.
154#[derive(Debug, Default)]
155struct Cleanup(Vec<PathBuf>);
156
157impl Drop for Cleanup {
158    fn drop(&mut self) {
159        for path in &self.0 {
160            // Best effort: these are our own temporary files.
161            let _removed = fs::remove_file(path);
162        }
163    }
164}
165
166/// How a temporary file is opened.
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168enum Access {
169    /// Written only: the archive and the manifest.
170    Write,
171    /// Written and read back: the spool.
172    ReadWrite,
173}
174
175/// Creates a new `0600` file; an existing one is never opened.
176fn create_private(path: &Path, access: Access) -> Result<File, CliError> {
177    OpenOptions::new()
178        .read(access == Access::ReadWrite)
179        .write(true)
180        .create_new(true)
181        .mode(0o600)
182        .open(path)
183        .map_err(|err| CliError::Local(format!("creating {} failed: {err}", path.display())))
184}
185
186/// A writer that hashes and counts what passes through it.
187struct Hashing<W> {
188    inner: W,
189    hasher: Sha256,
190    size: u64,
191}
192
193impl<W: Write> Write for Hashing<W> {
194    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
195        let written = self.inner.write(buf)?;
196        self.hasher.update(&buf[..written]);
197        self.size = self
198            .size
199            .saturating_add(u64::try_from(written).unwrap_or(u64::MAX));
200        Ok(written)
201    }
202
203    fn flush(&mut self) -> io::Result<()> {
204        self.inner.flush()
205    }
206}
207
208/// The archive being written.
209type Archive = tar::Builder<zstd::stream::write::Encoder<'static, Hashing<BufWriter<File>>>>;
210
211/// Something listed that the walk did not follow.
212#[derive(Debug, Clone)]
213struct Skipped {
214    listed_in: Option<PodPath>,
215    id: String,
216    reason: String,
217}
218
219/// The state of one walk.
220struct Walk<'a> {
221    gate: GateClient,
222    key: &'a NostrSecretKey,
223    root: PodPath,
224    archive: Archive,
225    spool: File,
226    created_at: UnixTime,
227    entries: Vec<Entry>,
228    visited: BTreeSet<PodPath>,
229    listings: BTreeMap<PodPath, BTreeSet<PodPath>>,
230    skipped: Vec<Skipped>,
231    vanished: Vec<PodPath>,
232    changed: Vec<(PodPath, String)>,
233    unverified: Vec<(PodPath, u16)>,
234    total_bytes: u64,
235}
236
237impl Walk<'_> {
238    /// Walks the pod breadth first from its root.
239    fn run(&mut self) -> Result<(), CliError> {
240        let root = self.root.clone();
241        let root_acl = root
242            .acl_path()
243            .ok_or_else(|| CliError::Local("the pod root has no ACL path".to_owned()))?;
244        self.visited.insert(root.clone());
245        self.visited.insert(root_acl.clone());
246        self.fetch(&root_acl, Reason::Beside, None)?;
247        let mut queue = VecDeque::from([root.clone()]);
248        while let Some(container) = queue.pop_front() {
249            let Some(children) = self.list(&container)? else {
250                continue;
251            };
252            self.add_container(&container)?;
253            if container != root {
254                if let Some(acl) = container.acl_path() {
255                    if self.visited.insert(acl.clone()) {
256                        self.fetch(&acl, Reason::Beside, Some(&container))?;
257                    }
258                }
259            }
260            let mut accepted = BTreeSet::new();
261            for child in children {
262                let path = match child {
263                    Child::Accepted(path) => path,
264                    Child::Refused { id, reason } => {
265                        self.skipped.push(Skipped {
266                            listed_in: Some(container.clone()),
267                            id,
268                            reason,
269                        });
270                        continue;
271                    }
272                };
273                accepted.insert(path.clone());
274                if !self.visited.insert(path.clone()) {
275                    continue;
276                }
277                if path.is_container() {
278                    queue.push_back(path);
279                    continue;
280                }
281                let present = self.fetch(&path, Reason::Listed, Some(&container))?;
282                if present {
283                    if let Some(acl) = path.acl_path() {
284                        if self.visited.insert(acl.clone()) {
285                            self.fetch(&acl, Reason::Beside, Some(&container))?;
286                        }
287                    }
288                }
289            }
290            self.listings.insert(container, accepted);
291        }
292        Ok(())
293    }
294
295    /// Reads a container's listing; `None` when it vanished or redirected.
296    fn list(&mut self, container: &PodPath) -> Result<Option<Vec<Child>>, CliError> {
297        let response = self.gate.fetch(
298            &Request::new("GET", container.as_str(), LD_JSON),
299            Some(self.key),
300            MAX_LISTING_BYTES,
301        )?;
302        let head = &response.head;
303        if head.is_success() {
304            let origin = self.gate.target().origin().clone();
305            return listing::children(&origin, container, &response.body).map(Some);
306        }
307        if *container == self.root {
308            return Err(response.into_error(Route::Pod));
309        }
310        if head.status == 404 {
311            self.vanished.push(container.clone());
312            return Ok(None);
313        }
314        if head.is_redirect() {
315            self.skip_redirect(container, None);
316            return Ok(None);
317        }
318        Err(response.into_error(Route::Pod))
319    }
320
321    /// Records a redirect, which is never followed.
322    fn skip_redirect(&mut self, path: &PodPath, listed_in: Option<&PodPath>) {
323        self.skipped.push(Skipped {
324            listed_in: listed_in.cloned(),
325            id: path.to_string(),
326            reason: "answered with a redirect, which is not followed".to_owned(),
327        });
328    }
329
330    /// Refuses one more entry when the archive already holds the most.
331    fn count_entry(&self) -> Result<(), CliError> {
332        check_entry_limit(u64::try_from(self.entries.len()).unwrap_or(u64::MAX))
333    }
334
335    /// Adds a container's directory entry.
336    fn add_container(&mut self, container: &PodPath) -> Result<(), CliError> {
337        self.count_entry()?;
338        let mut header = tar::Header::new_gnu();
339        header.set_entry_type(tar::EntryType::Directory);
340        header.set_size(0);
341        header.set_mode(0o700);
342        header.set_mtime(self.created_at.as_secs());
343        self.archive
344            .append_data(&mut header, archive_path(container), io::empty())
345            .map_err(|err| archive_error(&err))?;
346        self.entries.push(Entry {
347            path: container.clone(),
348            kind: Kind::Container,
349            size: 0,
350            sha256: None,
351            content_type: None,
352            etag: None,
353        });
354        Ok(())
355    }
356
357    /// Fetches a resource or ACL into the archive. Returns `false` when it
358    /// is absent (a 404) or was skipped.
359    fn fetch(
360        &mut self,
361        path: &PodPath,
362        reason: Reason,
363        listed_in: Option<&PodPath>,
364    ) -> Result<bool, CliError> {
365        self.count_entry()?;
366        self.spool
367            .set_len(0)
368            .and_then(|()| self.spool.seek(SeekFrom::Start(0)).map(drop))
369            .map_err(|err| spool_error(&err))?;
370        let request = Request::new("GET", path.as_str(), ANY);
371        let (head, outcome) = {
372            let mut sink = BufWriter::new(&self.spool);
373            let result =
374                self.gate
375                    .stream(&request, self.key, &mut sink, gate::MAX_RESOURCE_BYTES)?;
376            sink.flush().map_err(|err| spool_error(&err))?;
377            result
378        };
379        let streamed = match outcome {
380            Ok(streamed) => streamed,
381            Err(body) => {
382                if head.status == 404 {
383                    if reason == Reason::Listed {
384                        self.vanished.push(path.clone());
385                    }
386                    return Ok(false);
387                }
388                if head.is_redirect() {
389                    self.skip_redirect(path, listed_in);
390                    return Ok(false);
391                }
392                return Err(gate::error_from(&head, &body, Route::Pod));
393            }
394        };
395        self.total_bytes = self.total_bytes.saturating_add(streamed.size);
396        check_byte_limit(self.total_bytes)?;
397        if let Some(tag) = head.etag.as_deref().and_then(sha256_tag) {
398            if tag != streamed.sha256 {
399                self.changed.push((
400                    path.clone(),
401                    "the bytes received do not match the entity tag sent with them".to_owned(),
402                ));
403            }
404        }
405        self.spool
406            .seek(SeekFrom::Start(0))
407            .map_err(|err| spool_error(&err))?;
408        let mut header = tar::Header::new_gnu();
409        header.set_entry_type(tar::EntryType::Regular);
410        header.set_size(streamed.size);
411        header.set_mode(0o600);
412        header.set_mtime(self.created_at.as_secs());
413        self.archive
414            .append_data(
415                &mut header,
416                archive_path(path),
417                (&self.spool).take(streamed.size),
418            )
419            .map_err(|err| archive_error(&err))?;
420        let kind = if path.acl_path().is_none() {
421            Kind::Acl
422        } else {
423            Kind::Resource
424        };
425        self.entries.push(Entry {
426            path: path.clone(),
427            kind,
428            size: streamed.size,
429            sha256: Some(streamed.sha256),
430            content_type: head.content_type.as_deref().map(sanitize),
431            etag: head.etag,
432        });
433        Ok(true)
434    }
435
436    /// Fails with the gate's `suspended` refusal when a signed read of the
437    /// pod root is refused that way: an export cannot finish once the
438    /// owner is suspended, and its archive would be missing entries.
439    fn abort_if_suspended(&self) -> Result<(), CliError> {
440        let response = self.gate.fetch(
441            &Request::new("GET", self.root.as_str(), LD_JSON),
442            Some(self.key),
443            MAX_LISTING_BYTES,
444        )?;
445        if gate::envelope_code(&response.body).as_deref() == Some(SUSPENDED) {
446            return Err(response.into_error(Route::Pod));
447        }
448        Ok(())
449    }
450
451    /// After the walk: asks again for every resource's entity tag and every
452    /// container's listing, and records what changed or vanished meanwhile.
453    /// A `suspended` refusal ends the export with that error.
454    fn verify(&mut self) -> Result<(), CliError> {
455        let files: Vec<Entry> = self
456            .entries
457            .iter()
458            .filter(|entry| entry.kind != Kind::Container)
459            .cloned()
460            .collect();
461        for entry in files {
462            let response = self.gate.fetch(
463                &Request::new("HEAD", entry.path.as_str(), ANY),
464                Some(self.key),
465                MAX_RESPONSE_BYTES,
466            )?;
467            let head: &Head = &response.head;
468            if head.status == 403 {
469                // A `HEAD` refusal has no body to name its reason, so ask
470                // once whether the gate now refuses this member outright.
471                self.abort_if_suspended()?;
472            }
473            if head.status == 404 {
474                self.vanished.push(entry.path);
475            } else if head.is_success() {
476                if let Some(now) = &head.etag {
477                    let before = entry.etag.as_deref().and_then(sha256_tag).or(entry.sha256);
478                    let differs = match (sha256_tag(now), before) {
479                        (Some(now), Some(before)) => now != before,
480                        _ => entry.etag.as_deref() != Some(now.as_str()),
481                    };
482                    if differs {
483                        self.changed.push((
484                            entry.path,
485                            "its entity tag changed during the export".to_owned(),
486                        ));
487                    }
488                }
489            } else {
490                self.unverified.push((entry.path, head.status));
491            }
492        }
493        let listings = std::mem::take(&mut self.listings);
494        for (container, before) in &listings {
495            let response = self.gate.fetch(
496                &Request::new("GET", container.as_str(), LD_JSON),
497                Some(self.key),
498                MAX_LISTING_BYTES,
499            )?;
500            if response.head.status == 404 {
501                self.vanished.push(container.clone());
502                continue;
503            }
504            if gate::envelope_code(&response.body).as_deref() == Some(SUSPENDED) {
505                return Err(response.into_error(Route::Pod));
506            }
507            if !response.head.is_success() {
508                self.unverified
509                    .push((container.clone(), response.head.status));
510                continue;
511            }
512            let origin = self.gate.target().origin().clone();
513            let now: BTreeSet<PodPath> = listing::children(&origin, container, &response.body)?
514                .into_iter()
515                .filter_map(|child| match child {
516                    Child::Accepted(path) => Some(path),
517                    Child::Refused { .. } => None,
518                })
519                .collect();
520            if now != *before {
521                self.changed.push((
522                    container.clone(),
523                    "its listing changed during the export".to_owned(),
524                ));
525            }
526        }
527        self.listings = listings;
528        Ok(())
529    }
530}
531
532/// Refuses another entry when `held` entries are already archived.
533fn check_entry_limit(held: u64) -> Result<(), CliError> {
534    if held >= MAX_EXPORT_ENTRIES {
535        return Err(CliError::Local(format!(
536            "export stopped: the pod holds more than {MAX_EXPORT_ENTRIES} entries; \
537             nothing was written"
538        )));
539    }
540    Ok(())
541}
542
543/// Refuses a walk whose content has grown to `total` bytes, past the limit.
544fn check_byte_limit(total: u64) -> Result<(), CliError> {
545    if total > MAX_EXPORT_BYTES {
546        return Err(CliError::Local(format!(
547            "export stopped: the pod holds more than {MAX_EXPORT_BYTES} bytes (64 GiB); \
548             nothing was written"
549        )));
550    }
551    Ok(())
552}
553
554/// Reads an entity tag that is the quoted SHA-256 of the body, as the pod
555/// server sends; `None` for any other tag.
556fn sha256_tag(etag: &str) -> Option<Sha256Digest> {
557    let tag = etag.strip_prefix("W/").unwrap_or(etag);
558    tag.strip_prefix('"')?.strip_suffix('"')?.parse().ok()
559}
560
561/// Maps a failure to write the archive.
562fn archive_error(err: &io::Error) -> CliError {
563    CliError::Local(format!("writing the archive failed: {err}"))
564}
565
566/// Maps a failure of the spool file.
567fn spool_error(err: &io::Error) -> CliError {
568    CliError::Local(format!("the export's temporary file failed: {err}"))
569}
570
571/// Refuses an existing file before any work is done. This is an early,
572/// friendly refusal only: [`place`] is what guarantees that nothing that
573/// appears later is replaced.
574fn check_absent(path: &Path) -> Result<(), CliError> {
575    if fs::symlink_metadata(path).is_ok() {
576        return Err(CliError::Local(format!(
577            "{} already exists; pass --force to replace it",
578            path.display()
579        )));
580    }
581    Ok(())
582}
583
584/// What a finished walk found, for the manifest and the report.
585#[derive(Debug)]
586struct Findings {
587    root: PodPath,
588    entries: Vec<Entry>,
589    skipped: Vec<Skipped>,
590    vanished: Vec<PodPath>,
591    changed: Vec<(PodPath, String)>,
592    unverified: Vec<(PodPath, u16)>,
593    total_bytes: u64,
594}
595
596impl Findings {
597    /// Splits a finished walk into the archive and what it found.
598    fn from_walk(walk: Walk<'_>) -> (Archive, Self) {
599        let findings = Self {
600            root: walk.root,
601            entries: walk.entries,
602            skipped: walk.skipped,
603            vanished: walk.vanished,
604            changed: walk.changed,
605            unverified: walk.unverified,
606            total_bytes: walk.total_bytes,
607        };
608        (walk.archive, findings)
609    }
610
611    /// The ACLs that exist.
612    fn acls(&self) -> Vec<&PodPath> {
613        self.entries
614            .iter()
615            .filter(|entry| entry.kind == Kind::Acl)
616            .map(|entry| &entry.path)
617            .collect()
618    }
619
620    /// Returns `true` when nothing changed, vanished or was skipped.
621    fn is_complete(&self) -> bool {
622        self.changed.is_empty() && self.vanished.is_empty() && self.skipped.is_empty()
623    }
624
625    /// The members the manifest and the report share.
626    fn json_members(&self) -> serde_json::Map<String, Json> {
627        let mut map = serde_json::Map::new();
628        map.insert("total_bytes".to_owned(), json!(self.total_bytes));
629        map.insert("acls".to_owned(), json!(self.acls()));
630        map.insert(
631            "changed".to_owned(),
632            self.changed
633                .iter()
634                .map(|(path, why)| json!({"path": path, "reason": why}))
635                .collect(),
636        );
637        map.insert("vanished".to_owned(), json!(self.vanished));
638        map.insert(
639            "skipped".to_owned(),
640            self.skipped
641                .iter()
642                .map(|s| json!({"listed_in": s.listed_in, "id": s.id, "reason": s.reason}))
643                .collect(),
644        );
645        map.insert(
646            "unverified".to_owned(),
647            self.unverified
648                .iter()
649                .map(|(path, status)| json!({"path": path, "status": status}))
650                .collect(),
651        );
652        map
653    }
654}
655
656/// Finishes the tar stream and the zstd frame, syncs the file, and returns
657/// the archive's size and SHA-256.
658fn finish_archive(archive: Archive) -> Result<(u64, Sha256Digest), CliError> {
659    let encoder = archive.into_inner().map_err(|err| archive_error(&err))?;
660    let mut hashing = encoder.finish().map_err(|err| archive_error(&err))?;
661    hashing.flush().map_err(|err| archive_error(&err))?;
662    let size = hashing.size;
663    let digest: [u8; 32] = hashing.hasher.finalize().into();
664    let file = hashing
665        .inner
666        .into_inner()
667        .map_err(|err| archive_error(err.error()))?;
668    file.sync_all().map_err(|err| archive_error(&err))?;
669    Ok((size, Sha256Digest::from_bytes(digest)))
670}
671
672/// What an export does with files already at its final names.
673#[derive(Debug, Clone, Copy, PartialEq, Eq)]
674enum Existing {
675    /// Never replace them (the default).
676    Keep,
677    /// Replace them (`--force`).
678    Replace,
679}
680
681/// Writes the manifest under its temporary name, then puts both files in
682/// place with [`place`].
683fn install(
684    targets: &Targets,
685    manifest: &Json,
686    existing: Existing,
687    cleanup: &mut Cleanup,
688) -> Result<(), CliError> {
689    let mut text = serde_json::to_vec_pretty(manifest)
690        .map_err(|err| CliError::Local(format!("encoding the manifest failed: {err}")))?;
691    text.push(b'\n');
692    let mut file = create_private(&targets.manifest_temp, Access::Write)?;
693    cleanup.0.push(targets.manifest_temp.clone());
694    file.write_all(&text)
695        .and_then(|()| file.sync_all())
696        .map_err(|err| CliError::Local(format!("writing the manifest failed: {err}")))?;
697    drop(file);
698    place(targets, existing)
699}
700
701/// Puts the archive and then its manifest in place and syncs the directory.
702///
703/// The manifest is the commit point: it is always placed last, so a
704/// manifest under the final name always describes the archive beside it.
705/// An archive with no manifest is an export that did not finish.
706///
707/// With [`Existing::Keep`], both files are placed with [`private_file::place_new`],
708/// which never replaces anything: a file that appeared at either name after
709/// the absence check (another export, say) is kept, and the export fails.
710/// If the manifest's name is taken, the archive placed a moment before is
711/// withdrawn again.
712///
713/// With [`Existing::Replace`] (`--force`), two files cannot be replaced in
714/// one atomic step, so the old manifest is first moved aside (and the directory synced), then the
715/// archive and the manifest are renamed over the old files. If the archive
716/// cannot be moved, the old manifest is moved back and the old pair is as
717/// it was. If the manifest cannot be moved, the old one is discarded, as it
718/// describes an archive that is gone, and the new archive stays with no
719/// manifest. A crash between the steps leaves either the old archive or the
720/// new one with no manifest, and at most a hidden `.<name>.manifest-old-…`
721/// file. Concurrent forced exports to the same name are not coordinated.
722fn place(targets: &Targets, existing: Existing) -> Result<(), CliError> {
723    match existing {
724        Existing::Keep => place_new(targets)?,
725        Existing::Replace => place_replacing(targets)?,
726    }
727    sync_directory(targets, "the archive and its manifest are in place")
728}
729
730/// [`place`] with [`Existing::Keep`].
731fn place_new(targets: &Targets) -> Result<(), CliError> {
732    let refused = |path: &Path, err: &io::Error| {
733        if err.kind() == io::ErrorKind::AlreadyExists {
734            CliError::Local(format!(
735                "{} already exists; pass --force to replace it",
736                path.display()
737            ))
738        } else {
739            CliError::Local(format!(
740                "moving {} into place failed: {err}",
741                path.display()
742            ))
743        }
744    };
745    let ours = fs::symlink_metadata(&targets.archive_temp)
746        .map_err(|err| refused(&targets.archive, &err))?;
747    private_file::place_new(&targets.archive_temp, &targets.archive)
748        .map_err(|err| refused(&targets.archive, &err))?;
749    if let Err(err) = private_file::place_new(&targets.manifest_temp, &targets.manifest) {
750        // Withdraw the archive, but only if the name still holds our file.
751        if let Ok(now) = fs::symlink_metadata(&targets.archive) {
752            if (now.dev(), now.ino()) == (ours.dev(), ours.ino()) {
753                let _removed = fs::remove_file(&targets.archive);
754            }
755        }
756        return Err(refused(&targets.manifest, &err));
757    }
758    Ok(())
759}
760
761/// [`place`] with [`Existing::Replace`].
762fn place_replacing(targets: &Targets) -> Result<(), CliError> {
763    let aside = match fs::rename(&targets.manifest, &targets.manifest_aside) {
764        Ok(()) => {
765            sync_directory(targets, "the old manifest is set aside")?;
766            Some(&targets.manifest_aside)
767        }
768        Err(err) if err.kind() == io::ErrorKind::NotFound => None,
769        Err(err) => {
770            return Err(CliError::Local(format!(
771                "moving the old manifest {} aside failed: {err}",
772                targets.manifest.display()
773            )))
774        }
775    };
776    if let Err(err) = fs::rename(&targets.archive_temp, &targets.archive) {
777        let restored = aside.map_or(Ok(()), |old| fs::rename(old, &targets.manifest));
778        let note = match restored {
779            Ok(()) => String::new(),
780            Err(restore) => format!(
781                "; restoring the old manifest from {} failed: {restore}",
782                targets.manifest_aside.display()
783            ),
784        };
785        return Err(CliError::Local(format!(
786            "moving the archive into place at {} failed: {err}{note}",
787            targets.archive.display()
788        )));
789    }
790    if let Some(old) = aside {
791        // Best effort: it describes an archive that has just been replaced.
792        let _removed = fs::remove_file(old);
793    }
794    fs::rename(&targets.manifest_temp, &targets.manifest).map_err(|err| {
795        CliError::Local(format!(
796            "the archive is in place at {}, but moving its manifest into place at {} failed: \
797             {err}; no manifest is beside it",
798            targets.archive.display(),
799            targets.manifest.display()
800        ))
801    })
802}
803
804/// Syncs the target directory, so the renames so far are durable.
805fn sync_directory(targets: &Targets, done: &str) -> Result<(), CliError> {
806    File::open(&targets.directory)
807        .and_then(|dir| dir.sync_all())
808        .map_err(|err| {
809            CliError::Local(format!(
810                "{done}, but syncing {} failed: {err}",
811                targets.directory.display()
812            ))
813        })
814}
815
816impl Session {
817    /// `stratum export -o <archive.tar.zst> [--force]`: walks the caller's
818    /// own pod over signed requests and writes it as a tar archive
819    /// compressed with zstd, with a manifest beside it.
820    ///
821    /// The walk starts at the pod root `/pods/<pk>/` and fetches the root
822    /// ACL `/pods/<pk>.acl`. Each child a listing names under `ldp:contains`
823    /// is resolved against the listing's own address and followed only if
824    /// the result is on the canonical origin, parses as a pod path under the
825    /// Step 2 rules, is in the caller's own pod and lies under the container
826    /// listed; anything else is skipped and reported. Redirects are never
827    /// followed. For every container and resource the ACL beside it is
828    /// asked for (a 404 means none). No entry is fetched twice.
829    ///
830    /// The archive holds `pods/<pk>/…` (containers as directories) and
831    /// `pods/<pk>.acl`, so it unpacks to the bytes that were written. The
832    /// manifest, `<archive>.manifest.json`, lists every entry's path, kind,
833    /// size, SHA-256 and content type, which ACLs exist, the archive's own
834    /// size and SHA-256, and what was skipped. The export is not a snapshot:
835    /// after the walk each resource's entity tag and each container's
836    /// listing is asked for again, and entries that changed or vanished are
837    /// reported. The walk stops with an error at 100,000 entries or 64 GiB.
838    ///
839    /// Both files are written under temporary names in the target directory
840    /// (mode `0600`) and moved into place only once complete, the archive
841    /// first and the manifest last. A manifest present beside the archive
842    /// therefore always describes that archive; an archive with no manifest
843    /// is an export that did not finish and should not be trusted. Without
844    /// `force`, nothing is ever replaced, including a file that appears at
845    /// either name while the export runs: the export fails instead, and an
846    /// archive it had already placed is withdrawn. With `force`, the old
847    /// manifest is set aside before the archive is replaced, and put back if
848    /// the archive cannot be moved; the limit is that a failure or crash
849    /// between the two moves leaves the new (or old) archive with no
850    /// manifest, never with a mismatched one. Concurrent forced exports to
851    /// the same name are not coordinated.
852    ///
853    /// # Errors
854    ///
855    /// [`CliError::Local`] when a target exists without `force` (checked
856    /// before the walk and again when the files are placed), a limit is
857    /// reached or a file cannot be written; [`CliError::ExportIncomplete`]
858    /// (after both files are written) when anything changed, vanished or
859    /// was skipped; and key, transport and server errors.
860    pub fn export(&self, target: &GateTarget, options: &ExportOptions) -> Result<u8, CliError> {
861        let key = self.key()?;
862        let me = key.public();
863        let targets = Targets::new(&options.output)?;
864        if !options.force {
865            check_absent(&targets.archive)?;
866            check_absent(&targets.manifest)?;
867        }
868
869        let mut cleanup = Cleanup::default();
870        let archive_file = create_private(&targets.archive_temp, Access::Write)?;
871        cleanup.0.push(targets.archive_temp.clone());
872        let spool = create_private(&targets.spool, Access::ReadWrite)?;
873        cleanup.0.push(targets.spool.clone());
874        let encoder = zstd::stream::write::Encoder::new(
875            Hashing {
876                inner: BufWriter::new(archive_file),
877                hasher: Sha256::new(),
878                size: 0,
879            },
880            ZSTD_LEVEL,
881        )
882        .map_err(|err| archive_error(&err))?;
883        let created_at = client::now()?;
884        let mut walk = Walk {
885            gate: GateClient::new(target.clone()).with_busy_retries(*self.output()),
886            key: &key,
887            root: PodPath::pod_root(&me),
888            archive: tar::Builder::new(encoder),
889            spool,
890            created_at,
891            entries: Vec::new(),
892            visited: BTreeSet::new(),
893            listings: BTreeMap::new(),
894            skipped: Vec::new(),
895            vanished: Vec::new(),
896            changed: Vec::new(),
897            unverified: Vec::new(),
898            total_bytes: 0,
899        };
900        self.output()
901            .note(&format!("exporting {} from {}", walk.root, target.origin()))?;
902        walk.run()?;
903        walk.verify()?;
904        let (archive, findings) = Findings::from_walk(walk);
905        let (archive_size, archive_sha256) = finish_archive(archive)?;
906
907        let archive_name = targets
908            .archive
909            .file_name()
910            .map(|n| n.to_string_lossy().into_owned())
911            .unwrap_or_default();
912        let mut manifest = json!({
913            "format": MANIFEST_FORMAT,
914            "format_version": MANIFEST_FORMAT_VERSION,
915            "origin": target.origin().as_str(),
916            "owner": me,
917            "pod_root": findings.root,
918            "created_at": created_at,
919            "archive": {"name": archive_name, "size": archive_size, "sha256": archive_sha256},
920            "entries": findings.entries.iter().map(Entry::to_json).collect::<Vec<_>>(),
921        });
922        if let Json::Object(map) = &mut manifest {
923            map.extend(findings.json_members());
924        }
925        let existing = if options.force {
926            Existing::Replace
927        } else {
928            Existing::Keep
929        };
930        install(&targets, &manifest, existing, &mut cleanup)?;
931        drop(cleanup);
932        self.report_export(&targets, archive_size, archive_sha256, &findings)
933    }
934
935    /// Prints what an export wrote and found.
936    fn report_export(
937        &self,
938        targets: &Targets,
939        archive_size: u64,
940        archive_sha256: Sha256Digest,
941        findings: &Findings,
942    ) -> Result<u8, CliError> {
943        let mut report = json!({
944            "archive": targets.archive.display().to_string(),
945            "manifest": targets.manifest.display().to_string(),
946            "archive_size": archive_size,
947            "archive_sha256": archive_sha256,
948            "entries": findings.entries.len(),
949        });
950        if let Json::Object(map) = &mut report {
951            map.extend(findings.json_members());
952        }
953        self.output().json(&report)?;
954        self.output().line(&format!(
955            "archive: {} ({archive_size} bytes, sha256 {archive_sha256})",
956            targets.archive.display()
957        ))?;
958        self.output()
959            .line(&format!("manifest: {}", targets.manifest.display()))?;
960        self.output().line(&format!(
961            "entries: {} ({} bytes of content, {} ACLs)",
962            findings.entries.len(),
963            findings.total_bytes,
964            findings.acls().len()
965        ))?;
966        for (path, why) in &findings.changed {
967            self.output().line(&format!("changed: {path}: {why}"))?;
968        }
969        for path in &findings.vanished {
970            self.output().line(&format!("vanished: {path}"))?;
971        }
972        for s in &findings.skipped {
973            let place = s
974                .listed_in
975                .as_ref()
976                .map(|p| format!(" (listed in {p})"))
977                .unwrap_or_default();
978            self.output()
979                .line(&format!("skipped: {:?}{place}: {}", s.id, s.reason))?;
980        }
981        for (path, status) in &findings.unverified {
982            self.output()
983                .line(&format!("not rechecked: {path}: HTTP {status}"))?;
984        }
985        if findings.is_complete() {
986            return Ok(exit::OK);
987        }
988        Err(CliError::ExportIncomplete(format!(
989            "the archive is written, but {} entries changed, {} vanished and {} listed children \
990             were skipped during the walk; the manifest lists them",
991            findings.changed.len(),
992            findings.vanished.len(),
993            findings.skipped.len()
994        )))
995    }
996}
997
998#[cfg(test)]
999mod tests {
1000    use super::*;
1001
1002    #[test]
1003    fn entity_tags_are_read_as_quoted_digests() {
1004        let hex = "ab".repeat(32);
1005        let digest: Sha256Digest = hex.parse().expect("digest");
1006        assert_eq!(sha256_tag(&format!("\"{hex}\"")), Some(digest));
1007        assert_eq!(sha256_tag(&format!("W/\"{hex}\"")), Some(digest));
1008        assert_eq!(sha256_tag(&hex), None);
1009        assert_eq!(sha256_tag("\"abc\""), None);
1010    }
1011
1012    #[test]
1013    fn the_walk_stops_at_the_limits() {
1014        assert!(check_entry_limit(MAX_EXPORT_ENTRIES - 1).is_ok());
1015        let err = check_entry_limit(MAX_EXPORT_ENTRIES).expect_err("the 100,001st entry");
1016        assert!(err.to_string().contains("100000 entries"), "{err}");
1017        assert!(check_byte_limit(MAX_EXPORT_BYTES).is_ok());
1018        let err = check_byte_limit(MAX_EXPORT_BYTES + 1).expect_err("one byte over 64 GiB");
1019        assert!(err.to_string().contains("64 GiB"), "{err}");
1020        assert_eq!(err.exit_code(), exit::FAILURE);
1021    }
1022
1023    #[test]
1024    fn targets_sit_beside_the_archive() {
1025        let targets = Targets::new(Path::new("out/pod.tar.zst")).expect("targets");
1026        assert_eq!(targets.manifest, Path::new("out/pod.tar.zst.manifest.json"));
1027        assert_eq!(targets.directory, Path::new("out"));
1028        assert!(targets
1029            .archive_temp
1030            .to_string_lossy()
1031            .starts_with("out/.pod.tar.zst.partial-"));
1032        let bare = Targets::new(Path::new("pod.tar.zst")).expect("targets");
1033        assert_eq!(bare.directory, Path::new("."));
1034    }
1035    /// An export's targets in a fresh directory, with both temporary files
1036    /// written: an archive holding `archive` and a manifest naming its
1037    /// SHA-256.
1038    fn staged(archive: &[u8]) -> (tempfile::TempDir, Targets) {
1039        let dir = tempfile::tempdir().expect("tempdir");
1040        let targets = Targets::new(&dir.path().join("pod.tar.zst")).expect("targets");
1041        fs::write(&targets.archive_temp, archive).expect("archive");
1042        fs::write(&targets.manifest_temp, manifest_for(archive)).expect("manifest");
1043        (dir, targets)
1044    }
1045
1046    /// A manifest that describes `archive`.
1047    fn manifest_for(archive: &[u8]) -> Vec<u8> {
1048        json!({"archive": {"sha256": Sha256Digest::of(archive)}})
1049            .to_string()
1050            .into_bytes()
1051    }
1052
1053    /// Whether the manifest beside the archive, if any, describes it.
1054    fn pair_is_consistent(targets: &Targets) -> bool {
1055        let Ok(manifest) = fs::read(&targets.manifest) else {
1056            return true;
1057        };
1058        let Ok(archive) = fs::read(&targets.archive) else {
1059            return false;
1060        };
1061        let manifest: Json = serde_json::from_slice(&manifest).expect("manifest json");
1062        manifest["archive"]["sha256"] == json!(Sha256Digest::of(&archive))
1063    }
1064
1065    /// The names in `dir`, sorted.
1066    fn names(dir: &Path) -> Vec<String> {
1067        let mut names: Vec<String> = fs::read_dir(dir)
1068            .expect("read dir")
1069            .map(|entry| {
1070                entry
1071                    .expect("entry")
1072                    .file_name()
1073                    .to_string_lossy()
1074                    .into_owned()
1075            })
1076            .collect();
1077        names.sort();
1078        names
1079    }
1080
1081    #[test]
1082    fn an_archive_appearing_after_the_check_is_never_replaced() {
1083        let (_dir, targets) = staged(b"new");
1084        fs::write(&targets.archive, b"theirs").expect("theirs");
1085        let err = place(&targets, Existing::Keep).expect_err("refused");
1086        assert!(err.to_string().contains("already exists"), "{err}");
1087        assert_eq!(
1088            fs::read(&targets.archive).expect("archive"),
1089            b"theirs",
1090            "kept"
1091        );
1092        assert!(
1093            fs::metadata(&targets.manifest).is_err(),
1094            "no manifest beside it"
1095        );
1096    }
1097
1098    #[test]
1099    fn a_manifest_appearing_after_the_check_is_never_replaced() {
1100        let (_dir, targets) = staged(b"new");
1101        fs::write(&targets.manifest, b"theirs").expect("theirs");
1102        let err = place(&targets, Existing::Keep).expect_err("refused");
1103        assert!(err.to_string().contains("already exists"), "{err}");
1104        assert_eq!(
1105            fs::read(&targets.manifest).expect("manifest"),
1106            b"theirs",
1107            "kept"
1108        );
1109        assert!(
1110            fs::metadata(&targets.archive).is_err(),
1111            "the archive placed a moment earlier is withdrawn"
1112        );
1113    }
1114
1115    #[test]
1116    fn a_failed_manifest_step_never_leaves_a_new_archive_beside_an_old_manifest() {
1117        let (dir, targets) = staged(b"new");
1118        fs::write(&targets.archive, b"old").expect("old archive");
1119        fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
1120        fs::remove_file(&targets.manifest_temp).expect("make the manifest step fail");
1121        let err = place(&targets, Existing::Replace).expect_err("the manifest step fails");
1122        assert!(err.to_string().contains("no manifest"), "{err}");
1123        assert!(pair_is_consistent(&targets), "{:?}", names(dir.path()));
1124        let visible: Vec<String> = names(dir.path())
1125            .into_iter()
1126            .filter(|name| !name.starts_with('.'))
1127            .collect();
1128        assert_eq!(
1129            visible,
1130            ["pod.tar.zst"],
1131            "the archive alone, with no manifest"
1132        );
1133    }
1134
1135    #[test]
1136    fn a_failed_archive_step_keeps_the_old_pair() {
1137        let (dir, targets) = staged(b"new");
1138        // A non-empty directory at the archive's name makes its rename fail.
1139        fs::create_dir(&targets.archive).expect("dir");
1140        fs::write(targets.archive.join("x"), b"x").expect("x");
1141        fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
1142        let err = place(&targets, Existing::Replace).expect_err("the archive step fails");
1143        assert!(err.to_string().contains("moving the archive"), "{err}");
1144        assert_eq!(
1145            fs::read(&targets.manifest).expect("manifest"),
1146            manifest_for(b"old"),
1147            "the old manifest is back: {:?}",
1148            names(dir.path())
1149        );
1150    }
1151
1152    #[test]
1153    fn a_forced_export_replaces_the_pair() {
1154        let (dir, targets) = staged(b"new");
1155        fs::write(&targets.archive, b"old").expect("old archive");
1156        fs::write(&targets.manifest, manifest_for(b"old")).expect("old manifest");
1157        place(&targets, Existing::Replace).expect("placed");
1158        assert_eq!(fs::read(&targets.archive).expect("archive"), b"new", "new");
1159        assert!(pair_is_consistent(&targets), "the manifest describes it");
1160        assert_eq!(
1161            names(dir.path()),
1162            ["pod.tar.zst", "pod.tar.zst.manifest.json"],
1163            "nothing else is left"
1164        );
1165    }
1166}