steid

@jamesgill /

Rust70.6 KBCode·Blame·History·Raw
1//! Backup adapters: a consistent database snapshot, and the `tar.gz` it travels in.
2//!
3//! Two ports, one file, because they are two halves of one file format and reading them
4//! apart would mean reading the layout twice.
5//!
6//! **The archive work is blocking.** `tar` and `flate2` are synchronous, and gzipping a
7//! repository directory is real CPU rather than a wait, so every one of these runs
8//! inside `spawn_blocking` rather than pretending to be async on the runtime's threads.
9
10use std::{
11 cmp::Ordering,
12 ffi::OsStr,
13 fs::{self, File},
14 io::{self, Read, Write},
15 path::{Path, PathBuf},
16 sync::{Arc, Mutex},
17 time::{SystemTime, UNIX_EPOCH},
18};
19
20use flate2::{Compression, read::GzDecoder, write::GzEncoder};
21use sqlx::SqlitePool;
22
23use crate::application::{
24 backup::BackupManifest,
25 port::{
26 BACKUP_DATA_PREFIX, BACKUP_DATABASE, BACKUP_MANIFEST, BackupArchive, BackupError,
27 BackupPlan, DatabaseSnapshot, ExistingData, RestorePlan,
28 },
29};
30
31/// Where the live SQLite database file is, read out of a connection string.
32///
33/// `sqlite:steid.db?mode=rwc`, `sqlite://steid.db`, and a bare path all name a file;
34/// `sqlite::memory:` names nothing, which is `None` rather than an error — an in-memory
35/// instance genuinely has no file to snapshot, and saying so is more useful than
36/// inventing a path called `:memory:`.
37#[must_use]
38pub fn database_file(url: &str) -> Option<PathBuf> {
39 let rest = url
40 .strip_prefix("sqlite://")
41 .or_else(|| url.strip_prefix("sqlite:"))
42 .unwrap_or(url);
43
44 // Everything from the first `?` is sqlx's own options — `mode=rwc` and friends —
45 // and is not part of the filename.
46 let path = rest.split('?').next().unwrap_or_default();
47
48 (!path.is_empty() && path != ":memory:").then(|| PathBuf::from(path))
49}
50
51/// `VACUUM INTO`, which is SQLite's own answer to "copy this while it is in use".
52#[derive(Debug, Clone)]
53pub struct SqliteDatabaseSnapshot {
54 pool: SqlitePool,
55 /// The live file, for [`replace`](DatabaseSnapshot::replace). Never read when only
56 /// taking a snapshot — that goes through the pool, which is the point.
57 database: PathBuf,
58}
59
60impl SqliteDatabaseSnapshot {
61 pub fn new(pool: SqlitePool, database: impl Into<PathBuf>) -> Self {
62 Self {
63 pool,
64 database: database.into(),
65 }
66 }
67}
68
69impl DatabaseSnapshot for SqliteDatabaseSnapshot {
70 async fn snapshot(&self, workspace: &Path) -> Result<PathBuf, BackupError> {
71 let destination = workspace.join(format!("steid-snapshot-{}.db", uuid::Uuid::new_v4()));
72
73 let target = destination
74 .to_str()
75 .ok_or_else(|| BackupError::backend("the workspace path is not valid UTF-8"))?;
76
77 // Bound rather than interpolated: the path is ours, but a filename reaching a
78 // SQL statement by string concatenation is how the next one gets there too.
79 // `VACUUM INTO` refuses a destination that already exists, which is why the
80 // filename carries a fresh UUID rather than being a fixed name in a fresh
81 // directory — a workspace reused by mistake fails loudly instead of silently
82 // packing yesterday's database.
83 sqlx::query("vacuum into ?")
84 .bind(target)
85 .execute(&self.pool)
86 .await
87 .map_err(BackupError::backend)?;
88
89 Ok(destination)
90 }
91
92 async fn replace(&self, source: &Path) -> Result<(), BackupError> {
93 // Nothing may hold the file across the swap. Closing a clone closes the pool
94 // every other adapter in this process shares, which is the intent: after this
95 // line the process has no database, and the only thing it may do is finish
96 // restoring and exit.
97 self.pool.close().await;
98
99 let source = source.to_path_buf();
100 let database = self.database.clone();
101
102 blocking(move || {
103 // The journal siblings go first. A `-wal` left beside a replaced database
104 // belongs to the database that is no longer there, and SQLite would apply
105 // it — which is corruption, not staleness.
106 for suffix in ["-wal", "-shm"] {
107 let sibling = sibling(&database, suffix);
108 if sibling.exists() {
109 fs::remove_file(&sibling).map_err(BackupError::backend)?;
110 }
111 }
112
113 move_file(&source, &database)
114 })
115 .await
116 }
117}
118
119/// One backup as a gzipped tar.
120///
121/// The layout is the port's contract: `manifest.json`, `steid.db`, and the data
122/// directory under `data/`.
123#[derive(Debug, Clone, Copy, Default)]
124pub struct TarGzBackupArchive;
125
126impl TarGzBackupArchive {
127 #[must_use]
128 pub fn new() -> Self {
129 Self
130 }
131}
132
133impl BackupArchive for TarGzBackupArchive {
134 async fn pack(&self, plan: BackupPlan) -> Result<u64, BackupError> {
135 blocking(move || pack(&plan)).await
136 }
137
138 async fn manifest(&self, archive: &Path) -> Result<BackupManifest, BackupError> {
139 let archive = archive.to_path_buf();
140 blocking(move || read_manifest(&archive)).await
141 }
142
143 async fn unpack(&self, plan: RestorePlan) -> Result<(), BackupError> {
144 blocking(move || unpack(&plan)).await
145 }
146}
147
148/// Runs synchronous filesystem work off the runtime's threads.
149async fn blocking<T, F>(work: F) -> Result<T, BackupError>
150where
151 F: FnOnce() -> Result<T, BackupError> + Send + 'static,
152 T: Send + 'static,
153{
154 tokio::task::spawn_blocking(work)
155 .await
156 .map_err(BackupError::backend)?
157}
158
159/// `steid.db` → `steid.db-wal`.
160fn sibling(database: &Path, suffix: &str) -> PathBuf {
161 let mut name = database.as_os_str().to_os_string();
162 name.push(suffix);
163 PathBuf::from(name)
164}
165
166/// Moves a file, falling back to a copy when the two ends are on different filesystems.
167///
168/// A backup destination on a mounted volume is the ordinary case rather than the exotic
169/// one, and `rename` answers `EXDEV` there.
170fn move_file(source: &Path, destination: &Path) -> Result<(), BackupError> {
171 if let Some(parent) = destination.parent() {
172 fs::create_dir_all(parent).map_err(BackupError::backend)?;
173 }
174
175 match fs::rename(source, destination) {
176 Ok(()) => Ok(()),
177 Err(_) => {
178 fs::copy(source, destination).map_err(BackupError::backend)?;
179 // Best effort: the copy is what matters, and a scratch file left behind is
180 // the caller's workspace to clean up anyway.
181 let _ = fs::remove_file(source);
182 Ok(())
183 }
184 }
185}
186
187/// Writes the archive, and says how large it came out.
188///
189/// Built beside the destination as `<name>.partial` and renamed at the end, so an
190/// interrupted backup leaves something obviously unfinished rather than a truncated
191/// `.tar.gz` a later restore would trust.
192fn pack(plan: &BackupPlan) -> Result<u64, BackupError> {
193 pack_with(plan, &mut |_, _| {})
194}
195
196/// A point in the walk at which [`pack_with`] calls its hook, with the path it is at.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198enum Moment {
199 /// Just before the walk looks at the path: before it is listed, stat'ed or opened.
200 Reaching,
201 /// The file is open and the size its header declares has been read; its bytes are
202 /// copied next.
203 Copying,
204}
205
206/// [`pack`], calling `watch` at each [`Moment`] of the walk of the data directory.
207///
208/// The seam the race tests stand in. The data directory is copied while pushes and git's
209/// own housekeeping keep running, and a hook that pushes, packs refs, deletes a file or
210/// grows one at one exact point in the walk is what makes each of those races repeatable
211/// rather than a matter of timing. Nothing but a test passes anything other than a no-op.
212fn pack_with(plan: &BackupPlan, watch: &mut dyn FnMut(Moment, &Path)) -> Result<u64, BackupError> {
213 if plan.destination.exists() {
214 return Err(BackupError::refused(format!(
215 "{} already exists",
216 plan.destination.display()
217 )));
218 }
219
220 if let Some(parent) = plan
221 .destination
222 .parent()
223 .filter(|parent| !parent.as_os_str().is_empty())
224 {
225 fs::create_dir_all(parent).map_err(BackupError::backend)?;
226 }
227
228 let partial = sibling(&plan.destination, ".partial");
229 let file = File::create(&partial).map_err(BackupError::backend)?;
230 let mut builder = tar::Builder::new(GzEncoder::new(file, Compression::default()));
231 // Never follow a symlink out of the data directory: with this off, a link is
232 // archived as a link, and `unpack` refuses one outright.
233 builder.follow_symlinks(false);
234
235 let manifest = serde_json::to_vec_pretty(&plan.manifest).map_err(BackupError::backend)?;
236 let mut header = tar::Header::new_gnu();
237 header.set_size(manifest.len() as u64);
238 header.set_mode(0o600);
239 header.set_mtime(epoch_seconds());
240 header.set_cksum();
241 builder
242 .append_data(&mut header, BACKUP_MANIFEST, manifest.as_slice())
243 .map_err(BackupError::backend)?;
244
245 builder
246 .append_path_with_name(&plan.database, BACKUP_DATABASE)
247 .map_err(BackupError::backend)?;
248
249 append_data_dir(&mut builder, &plan.data_dir, watch)?;
250
251 let encoder = builder.into_inner().map_err(BackupError::backend)?;
252 let mut file = encoder.finish().map_err(BackupError::backend)?;
253 file.flush().map_err(BackupError::backend)?;
254 drop(file);
255
256 let bytes = fs::metadata(&partial).map_err(BackupError::backend)?.len();
257 fs::rename(&partial, &plan.destination).map_err(BackupError::backend)?;
258
259 Ok(bytes)
260}
261
262fn epoch_seconds() -> u64 {
263 SystemTime::now()
264 .duration_since(UNIX_EPOCH)
265 .map(|since| since.as_secs())
266 .unwrap_or_default()
267}
268
269/// Adds the whole data directory under `data/`.
270///
271/// Walked by hand rather than with `append_dir_all`, for rules that walk cannot express:
272///
273/// - **A repository is copied in git's own order** — see [`walk_order`] — because the
274/// directory is copied while pushes and `gc --auto` keep writing to it.
275/// - **Git's own scratch is never archived** — see [`is_scratch`] — and **anything else
276/// that vanishes mid-walk fails the backup**, naming it ([`unreadable`]).
277/// - **A file holds exactly the bytes it held when opened**, so one git appends to
278/// mid-copy cannot tear the archive — see [`copy_file`].
279/// - **Symlinks are skipped**, not followed and not stored. A link inside a bare
280/// repository is not something git puts there, and following one is the only way a
281/// path outside the data directory could get into the archive.
282/// - **Top-level dot-directories are skipped.** A handle is `[a-z0-9-]` and can never
283/// start with a dot, so nothing here is a repository — and the backup's own scratch
284/// directory lives at `<data_dir>/.backup`, which must not end up inside the archive
285/// it is being built in.
286/// - **Anything that is neither a file nor a directory is skipped**, with a line saying
287/// so, rather than failing the backup over a stray socket or device node.
288fn append_data_dir<W: Write>(
289 builder: &mut tar::Builder<W>,
290 data_dir: &Path,
291 watch: &mut dyn FnMut(Moment, &Path),
292) -> Result<(), BackupError> {
293 // The root, always — a restore of an instance with no repositories must still make
294 // the directory.
295 let mut root = tar::Header::new_gnu();
296 root.set_entry_type(tar::EntryType::Directory);
297 root.set_size(0);
298 root.set_mode(0o750);
299 root.set_mtime(epoch_seconds());
300 root.set_cksum();
301 builder
302 .append_data(&mut root, format!("{BACKUP_DATA_PREFIX}/"), io::empty())
303 .map_err(BackupError::backend)?;
304
305 if !data_dir.is_dir() {
306 return Ok(());
307 }
308
309 walk(builder, data_dir, data_dir, Place::Top, watch)
310}
311
312/// The file git keeps packed refs in, inside a bare repository.
313const PACKED_REFS: &str = "packed-refs";
314
315/// The directory git keeps objects in, inside a bare repository.
316const OBJECTS: &str = "objects";
317
318/// The directory git keeps packs in, inside `objects/`.
319const PACKS: &str = "pack";
320
321/// Where in the data directory the walk is, which decides the rules that apply there.
322///
323/// Read off Steid's own layout, `{data_dir}/{handle}/{name}.git`, rather than by looking
324/// inside directories for something repository-shaped — the reason `DiskGitStorage`
325/// walks it as two levels of its own making. Inside a repository nothing is re-read as a
326/// repository, because a branch may be called `objects/x` or `x.git/y`.
327#[derive(Debug, Clone, Copy, PartialEq, Eq)]
328enum Place {
329 /// The data directory itself.
330 Top,
331 /// One level down: a handle's directory, or `orphaned/`.
332 Handle,
333 /// A bare repository's own directory, walked in [`walk_order`].
334 Repository,
335 /// Inside a repository, outside its `objects/`.
336 InRepository,
337 /// A repository's `objects/` directory itself.
338 Objects,
339 /// A repository's `objects/pack/`.
340 Packs,
341 /// Anywhere deeper inside a repository's `objects/`.
342 InObjects,
343 /// Anything else, such as a quarantined repository under `orphaned/`, which nothing
344 /// writes to any more.
345 Elsewhere,
346}
347
348impl Place {
349 /// Where the directory `name`, found here, is.
350 fn below(self, name: &str) -> Self {
351 match self {
352 Self::Top => Self::Handle,
353 Self::Handle if name.ends_with(".git") => Self::Repository,
354 Self::Handle | Self::Elsewhere => Self::Elsewhere,
355 Self::Repository if name == OBJECTS => Self::Objects,
356 Self::Repository | Self::InRepository => Self::InRepository,
357 Self::Objects if name == PACKS => Self::Packs,
358 Self::Objects | Self::Packs | Self::InObjects => Self::InObjects,
359 }
360 }
361
362 /// Whether this is a repository's `objects/` or anywhere inside it.
363 fn is_objects(self) -> bool {
364 matches!(self, Self::Objects | Self::Packs | Self::InObjects)
365 }
366}
367
368/// The order a bare repository's own entries are copied in: everything else by name,
369/// then `packed-refs`, then `objects`.
370///
371/// This is git's own rule for reading a repository while it is being written, and the
372/// archive is read exactly that way, because pushes and `gc --auto` carry on throughout:
373///
374/// - **Refs before objects.** Git writes a commit's objects before it moves a ref to it,
375/// so a ref read first names objects that already exist, and they still exist when
376/// `objects/` is copied after: a ref moved away in between leaves its old commit in
377/// the reflog, which gc keeps. Copied the other way round, a push landing between the
378/// two leaves a ref naming a commit the archive does not hold.
379/// - **Loose refs before `packed-refs`.** `pack-refs`, part of `gc --auto`, writes a ref
380/// into `packed-refs` before it deletes the loose file, so read in this order a ref is
381/// in one or the other. Read the other way round, a `pack-refs` landing in between
382/// drops the branch from the archive entirely.
383///
384/// Every other entry keeps its sorted place, so two backups of one state still list the
385/// same entries in the same order.
386fn walk_order(a: &Path, b: &Path) -> Ordering {
387 fn rank(path: &Path) -> u8 {
388 match path.file_name().and_then(OsStr::to_str) {
389 Some(PACKED_REFS) => 1,
390 Some(OBJECTS) => 2,
391 _ => 0,
392 }
393 }
394
395 rank(a).cmp(&rank(b)).then_with(|| a.cmp(b))
396}
397
398/// Whether `name`, found in a directory at `place`, is git's own scratch, which a backup
399/// never archives.
400///
401/// This is launch decision 10, as amended on 2026-10-21: never archive `*.lock`,
402/// `objects/tmp_*` or `objects/pack/*.keep`, and fail loudly if anything else vanishes
403/// ([`unreadable`]).
404///
405/// - **`*.lock`, anywhere.** Git takes a lock by creating `<file>.lock` and lets go by
406/// renaming or deleting it. An archived one outlives the process that held it: a
407/// restored `refs/heads/main.lock` refuses every push to `main`. Git forbids a refname
408/// ending in `.lock`, so no ref is ever one, and Steid writes no file of that name.
409/// - **`tmp_*` under a repository's `objects/`.** The push quarantine
410/// (`tmp_objdir-incoming-*`), a pack being indexed (`pack/tmp_pack_*`), a loose object
411/// being written (`tmp_obj_*`). Each becomes real only by a rename to its final name,
412/// which the walk copies if it is there by then. Outside `objects/` the rule does not
413/// apply: a branch may be called `tmp_x`.
414/// - **`*.keep` in a repository's `objects/pack/`, and nowhere else.** receive-pack keeps
415/// a push of 100 objects or more (`receive.unpackLimit`) as a pack, and marks it
416/// `pack-<hash>.keep` from the moment it is written until the push's refs are in, so
417/// that a gc running meanwhile leaves it alone; then it deletes the marker. Listed and
418/// gone by its turn, it failed backups of busy repositories for nothing. A `.keep` only
419/// asks gc not to repack a pack, so one left out — even one an administrator made on
420/// purpose — costs at most a repack after a restore, never an object. Only that
421/// directory: a branch may be called `x.keep`, and branches live under `refs/`.
422///
423/// All three go by name alone, before anything is read, so one that disappears between
424/// the listing and its turn — which is what they do — cannot fail the backup.
425fn is_scratch(place: Place, name: &str) -> bool {
426 name.ends_with(".lock")
427 || (place.is_objects() && name.starts_with("tmp_"))
428 || (place == Place::Packs && name.ends_with(".keep"))
429}
430
431/// A failure to read `path` during the walk, naming it.
432///
433/// **Something that vanished fails the backup**, loudly. The walk listed it and it was
434/// gone before it could be read: gc replacing a pack, `pack-refs` pruning a loose ref, a
435/// repository deleted mid-backup. Skipped quietly, the archive would lack it — a pack's
436/// objects, a branch — and nothing would say so until a restore. Git's own scratch never
437/// gets this far ([`is_scratch`]), a push's `.keep` included. A failed backup costs a rerun; a quietly incomplete
438/// one costs the data it was taken to keep.
439fn unreadable(path: &Path, error: &io::Error) -> BackupError {
440 if error.kind() == io::ErrorKind::NotFound {
441 BackupError::backend(format!(
442 "{} vanished while the backup was copying it, so the archive would have been \
443 missing it and was not finished. Something changed the data directory \
444 mid-backup — a push, or git's own housekeeping; run the backup again",
445 path.display()
446 ))
447 } else {
448 BackupError::backend(format!("could not back up {}: {error}", path.display()))
449 }
450}
451
452fn walk<W: Write>(
453 builder: &mut tar::Builder<W>,
454 data_dir: &Path,
455 dir: &Path,
456 place: Place,
457 watch: &mut dyn FnMut(Moment, &Path),
458) -> Result<(), BackupError> {
459 let mut entries: Vec<PathBuf> = fs::read_dir(dir)
460 .map_err(|error| unreadable(dir, &error))?
461 .map(|entry| entry.map(|entry| entry.path()))
462 .collect::<Result<_, _>>()
463 .map_err(|error| unreadable(dir, &error))?;
464
465 // `packed-refs` is looked for at its turn, not taken from this listing. The listing is
466 // made before the loose refs are read, and a `pack-refs` in between creates the file
467 // and prunes the loose refs into it: had the walk gone by the listing, a repository
468 // that had no `packed-refs` when the backup reached it would lose every branch. Git
469 // reads it the same way, at the moment it needs it.
470 let mut looked_for = None;
471
472 // Directory order is filesystem order, which differs between machines. Sorting makes
473 // two backups of the same state produce the same entry order, which is what lets
474 // anyone compare them.
475 if place == Place::Repository {
476 let packed_refs = dir.join(PACKED_REFS);
477 if !entries.contains(&packed_refs) {
478 entries.push(packed_refs.clone());
479 looked_for = Some(packed_refs);
480 }
481
482 entries.sort_by(|a, b| walk_order(a, b));
483 } else {
484 entries.sort();
485 }
486
487 for path in entries {
488 watch(Moment::Reaching, &path);
489
490 let name = path
491 .file_name()
492 .and_then(|name| name.to_str())
493 .ok_or_else(|| {
494 BackupError::backend(format!("{} is not a valid UTF-8 name", path.display()))
495 })?;
496
497 if (place == Place::Top && name.starts_with('.')) || is_scratch(place, name) {
498 continue;
499 }
500
501 let metadata = match fs::symlink_metadata(&path) {
502 Ok(metadata) => metadata,
503 // Looked for rather than listed, and not there: the repository has no packed
504 // refs, which is exactly what git would read at this moment.
505 Err(error)
506 if error.kind() == io::ErrorKind::NotFound
507 && looked_for.as_ref() == Some(&path) =>
508 {
509 continue;
510 }
511 Err(error) => return Err(unreadable(&path, &error)),
512 };
513
514 let relative = path.strip_prefix(data_dir).map_err(BackupError::backend)?;
515 let entry = format!("{BACKUP_DATA_PREFIX}/{}", relative.to_string_lossy());
516
517 if metadata.is_symlink() {
518 eprintln!("steid: backup skipped the symlink {}", path.display());
519 continue;
520 }
521
522 if metadata.is_dir() {
523 builder
524 .append_dir(format!("{entry}/"), &path)
525 .map_err(|error| unreadable(&path, &error))?;
526 walk(builder, data_dir, &path, place.below(name), watch)?;
527 } else if metadata.is_file() {
528 copy_file(builder, &entry, &path, watch)?;
529 } else {
530 eprintln!(
531 "steid: backup skipped {}, which is not a file",
532 path.display()
533 );
534 }
535 }
536
537 Ok(())
538}
539
540/// Adds the file at `path` as `entry`, holding exactly the bytes it held when opened.
541///
542/// Not `tar::Builder::append_file`, which writes the size it reads into the header and
543/// then copies to the end of the file (tar 0.4.45, `builder.rs:687-716`). Git appends to a
544/// reflog in place, so a push landing mid-copy made the entry longer than its header
545/// said. Nothing failed at backup; once the extra bytes crossed a 512-byte block, every
546/// entry after it was misread, and the archive failed only at restore.
547///
548/// - **A file that grows is copied up to the size first read.** Git changes a file in
549/// place only by appending to it, so those bytes are the file as it was a moment
550/// earlier: a reflog without its newest lines, which is still a valid reflog.
551/// - **A file that comes up short fails the backup**, naming it ([`shrank`]). Git never
552/// truncates a file in place, so something else is rewriting the data directory, and
553/// the header has already promised bytes that are not there.
554///
555/// The header is otherwise what `append_file` wrote: [`tar::HeaderMode::Complete`], the
556/// builder's default. Unlike it, a sparse file is copied whole; git writes none.
557fn copy_file<W: Write>(
558 builder: &mut tar::Builder<W>,
559 entry: &str,
560 path: &Path,
561 watch: &mut dyn FnMut(Moment, &Path),
562) -> Result<(), BackupError> {
563 let file = File::open(path).map_err(|error| unreadable(path, &error))?;
564 let stat = file.metadata().map_err(|error| unreadable(path, &error))?;
565 let size = stat.len();
566
567 let mut header = tar::Header::new_gnu();
568 header.set_metadata_in_mode(&stat, tar::HeaderMode::Complete);
569 watch(Moment::Copying, path);
570
571 let mut bytes = file.take(size);
572 builder
573 .append_data(&mut header, entry, &mut bytes)
574 .map_err(|error| unreadable(path, &error))?;
575
576 // `take` stops at `size` however much the file has grown; what it has left is what
577 // the file no longer held.
578 match bytes.limit() {
579 0 => Ok(()),
580 missing => Err(shrank(path, size, size - missing)),
581 }
582}
583
584/// A file that ended before the size its header declared.
585fn shrank(path: &Path, size: u64, copied: u64) -> BackupError {
586 BackupError::backend(format!(
587 "{} shrank while the backup was copying it, from {size} bytes to {copied}, so the \
588 archive would have held a broken copy of it and was not finished. Git only ever \
589 appends to a file in place, so something else rewrote it mid-backup; run the \
590 backup again",
591 path.display()
592 ))
593}
594
595/// The manifest, without extracting anything else.
596fn read_manifest(archive: &Path) -> Result<BackupManifest, BackupError> {
597 /// Enough for a manifest many times over, and not enough for a hostile archive to
598 /// make this allocate. It holds three numbers and two short strings.
599 const MAX: u64 = 64 * 1024;
600
601 for entry in open(archive)?.entries().map_err(BackupError::backend)? {
602 let mut entry = entry.map_err(BackupError::backend)?;
603 let path = entry.path().map_err(BackupError::backend)?.into_owned();
604
605 if path != Path::new(BACKUP_MANIFEST) {
606 continue;
607 }
608
609 let mut json = String::new();
610 entry
611 .by_ref()
612 .take(MAX)
613 .read_to_string(&mut json)
614 .map_err(|error| {
615 BackupError::malformed(format!("the manifest is unreadable: {error}"))
616 })?;
617
618 return serde_json::from_str(&json).map_err(|error| {
619 BackupError::malformed(format!("the manifest does not parse: {error}"))
620 });
621 }
622
623 Err(BackupError::malformed(
624 "there is no manifest.json in it, so it is not a Steid backup",
625 ))
626}
627
628fn open(archive: &Path) -> Result<tar::Archive<GzDecoder<File>>, BackupError> {
629 let file = File::open(archive).map_err(|error| {
630 BackupError::malformed(format!(
631 "{} could not be opened: {error}",
632 archive.display()
633 ))
634 })?;
635
636 Ok(tar::Archive::new(GzDecoder::new(file)))
637}
638
639/// Extracts an archive, refusing anything it did not write.
640///
641/// Every entry is checked before it is written, and the checks are the security of the
642/// whole feature: an archive is a file somebody hands the process, and `tar` has been a
643/// path-traversal primitive for forty years. An entry may only be a regular file or a
644/// directory, may only sit at `manifest.json`, `steid.db` or under `data/`, may not be
645/// absolute, and may not contain `..` — so no entry can name a path outside the two
646/// destinations, whatever the archive says.
647///
648/// Under [`ExistingData::Replace`] the `data/` entries land in `staging` instead, and
649/// [`swap`] moves them into place afterwards. The refuse-to-overwrite rule is unchanged
650/// by that and is what makes `staging` have to be a directory nothing has used before.
651fn unpack(plan: &RestorePlan) -> Result<(), BackupError> {
652 let mut database = false;
653
654 // Where the `data/` entries are written. Not the live directory when there is
655 // something in it to preserve — see the module note on unpacking beside.
656 let data_dir = match &plan.existing {
657 ExistingData::Refuse => plan.data_dir.clone(),
658 ExistingData::Replace { staging, .. } => {
659 if staging.exists() {
660 return Err(BackupError::refused(format!(
661 "{} already exists, and a restore stages into a fresh directory",
662 staging.display()
663 )));
664 }
665
666 staging.clone()
667 }
668 };
669
670 for entry in open(&plan.archive)?
671 .entries()
672 .map_err(BackupError::backend)?
673 {
674 let mut entry = entry.map_err(BackupError::backend)?;
675 let path = entry.path().map_err(BackupError::backend)?.into_owned();
676
677 let kind = entry.header().entry_type();
678 if !(kind.is_file() || kind.is_dir()) {
679 return Err(BackupError::malformed(format!(
680 "{} is a {kind:?}, and a backup holds only files and directories",
681 path.display()
682 )));
683 }
684
685 let Some(relative) = safe(&path) else {
686 return Err(BackupError::malformed(format!(
687 "{} is not a path a backup may contain",
688 path.display()
689 )));
690 };
691
692 let destination = if relative == Path::new(BACKUP_MANIFEST) {
693 // Already read, and not something the instance keeps.
694 continue;
695 } else if relative == Path::new(BACKUP_DATABASE) {
696 database = true;
697 plan.database.clone()
698 } else if let Ok(rest) = relative.strip_prefix(BACKUP_DATA_PREFIX) {
699 data_dir.join(rest)
700 } else {
701 return Err(BackupError::malformed(format!(
702 "{} is not part of a Steid backup",
703 path.display()
704 )));
705 };
706
707 if kind.is_dir() {
708 fs::create_dir_all(&destination).map_err(BackupError::backend)?;
709 continue;
710 }
711
712 // The use case established that the instance is empty; anything here means it
713 // was wrong, and overwriting is the one outcome a restore must never have.
714 if destination.exists() {
715 return Err(BackupError::refused(format!(
716 "{} already exists",
717 destination.display()
718 )));
719 }
720
721 if let Some(parent) = destination.parent() {
722 fs::create_dir_all(parent).map_err(BackupError::backend)?;
723 }
724
725 entry.unpack(&destination).map_err(BackupError::backend)?;
726 }
727
728 if !database {
729 return Err(BackupError::malformed(
730 "there is no steid.db in it, so it is not a Steid backup",
731 ));
732 }
733
734 // Only now: everything above could still fail, and until this line the live data
735 // directory has not been touched.
736 if let ExistingData::Replace { staging, aside } = &plan.existing {
737 swap(&plan.data_dir, staging, aside)?;
738 }
739
740 Ok(())
741}
742
743/// Moves what the data directory holds into `aside`, then the staged tree into its place.
744///
745/// Renames, so the two ends must share a filesystem — they do by construction, since the
746/// staging directory is inside the backup workspace which is inside the data directory.
747/// A rename is also the only move that cannot half-copy a bare repository.
748///
749/// **Top-level dot entries are left exactly where they are.** That is the backup
750/// workspace this is running out of, and any earlier `.replaced-…` — neither of which is
751/// state the archive is replacing, and moving the first would move the ground out from
752/// under the second loop.
753///
754/// Nothing is deleted. `aside` holds the previous instance until somebody removes it by
755/// hand.
756fn swap(data_dir: &Path, staging: &Path, aside: &Path) -> Result<(), BackupError> {
757 fs::create_dir_all(aside).map_err(BackupError::backend)?;
758
759 for path in entries(data_dir)? {
760 let name = file_name(&path)?;
761
762 if name.starts_with('.') {
763 continue;
764 }
765
766 fs::rename(&path, aside.join(name)).map_err(|error| {
767 BackupError::backend(format!(
768 "could not move {} aside to {}: {error}",
769 path.display(),
770 aside.display()
771 ))
772 })?;
773 }
774
775 for path in entries(staging)? {
776 let name = file_name(&path)?;
777
778 fs::rename(&path, data_dir.join(name)).map_err(|error| {
779 BackupError::backend(format!(
780 "could not move the restored {} into {}: {error}",
781 path.display(),
782 data_dir.display()
783 ))
784 })?;
785 }
786
787 // Empty by now. Best effort: the workspace is the caller's to remove anyway.
788 let _ = fs::remove_dir(staging);
789
790 Ok(())
791}
792
793/// One directory's entries, sorted, so a swap is the same operation twice running.
794fn entries(dir: &Path) -> Result<Vec<PathBuf>, BackupError> {
795 let mut found: Vec<PathBuf> = fs::read_dir(dir)
796 .map_err(|error| {
797 BackupError::backend(format!("could not read {}: {error}", dir.display()))
798 })?
799 .map(|entry| entry.map(|entry| entry.path()))
800 .collect::<Result<_, _>>()
801 .map_err(BackupError::backend)?;
802
803 found.sort();
804
805 Ok(found)
806}
807
808fn file_name(path: &Path) -> Result<&str, BackupError> {
809 path.file_name()
810 .and_then(|name| name.to_str())
811 .ok_or_else(|| {
812 BackupError::backend(format!("{} is not a valid UTF-8 name", path.display()))
813 })
814}
815
816/// An entry path, if it is one a backup may legally contain.
817///
818/// Relative, no `..`, no root, no Windows prefix, and no empty components. `None` means
819/// refuse — never "sanitise and carry on", because a path that needed sanitising was
820/// written by something that is not Steid.
821fn safe(path: &Path) -> Option<&Path> {
822 use std::path::Component;
823
824 let ordinary = path
825 .components()
826 .all(|component| matches!(component, Component::Normal(_)));
827
828 (ordinary && path.components().next().is_some()).then_some(path)
829}
830
831/// The in-memory [`DatabaseSnapshot`], for use-case tests.
832///
833/// Touches no disk: it hands back a path inside the workspace it was given and records
834/// what it was asked to do, which is all a use case's decisions can be checked against.
835#[derive(Debug, Default, Clone)]
836pub struct InMemoryDatabaseSnapshot {
837 taken: Arc<Mutex<u64>>,
838 installed: Arc<Mutex<Vec<PathBuf>>>,
839}
840
841impl InMemoryDatabaseSnapshot {
842 #[must_use]
843 pub fn new() -> Self {
844 Self::default()
845 }
846
847 /// How many snapshots were taken.
848 #[must_use]
849 pub fn taken(&self) -> u64 {
850 *self.taken.lock().expect("lock poisoned")
851 }
852
853 /// Every file that was installed as the live database, in order.
854 #[must_use]
855 pub fn installed(&self) -> Vec<PathBuf> {
856 self.installed.lock().expect("lock poisoned").clone()
857 }
858}
859
860impl DatabaseSnapshot for InMemoryDatabaseSnapshot {
861 async fn snapshot(&self, workspace: &Path) -> Result<PathBuf, BackupError> {
862 let mut taken = self.taken.lock().expect("lock poisoned");
863 *taken += 1;
864
865 Ok(workspace.join(format!("snapshot-{taken}.db")))
866 }
867
868 async fn replace(&self, source: &Path) -> Result<(), BackupError> {
869 self.installed
870 .lock()
871 .expect("lock poisoned")
872 .push(source.to_path_buf());
873
874 Ok(())
875 }
876}
877
878/// The in-memory [`BackupArchive`], for use-case tests.
879///
880/// Archives are entries in a map keyed by their path, so a backup taken through one
881/// handle can be restored through a clone of it — which is how a test copies an archive
882/// from one instance to another without a filesystem.
883#[derive(Debug, Default, Clone)]
884pub struct InMemoryBackupArchive {
885 manifests: Arc<Mutex<Vec<(PathBuf, BackupManifest)>>>,
886 packed: Arc<Mutex<Vec<BackupPlan>>>,
887 unpacked: Arc<Mutex<Vec<RestorePlan>>>,
888}
889
890impl InMemoryBackupArchive {
891 #[must_use]
892 pub fn new() -> Self {
893 Self::default()
894 }
895
896 /// Puts an archive there without going through [`pack`](BackupArchive::pack), for
897 /// testing what a restore does with a manifest it did not write.
898 pub fn plant(&self, path: impl Into<PathBuf>, manifest: BackupManifest) {
899 self.manifests
900 .lock()
901 .expect("lock poisoned")
902 .push((path.into(), manifest));
903 }
904
905 #[must_use]
906 pub fn packed(&self) -> Vec<BackupPlan> {
907 self.packed.lock().expect("lock poisoned").clone()
908 }
909
910 #[must_use]
911 pub fn unpacked(&self) -> Vec<RestorePlan> {
912 self.unpacked.lock().expect("lock poisoned").clone()
913 }
914}
915
916impl BackupArchive for InMemoryBackupArchive {
917 async fn pack(&self, plan: BackupPlan) -> Result<u64, BackupError> {
918 self.plant(plan.destination.clone(), plan.manifest.clone());
919 self.packed.lock().expect("lock poisoned").push(plan);
920
921 Ok(1024)
922 }
923
924 async fn manifest(&self, archive: &Path) -> Result<BackupManifest, BackupError> {
925 self.manifests
926 .lock()
927 .expect("lock poisoned")
928 .iter()
929 .find(|(path, _)| path == archive)
930 .map(|(_, manifest)| manifest.clone())
931 .ok_or_else(|| BackupError::malformed(format!("no archive at {}", archive.display())))
932 }
933
934 async fn unpack(&self, plan: RestorePlan) -> Result<(), BackupError> {
935 // Reads the manifest first, so a plan naming an archive that is not there fails
936 // here exactly as it would on disk.
937 self.manifest(&plan.archive).await?;
938 self.unpacked.lock().expect("lock poisoned").push(plan);
939
940 Ok(())
941 }
942}
943
944#[cfg(test)]
945mod tests {
946 use super::*;
947 use crate::application::backup::BackupCounts;
948
949 fn manifest() -> BackupManifest {
950 BackupManifest {
951 version: "0.4.0".to_owned(),
952 taken_at: "2026-09-08T14:25:30Z".to_owned(),
953 counts: BackupCounts {
954 users: 1,
955 organisations: 1,
956 repositories: 2,
957 },
958 }
959 }
960
961 /// A data directory with one bare-repository-shaped tree in it.
962 fn fixture(root: &Path) -> PathBuf {
963 let data = root.join("repos");
964 fs::create_dir_all(data.join("james/steid.git/refs/heads")).expect("mkdir");
965 fs::write(data.join("james/steid.git/HEAD"), b"ref: refs/heads/main\n").expect("write");
966 fs::write(data.join("james/steid.git/refs/heads/main"), b"abc123\n").expect("write");
967 data
968 }
969
970 fn plan(root: &Path, data: &Path) -> BackupPlan {
971 let database = root.join("snapshot.db");
972 fs::write(&database, b"SQLite format 3\0not really").expect("write");
973
974 BackupPlan {
975 destination: root.join("out.tar.gz"),
976 database,
977 data_dir: data.to_path_buf(),
978 manifest: manifest(),
979 }
980 }
981
982 #[test]
983 fn a_database_url_names_a_file() {
984 assert_eq!(
985 database_file("sqlite:/var/lib/steid/steid.db?mode=rwc"),
986 Some(PathBuf::from("/var/lib/steid/steid.db"))
987 );
988 assert_eq!(
989 database_file("sqlite://steid.db"),
990 Some(PathBuf::from("steid.db"))
991 );
992 assert_eq!(database_file("steid.db"), Some(PathBuf::from("steid.db")));
993 assert_eq!(database_file("sqlite::memory:"), None);
994 }
995
996 #[test]
997 fn an_archive_round_trips_the_database_and_every_repository() {
998 let root = tempfile::tempdir().expect("tempdir");
999 let data = fixture(root.path());
1000 let plan = plan(root.path(), &data);
1001
1002 let bytes = pack(&plan).expect("should pack");
1003 assert!(bytes > 0);
1004 assert_eq!(
1005 read_manifest(&plan.destination).expect("manifest"),
1006 manifest()
1007 );
1008
1009 let into = root.path().join("restored");
1010 unpack(&RestorePlan {
1011 archive: plan.destination.clone(),
1012 database: into.join("steid.db"),
1013 data_dir: into.join("repos"),
1014 existing: ExistingData::Refuse,
1015 })
1016 .expect("should unpack");
1017
1018 assert_eq!(
1019 fs::read(into.join("steid.db")).expect("read"),
1020 b"SQLite format 3\0not really"
1021 );
1022 assert_eq!(
1023 fs::read_to_string(into.join("repos/james/steid.git/HEAD")).expect("read"),
1024 "ref: refs/heads/main\n"
1025 );
1026 assert!(into.join("repos/james/steid.git/refs/heads/main").is_file());
1027 }
1028
1029 #[test]
1030 fn a_replace_swaps_the_tree_in_and_leaves_the_old_one_beside_it() {
1031 // The live data directory here is the one the archive is being poured over, and
1032 // it holds the backup workspace the restore is running out of — which is why the
1033 // swap has to leave top-level dot entries alone.
1034 let root = tempfile::tempdir().expect("tempdir");
1035 let plan = plan(root.path(), &fixture(root.path()));
1036 pack(&plan).expect("should pack");
1037
1038 let live = root.path().join("live");
1039 fs::create_dir_all(live.join("bob/notes.git")).expect("mkdir");
1040 fs::write(live.join("bob/notes.git/HEAD"), b"mine\n").expect("write");
1041 let workspace = live.join(".backup");
1042 fs::create_dir_all(&workspace).expect("mkdir");
1043 fs::write(workspace.join("keep-me"), b"scratch\n").expect("write");
1044
1045 let aside = live.join(".replaced-20260908T142530Z");
1046 unpack(&RestorePlan {
1047 archive: plan.destination.clone(),
1048 database: workspace.join("steid.db"),
1049 data_dir: live.clone(),
1050 existing: ExistingData::Replace {
1051 staging: workspace.join("incoming"),
1052 aside: aside.clone(),
1053 },
1054 })
1055 .expect("should unpack and swap");
1056
1057 assert_eq!(
1058 fs::read_to_string(live.join("james/steid.git/HEAD")).expect("read"),
1059 "ref: refs/heads/main\n",
1060 "the archive's tree is not in place"
1061 );
1062 assert!(
1063 !live.join("bob").exists(),
1064 "the old tree is still where it was"
1065 );
1066 assert_eq!(
1067 fs::read_to_string(aside.join("bob/notes.git/HEAD")).expect("read"),
1068 "mine\n",
1069 "the old tree was not moved aside intact"
1070 );
1071 assert!(
1072 fs::read_to_string(workspace.join("keep-me")).expect("read") == "scratch\n",
1073 "the swap moved the workspace it is running out of"
1074 );
1075 assert!(
1076 !workspace.join("incoming").exists(),
1077 "the staging directory survived the swap"
1078 );
1079 }
1080
1081 #[test]
1082 fn a_failed_replace_leaves_the_live_directory_exactly_as_it_was() {
1083 // Unpack beside, then swap: the extraction is where a corrupt archive fails, and
1084 // it must fail before anything live has moved.
1085 let root = tempfile::tempdir().expect("tempdir");
1086 let truncated = root.path().join("half.tar.gz");
1087 fs::write(&truncated, b"not a gzip at all").expect("write");
1088
1089 let live = root.path().join("live");
1090 fs::create_dir_all(live.join("bob/notes.git")).expect("mkdir");
1091 fs::write(live.join("bob/notes.git/HEAD"), b"mine\n").expect("write");
1092 let workspace = live.join(".backup");
1093 fs::create_dir_all(&workspace).expect("mkdir");
1094
1095 let refused = unpack(&RestorePlan {
1096 archive: truncated,
1097 database: workspace.join("steid.db"),
1098 data_dir: live.clone(),
1099 existing: ExistingData::Replace {
1100 staging: workspace.join("incoming"),
1101 aside: live.join(".replaced-20260908T142530Z"),
1102 },
1103 });
1104
1105 assert!(refused.is_err(), "a truncated archive is not a restore");
1106 assert_eq!(
1107 fs::read_to_string(live.join("bob/notes.git/HEAD")).expect("read"),
1108 "mine\n",
1109 "the instance lost its state to a failed restore"
1110 );
1111 assert!(
1112 !live.join(".replaced-20260908T142530Z").exists(),
1113 "nothing should have been moved aside"
1114 );
1115 }
1116
1117 #[test]
1118 fn a_replace_refuses_to_stage_into_a_directory_that_already_exists() {
1119 // The refuse-to-overwrite rule still applies inside the staging directory, so a
1120 // staging directory somebody else is using would turn into a half-merge.
1121 let root = tempfile::tempdir().expect("tempdir");
1122 let plan = plan(root.path(), &fixture(root.path()));
1123 pack(&plan).expect("should pack");
1124
1125 let live = root.path().join("live");
1126 let workspace = live.join(".backup");
1127 fs::create_dir_all(workspace.join("incoming")).expect("mkdir");
1128
1129 let refused = unpack(&RestorePlan {
1130 archive: plan.destination.clone(),
1131 database: workspace.join("steid.db"),
1132 data_dir: live.clone(),
1133 existing: ExistingData::Replace {
1134 staging: workspace.join("incoming"),
1135 aside: live.join(".replaced-20260908T142530Z"),
1136 },
1137 });
1138
1139 assert!(
1140 matches!(refused, Err(BackupError::Refused(_))),
1141 "{refused:?}"
1142 );
1143 }
1144
1145 #[test]
1146 fn an_empty_data_directory_still_restores_as_a_directory() {
1147 let root = tempfile::tempdir().expect("tempdir");
1148 let data = root.path().join("repos");
1149 fs::create_dir_all(&data).expect("mkdir");
1150
1151 let plan = plan(root.path(), &data);
1152 pack(&plan).expect("should pack");
1153
1154 let into = root.path().join("restored");
1155 unpack(&RestorePlan {
1156 archive: plan.destination.clone(),
1157 database: into.join("steid.db"),
1158 data_dir: into.join("repos"),
1159 existing: ExistingData::Refuse,
1160 })
1161 .expect("should unpack");
1162
1163 assert!(into.join("repos").is_dir());
1164 }
1165
1166 #[test]
1167 fn no_entry_names_a_path_outside_the_data_directory() {
1168 let root = tempfile::tempdir().expect("tempdir");
1169 let data = fixture(root.path());
1170
1171 // A secret next door, and a symlink from inside the data directory to it: the
1172 // one way a walk could pull a path in from outside.
1173 let secret = root.path().join("secret.txt");
1174 fs::write(&secret, b"not yours").expect("write");
1175 std::os::unix::fs::symlink(&secret, data.join("james/escape")).expect("symlink");
1176 // And the backup's own scratch directory, which sits inside the data directory
1177 // and must not end up inside the archive being built in it.
1178 fs::create_dir_all(data.join(".backup/whatever")).expect("mkdir");
1179 fs::write(data.join(".backup/whatever/big.db"), b"scratch").expect("write");
1180
1181 let plan = plan(root.path(), &data);
1182 pack(&plan).expect("should pack");
1183
1184 let names = entry_names(&plan.destination);
1185
1186 for name in &names {
1187 let path = Path::new(name);
1188 assert!(
1189 safe(path).is_some(),
1190 "{name} is not a path a restore would accept"
1191 );
1192 assert!(
1193 name == BACKUP_MANIFEST
1194 || name == BACKUP_DATABASE
1195 || name.starts_with(&format!("{BACKUP_DATA_PREFIX}/")),
1196 "{name} is outside the archive's three destinations"
1197 );
1198 }
1199
1200 assert!(
1201 !names.iter().any(|name| name.contains("escape")),
1202 "the symlink was archived: {names:?}"
1203 );
1204 assert!(
1205 !names.iter().any(|name| name.contains(".backup")),
1206 "the scratch directory was archived: {names:?}"
1207 );
1208 }
1209
1210 #[test]
1211 fn a_restore_refuses_an_entry_that_climbs_out() {
1212 assert!(safe(Path::new("data/james/steid.git/HEAD")).is_some());
1213 assert!(safe(Path::new("../etc/passwd")).is_none());
1214 assert!(safe(Path::new("data/../../etc/passwd")).is_none());
1215 assert!(safe(Path::new("/etc/passwd")).is_none());
1216 assert!(safe(Path::new("")).is_none());
1217 }
1218
1219 #[test]
1220 fn a_restore_refuses_to_overwrite_what_is_already_there() {
1221 let root = tempfile::tempdir().expect("tempdir");
1222 let data = fixture(root.path());
1223 let plan = plan(root.path(), &data);
1224 pack(&plan).expect("should pack");
1225
1226 let into = root.path().join("restored");
1227 fs::create_dir_all(into.join("repos/james/steid.git")).expect("mkdir");
1228 fs::write(into.join("repos/james/steid.git/HEAD"), b"mine\n").expect("write");
1229
1230 let refused = unpack(&RestorePlan {
1231 archive: plan.destination.clone(),
1232 database: into.join("steid.db"),
1233 data_dir: into.join("repos"),
1234 existing: ExistingData::Refuse,
1235 });
1236
1237 assert!(
1238 matches!(refused, Err(BackupError::Refused(_))),
1239 "{refused:?}"
1240 );
1241 assert_eq!(
1242 fs::read_to_string(into.join("repos/james/steid.git/HEAD")).expect("read"),
1243 "mine\n",
1244 "the existing file was left alone"
1245 );
1246 }
1247
1248 #[test]
1249 fn something_that_is_not_a_backup_is_said_to_be_one() {
1250 let root = tempfile::tempdir().expect("tempdir");
1251 let not = root.path().join("holiday.tar.gz");
1252 fs::write(&not, b"not a gzip at all").expect("write");
1253
1254 assert!(matches!(
1255 read_manifest(&not),
1256 Err(BackupError::Malformed(_) | BackupError::Backend(_))
1257 ));
1258 }
1259
1260 #[test]
1261 fn packing_refuses_to_overwrite_an_existing_archive() {
1262 let root = tempfile::tempdir().expect("tempdir");
1263 let data = fixture(root.path());
1264 let plan = plan(root.path(), &data);
1265 fs::write(&plan.destination, b"someone else's").expect("write");
1266
1267 assert!(matches!(pack(&plan), Err(BackupError::Refused(_))));
1268 }
1269
1270 // --- Copying repositories that are in use ------------------------------------------
1271 //
1272 // Real git throughout: what is under test is git's own on-disk behaviour, and an
1273 // imitation of it would test the imitation. The hook given to `pack_with` is what
1274 // makes each race land at one exact point in the walk, so nothing here waits or
1275 // depends on timing.
1276
1277 /// A data directory holding one bare repository with one pushed commit, laid out as
1278 /// Steid lays it out, and a working clone beside it holding a second commit that has
1279 /// not been pushed yet.
1280 struct Live {
1281 root: tempfile::TempDir,
1282 data: PathBuf,
1283 repo: PathBuf,
1284 work: PathBuf,
1285 }
1286
1287 fn live() -> Live {
1288 let root = tempfile::tempdir().expect("tempdir");
1289 let data = root.path().join("repos");
1290 let repo = data.join("james/steid.git");
1291 let work = root.path().join("work");
1292
1293 // As `DiskGitStorage::init_bare` makes one: no template, `main`, and a reflog.
1294 git(
1295 root.path(),
1296 &[
1297 "init",
1298 "--bare",
1299 "--quiet",
1300 "--template=",
1301 "--initial-branch=main",
1302 path_str(&repo),
1303 ],
1304 );
1305 git(&repo, &["config", "core.logAllRefUpdates", "true"]);
1306
1307 git(
1308 root.path(),
1309 &["init", "--quiet", "--initial-branch=main", path_str(&work)],
1310 );
1311 fs::write(work.join("README"), "one\n").expect("write");
1312 git(&work, &["add", "README"]);
1313 git(&work, &["commit", "--quiet", "-m", "one"]);
1314 git(&work, &["remote", "add", "origin", path_str(&repo)]);
1315 git(&work, &["push", "--quiet", "origin", "main"]);
1316
1317 fs::write(work.join("README"), "two\n").expect("write");
1318 git(&work, &["commit", "--quiet", "-am", "two"]);
1319
1320 Live {
1321 root,
1322 data,
1323 repo,
1324 work,
1325 }
1326 }
1327
1328 impl Live {
1329 /// A plan writing to `name` under the fixture's root.
1330 fn plan(&self, name: &str) -> BackupPlan {
1331 BackupPlan {
1332 destination: self.root.path().join(name),
1333 ..plan(self.root.path(), &self.data)
1334 }
1335 }
1336
1337 /// Extracts an archive with the real restore, and says where the repository is.
1338 fn restore(&self, archive: &Path, into: &str) -> PathBuf {
1339 let into = self.root.path().join(into);
1340 unpack(&RestorePlan {
1341 archive: archive.to_path_buf(),
1342 database: into.join("steid.db"),
1343 data_dir: into.join("repos"),
1344 existing: ExistingData::Refuse,
1345 })
1346 .expect("should unpack");
1347
1348 into.join("repos/james/steid.git")
1349 }
1350 }
1351
1352 /// A [`pack_with`] hook that acts only as the walk reaches each path.
1353 fn reaching(mut hook: impl FnMut(&Path)) -> impl FnMut(Moment, &Path) {
1354 move |moment, path| {
1355 if moment == Moment::Reaching {
1356 hook(path);
1357 }
1358 }
1359 }
1360
1361 /// The names of the repository's own entries, in the order the walk reaches them.
1362 ///
1363 /// Read off a backup of a fresh fixture rather than written down, so the race tests
1364 /// below cover every boundary the walk really has, in whatever order it really has
1365 /// them.
1366 fn repository_entries() -> Vec<String> {
1367 let fixture = live();
1368 let mut seen = Vec::new();
1369
1370 pack_with(
1371 &fixture.plan("probe.tar.gz"),
1372 &mut reaching(|path| {
1373 if path.parent() == Some(fixture.repo.as_path()) {
1374 seen.push(path_str(path.file_name().expect("a name").as_ref()).to_owned());
1375 }
1376 }),
1377 )
1378 .expect("should pack");
1379
1380 seen
1381 }
1382
1383 #[test]
1384 fn a_push_during_a_backup_never_leaves_a_ref_without_its_objects() {
1385 let entries = repository_entries();
1386 assert!(entries.contains(&"refs".to_owned()), "{entries:?}");
1387
1388 // One backup per boundary, each with a push landing just before that entry.
1389 for entry in &entries {
1390 let fixture = live();
1391 let plan = fixture.plan("out.tar.gz");
1392 let mut pushed = false;
1393
1394 pack_with(
1395 &plan,
1396 &mut reaching(|path| {
1397 if !pushed && path == fixture.repo.join(entry) {
1398 git(&fixture.work, &["push", "--quiet", "origin", "main"]);
1399 pushed = true;
1400 }
1401 }),
1402 )
1403 .expect("should pack");
1404 assert!(pushed, "the push never ran before {entry}");
1405
1406 let restored = fixture.restore(&plan.destination, "restored");
1407 let fsck = git_output(&restored, &["fsck", "--connectivity-only"]);
1408 assert!(
1409 fsck.status.success(),
1410 "a push just before {entry} left the archive inconsistent: {}",
1411 String::from_utf8_lossy(&fsck.stderr)
1412 );
1413 }
1414 }
1415
1416 #[test]
1417 fn a_pack_refs_during_a_backup_never_drops_a_branch() {
1418 let entries = repository_entries();
1419
1420 for entry in &entries {
1421 let fixture = live();
1422 let main = git(&fixture.repo, &["rev-parse", "refs/heads/main"]);
1423 let plan = fixture.plan("out.tar.gz");
1424 let mut packed = false;
1425
1426 pack_with(
1427 &plan,
1428 &mut reaching(|path| {
1429 if !packed && path == fixture.repo.join(entry) {
1430 git(&fixture.repo, &["pack-refs", "--all", "--prune"]);
1431 packed = true;
1432 }
1433 }),
1434 )
1435 .expect("should pack");
1436 assert!(packed, "pack-refs never ran before {entry}");
1437
1438 let restored = fixture.restore(&plan.destination, "restored");
1439 let found = git_output(&restored, &["rev-parse", "--verify", "refs/heads/main"]);
1440 assert!(
1441 found.status.success(),
1442 "a pack-refs just before {entry} dropped main: {}",
1443 String::from_utf8_lossy(&found.stderr)
1444 );
1445 assert_eq!(String::from_utf8_lossy(&found.stdout).trim(), main);
1446 git(&restored, &["fsck", "--connectivity-only"]);
1447 }
1448 }
1449
1450 #[test]
1451 fn git_lock_files_are_never_archived_and_may_vanish_mid_walk() {
1452 let fixture = live();
1453 let held = fixture.repo.join("refs/heads/main.lock");
1454 let released = fixture.repo.join("refs/heads/topic.lock");
1455 let plan = fixture.plan("out.tar.gz");
1456
1457 pack_with(
1458 &plan,
1459 &mut reaching(|path| {
1460 // Both taken before `refs/heads` is listed, as a push holding them would be.
1461 if path == fixture.repo.join("refs") {
1462 fs::write(&held, b"locked\n").expect("write");
1463 fs::write(&released, b"locked\n").expect("write");
1464 }
1465 // And one let go after it was listed and before the walk reached it.
1466 if path == released {
1467 fs::remove_file(&released).expect("remove");
1468 }
1469 }),
1470 )
1471 .expect("a lock that vanishes must not fail the backup");
1472
1473 let names = entry_names(&plan.destination);
1474 assert!(
1475 !names.iter().any(|name| name.ends_with(".lock")),
1476 "a lock file was archived: {names:?}"
1477 );
1478
1479 // The reason it matters: a restored `main.lock` refuses every update to `main`.
1480 let restored = fixture.restore(&plan.destination, "restored");
1481 git(
1482 &fixture.work,
1483 &["push", "--quiet", path_str(&restored), "main"],
1484 );
1485 }
1486
1487 #[test]
1488 fn the_push_quarantine_and_gits_temporary_files_are_never_archived() {
1489 let fixture = live();
1490 let quarantine = fixture.repo.join("objects/tmp_objdir-incoming-AbC123");
1491 let partial = fixture.repo.join("objects/pack/tmp_pack_XyZ789");
1492 let plan = fixture.plan("out.tar.gz");
1493
1494 pack_with(
1495 &plan,
1496 &mut reaching(|path| {
1497 // A push mid-receive: its quarantine, and an index-pack writing beside the packs.
1498 if path == fixture.repo.join("objects") {
1499 fs::create_dir_all(quarantine.join("pack")).expect("mkdir");
1500 fs::write(quarantine.join("pack/tmp_pack_1"), b"half a pack").expect("write");
1501 fs::write(&partial, b"half a pack").expect("write");
1502 }
1503 // The push finishing after `objects/pack` was listed: its scratch is gone.
1504 if path == partial {
1505 fs::remove_file(&partial).expect("remove");
1506 }
1507 }),
1508 )
1509 .expect("git's scratch vanishing must not fail the backup");
1510
1511 let names = entry_names(&plan.destination);
1512 assert!(
1513 !names.iter().any(|name| name.contains("tmp_")),
1514 "git's temporary files were archived: {names:?}"
1515 );
1516 }
1517
1518 #[test]
1519 fn a_pack_deleted_mid_walk_fails_the_backup_and_names_it() {
1520 let fixture = live();
1521 git(&fixture.repo, &["repack", "-a", "-d", "-q"]);
1522 let plan = fixture.plan("out.tar.gz");
1523 let mut deleted = None;
1524
1525 let failed = pack_with(
1526 &plan,
1527 &mut reaching(|path| {
1528 // gc replacing a pack: listed, then gone before the walk could open it.
1529 if deleted.is_none() && path.extension().is_some_and(|ext| ext == "pack") {
1530 fs::remove_file(path).expect("remove");
1531 deleted = Some(path.to_path_buf());
1532 }
1533 }),
1534 );
1535
1536 let deleted = deleted.expect("the fixture should hold a pack");
1537 let error = failed
1538 .expect_err("a pack that vanished must fail the backup")
1539 .to_string();
1540 assert!(
1541 error.contains(&deleted.display().to_string()) && error.contains("vanished"),
1542 "the failure does not say which file went: {error}"
1543 );
1544 assert!(!plan.destination.exists(), "an archive was written anyway");
1545 }
1546
1547 #[test]
1548 fn a_pushed_packs_keep_marker_is_never_archived_and_may_vanish_mid_walk() {
1549 // receive-pack keeps a push of 100 objects or more (`receive.unpackLimit`) as a
1550 // pack, marked `objects/pack/pack-*.keep` until the push's refs are in. Here a
1551 // real push is parked in its `reference-transaction` hook while the walk lists
1552 // `objects/pack`, and let go just before the walk reaches the `.keep`.
1553 let fixture = live();
1554 let parked = fixture.root.path().join("parked");
1555 let release = fixture.root.path().join("release");
1556 park_pushes(&fixture, &parked, &release);
1557
1558 // 150 files: a commit of well over 100 objects.
1559 for n in 0..150 {
1560 fs::write(fixture.work.join(format!("file-{n}")), format!("{n}\n")).expect("write");
1561 }
1562 git(&fixture.work, &["add", "."]);
1563 git(&fixture.work, &["commit", "--quiet", "-m", "big"]);
1564
1565 let pack_dir = fixture.repo.join("objects/pack");
1566 let plan = fixture.plan("out.tar.gz");
1567 let mut push = None;
1568 let mut keep = None;
1569
1570 let packed = pack_with(
1571 &plan,
1572 &mut reaching(|path| {
1573 // Started before `objects/pack` is listed, and parked with its pack and its
1574 // `.keep` in place by the time the walk lists the directory.
1575 if push.is_none() && keep.is_none() && path == pack_dir {
1576 let child = git_command(&fixture.work, &["push", "--quiet", "origin", "main"])
1577 .stdout(std::process::Stdio::null())
1578 .stderr(std::process::Stdio::piped())
1579 .spawn()
1580 .expect("git should be on PATH");
1581 push = Some(child);
1582 wait_for(&parked);
1583 }
1584 // Listed, then let go: receive-pack deletes the `.keep` once its refs are in.
1585 if keep.is_none() && path.extension().is_some_and(|ext| ext == "keep") {
1586 fs::write(&release, b"").expect("write");
1587 let pushed = push
1588 .take()
1589 .expect("a .keep with no push running")
1590 .wait_with_output()
1591 .expect("wait");
1592 assert!(
1593 pushed.status.success(),
1594 "the push failed: {}",
1595 String::from_utf8_lossy(&pushed.stderr)
1596 );
1597 assert!(!path.exists(), "receive-pack left its .keep behind");
1598 keep = Some(path.to_path_buf());
1599 }
1600 }),
1601 );
1602
1603 let keep = keep.expect("the walk never listed the push's .keep");
1604 packed.expect("a .keep that vanishes must not fail the backup");
1605
1606 let names = entry_names(&plan.destination);
1607 assert!(
1608 !names.iter().any(|name| name.ends_with(".keep")),
1609 "a .keep was archived: {names:?}"
1610 );
1611 // The pack it marked is archived all the same: only the marker is left out.
1612 let pack = keep.with_extension("pack");
1613 let relative = pack
1614 .strip_prefix(&fixture.data)
1615 .expect("inside the data directory");
1616 let pack_entry = format!("{BACKUP_DATA_PREFIX}/{}", path_str(relative));
1617 assert!(
1618 names.contains(&pack_entry),
1619 "{pack_entry} is not in {names:?}"
1620 );
1621
1622 let restored = fixture.restore(&plan.destination, "restored");
1623 git(&restored, &["fsck", "--connectivity-only"]);
1624 }
1625
1626 #[test]
1627 fn a_file_that_grows_while_it_is_copied_is_archived_as_it_was_when_opened() {
1628 // Git appends to a reflog in place. Real pushes append to `main`'s here, after
1629 // the walk has opened it and read the size for its header, before its bytes are
1630 // copied.
1631 let fixture = live();
1632 let reflog = fixture.repo.join("logs/refs/heads/main");
1633 let plan = fixture.plan("out.tar.gz");
1634 let mut opened = None;
1635
1636 pack_with(&plan, &mut |moment, path| {
1637 if moment == Moment::Copying && path == reflog && opened.is_none() {
1638 opened = Some(fs::read(&reflog).expect("read"));
1639 for n in 0..4 {
1640 fs::write(fixture.work.join("README"), format!("{n}\n")).expect("write");
1641 git(&fixture.work, &["commit", "--quiet", "-am", "more"]);
1642 git(&fixture.work, &["push", "--quiet", "origin", "main"]);
1643 }
1644 }
1645 })
1646 .expect("should pack");
1647
1648 let opened = opened.expect("the walk never copied the reflog");
1649 let grown = fs::read(&reflog).expect("read");
1650 assert!(grown.starts_with(&opened), "git rewrote the reflog");
1651 // Past the end of the last 512-byte block the header accounts for, which is what
1652 // broke the archive when the copy ran to the end of the file.
1653 assert!(
1654 grown.len().div_ceil(512) > opened.len().div_ceil(512),
1655 "the pushes grew the reflog from {} to {} bytes, inside one block",
1656 opened.len(),
1657 grown.len()
1658 );
1659
1660 let restored = fixture.restore(&plan.destination, "restored");
1661 assert_eq!(
1662 fs::read(restored.join("logs/refs/heads/main")).expect("read"),
1663 opened,
1664 "the archive does not hold exactly the first {} bytes",
1665 opened.len()
1666 );
1667 git(&restored, &["fsck", "--connectivity-only"]);
1668 }
1669
1670 #[test]
1671 fn a_file_that_shrinks_while_it_is_copied_fails_the_backup_and_names_it() {
1672 // Git never truncates a file in place. Whatever did has made the size in the
1673 // entry's header a promise the copy cannot keep.
1674 let fixture = live();
1675 let reflog = fixture.repo.join("logs/refs/heads/main");
1676 let plan = fixture.plan("out.tar.gz");
1677 let mut cut = false;
1678
1679 let failed = pack_with(&plan, &mut |moment, path| {
1680 if moment == Moment::Copying && path == reflog && !cut {
1681 let file = fs::OpenOptions::new()
1682 .write(true)
1683 .open(&reflog)
1684 .expect("open");
1685 let len = file.metadata().expect("stat").len();
1686 file.set_len(len / 2).expect("truncate");
1687 cut = true;
1688 }
1689 });
1690
1691 assert!(cut, "the walk never copied the reflog");
1692 let error = failed
1693 .expect_err("a file that shrank must fail the backup")
1694 .to_string();
1695 assert!(
1696 error.contains(&reflog.display().to_string()) && error.contains("shrank"),
1697 "the failure does not say which file shrank: {error}"
1698 );
1699 assert!(!plan.destination.exists(), "an archive was written anyway");
1700 }
1701
1702 #[test]
1703 fn a_branch_named_like_gits_scratch_is_still_archived() {
1704 // `tmp_*` is git's scratch only inside `objects/`, and `*.keep` only inside
1705 // `objects/pack/`. A branch may be called `objects/tmp_x` or
1706 // `objects/pack/x.keep`, and its loose ref lives under `refs/heads/objects/`.
1707 let fixture = live();
1708 let branches = ["refs/heads/objects/tmp_x", "refs/heads/objects/pack/x.keep"];
1709 for branch in branches {
1710 git(&fixture.repo, &["update-ref", branch, "refs/heads/main"]);
1711 }
1712 let plan = fixture.plan("out.tar.gz");
1713 pack(&plan).expect("should pack");
1714
1715 let restored = fixture.restore(&plan.destination, "restored");
1716 for branch in branches {
1717 git(&restored, &["rev-parse", "--verify", branch]);
1718 }
1719 }
1720
1721 #[test]
1722 fn two_backups_of_one_state_hold_the_same_entries_in_the_same_order() {
1723 let fixture = live();
1724 git(&fixture.repo, &["tag", "v1", "main"]);
1725 git(&fixture.repo, &["pack-refs", "--all"]);
1726 git(&fixture.repo, &["repack", "-a", "-d", "-q"]);
1727
1728 let first = fixture.plan("first.tar.gz");
1729 let second = fixture.plan("second.tar.gz");
1730 pack(&first).expect("should pack");
1731 pack(&second).expect("should pack");
1732
1733 let names = entry_names(&first.destination);
1734 assert_eq!(names, entry_names(&second.destination));
1735
1736 // Git's own order inside the repository: refs, then packed-refs, then objects.
1737 let position = |wanted: &str| {
1738 names
1739 .iter()
1740 .position(|name| name == wanted)
1741 .unwrap_or_else(|| panic!("{wanted} is not in {names:?}"))
1742 };
1743 let repo = format!("{BACKUP_DATA_PREFIX}/james/steid.git");
1744 assert!(
1745 position(&format!("{repo}/refs/heads/")) < position(&format!("{repo}/packed-refs"))
1746 );
1747 assert!(position(&format!("{repo}/packed-refs")) < position(&format!("{repo}/objects/")));
1748 }
1749
1750 /// Runs git in `dir`, isolated from the host as Steid's own calls are, with a fixed
1751 /// identity and clock. Fails the test on a non-zero exit; answers stdout, trimmed.
1752 fn git(dir: &Path, args: &[&str]) -> String {
1753 let output = git_output(dir, args);
1754 assert!(
1755 output.status.success(),
1756 "git {args:?} failed: {}",
1757 String::from_utf8_lossy(&output.stderr)
1758 );
1759
1760 String::from_utf8_lossy(&output.stdout).trim().to_owned()
1761 }
1762
1763 fn git_output(dir: &Path, args: &[&str]) -> std::process::Output {
1764 git_command(dir, args)
1765 .output()
1766 .expect("git should be on PATH")
1767 }
1768
1769 /// git in `dir`, set up as [`git`] runs it, for a test that must start it and carry on.
1770 fn git_command(dir: &Path, args: &[&str]) -> std::process::Command {
1771 let mut command = std::process::Command::new("git");
1772 command
1773 .arg("-C")
1774 .arg(dir)
1775 .args(args)
1776 .env("GIT_CONFIG_GLOBAL", "/dev/null")
1777 .env("GIT_CONFIG_SYSTEM", "/dev/null")
1778 .env("GIT_AUTHOR_NAME", "Ada")
1779 .env("GIT_AUTHOR_EMAIL", "ada@example.com")
1780 .env("GIT_COMMITTER_NAME", "Ada")
1781 .env("GIT_COMMITTER_EMAIL", "ada@example.com")
1782 .env("GIT_AUTHOR_DATE", "2026-10-07T12:00:00Z")
1783 .env("GIT_COMMITTER_DATE", "2026-10-07T12:00:00Z");
1784
1785 for variable in [
1786 "GIT_ALTERNATE_OBJECT_DIRECTORIES",
1787 "GIT_DIR",
1788 "GIT_INDEX_FILE",
1789 "GIT_OBJECT_DIRECTORY",
1790 "GIT_WORK_TREE",
1791 ] {
1792 command.env_remove(variable);
1793 }
1794
1795 command
1796 }
1797
1798 /// Makes every push into the fixture's repository stop once its refs are committed,
1799 /// create `parked`, and wait there until `release` exists.
1800 ///
1801 /// `reference-transaction` is called with `committed` after receive-pack has moved
1802 /// the pushed pack out of quarantine and updated the refs, and before it deletes the
1803 /// pack's `.keep` (checked with git 2.50): the window a backup can list one in. The
1804 /// hook gives up after a minute, so a failed test cannot leave a push parked for ever.
1805 fn park_pushes(fixture: &Live, parked: &Path, release: &Path) {
1806 use std::os::unix::fs::PermissionsExt;
1807
1808 let hooks = fixture.root.path().join("hooks");
1809 fs::create_dir_all(&hooks).expect("mkdir");
1810 let hook = hooks.join("reference-transaction");
1811 fs::write(
1812 &hook,
1813 format!(
1814 "#!/bin/sh\n\
1815 [ \"$1\" = committed ] || exit 0\n\
1816 : > '{parked}'\n\
1817 tries=0\n\
1818 while [ ! -e '{release}' ]; do\n\
1819 \x20 tries=$((tries + 1))\n\
1820 \x20 [ \"$tries\" -gt 600 ] && exit 1\n\
1821 \x20 sleep 0.1\n\
1822 done\n",
1823 parked = path_str(parked),
1824 release = path_str(release),
1825 ),
1826 )
1827 .expect("write");
1828 fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).expect("chmod");
1829 git(
1830 &fixture.repo,
1831 &["config", "core.hooksPath", path_str(&hooks)],
1832 );
1833 }
1834
1835 /// Waits for a parked git to say it has got there, by creating `path`.
1836 fn wait_for(path: &Path) {
1837 use std::time::{Duration, Instant};
1838
1839 let deadline = Instant::now() + Duration::from_secs(60);
1840 while !path.exists() {
1841 assert!(
1842 Instant::now() < deadline,
1843 "{} never appeared",
1844 path.display()
1845 );
1846 std::thread::sleep(Duration::from_millis(10));
1847 }
1848 }
1849
1850 fn path_str(path: &Path) -> &str {
1851 path.to_str().expect("a UTF-8 temp path")
1852 }
1853
1854 /// Every entry name in an archive, in order.
1855 fn entry_names(archive: &Path) -> Vec<String> {
1856 open(archive)
1857 .expect("open")
1858 .entries()
1859 .expect("entries")
1860 .map(|entry| {
1861 entry
1862 .expect("entry")
1863 .path()
1864 .expect("path")
1865 .to_string_lossy()
1866 .into_owned()
1867 })
1868 .collect()
1869 }
1870}