The AWS program becomes a skipped clap field so tests can substitute a fake; run is split into reconcile (returns the report) and a printing wrapper. No behaviour change. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
788 lines
27 KiB
Rust
788 lines
27 KiB
Rust
use anyhow::{ensure, Context, Result};
|
|
use chrono::{DateTime, Utc};
|
|
use clap::{Args, ValueEnum};
|
|
use serde::{Deserialize, Serialize};
|
|
use sha2::{Digest, Sha256};
|
|
use std::{
|
|
fs::File,
|
|
io::{self, Read, Seek, SeekFrom},
|
|
path::PathBuf,
|
|
process::{Command, Stdio},
|
|
};
|
|
use tessera_core::SnapshotManifest;
|
|
use tessera_store::Vault;
|
|
use uuid::Uuid;
|
|
|
|
#[derive(Args, Clone)]
|
|
pub struct ImportArgs {
|
|
#[arg(long)]
|
|
bucket: String,
|
|
#[arg(long)]
|
|
prefix: String,
|
|
#[arg(long)]
|
|
endpoint: Option<String>,
|
|
#[arg(long)]
|
|
orbit_id: Uuid,
|
|
#[arg(long)]
|
|
application: String,
|
|
#[arg(long, value_enum)]
|
|
engine: Engine,
|
|
/// Consistent SQLite export of the old service's job history.
|
|
#[arg(long)]
|
|
history: Option<PathBuf>,
|
|
/// Reconcile counts, times and sizes without downloading or writing snapshots.
|
|
#[arg(long)]
|
|
inventory_only: bool,
|
|
/// The AWS CLI to run; a field only so tests can substitute a fake one.
|
|
#[arg(skip = PathBuf::from("aws"))]
|
|
program: PathBuf,
|
|
}
|
|
|
|
#[derive(Clone, Copy, ValueEnum)]
|
|
enum Engine {
|
|
Postgres,
|
|
Mysql,
|
|
}
|
|
|
|
impl Engine {
|
|
fn name(self) -> &'static str {
|
|
match self {
|
|
Self::Postgres => "postgres",
|
|
Self::Mysql => "mysql",
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(rename_all = "PascalCase")]
|
|
struct Listing {
|
|
#[serde(default)]
|
|
contents: Vec<Object>,
|
|
}
|
|
|
|
#[derive(Deserialize, Serialize)]
|
|
#[serde(rename_all(deserialize = "PascalCase"))]
|
|
struct Object {
|
|
key: String,
|
|
#[serde(rename(deserialize = "ETag"))]
|
|
etag: String,
|
|
size: u64,
|
|
last_modified: DateTime<Utc>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
#[serde(rename_all = "PascalCase")]
|
|
struct Downloaded {
|
|
#[serde(rename = "ETag")]
|
|
etag: String,
|
|
content_length: u64,
|
|
last_modified: DateTime<Utc>,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct Entry {
|
|
snapshot_id: Uuid,
|
|
#[serde(flatten)]
|
|
object: Object,
|
|
status: &'static str,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct Report {
|
|
application: String,
|
|
bucket: String,
|
|
prefix: String,
|
|
count: usize,
|
|
bytes: u64,
|
|
history_snapshot_id: Option<Uuid>,
|
|
objects: Vec<Entry>,
|
|
}
|
|
|
|
pub fn run(vault: &Vault, args: ImportArgs) -> Result<()> {
|
|
let report = reconcile(vault, args)?;
|
|
println!("{}", serde_json::to_string_pretty(&report)?);
|
|
Ok(())
|
|
}
|
|
|
|
fn reconcile(vault: &Vault, args: ImportArgs) -> Result<Report> {
|
|
ensure!(
|
|
!args.prefix.is_empty() && args.prefix.ends_with('/'),
|
|
"provide a per-application prefix ending in '/'"
|
|
);
|
|
ensure!(
|
|
!args.application.trim().is_empty()
|
|
&& args.application.len() <= 128
|
|
&& !args.application.chars().any(char::is_control),
|
|
"invalid application name"
|
|
);
|
|
if let Some(endpoint) = &args.endpoint {
|
|
ensure!(
|
|
(endpoint.starts_with("https://") || endpoint.starts_with("http://127.0.0.1:"))
|
|
&& !endpoint.contains(['@', '?', '#', '\r', '\n']),
|
|
"use an HTTPS S3 endpoint without embedded credentials"
|
|
);
|
|
}
|
|
let output = aws(&args, "list-objects-v2")
|
|
.arg(format!("--prefix={}", args.prefix))
|
|
.output()
|
|
.context("run AWS CLI S3 inventory")?;
|
|
ensure!(
|
|
output.status.success(),
|
|
"could not list legacy S3 objects ({})",
|
|
output.status
|
|
);
|
|
let listing: Listing =
|
|
serde_json::from_slice(&output.stdout).context("parse legacy S3 inventory")?;
|
|
let mut objects = Vec::new();
|
|
let mut bytes = 0u64;
|
|
for object in listing.contents {
|
|
if !object.key.starts_with(&args.prefix)
|
|
|| !(object.key.ends_with(".sql") || object.key.ends_with(".sql.gz"))
|
|
{
|
|
continue;
|
|
}
|
|
ensure!(
|
|
object.size > 0 && !object.etag.is_empty() && object.etag != "*",
|
|
"invalid legacy archive metadata"
|
|
);
|
|
bytes = bytes
|
|
.checked_add(object.size)
|
|
.context("legacy inventory byte count overflow")?;
|
|
let key = serde_json::to_vec(&(
|
|
"s3-legacy",
|
|
&args.endpoint,
|
|
&args.bucket,
|
|
&object.key,
|
|
&object.etag,
|
|
object.size,
|
|
object.last_modified,
|
|
args.orbit_id,
|
|
))?;
|
|
let snapshot_id = Uuid::new_v5(&Uuid::NAMESPACE_URL, &key);
|
|
let status = if args.inventory_only {
|
|
"inventoried"
|
|
} else if vault.legacy_import_exists(snapshot_id)? {
|
|
"already_imported"
|
|
} else if import_object(vault, &args, &object, snapshot_id)? {
|
|
"imported"
|
|
} else {
|
|
"already_imported"
|
|
};
|
|
objects.push(Entry {
|
|
snapshot_id,
|
|
object,
|
|
status,
|
|
});
|
|
}
|
|
let history_snapshot_id = if args.inventory_only {
|
|
None
|
|
} else {
|
|
args.history
|
|
.as_ref()
|
|
.map(|path| import_history(vault, path))
|
|
.transpose()?
|
|
};
|
|
Ok(Report {
|
|
application: args.application,
|
|
bucket: args.bucket,
|
|
prefix: args.prefix,
|
|
count: objects.len(),
|
|
bytes,
|
|
history_snapshot_id,
|
|
objects,
|
|
})
|
|
}
|
|
|
|
fn aws(args: &ImportArgs, operation: &str) -> Command {
|
|
let mut cmd = Command::new(&args.program);
|
|
cmd.args([
|
|
"--no-cli-pager",
|
|
"--no-cli-auto-prompt",
|
|
"--output",
|
|
"json",
|
|
"s3api",
|
|
operation,
|
|
])
|
|
.arg(format!("--bucket={}", args.bucket))
|
|
.stdin(Stdio::null())
|
|
.stderr(Stdio::null());
|
|
if let Some(endpoint) = &args.endpoint {
|
|
cmd.arg(format!("--endpoint-url={endpoint}"));
|
|
}
|
|
cmd
|
|
}
|
|
|
|
fn import_object(vault: &Vault, args: &ImportArgs, object: &Object, id: Uuid) -> Result<bool> {
|
|
let file = tempfile::NamedTempFile::new()?;
|
|
let output = aws(args, "get-object")
|
|
.arg(format!("--key={}", object.key))
|
|
.arg(format!("--if-match={}", object.etag))
|
|
.arg(file.path())
|
|
.output()
|
|
.context("run conditional AWS CLI S3 download")?;
|
|
ensure!(
|
|
output.status.success(),
|
|
"legacy archive download failed ({})",
|
|
output.status
|
|
);
|
|
let received: Downloaded =
|
|
serde_json::from_slice(&output.stdout).context("parse downloaded object metadata")?;
|
|
ensure!(
|
|
received.etag == object.etag
|
|
&& received.last_modified == object.last_modified
|
|
&& received.content_length == object.size
|
|
&& file.as_file().metadata()?.len() == object.size,
|
|
"legacy object changed since inventory"
|
|
);
|
|
let mut file = file.reopen()?;
|
|
let format = if object.key.ends_with(".sql.gz") {
|
|
let mut signature = [0; 2];
|
|
file.read_exact(&mut signature)?;
|
|
ensure!(
|
|
signature == [0x1f, 0x8b],
|
|
"legacy archive is missing a gzip header"
|
|
);
|
|
file.seek(SeekFrom::Start(0))?;
|
|
"sql_gzip"
|
|
} else {
|
|
"plain"
|
|
};
|
|
let manifest = SnapshotManifest {
|
|
snapshot_id: id,
|
|
orbit_id: args.orbit_id,
|
|
orbit_name: args.application.clone(),
|
|
provider: args.engine.name().into(),
|
|
labels: vec!["legacy-import".into()],
|
|
paths: vec![],
|
|
restore_hints: serde_json::json!({
|
|
"format": format, "legacy": { "bucket": args.bucket, "key": object.key,
|
|
"etag": object.etag, "bytes": object.size, "last_modified": object.last_modified }
|
|
}),
|
|
};
|
|
vault.import_legacy_payload(manifest, file, object.last_modified)
|
|
}
|
|
|
|
fn import_history(vault: &Vault, path: &std::path::Path) -> Result<Uuid> {
|
|
let mut original = File::open(path).context("open legacy history export")?;
|
|
let mut signature = [0; 16];
|
|
original.read_exact(&mut signature)?;
|
|
ensure!(
|
|
&signature == b"SQLite format 3\0",
|
|
"legacy history must be a consistent SQLite export"
|
|
);
|
|
original.seek(SeekFrom::Start(0))?;
|
|
let mut staged = tempfile::tempfile()?;
|
|
let bytes = io::copy(&mut original, &mut staged)?;
|
|
staged.seek(SeekFrom::Start(0))?;
|
|
let mut digest = Sha256::new();
|
|
io::copy(&mut staged, &mut digest)?;
|
|
let checksum = hex::encode(digest.finalize());
|
|
let key = format!("legacy-history:{checksum}");
|
|
let id = Uuid::new_v5(&Uuid::NAMESPACE_URL, key.as_bytes());
|
|
let taken_at: DateTime<Utc> = original.metadata()?.modified()?.into();
|
|
let manifest = SnapshotManifest {
|
|
snapshot_id: id,
|
|
orbit_id: Uuid::nil(),
|
|
orbit_name: "Legacy operator history".into(),
|
|
provider: "legacy-history".into(),
|
|
labels: vec!["legacy-history".into()],
|
|
paths: vec![],
|
|
restore_hints: serde_json::json!({"format": "sqlite", "sha256": checksum, "legacy_bytes": bytes}),
|
|
};
|
|
vault.import_legacy_payload(manifest, staged, taken_at)?;
|
|
Ok(id)
|
|
}
|
|
|
|
/// These drive `reconcile` against a stand-in `aws` (a shell script that serves a local directory), so the
|
|
/// listing, conditional download, receipts and history paths all run for real; only S3 is faked.
|
|
#[cfg(all(test, unix))]
|
|
mod tests {
|
|
use super::*;
|
|
use serde_json::{json, Value};
|
|
use std::{fs, os::unix::fs::PermissionsExt, path::Path};
|
|
|
|
const ETAG: &str = "\"9b2cf535f27731c974343645a3985328\"";
|
|
const WHEN: &str = "2026-01-02T03:04:05+00:00";
|
|
|
|
struct Fixture {
|
|
dir: tempfile::TempDir,
|
|
vault: Vault,
|
|
listing: Vec<Value>,
|
|
}
|
|
|
|
impl Fixture {
|
|
fn new() -> Self {
|
|
let dir = tempfile::tempdir().unwrap();
|
|
let vault = Vault::init(dir.path().join("vault"), "synthetic-passphrase").unwrap();
|
|
let fake = dir.path().join("fake");
|
|
fs::create_dir_all(fake.join("obj")).unwrap();
|
|
fs::create_dir_all(fake.join("meta")).unwrap();
|
|
let script = format!(
|
|
r#"#!/bin/sh
|
|
D='{}'
|
|
op="$6"
|
|
echo "$op" >> "$D/calls"
|
|
case "$op" in
|
|
list-objects-v2)
|
|
[ -f "$D/list.fail" ] && exit 1
|
|
cat "$D/list.json" ;;
|
|
get-object)
|
|
for a in "$@"; do
|
|
last="$a"
|
|
case "$a" in --key=*) key="${{a#--key=}}" ;; esac
|
|
done
|
|
name=$(basename "$key")
|
|
[ -f "$D/get.fail.$name" ] && exit 1
|
|
cp "$D/obj/$name" "$last"
|
|
cat "$D/meta/$name.json" ;;
|
|
esac
|
|
"#,
|
|
fake.display()
|
|
);
|
|
let program = dir.path().join("aws");
|
|
fs::write(&program, script).unwrap();
|
|
fs::set_permissions(&program, fs::Permissions::from_mode(0o755)).unwrap();
|
|
let fixture = Self {
|
|
dir,
|
|
vault,
|
|
listing: vec![],
|
|
};
|
|
fixture.publish();
|
|
fixture
|
|
}
|
|
|
|
fn fake(&self) -> std::path::PathBuf {
|
|
self.dir.path().join("fake")
|
|
}
|
|
|
|
fn publish(&self) {
|
|
fs::write(
|
|
self.fake().join("list.json"),
|
|
json!({ "Contents": self.listing }).to_string(),
|
|
)
|
|
.unwrap();
|
|
}
|
|
|
|
/// Put an object in the listing and on the fake bucket, with matching download metadata.
|
|
fn add(&mut self, key: &str, body: &[u8]) {
|
|
self.add_listed(key, body, body.len() as u64, ETAG);
|
|
let name = key.rsplit('/').next().unwrap();
|
|
fs::write(self.fake().join("obj").join(name), body).unwrap();
|
|
self.meta(key, ETAG, body.len() as u64, WHEN);
|
|
}
|
|
|
|
/// Only the listing entry, for metadata the object itself would not match.
|
|
fn add_listed(&mut self, key: &str, _body: &[u8], size: u64, etag: &str) {
|
|
self.listing.push(json!({
|
|
"Key": key, "ETag": etag, "Size": size, "LastModified": WHEN
|
|
}));
|
|
self.publish();
|
|
}
|
|
|
|
fn meta(&self, key: &str, etag: &str, length: u64, modified: &str) {
|
|
let name = key.rsplit('/').next().unwrap();
|
|
fs::write(
|
|
self.fake().join("meta").join(format!("{name}.json")),
|
|
json!({"ETag": etag, "ContentLength": length, "LastModified": modified})
|
|
.to_string(),
|
|
)
|
|
.unwrap();
|
|
}
|
|
|
|
fn calls(&self) -> Vec<String> {
|
|
fs::read_to_string(self.fake().join("calls"))
|
|
.unwrap_or_default()
|
|
.lines()
|
|
.map(str::to_owned)
|
|
.collect()
|
|
}
|
|
|
|
fn args(&self) -> ImportArgs {
|
|
ImportArgs {
|
|
bucket: "legacy-bucket".into(),
|
|
prefix: "backups/shop/".into(),
|
|
endpoint: None,
|
|
orbit_id: Uuid::from_u128(7),
|
|
application: "shop".into(),
|
|
engine: Engine::Postgres,
|
|
history: None,
|
|
inventory_only: false,
|
|
program: self.dir.path().join("aws"),
|
|
}
|
|
}
|
|
|
|
fn run(&self, args: ImportArgs) -> Result<Report> {
|
|
reconcile(&self.vault, args)
|
|
}
|
|
|
|
fn snapshots(&self) -> usize {
|
|
self.vault.list_snapshots().unwrap().len()
|
|
}
|
|
|
|
fn receipts(&self) -> usize {
|
|
fs::read_dir(self.vault.root().join("keys/legacy-imports"))
|
|
.map(|entries| entries.count())
|
|
.unwrap_or(0)
|
|
}
|
|
}
|
|
|
|
fn gzip_header(rest: &[u8]) -> Vec<u8> {
|
|
[&[0x1f, 0x8b][..], rest].concat()
|
|
}
|
|
|
|
fn statuses(report: &Report) -> Vec<&'static str> {
|
|
report.objects.iter().map(|o| o.status).collect()
|
|
}
|
|
|
|
// ---- arguments are validated before anything is listed ----
|
|
|
|
#[test]
|
|
fn bad_arguments_are_refused_before_aws_is_run() {
|
|
let fx = Fixture::new();
|
|
type Tweak = fn(&mut ImportArgs);
|
|
let cases: [(&str, Tweak); 11] = [
|
|
("empty prefix", |a| a.prefix = String::new()),
|
|
("prefix without a trailing slash", |a| {
|
|
a.prefix = "backups/shop".into()
|
|
}),
|
|
("blank application", |a| a.application = " ".into()),
|
|
("long application", |a| a.application = "a".repeat(129)),
|
|
("control in application", |a| {
|
|
a.application = "sh\nop".into()
|
|
}),
|
|
("plain http endpoint", |a| {
|
|
a.endpoint = Some("http://s3.example.com".into())
|
|
}),
|
|
("http on another loopback port form", |a| {
|
|
a.endpoint = Some("http://localhost:9000".into())
|
|
}),
|
|
("credentials in the endpoint", |a| {
|
|
a.endpoint = Some("https://user:pw@s3.example.com".into())
|
|
}),
|
|
("query in the endpoint", |a| {
|
|
a.endpoint = Some("https://s3.example.com/?x=1".into())
|
|
}),
|
|
("fragment in the endpoint", |a| {
|
|
a.endpoint = Some("https://s3.example.com/#x".into())
|
|
}),
|
|
("newline in the endpoint", |a| {
|
|
a.endpoint = Some("https://s3.example.com/\nx".into())
|
|
}),
|
|
];
|
|
for (what, tweak) in cases {
|
|
let mut args = fx.args();
|
|
tweak(&mut args);
|
|
assert!(fx.run(args).is_err(), "{what} must be refused");
|
|
}
|
|
assert!(fx.calls().is_empty(), "aws was never run");
|
|
let mut ok = fx.args();
|
|
ok.endpoint = Some("http://127.0.0.1:9000".into());
|
|
assert!(fx.run(ok).is_ok(), "a local test endpoint is allowed");
|
|
let mut ok = fx.args();
|
|
ok.endpoint = Some("https://s3.example.com".into());
|
|
assert!(fx.run(ok).is_ok());
|
|
}
|
|
|
|
// ---- inventory ----
|
|
|
|
#[test]
|
|
fn inventory_counts_only_sql_archives_under_the_prefix_and_writes_nothing() {
|
|
let mut fx = Fixture::new();
|
|
fx.add("backups/shop/a.sql", b"select 1;");
|
|
fx.add("backups/shop/b.sql.gz", &gzip_header(b"zz"));
|
|
fx.add("backups/shop/readme.txt", b"not a dump");
|
|
fx.add("backups/shop/nested/c.sql", b"select 3;");
|
|
fx.add("backups/shop/d.sql.bak", b"select 4;");
|
|
fx.add("backups/other/e.sql", b"another application");
|
|
fx.add("backups/shopping/f.sql", b"prefix lookalike");
|
|
let mut args = fx.args();
|
|
args.inventory_only = true;
|
|
let report = fx.run(args).unwrap();
|
|
assert_eq!(report.count, 3, "a, b and nested/c");
|
|
assert_eq!(report.bytes, 9 + 4 + 9);
|
|
assert_eq!(statuses(&report), ["inventoried"; 3]);
|
|
assert!(report.history_snapshot_id.is_none());
|
|
assert_eq!(fx.snapshots(), 0);
|
|
assert_eq!(fx.receipts(), 0);
|
|
assert_eq!(fx.calls(), ["list-objects-v2"], "no object was downloaded");
|
|
}
|
|
|
|
#[test]
|
|
fn inventory_only_ignores_a_history_export() {
|
|
let fx = Fixture::new();
|
|
let history = fx.dir.path().join("history.sqlite");
|
|
fs::write(&history, b"SQLite format 3\0 rows").unwrap();
|
|
let mut args = fx.args();
|
|
args.inventory_only = true;
|
|
args.history = Some(history);
|
|
let report = fx.run(args).unwrap();
|
|
assert!(report.history_snapshot_id.is_none());
|
|
assert_eq!(fx.snapshots(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn an_empty_or_missing_listing_is_a_clean_zero() {
|
|
let fx = Fixture::new();
|
|
let report = fx.run(fx.args()).unwrap();
|
|
assert_eq!((report.count, report.bytes), (0, 0));
|
|
fs::write(fx.fake().join("list.json"), "{}").unwrap();
|
|
assert_eq!(fx.run(fx.args()).unwrap().count, 0);
|
|
}
|
|
|
|
#[test]
|
|
fn listing_failures_stop_the_run() {
|
|
let fx = Fixture::new();
|
|
fs::write(fx.fake().join("list.fail"), "").unwrap();
|
|
let err = fx.run(fx.args()).err().unwrap();
|
|
assert!(format!("{err:#}").contains("could not list"), "{err:#}");
|
|
fs::remove_file(fx.fake().join("list.fail")).unwrap();
|
|
for broken in [
|
|
"",
|
|
"not json",
|
|
r#"{"Contents":[{"Key":"x"}]}"#,
|
|
r#"{"Contents":"x"}"#,
|
|
] {
|
|
fs::write(fx.fake().join("list.json"), broken).unwrap();
|
|
assert!(fx.run(fx.args()).is_err(), "listing {broken:?}");
|
|
}
|
|
let missing = ImportArgs {
|
|
program: fx.dir.path().join("no-such-aws"),
|
|
..fx.args()
|
|
};
|
|
assert!(fx.run(missing).is_err(), "no aws binary is an error");
|
|
assert_eq!(fx.snapshots(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn untrustworthy_inventory_metadata_is_refused() {
|
|
for (size, etag) in [(0, ETAG), (5, ""), (5, "*")] {
|
|
let mut fx = Fixture::new();
|
|
fx.add_listed("backups/shop/a.sql", b"", size, etag);
|
|
let err = fx.run(fx.args()).err().unwrap();
|
|
assert!(
|
|
format!("{err:#}").contains("invalid legacy archive metadata"),
|
|
"size {size} etag {etag:?}: {err:#}"
|
|
);
|
|
assert_eq!(fx.snapshots(), 0);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_inventory_whose_sizes_overflow_is_refused() {
|
|
let mut fx = Fixture::new();
|
|
fx.add_listed("backups/shop/a.sql", b"", u64::MAX, ETAG);
|
|
fx.add_listed("backups/shop/b.sql", b"", 2, "\"other\"");
|
|
let mut args = fx.args();
|
|
args.inventory_only = true;
|
|
let err = fx.run(args).err().unwrap();
|
|
assert!(format!("{err:#}").contains("overflow"), "{err:#}");
|
|
}
|
|
|
|
// ---- import ----
|
|
|
|
#[test]
|
|
fn importing_stores_each_archive_once_and_a_rerun_changes_nothing() {
|
|
let mut fx = Fixture::new();
|
|
fx.add("backups/shop/a.sql", b"create table a();");
|
|
fx.add("backups/shop/b.sql.gz", &gzip_header(b"compressed"));
|
|
let first = fx.run(fx.args()).unwrap();
|
|
assert_eq!(statuses(&first), ["imported", "imported"]);
|
|
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
|
|
let stored = fx
|
|
.vault
|
|
.get_snapshot(first.objects[0].snapshot_id)
|
|
.unwrap()
|
|
.expect("stored under the reported id");
|
|
assert_eq!(stored.manifest.orbit_id, Uuid::from_u128(7));
|
|
assert_eq!(stored.manifest.orbit_name, "shop");
|
|
assert_eq!(stored.manifest.provider, "postgres");
|
|
assert_eq!(stored.manifest.labels, ["legacy-import"]);
|
|
assert_eq!(stored.manifest.restore_hints["format"], "plain");
|
|
assert_eq!(stored.manifest.restore_hints["legacy"]["etag"], ETAG);
|
|
let gz = fx
|
|
.vault
|
|
.get_snapshot(first.objects[1].snapshot_id)
|
|
.unwrap()
|
|
.unwrap();
|
|
assert_eq!(gz.manifest.restore_hints["format"], "sql_gzip");
|
|
assert_eq!(
|
|
stored.taken_at,
|
|
"2026-01-02T03:04:05Z".parse::<DateTime<Utc>>().unwrap(),
|
|
"the snapshot keeps the original time, not the import time"
|
|
);
|
|
let calls_before = fx.calls().len();
|
|
let second = fx.run(fx.args()).unwrap();
|
|
assert_eq!(statuses(&second), ["already_imported", "already_imported"]);
|
|
assert_eq!(
|
|
fx.calls().len(),
|
|
calls_before + 1,
|
|
"the rerun listed but downloaded nothing"
|
|
);
|
|
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
|
|
assert_eq!(
|
|
first.objects[0].snapshot_id, second.objects[0].snapshot_id,
|
|
"ids are derived, so a rerun finds its own work"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn the_engine_orbit_and_endpoint_decide_the_mysql_manifest_and_the_snapshot_id() {
|
|
let mut fx = Fixture::new();
|
|
fx.add("backups/shop/a.sql", b"create table a();");
|
|
let mut mysql = fx.args();
|
|
mysql.engine = Engine::Mysql;
|
|
let first = fx.run(mysql).unwrap();
|
|
let stored = fx
|
|
.vault
|
|
.get_snapshot(first.objects[0].snapshot_id)
|
|
.unwrap()
|
|
.unwrap();
|
|
assert_eq!(stored.manifest.provider, "mysql");
|
|
// another orbit is a different import of the same bytes, not a duplicate
|
|
let mut other = fx.args();
|
|
other.orbit_id = Uuid::from_u128(8);
|
|
let second = fx.run(other).unwrap();
|
|
assert_ne!(first.objects[0].snapshot_id, second.objects[0].snapshot_id);
|
|
assert_eq!(statuses(&second), ["imported"]);
|
|
// so is another endpoint
|
|
let mut elsewhere = fx.args();
|
|
elsewhere.endpoint = Some("https://s3.example.com".into());
|
|
let third = fx.run(elsewhere).unwrap();
|
|
assert_ne!(first.objects[0].snapshot_id, third.objects[0].snapshot_id);
|
|
assert_eq!(fx.snapshots(), 3);
|
|
}
|
|
|
|
#[test]
|
|
fn an_object_that_changed_since_the_inventory_is_not_imported() {
|
|
for (what, etag, length, modified) in [
|
|
("etag", "\"changed\"", 17, WHEN),
|
|
("length", ETAG, 18, WHEN),
|
|
("time", ETAG, 17, "2026-01-02T03:04:06+00:00"),
|
|
] {
|
|
let mut fx = Fixture::new();
|
|
fx.add("backups/shop/a.sql", b"create table a();");
|
|
fx.meta("backups/shop/a.sql", etag, length, modified);
|
|
let err = fx.run(fx.args()).err().unwrap();
|
|
assert!(
|
|
format!("{err:#}").contains("changed since inventory"),
|
|
"{what}: {err:#}"
|
|
);
|
|
assert_eq!((fx.snapshots(), fx.receipts()), (0, 0), "{what}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_downloaded_file_of_the_wrong_size_is_not_imported() {
|
|
let mut fx = Fixture::new();
|
|
fx.add("backups/shop/a.sql", b"create table a();");
|
|
// the metadata agrees with the listing but fewer bytes arrived
|
|
fs::write(fx.fake().join("obj/a.sql"), b"create").unwrap();
|
|
let err = fx.run(fx.args()).err().unwrap();
|
|
assert!(format!("{err:#}").contains("changed since inventory"));
|
|
assert_eq!(fx.snapshots(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn a_gzip_named_archive_must_start_with_the_gzip_signature() {
|
|
let mut fx = Fixture::new();
|
|
fx.add("backups/shop/b.sql.gz", b"plainly not gzip");
|
|
let err = fx.run(fx.args()).err().unwrap();
|
|
assert!(format!("{err:#}").contains("gzip header"), "{err:#}");
|
|
assert_eq!((fx.snapshots(), fx.receipts()), (0, 0));
|
|
// a one-byte file cannot even hold the signature
|
|
let mut tiny = Fixture::new();
|
|
tiny.add("backups/shop/t.sql.gz", &[0x1f]);
|
|
assert!(tiny.run(tiny.args()).is_err());
|
|
assert_eq!(tiny.snapshots(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn a_plain_sql_archive_is_not_inspected_for_a_signature() {
|
|
let mut fx = Fixture::new();
|
|
fx.add("backups/shop/a.sql", &gzip_header(b"gz bytes in a .sql"));
|
|
let report = fx.run(fx.args()).unwrap();
|
|
assert_eq!(statuses(&report), ["imported"]);
|
|
}
|
|
|
|
#[test]
|
|
fn a_failed_download_stops_the_run_and_a_retry_resumes_where_it_left_off() {
|
|
let mut fx = Fixture::new();
|
|
fx.add("backups/shop/a.sql", b"create table a();");
|
|
fx.add("backups/shop/b.sql", b"create table b();");
|
|
fs::write(fx.fake().join("get.fail.b.sql"), "").unwrap();
|
|
let err = fx.run(fx.args()).err().unwrap();
|
|
assert!(format!("{err:#}").contains("download failed"), "{err:#}");
|
|
assert_eq!((fx.snapshots(), fx.receipts()), (1, 1), "a was kept");
|
|
fs::remove_file(fx.fake().join("get.fail.b.sql")).unwrap();
|
|
let retry = fx.run(fx.args()).unwrap();
|
|
assert_eq!(statuses(&retry), ["already_imported", "imported"]);
|
|
assert_eq!((fx.snapshots(), fx.receipts()), (2, 2));
|
|
}
|
|
|
|
#[test]
|
|
fn a_receipt_keeps_an_archive_from_returning_after_its_snapshot_is_forgotten() {
|
|
let mut fx = Fixture::new();
|
|
fx.add("backups/shop/a.sql", b"create table a();");
|
|
let first = fx.run(fx.args()).unwrap();
|
|
let id = first.objects[0].snapshot_id;
|
|
assert!(fx.vault.legacy_import_exists(id).unwrap());
|
|
fx.vault.forget(&[id]).unwrap();
|
|
assert_eq!(fx.snapshots(), 0);
|
|
let again = fx.run(fx.args()).unwrap();
|
|
assert_eq!(statuses(&again), ["already_imported"]);
|
|
assert_eq!(fx.snapshots(), 0, "retention's decision is not undone");
|
|
}
|
|
|
|
// ---- the operator-history export ----
|
|
|
|
#[test]
|
|
fn a_history_export_must_be_a_sqlite_file() {
|
|
let fx = Fixture::new();
|
|
let write = |name: &str, bytes: &[u8]| {
|
|
let path = fx.dir.path().join(name);
|
|
fs::write(&path, bytes).unwrap();
|
|
path
|
|
};
|
|
for (name, bytes) in [
|
|
("empty", &b""[..]),
|
|
("short", b"SQLite"),
|
|
("text", b"just a text file, long enough to read"),
|
|
("near", b"SQLite format 3 not-nul-terminated"),
|
|
("wal", b"SQLite format 4\0 later version"),
|
|
] {
|
|
let mut args = fx.args();
|
|
args.history = Some(write(name, bytes));
|
|
assert!(fx.run(args).is_err(), "{name} must be refused");
|
|
}
|
|
let mut missing = fx.args();
|
|
missing.history = Some(Path::new("/definitely/not/here.sqlite").into());
|
|
assert!(fx.run(missing).is_err());
|
|
assert_eq!(fx.snapshots(), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn a_history_export_is_stored_once_and_identified_by_its_content() {
|
|
let fx = Fixture::new();
|
|
let path = fx.dir.path().join("history.sqlite");
|
|
fs::write(&path, b"SQLite format 3\0 first export").unwrap();
|
|
let mut args = fx.args();
|
|
args.history = Some(path.clone());
|
|
let first = fx.run(args.clone()).unwrap();
|
|
let id = first.history_snapshot_id.expect("history imported");
|
|
assert_eq!(fx.snapshots(), 1);
|
|
let stored = fx.vault.get_snapshot(id).unwrap().unwrap();
|
|
assert_eq!(stored.manifest.provider, "legacy-history");
|
|
assert_eq!(stored.manifest.orbit_id, Uuid::nil());
|
|
assert_eq!(stored.manifest.restore_hints["format"], "sqlite");
|
|
// same bytes: same snapshot, nothing new stored
|
|
let second = fx.run(args.clone()).unwrap();
|
|
assert_eq!(second.history_snapshot_id, Some(id));
|
|
assert_eq!(fx.snapshots(), 1);
|
|
// different bytes: a different snapshot
|
|
fs::write(&path, b"SQLite format 3\0 second export").unwrap();
|
|
let third = fx.run(args).unwrap();
|
|
assert_ne!(third.history_snapshot_id, Some(id));
|
|
assert_eq!(fx.snapshots(), 2);
|
|
}
|
|
}
|