steid

@jamesgill /

Rust31.4 KBCode·Blame·History·Raw
1//! One consistent archive of the whole instance, in and out.
2//!
3//! Steid's state is exactly two things: a SQLite database and a directory of bare
4//! repositories. A backup is both of them together, taken at one moment, in one file
5//! somebody can copy off the machine — and a restore is that file poured into an
6//! instance that has nothing in it yet.
7//!
8//! **Consistency is the reason this exists at all.** `cp steid.db` while the server is
9//! running catches whatever the copy happened to see and leaves the `-wal` behind, so
10//! the copy restores to a database that never existed. [`DatabaseSnapshot`] is the port
11//! that makes the copy an engine-level `VACUUM INTO` instead.
12//!
13//! ## Two entry points, and why
14//!
15//! [`back_up`] takes no [`Actor`]. It is the command line's, and the command line has no
16//! actor to take: whoever runs `steid backup` is root on the box, already holds the
17//! database file and the repositories, and is not asking Steid for permission to read
18//! what they already own. Inventing a `Actor::System` to satisfy the rule would create a
19//! variant that means "skip the check" — which is how the rule stops meaning anything.
20//!
21//! [`back_up_for`] is the same work behind an owner check, and is the only one anything
22//! reachable from the network may call. The layer rule is intact where it matters: the
23//! request path goes through a use case that authorizes before any side effect.
24
25use std::{
26 path::{Path, PathBuf},
27 time::{SystemTime, UNIX_EPOCH},
28};
29
30use serde::{Deserialize, Serialize};
31
32use crate::domain::{
33 Actor, DomainError,
34 repository::{OrgRepository, RepoRepository, UserRepository},
35};
36
37use super::{
38 access::instance_owner,
39 error::Result,
40 port::{
41 BackupArchive, BackupError, BackupPlan, DatabaseSnapshot, ExistingData, GitStorage,
42 RestorePlan,
43 },
44};
45
46/// The version this binary writes into a manifest, and refuses to read past.
47pub const VERSION: &str = env!("CARGO_PKG_VERSION");
48
49/// What an archive says about itself.
50///
51/// Small on purpose. It answers the two questions a restore has to ask — *can this
52/// binary read it* and *when was it taken* — plus the one a person asks afterwards:
53/// did everything come back.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55pub struct BackupManifest {
56 /// The Steid version that wrote it, e.g. `0.4.0`.
57 pub version: String,
58 /// When it was taken, RFC 3339 in UTC.
59 ///
60 /// A string rather than a number because the one thing that reads it is a person,
61 /// and `1757340000` in a JSON file at the top of a tarball helps nobody.
62 pub taken_at: String,
63 pub counts: BackupCounts,
64}
65
66/// How much was in the instance when the archive was taken.
67#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
68pub struct BackupCounts {
69 pub users: u64,
70 pub organisations: u64,
71 pub repositories: u64,
72}
73
74/// One archive, written.
75#[derive(Debug, Clone, PartialEq, Eq)]
76pub struct BackupWritten {
77 pub path: PathBuf,
78 pub bytes: u64,
79 pub manifest: BackupManifest,
80}
81
82/// One archive, restored.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct Restored {
85 pub manifest: BackupManifest,
86 /// Where the state this restore threw away was put, under
87 /// [`RestoreMode::Replace`]. `None` when the instance was empty and there was
88 /// nothing to move.
89 ///
90 /// Carried out to the caller because it is the one thing the operator has to be
91 /// told: it is a full copy of the previous instance, it is as large as that
92 /// instance was, and **nothing ever deletes it**.
93 pub replaced: Option<PathBuf>,
94}
95
96/// What a restore may do to an instance that is not empty.
97///
98/// An enum rather than a `bool`, because `restore(.., true, ..)` at a call site says
99/// nothing about what is true, and the two answers here are "refuse" and "destroy
100/// everything" — the pair least worth guessing at from a call site.
101#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
102pub enum RestoreMode {
103 /// Refuse unless the instance holds no user and no repository. **The default**, and
104 /// what `steid restore` does: a self-hoster who points it at the wrong box must get
105 /// a refusal rather than a site with somebody else's account in it.
106 #[default]
107 OnlyIfEmpty,
108 /// Replace whatever the instance holds with the archive's, whoever is in it.
109 ///
110 /// `steid restore --replace`. It exists for a managed instance, which is born owned
111 /// ([`OwnerSeed`](super::claim::OwnerSeed)) and therefore always holds a user, so the
112 /// refusal above can never be satisfied and a console restore could never succeed.
113 Replace,
114}
115
116/// The prefix of the directory a [`RestoreMode::Replace`] moves the old state into.
117///
118/// A dot, and load-bearing three times over: a handle can never start with one, so the
119/// backup packer skips it, `GitStorage::list_repo_dirs` never reads a repository out of
120/// it, and the swap itself can skip every top-level dot entry and so leave the backup
121/// workspace — and any earlier replacement — where they are.
122pub const REPLACED_PREFIX: &str = ".replaced-";
123
124/// What a backup taken now would be called.
125///
126/// `steid-0.4.0-20260908T142530Z.tar.gz`. The version is in the name because the
127/// restoring binary has to be at least this new and finding that out by unpacking is
128/// too late; the stamp is compact rather than RFC 3339 because a colon is a filename
129/// most tools will take and some will not.
130///
131/// Pure, so `steid backup /var/backups` can resolve a directory into a filename without
132/// this module knowing what a directory is.
133#[must_use]
134pub fn archive_name(now: SystemTime) -> String {
135 format!("steid-{VERSION}-{}.tar.gz", stamp(now))
136}
137
138/// A moment compressed into something that is a filename on every filesystem.
139///
140/// `20260908T142530Z`. Shared by [`archive_name`] and by the directory a
141/// [`RestoreMode::Replace`] moves the old state into, because both are names a person
142/// has to be able to sort by eye.
143fn stamp(now: SystemTime) -> String {
144 let (date, time) = utc_parts(now);
145
146 format!(
147 "{:04}{:02}{:02}T{:02}{:02}{:02}Z",
148 date.0, date.1, date.2, time.0, time.1, time.2
149 )
150}
151
152/// Writes one archive of the whole instance.
153///
154/// **No actor** — see the module note. The order matters and is the whole of the
155/// consistency story: the database snapshot is taken first, into `workspace`, and the
156/// data directory is packed from it afterwards. A repository pushed between the two ends
157/// up in the archive without a row, which reconciliation on boot handles
158/// ([`sweep_orphan_directories`](super::reconcile::sweep_orphan_directories)); the other
159/// order would give a row with no repository, which nothing handles.
160///
161/// `workspace` must exist and is the caller's to remove — it holds a full copy of the
162/// database until they do.
163#[allow(clippy::too_many_arguments)]
164pub async fn back_up(
165 now: SystemTime,
166 destination: &Path,
167 data_dir: &Path,
168 workspace: &Path,
169 users: &impl UserRepository,
170 orgs: &impl OrgRepository,
171 repos: &impl RepoRepository,
172 snapshots: &impl DatabaseSnapshot,
173 archives: &impl BackupArchive,
174) -> Result<BackupWritten> {
175 let manifest = BackupManifest {
176 version: VERSION.to_owned(),
177 taken_at: rfc3339(now),
178 counts: BackupCounts {
179 users: users.count().await?,
180 organisations: orgs.count().await?,
181 repositories: repos.count().await?,
182 },
183 };
184
185 let database = snapshots.snapshot(workspace).await?;
186
187 let bytes = archives
188 .pack(BackupPlan {
189 destination: destination.to_path_buf(),
190 database,
191 data_dir: data_dir.to_path_buf(),
192 manifest: manifest.clone(),
193 })
194 .await?;
195
196 Ok(BackupWritten {
197 path: destination.to_path_buf(),
198 bytes,
199 manifest,
200 })
201}
202
203/// [`back_up`] for a request: the instance's owner, and nobody else.
204///
205/// A backup is every row and every repository, private ones included, so the question is
206/// not "may this actor read some organisation" — it is "is this actor the person who
207/// owns the instance". Membership of an org is the wrong test and would hand the whole
208/// database to anyone who owns one.
209#[allow(clippy::too_many_arguments)]
210pub async fn back_up_for(
211 actor: &Actor,
212 now: SystemTime,
213 destination: &Path,
214 data_dir: &Path,
215 workspace: &Path,
216 users: &impl UserRepository,
217 orgs: &impl OrgRepository,
218 repos: &impl RepoRepository,
219 snapshots: &impl DatabaseSnapshot,
220 archives: &impl BackupArchive,
221) -> Result<BackupWritten> {
222 if !instance_owner(actor, users).await? {
223 return Err(DomainError::Forbidden.into());
224 }
225
226 back_up(
227 now,
228 destination,
229 data_dir,
230 workspace,
231 users,
232 orgs,
233 repos,
234 snapshots,
235 archives,
236 )
237 .await
238}
239
240/// Pours an archive into an instance, refusing by default to do it over anybody.
241///
242/// **Refuses rather than merges.** Every check happens before a byte is written, and
243/// under [`RestoreMode::OnlyIfEmpty`] there are three:
244///
245/// 1. the database holds no user — a claimed instance is somebody's, and restoring over
246/// it would replace their account with the archive's;
247/// 2. the data directory holds no repository — the same, for the half of the state that
248/// is not in the database;
249/// 3. the archive was written by this version or an older one — a newer Steid may have
250/// migrated the schema in ways this binary cannot read, and a migration only runs
251/// forwards.
252///
253/// The database is unpacked into `workspace` and only installed once the whole
254/// extraction has succeeded, so an archive that fails halfway leaves the live database
255/// alone. `workspace` must exist and is the caller's to remove.
256///
257/// ## [`RestoreMode::Replace`]
258///
259/// The first two checks are the consent, and `--replace` is somebody giving it; the
260/// third stands either way, because an unreadable schema is not a thing consent helps
261/// with. The rest of this function is then about not losing the instance on the way:
262///
263/// 1. the archive is extracted into `<workspace>/incoming`, so **a failure during
264/// extraction has still touched nothing live**;
265/// 2. the data directory's current contents are *moved* — never deleted — into
266/// `<data_dir>/.replaced-<stamp>/`, and the extracted tree is moved into their place;
267/// 3. a consistent copy of the database that is about to be thrown away is written
268/// beside them, so the aside directory holds the whole previous instance rather than
269/// half of it;
270/// 4. the archive's database is installed last.
271///
272/// The aside directory is **never removed by Steid**. Somebody has to delete it, and
273/// until they do the instance occupies roughly twice what it did — which is why
274/// [`Restored::replaced`] carries the path out to whoever is reporting.
275///
276/// **A restore into a running process is the operator's problem, not this function's.**
277/// Steid holds the data directory open and serves out of it; the managed console stops
278/// the service before it runs this and starts it afterwards, and a self-hoster running
279/// `--replace` by hand should do the same. Nothing here checks, because there is nothing
280/// portable to check with.
281///
282/// The window that is not atomic is between (2) and (4): the repositories are the
283/// archive's and the database is still the old one. A failure there leaves an instance
284/// whose two halves disagree, and the recovery is the aside directory plus the archive —
285/// both of which are still on disk, which is the property worth having.
286#[allow(clippy::too_many_arguments)]
287pub async fn restore(
288 now: SystemTime,
289 archive: &Path,
290 data_dir: &Path,
291 workspace: &Path,
292 mode: RestoreMode,
293 users: &impl UserRepository,
294 storage: &impl GitStorage,
295 snapshots: &impl DatabaseSnapshot,
296 archives: &impl BackupArchive,
297) -> Result<Restored> {
298 if mode == RestoreMode::OnlyIfEmpty {
299 if users.any_exist().await? {
300 return Err(DomainError::Unavailable {
301 entity: "instance",
302 reason: "it already has a user; restore only into an unclaimed instance, or \
303 pass --replace to replace everything it holds"
304 .to_owned(),
305 }
306 .into());
307 }
308
309 let existing = storage.list_repo_dirs().await?;
310 if !existing.is_empty() {
311 return Err(DomainError::Unavailable {
312 entity: "instance",
313 reason: format!(
314 "the data directory already holds {} repository/repositories; pass \
315 --replace to replace everything it holds",
316 existing.len()
317 ),
318 }
319 .into());
320 }
321 }
322
323 let manifest = archives.manifest(archive).await?;
324
325 if is_newer(&manifest.version, VERSION)? {
326 return Err(BackupError::refused(format!(
327 "the archive was written by Steid {} and this is {VERSION}; upgrade first",
328 manifest.version
329 ))
330 .into());
331 }
332
333 let staged = workspace.join("steid.db");
334
335 let replaced = match mode {
336 RestoreMode::OnlyIfEmpty => None,
337 RestoreMode::Replace => Some(data_dir.join(format!("{REPLACED_PREFIX}{}", stamp(now)))),
338 };
339
340 archives
341 .unpack(RestorePlan {
342 archive: archive.to_path_buf(),
343 database: staged.clone(),
344 data_dir: data_dir.to_path_buf(),
345 existing: match &replaced {
346 None => ExistingData::Refuse,
347 Some(aside) => ExistingData::Replace {
348 staging: workspace.join(INCOMING),
349 aside: aside.clone(),
350 },
351 },
352 })
353 .await?;
354
355 // Between the swap and the line below, the live database is still the old one — so
356 // this is the last moment a consistent copy of it can be taken, and the aside
357 // directory is where it belongs: beside the repositories it agrees with.
358 if let Some(aside) = &replaced {
359 snapshots.snapshot(aside).await?;
360 }
361
362 // Last, and only once the repositories are on disk: under `OnlyIfEmpty` the instance
363 // is still the empty one it was until this line, so a failure above is a failure that
364 // changed nothing anybody can see.
365 snapshots.replace(&staged).await?;
366
367 Ok(Restored { manifest, replaced })
368}
369
370/// Where a [`RestoreMode::Replace`] extracts to, inside the workspace.
371const INCOMING: &str = "incoming";
372
373/// Whether `candidate` is a later release than `current`.
374///
375/// Three numbers, and anything after a `-` or `+` ignored: a pre-release of 0.5.0 is
376/// still 0.5.0 as far as "can this binary read it" goes, because the schema is what
377/// matters and a suffix does not change it. A version that will not parse is refused
378/// rather than waved through — an unreadable version is not evidence of anything, and
379/// the safe direction here is to stop.
380fn is_newer(candidate: &str, current: &str) -> Result<bool> {
381 Ok(release(candidate)? > release(current)?)
382}
383
384fn release(value: &str) -> Result<(u64, u64, u64)> {
385 let core = value
386 .split(['-', '+'])
387 .next()
388 .unwrap_or_default()
389 .trim()
390 .to_owned();
391
392 let mut parts = core.split('.');
393 let mut number = || {
394 parts
395 .next()
396 .and_then(|part| part.parse::<u64>().ok())
397 .ok_or_else(|| {
398 DomainError::validation("version", format!("{value:?} is not a Steid version"))
399 })
400 };
401
402 Ok((number()?, number()?, number()?))
403}
404
405/// A timestamp as the manifest writes it: RFC 3339, UTC, seconds.
406fn rfc3339(time: SystemTime) -> String {
407 let ((year, month, day), (hour, minute, second)) = utc_parts(time);
408
409 format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
410}
411
412/// A `SystemTime` split into a UTC date and time-of-day.
413///
414/// The date arithmetic is Howard Hinnant's `civil_from_days`, which is also what
415/// `web::browse` does — written again here rather than reached for, because the
416/// application layer may not depend on the web layer and one shared twelve-line
417/// function is not worth a module that both can see. If a third caller appears, that
418/// module is the answer.
419fn utc_parts(time: SystemTime) -> ((i64, u32, u32), (u64, u64, u64)) {
420 let seconds = time
421 .duration_since(UNIX_EPOCH)
422 .map(|since| since.as_secs() as i64)
423 .unwrap_or(0);
424
425 let rest = seconds.rem_euclid(86_400) as u64;
426
427 (
428 civil_from_days(seconds.div_euclid(86_400)),
429 (rest / 3600, (rest % 3600) / 60, rest % 60),
430 )
431}
432
433/// Days since the Unix epoch to a civil `(year, month, day)`.
434fn civil_from_days(days: i64) -> (i64, u32, u32) {
435 let z = days + 719_468;
436 let era = z.div_euclid(146_097);
437 let doe = z.rem_euclid(146_097);
438 let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
439 let year = yoe + era * 400;
440 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
441 let mp = (5 * doy + 2) / 153;
442 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
443 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
444
445 (year + i64::from(month <= 2), month, day)
446}
447
448#[cfg(test)]
449mod tests {
450 use std::time::Duration;
451
452 use super::super::port::ExistingData;
453 use super::*;
454 use crate::{
455 application::error::Error,
456 domain::{
457 Email, OrgId, Organization, PasswordHash, RepoId, Repository, User, UserId, Visibility,
458 },
459 infrastructure::{
460 backup::{InMemoryBackupArchive, InMemoryDatabaseSnapshot},
461 git::InMemoryGitStorage,
462 repository::{InMemoryOrgRepo, InMemoryRepoRepo, InMemoryUserRepo},
463 },
464 };
465
466 /// 2026-09-08T14:25:30Z.
467 fn at() -> SystemTime {
468 UNIX_EPOCH + Duration::from_secs(1_788_877_530)
469 }
470
471 struct Fixture {
472 users: InMemoryUserRepo,
473 orgs: InMemoryOrgRepo,
474 repos: InMemoryRepoRepo,
475 storage: InMemoryGitStorage,
476 snapshots: InMemoryDatabaseSnapshot,
477 archives: InMemoryBackupArchive,
478 owner: Actor,
479 }
480
481 impl Fixture {
482 /// An unclaimed instance: no user, no organisation, nothing on disk.
483 fn empty() -> Self {
484 Self {
485 users: InMemoryUserRepo::new(),
486 orgs: InMemoryOrgRepo::new(),
487 repos: InMemoryRepoRepo::new(),
488 storage: InMemoryGitStorage::new(),
489 snapshots: InMemoryDatabaseSnapshot::new(),
490 archives: InMemoryBackupArchive::new(),
491 owner: Actor::Anonymous,
492 }
493 }
494
495 /// An instance with an owner, their organisation, and one repository.
496 async fn claimed() -> Self {
497 let mut f = Self::empty();
498
499 let org = Organization::new(OrgId::generate(), "james", None).expect("valid org");
500 f.orgs.save(&org).await.expect("save org");
501
502 let user = User::new(
503 UserId::generate(),
504 Email::new("dev@example.com").expect("valid email"),
505 PasswordHash::from_trusted("$argon2id$test"),
506 org.id.clone(),
507 );
508 f.users.save(&user).await.expect("save user");
509 f.repos
510 .save(
511 &Repository::new(
512 RepoId::generate(),
513 org.id.clone(),
514 "steid",
515 None,
516 Visibility::Public,
517 at(),
518 )
519 .expect("valid repository"),
520 )
521 .await
522 .expect("save repository");
523
524 f.owner = Actor::User(user.id);
525 f
526 }
527
528 async fn back_up(&self, to: &str) -> Result<BackupWritten> {
529 back_up(
530 at(),
531 Path::new(to),
532 Path::new("/data"),
533 Path::new("/work"),
534 &self.users,
535 &self.orgs,
536 &self.repos,
537 &self.snapshots,
538 &self.archives,
539 )
540 .await
541 }
542
543 async fn restore(&self, from: &str) -> Result<Restored> {
544 self.restore_with(from, RestoreMode::OnlyIfEmpty).await
545 }
546
547 async fn restore_with(&self, from: &str, mode: RestoreMode) -> Result<Restored> {
548 restore(
549 at(),
550 Path::new(from),
551 Path::new("/data"),
552 Path::new("/work"),
553 mode,
554 &self.users,
555 &self.storage,
556 &self.snapshots,
557 &self.archives,
558 )
559 .await
560 }
561 }
562
563 #[test]
564 fn an_archive_is_named_for_the_version_and_the_moment() {
565 assert_eq!(
566 archive_name(at()),
567 format!("steid-{VERSION}-20260908T142530Z.tar.gz")
568 );
569 }
570
571 #[test]
572 fn a_manifest_timestamp_is_rfc_3339_in_utc() {
573 assert_eq!(rfc3339(at()), "2026-09-08T14:25:30Z");
574 assert_eq!(rfc3339(UNIX_EPOCH), "1970-01-01T00:00:00Z");
575 }
576
577 #[tokio::test]
578 async fn a_backup_records_what_the_instance_held() {
579 let f = Fixture::claimed().await;
580
581 let written = f.back_up("/out.tar.gz").await.expect("should back up");
582
583 assert_eq!(written.path, PathBuf::from("/out.tar.gz"));
584 assert_eq!(written.manifest.version, VERSION);
585 assert_eq!(written.manifest.taken_at, "2026-09-08T14:25:30Z");
586 assert_eq!(
587 written.manifest.counts,
588 BackupCounts {
589 users: 1,
590 organisations: 1,
591 repositories: 1,
592 }
593 );
594 }
595
596 #[tokio::test]
597 async fn a_backup_packs_the_snapshot_rather_than_the_live_database() {
598 // The whole point of the port: what reaches the archive is the copy `snapshot`
599 // made, never a path into the running instance.
600 let f = Fixture::claimed().await;
601
602 f.back_up("/out.tar.gz").await.expect("should back up");
603
604 let plan = f.archives.packed().pop().expect("one archive");
605 assert_eq!(plan.database, PathBuf::from("/work/snapshot-1.db"));
606 assert_eq!(plan.data_dir, PathBuf::from("/data"));
607 assert_eq!(f.snapshots.taken(), 1);
608 }
609
610 #[tokio::test]
611 async fn only_the_instance_owner_may_download_a_backup() {
612 let f = Fixture::claimed().await;
613
614 let refused = back_up_for(
615 &Actor::Anonymous,
616 at(),
617 Path::new("/out.tar.gz"),
618 Path::new("/data"),
619 Path::new("/work"),
620 &f.users,
621 &f.orgs,
622 &f.repos,
623 &f.snapshots,
624 &f.archives,
625 )
626 .await;
627
628 assert!(matches!(
629 refused,
630 Err(Error::Domain(DomainError::Forbidden))
631 ));
632 assert!(f.archives.packed().is_empty(), "nothing was written");
633
634 assert!(
635 back_up_for(
636 &f.owner,
637 at(),
638 Path::new("/out.tar.gz"),
639 Path::new("/data"),
640 Path::new("/work"),
641 &f.users,
642 &f.orgs,
643 &f.repos,
644 &f.snapshots,
645 &f.archives,
646 )
647 .await
648 .is_ok()
649 );
650 }
651
652 #[tokio::test]
653 async fn a_signed_in_stranger_is_not_the_instance_owner() {
654 // Being a user is not being *the* user. This is the check that
655 // `instance_owner` has not quietly become `is_authenticated`.
656 let f = Fixture::claimed().await;
657
658 assert!(
659 !instance_owner(&Actor::User(UserId::generate()), &f.users)
660 .await
661 .expect("should read")
662 );
663 }
664
665 #[tokio::test]
666 async fn a_backup_restores_into_an_empty_instance() {
667 let source = Fixture::claimed().await;
668 let written = source.back_up("/out.tar.gz").await.expect("should back up");
669
670 let target = Fixture::empty();
671 // The same fake archive store, standing in for the file being copied across.
672 let target = Fixture {
673 archives: source.archives.clone(),
674 ..target
675 };
676
677 let restored = target.restore("/out.tar.gz").await.expect("should restore");
678
679 assert_eq!(restored.manifest, written.manifest);
680 assert_eq!(
681 target
682 .archives
683 .unpacked()
684 .pop()
685 .expect("one restore")
686 .data_dir,
687 PathBuf::from("/data")
688 );
689 // Installed last, and only once: a half-unpacked archive never becomes live.
690 assert_eq!(
691 target.snapshots.installed(),
692 vec![PathBuf::from("/work/steid.db")]
693 );
694 }
695
696 #[tokio::test]
697 async fn a_restore_refuses_an_instance_that_already_has_a_user() {
698 let f = Fixture::claimed().await;
699 f.back_up("/out.tar.gz").await.expect("should back up");
700
701 let refused = f.restore("/out.tar.gz").await;
702
703 assert!(matches!(
704 refused,
705 Err(Error::Domain(DomainError::Unavailable {
706 entity: "instance",
707 ..
708 }))
709 ));
710 assert!(f.snapshots.installed().is_empty(), "nothing was replaced");
711 assert!(f.archives.unpacked().is_empty(), "nothing was extracted");
712 }
713
714 #[tokio::test]
715 async fn a_restore_refuses_a_data_directory_that_already_holds_repositories() {
716 let source = Fixture::claimed().await;
717 source.back_up("/out.tar.gz").await.expect("should back up");
718
719 let target = Fixture {
720 archives: source.archives.clone(),
721 ..Fixture::empty()
722 };
723 target
724 .storage
725 .init_bare(
726 &crate::domain::OrgName::new("someone").expect("valid handle"),
727 &crate::domain::RepoName::new("thing").expect("valid name"),
728 )
729 .await
730 .expect("init");
731
732 let refused = target.restore("/out.tar.gz").await;
733
734 assert!(matches!(
735 refused,
736 Err(Error::Domain(DomainError::Unavailable {
737 entity: "instance",
738 ..
739 }))
740 ));
741 assert!(
742 target.archives.unpacked().is_empty(),
743 "nothing was extracted"
744 );
745 }
746
747 #[tokio::test]
748 async fn replace_restores_over_an_instance_that_already_holds_somebody() {
749 // Both halves of "already holds somebody": a user in the database and a
750 // repository on disk. Without the flag either one alone is a refusal.
751 let source = Fixture::claimed().await;
752 source.back_up("/out.tar.gz").await.expect("should back up");
753
754 let target = Fixture {
755 archives: source.archives.clone(),
756 ..Fixture::claimed().await
757 };
758 target
759 .storage
760 .init_bare(
761 &crate::domain::OrgName::new("someone").expect("valid handle"),
762 &crate::domain::RepoName::new("thing").expect("valid name"),
763 )
764 .await
765 .expect("init");
766
767 assert!(
768 target.restore("/out.tar.gz").await.is_err(),
769 "the refusal is the default and must stay it"
770 );
771
772 let restored = target
773 .restore_with("/out.tar.gz", RestoreMode::Replace)
774 .await
775 .expect("--replace is the consent");
776
777 let aside = restored
778 .replaced
779 .expect("a replace says where the old state went");
780 assert_eq!(aside, PathBuf::from("/data/.replaced-20260908T142530Z"));
781
782 // Unpacked beside, not into the live directory, and swapped in by the adapter:
783 // the plan the use case built is where that decision lives.
784 let plan = target.archives.unpacked().pop().expect("one restore");
785 assert_eq!(plan.data_dir, PathBuf::from("/data"));
786 assert_eq!(
787 plan.existing,
788 ExistingData::Replace {
789 staging: PathBuf::from("/work/incoming"),
790 aside: aside.clone(),
791 }
792 );
793
794 // One snapshot into the aside directory — the database about to be thrown away —
795 // and the archive's installed after it.
796 assert_eq!(target.snapshots.taken(), 1);
797 assert_eq!(
798 target.snapshots.installed(),
799 vec![PathBuf::from("/work/steid.db")]
800 );
801 }
802
803 #[tokio::test]
804 async fn replace_still_refuses_an_archive_from_a_newer_steid() {
805 // Consent covers "this instance is somebody's". It does not cover a schema this
806 // binary cannot read, because no amount of consent makes that work.
807 let f = Fixture::claimed().await;
808 f.archives.plant(
809 "/future.tar.gz",
810 BackupManifest {
811 version: "99.0.0".to_owned(),
812 taken_at: "2030-01-01T00:00:00Z".to_owned(),
813 counts: BackupCounts::default(),
814 },
815 );
816
817 assert!(matches!(
818 f.restore_with("/future.tar.gz", RestoreMode::Replace).await,
819 Err(Error::Backup(BackupError::Refused(_))),
820 ));
821 assert!(f.archives.unpacked().is_empty(), "nothing was extracted");
822 }
823
824 #[tokio::test]
825 async fn an_empty_instance_restored_without_replace_moves_nothing_aside() {
826 let source = Fixture::claimed().await;
827 source.back_up("/out.tar.gz").await.expect("should back up");
828
829 let target = Fixture {
830 archives: source.archives.clone(),
831 ..Fixture::empty()
832 };
833
834 let restored = target.restore("/out.tar.gz").await.expect("should restore");
835
836 assert_eq!(restored.replaced, None);
837 assert_eq!(
838 target
839 .archives
840 .unpacked()
841 .pop()
842 .expect("one restore")
843 .existing,
844 ExistingData::Refuse
845 );
846 // No copy of an old database, because there was no old instance.
847 assert_eq!(target.snapshots.taken(), 0);
848 }
849
850 #[tokio::test]
851 async fn a_restore_refuses_an_archive_from_a_newer_steid() {
852 let f = Fixture::empty();
853 f.archives.plant(
854 "/future.tar.gz",
855 BackupManifest {
856 version: "99.0.0".to_owned(),
857 taken_at: "2030-01-01T00:00:00Z".to_owned(),
858 counts: BackupCounts::default(),
859 },
860 );
861
862 let refused = f.restore("/future.tar.gz").await;
863
864 assert!(matches!(
865 refused,
866 Err(Error::Backup(BackupError::Refused(_))),
867 ));
868 assert!(f.archives.unpacked().is_empty(), "nothing was extracted");
869 }
870
871 #[tokio::test]
872 async fn a_restore_accepts_an_archive_from_an_older_steid() {
873 let f = Fixture::empty();
874 f.archives.plant(
875 "/old.tar.gz",
876 BackupManifest {
877 version: "0.0.1".to_owned(),
878 taken_at: "2026-01-01T00:00:00Z".to_owned(),
879 counts: BackupCounts::default(),
880 },
881 );
882
883 assert!(f.restore("/old.tar.gz").await.is_ok());
884 }
885
886 #[test]
887 fn a_version_is_compared_by_its_three_numbers() {
888 assert!(is_newer("0.5.0", "0.4.0").expect("parses"));
889 assert!(is_newer("0.4.1", "0.4.0").expect("parses"));
890 assert!(!is_newer("0.4.0", "0.4.0").expect("parses"));
891 assert!(!is_newer("0.3.9", "0.4.0").expect("parses"));
892 // A pre-release of the same release reads the same schema.
893 assert!(!is_newer("0.4.0-rc.1", "0.4.0").expect("parses"));
894 // Unparseable is refused, not waved through.
895 assert!(is_newer("banana", "0.4.0").is_err());
896 assert!(is_newer("0.4", "0.4.0").is_err());
897 }
898}