1use std::collections::BTreeSet;
2use std::fs;
3use std::io;
4use std::path::{Component, Path, PathBuf};
5
6use serde_json::{json, Value};
7
8use crate::atomic::write_atomic;
9use crate::catalog::{parse_catalog, read_catalog_text, Catalog, ReadCatalogError};
10use crate::crypto::{CipherOptions, Sealer};
11use crate::errors::{HaysonCipherError, HaysonSchemaError};
12use crate::lock::DirLock;
13use crate::storage::{partition_names_in, LOG_SUFFIX};
14
15use super::database::{Database, DatabaseError, HeldLock, LockMode};
16use super::layout::{Layout, LayoutOptions};
17use super::verify::{verify, VerifyOptions};
18
19pub const BACKUP_MANIFEST: &str = "hayson-backup.json";
21const BACKUP_FORMAT: u64 = 1;
22const RESTORE_OLD: &str = ".restore-old";
23const RESTORE_NEW: &str = ".restore-new";
24
25#[derive(Debug, Clone)]
26pub struct BackupOptions {
27 pub lock: LockMode,
31 pub indexes: bool,
34 pub exclude_tables: Vec<String>,
38 pub encryption: Option<CipherOptions>,
41}
42
43impl Default for BackupOptions {
44 fn default() -> Self {
45 BackupOptions {
46 lock: LockMode::default(),
47 indexes: false,
48 exclude_tables: Vec::new(),
49 encryption: None,
50 }
51 }
52}
53
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct BackupResult {
56 pub dest: PathBuf,
57 pub files: usize,
58 pub bytes: u64,
59}
60
61#[derive(Debug, Clone, Default)]
62pub struct RestoreOptions {
63 pub lock: LockMode,
65 pub max_image_bytes: Option<u64>,
67 pub encryption: Option<CipherOptions>,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct RestoreResult {
73 pub dir: PathBuf,
74 pub files: usize,
75 pub bytes: u64,
76 pub replaced: usize,
78}
79
80pub(super) fn sealer_of(encryption: Option<&CipherOptions>) -> Result<Option<std::sync::Arc<Sealer>>, DatabaseError> {
82 Ok(encryption.map(Sealer::new).transpose()?.map(std::sync::Arc::new))
83}
84
85pub(super) fn refuse(message: String) -> DatabaseError {
86 DatabaseError::Schema(HaysonSchemaError(message))
87}
88
89pub(super) fn read_catalog_of(layout: &Layout, sealer: Option<&Sealer>) -> Result<Catalog, DatabaseError> {
90 let path = layout.metadata_path();
91 let raw = match read_catalog_text(path, sealer) {
92 Ok(Some(raw)) => raw,
93 Ok(None) => {
94 return Err(refuse(format!(
95 "\"{}\" does not exist — there is no database to back up",
96 path.display()
97 )))
98 }
99 Err(ReadCatalogError::Io(error)) => return Err(DatabaseError::Io(error)),
100 Err(
101 ReadCatalogError::Cipher(error)
102 | ReadCatalogError::Encrypted(error)
103 | ReadCatalogError::NotEncrypted(error),
104 ) => return Err(DatabaseError::Cipher(Box::new(error))),
105 };
106 let value: Value = serde_json::from_str(&raw)
107 .map_err(|error| DatabaseError::Catalog(format!("\"{}\" is not valid JSON: {error}", path.display())))?;
108 Ok(parse_catalog(&value)?)
109}
110
111fn relative_safely(root: &Path, path: &Path) -> Result<PathBuf, DatabaseError> {
112 let relative = path
113 .strip_prefix(root)
114 .map_err(|_| refuse(format!("\"{}\" is outside the database directory", path.display())))?;
115 check_relative(relative)?;
116 Ok(relative.to_path_buf())
117}
118
119pub(super) fn check_relative(path: &Path) -> Result<(), DatabaseError> {
121 let sane = path.components().all(|part| matches!(part, Component::Normal(_)));
122 if sane && path.components().next().is_some() {
123 Ok(())
124 } else {
125 Err(refuse(format!(
126 "\"{}\" is not a path inside the database directory",
127 path.display()
128 )))
129 }
130}
131
132fn files_in(dir: &Path) -> Result<Vec<PathBuf>, DatabaseError> {
133 let mut found = Vec::new();
134 let Ok(entries) = fs::read_dir(dir) else {
135 return Ok(found);
136 };
137 for entry in entries {
138 let entry = entry?;
139 let kind = entry.file_type()?;
140 if kind.is_symlink() {
141 return Err(refuse(format!(
142 "\"{}\" is a symbolic link — refusing to follow it",
143 entry.path().display()
144 )));
145 }
146 if kind.is_file() {
147 found.push(entry.path());
148 }
149 }
150 found.sort();
151 Ok(found)
152}
153
154pub(super) fn owned_files(
159 root: &Path,
160 layout: &Layout,
161 catalog: &Catalog,
162 indexes: bool,
163 exclude: &[String],
164) -> Result<Vec<PathBuf>, DatabaseError> {
165 if let Some(unknown) = exclude.iter().find(|name| !catalog.tables.contains_key(*name)) {
166 return Err(refuse(format!(
167 "cannot leave out table \"{unknown}\" — the database declares no such table"
168 )));
169 }
170 let mut owned: BTreeSet<PathBuf> = BTreeSet::new();
171 let mut add = |path: &Path| -> Result<(), DatabaseError> {
172 owned.insert(relative_safely(root, path)?);
173 Ok(())
174 };
175 add(layout.metadata_path())?;
176 for (name, entry) in &catalog.tables {
177 if exclude.contains(name) {
178 continue;
179 }
180 let flat = layout.log_path(name);
181 match fs::symlink_metadata(&flat) {
182 Ok(meta) if meta.file_type().is_symlink() => {
183 return Err(refuse(format!(
184 "\"{}\" is a symbolic link — refusing to follow it",
185 flat.display()
186 )))
187 }
188 Ok(meta) if meta.is_file() => add(&flat)?,
189 _ => {}
190 }
191 let partitions = layout.tables().join(name);
192 for part in partition_names_in(&partitions) {
193 add(&partitions.join(format!("{part}{LOG_SUFFIX}")))?;
194 }
195 if indexes && layout.index_path(name).is_file() {
196 add(&layout.index_path(name))?;
197 }
198 let image_dir = entry
199 .options
200 .as_ref()
201 .and_then(|options| options.image_dir.clone())
202 .or_else(|| catalog.defaults.as_ref().and_then(|d| d.image_dir.clone()))
203 .map(|dir| root.join(dir))
204 .unwrap_or_else(|| layout.tables().join(format!("{name}.images")));
205 for file in files_in(&image_dir)? {
206 add(&file)?;
207 }
208 }
209 Ok(owned.into_iter().collect())
210}
211
212pub(super) fn emptied_logs(root: &Path, layout: &Layout, catalog: &Catalog, exclude: &[String]) -> Vec<PathBuf> {
216 exclude
217 .iter()
218 .filter(|name| {
219 catalog
220 .tables
221 .get(*name)
222 .is_some_and(|entry| entry.partition_by.is_none())
223 })
224 .filter_map(|name| relative_safely(root, &layout.log_path(name)).ok())
225 .collect()
226}
227
228pub(super) fn hold(root: &Path, layout: &Layout, lock: &LockMode) -> Result<HeldLock, DatabaseError> {
229 let LockMode::Enabled(options) = lock else {
230 return Ok(HeldLock(None));
231 };
232 if root.is_dir() {
233 fs::create_dir_all(layout.runtime())?;
234 }
235 Ok(HeldLock(Some(DirLock::acquire_as(
236 layout.lock_path(),
237 options.clone(),
238 root.to_path_buf(),
239 )?)))
240}
241
242fn copy_synced(from: &Path, to: &Path) -> io::Result<u64> {
243 if let Some(parent) = to.parent() {
244 fs::create_dir_all(parent)?;
245 }
246 let bytes = fs::copy(from, to)?;
247 fs::File::open(to)?.sync_all()?;
248 Ok(bytes)
249}
250
251pub fn backup_database(dir: &Path, dest: &Path, options: &BackupOptions) -> Result<BackupResult, DatabaseError> {
262 let sealer = sealer_of(options.encryption.as_ref())?;
263 let layout = Database::resolve_layout_sealed(dir, &LayoutOptions::default(), sealer.as_deref())?;
264 let catalog = read_catalog_of(&layout, sealer.as_deref())?;
265 if dest.exists()
266 && fs::read_dir(dest)
267 .map(|mut entries| entries.next().is_some())
268 .unwrap_or(true)
269 {
270 return Err(refuse(format!(
271 "\"{}\" already exists and is not an empty directory",
272 dest.display()
273 )));
274 }
275 let partial = sibling(dest, ".partial");
276 if partial.exists() {
277 fs::remove_dir_all(&partial)?;
278 }
279
280 let held = hold(dir, &layout, &options.lock)?;
281 let outcome = copy_database(dir, &layout, &catalog, &partial, options);
282 drop(held);
283 match outcome {
284 Ok(result) => {
285 if dest.exists() {
286 fs::remove_dir(dest)?;
287 }
288 fs::rename(&partial, dest)?;
289 Ok(BackupResult {
290 dest: dest.to_path_buf(),
291 ..result
292 })
293 }
294 Err(error) => {
295 let _ = fs::remove_dir_all(&partial);
296 Err(error)
297 }
298 }
299}
300
301pub(super) fn sibling(path: &Path, suffix: &str) -> PathBuf {
302 let mut name = path.file_name().map(|n| n.to_os_string()).unwrap_or_default();
303 name.push(suffix);
304 path.with_file_name(name)
305}
306
307fn copy_database(
308 root: &Path,
309 layout: &Layout,
310 catalog: &Catalog,
311 partial: &Path,
312 options: &BackupOptions,
313) -> Result<BackupResult, DatabaseError> {
314 if layout.journal_path().exists() {
315 return Err(refuse(format!(
316 "\"{}\" holds an unfinished unit of work — open the database for writing once so it is finished, then back it up",
317 layout.journal_path().display()
318 )));
319 }
320 let mut files = owned_files(root, layout, catalog, options.indexes, &options.exclude_tables)?;
321 let emptied = emptied_logs(root, layout, catalog, &options.exclude_tables);
322 files.extend(emptied.iter().cloned());
323 files.sort();
324 fs::create_dir_all(partial)?;
325 let mut listed = Vec::new();
326 let mut total = 0u64;
327 for relative in &files {
328 let bytes = if emptied.contains(relative) {
329 let target = partial.join(relative);
330 if let Some(parent) = target.parent() {
331 fs::create_dir_all(parent)?;
332 }
333 fs::File::create(&target)?.sync_all()?;
334 0
335 } else {
336 copy_synced(&root.join(relative), &partial.join(relative))?
337 };
338 total += bytes;
339 listed.push(json!({ "path": relative.to_string_lossy().replace('\\', "/"), "bytes": bytes }));
340 }
341 let manifest = json!({
342 "format": BACKUP_FORMAT,
343 "createdAt": chrono::Utc::now().timestamp_millis(),
344 "engine": env!("CARGO_PKG_VERSION"),
345 "metadataFile": layout.metadata_file(),
346 "files": listed,
347 });
348 let mut text = serde_json::to_string_pretty(&manifest).map_err(|e| DatabaseError::Catalog(e.to_string()))?;
349 text.push('\n');
350 write_atomic(&partial.join(BACKUP_MANIFEST), text.as_bytes(), None)?;
351 Ok(BackupResult {
352 dest: partial.to_path_buf(),
353 files: files.len(),
354 bytes: total,
355 })
356}
357
358#[derive(Clone)]
359pub(super) struct ManifestEntry {
360 pub(super) relative: PathBuf,
361 pub(super) bytes: u64,
362}
363
364fn read_manifest(backup: &Path) -> Result<(String, Vec<ManifestEntry>), DatabaseError> {
365 let path = backup.join(BACKUP_MANIFEST);
366 let raw = fs::read_to_string(&path).map_err(|error| {
367 refuse(format!(
368 "\"{}\" is not a readable backup manifest: {error}",
369 path.display()
370 ))
371 })?;
372 parse_manifest(&raw, &path.display().to_string())
373}
374
375pub(super) fn parse_manifest(raw: &str, label: &str) -> Result<(String, Vec<ManifestEntry>), DatabaseError> {
376 let manifest: Value =
377 serde_json::from_str(raw).map_err(|error| refuse(format!("\"{label}\" is not valid JSON: {error}")))?;
378 if manifest.get("format").and_then(Value::as_u64) != Some(BACKUP_FORMAT) {
379 return Err(refuse(format!("\"{label}\" is not a backup format this engine reads")));
380 }
381 let metadata_file = manifest
382 .get("metadataFile")
383 .and_then(Value::as_str)
384 .ok_or_else(|| refuse("backup manifest names no \"metadataFile\"".to_string()))?
385 .to_string();
386 let listed = manifest
387 .get("files")
388 .and_then(Value::as_array)
389 .ok_or_else(|| refuse("backup manifest lists no \"files\"".to_string()))?;
390 let mut entries = Vec::new();
391 for item in listed {
392 let relative = PathBuf::from(
393 item.get("path")
394 .and_then(Value::as_str)
395 .ok_or_else(|| refuse("a backup manifest entry has no \"path\"".to_string()))?,
396 );
397 check_relative(&relative)?;
398 let bytes = item
399 .get("bytes")
400 .and_then(Value::as_u64)
401 .ok_or_else(|| refuse(format!("manifest entry \"{}\" has no \"bytes\"", relative.display())))?;
402 entries.push(ManifestEntry { relative, bytes });
403 }
404 Ok((metadata_file, entries))
405}
406
407pub fn restore_database(backup: &Path, dir: &Path, options: &RestoreOptions) -> Result<RestoreResult, DatabaseError> {
419 let (metadata_file, entries) = read_manifest(backup)?;
420 for entry in &entries {
421 let path = backup.join(&entry.relative);
422 let meta = fs::symlink_metadata(&path).map_err(|error| {
423 refuse(format!(
424 "backup file \"{}\" is missing: {error}",
425 entry.relative.display()
426 ))
427 })?;
428 if !meta.is_file() || meta.len() != entry.bytes {
429 return Err(refuse(format!(
430 "backup file \"{}\" does not match its manifest entry ({} bytes expected)",
431 entry.relative.display(),
432 entry.bytes
433 )));
434 }
435 }
436 let part = RestorePart {
437 sub: PathBuf::new(),
438 encryption: options.encryption.clone(),
439 metadata_file,
440 entries: entries.clone(),
441 };
442 restore_staged(dir, &[part], &options.lock, options.max_image_bytes, |staged| {
443 let mut total = 0u64;
444 for entry in &entries {
445 total += copy_synced(&backup.join(&entry.relative), &staged.join(&entry.relative))?;
446 }
447 Ok(total)
448 })
449}
450
451pub(super) struct RestorePart {
455 pub(super) sub: PathBuf,
456 pub(super) encryption: Option<CipherOptions>,
458 pub(super) metadata_file: String,
459 pub(super) entries: Vec<ManifestEntry>,
460}
461
462pub(super) fn restore_staged(
467 dir: &Path,
468 parts: &[RestorePart],
469 lock: &LockMode,
470 max_image_bytes: Option<u64>,
471 stage: impl FnOnce(&Path) -> Result<u64, DatabaseError>,
472) -> Result<RestoreResult, DatabaseError> {
473 let old = dir.join(RESTORE_OLD);
474 if old.exists() {
475 return Err(refuse(format!(
476 "\"{}\" exists — an earlier restore was interrupted and it may hold the only good copy of the database; move its files back (or delete it) before restoring again",
477 old.display()
478 )));
479 }
480 let mut created: Vec<PathBuf> = Vec::new();
481 let mut made_roots: Vec<bool> = Vec::new();
482 let mut layouts = Vec::new();
483 let mut held = Vec::new();
484 for part in parts {
485 let root = dir.join(&part.sub);
486 let first_new = root.ancestors().take_while(|path| !path.exists()).last();
488 made_roots.push(first_new.is_some());
489 if let Some(first_new) = first_new {
490 created.push(first_new.to_path_buf());
491 }
492 fs::create_dir_all(&root)?;
493 let sealer = sealer_of(part.encryption.as_ref())?;
494 let layout = Database::resolve_layout_sealed(
495 &root,
496 &LayoutOptions {
497 metadata_file: Some(part.metadata_file.clone()),
498 ..LayoutOptions::default()
499 },
500 sealer.as_deref(),
501 )?;
502 held.push(hold(&root, &layout, lock)?);
503 layouts.push(layout);
504 }
505 let staged = dir.join(RESTORE_NEW);
506 let outcome = install(dir, &layouts, parts, &staged, &old, max_image_bytes, stage);
507 let _ = fs::remove_dir_all(&staged);
508 drop(held);
509 if outcome.is_err() {
510 for (layout, made) in layouts.iter().zip(&made_roots) {
512 if *made {
513 let _ = fs::remove_dir_all(layout.runtime());
514 }
515 }
516 for path in created.iter().rev() {
517 let _ = fs::remove_dir(path);
518 let mut parent = path.parent();
519 while let Some(up) = parent {
520 if up == dir || fs::remove_dir(up).is_err() {
521 break;
522 }
523 parent = up.parent();
524 }
525 }
526 if dir.exists() && created.iter().any(|path| path == dir) {
527 let _ = fs::remove_dir(dir);
528 }
529 }
530 outcome
531}
532
533fn install(
534 root: &Path,
535 layouts: &[Layout],
536 parts: &[RestorePart],
537 staged: &Path,
538 old: &Path,
539 max_image_bytes: Option<u64>,
540 stage: impl FnOnce(&Path) -> Result<u64, DatabaseError>,
541) -> Result<RestoreResult, DatabaseError> {
542 if staged.exists() {
543 fs::remove_dir_all(staged)?;
544 }
545 let total = stage(staged)?;
546 for part in parts {
547 let report = verify(
548 &staged.join(&part.sub),
549 &VerifyOptions {
550 relations: false,
551 max_image_bytes,
552 encryption: part.encryption.clone(),
553 ..VerifyOptions::default()
554 },
555 );
556 let which = if part.sub.as_os_str().is_empty() {
557 String::new()
558 } else {
559 format!(" (database \"{}\")", part.sub.display())
560 };
561 if let Some(problem) = report.problems.iter().find(|p| {
562 matches!(
563 p.code,
564 "catalog-encrypted" | "catalog-key-rejected" | "catalog-not-encrypted"
565 )
566 }) {
567 return Err(DatabaseError::Cipher(Box::new(HaysonCipherError::new(
568 "",
569 crate::crypto::STORAGE_FIELD,
570 format!("{which}: {}", problem.message),
571 ))));
572 }
573 if let Some(problem) = report.problems.iter().find(|p| p.code == "image-oversize") {
574 return Err(refuse(format!(
575 "the backup holds an image over the size limit{which} ({}) — nothing was changed",
576 problem.message
577 )));
578 }
579 if let Some(problem) = report
580 .problems
581 .iter()
582 .find(|p| p.severity == super::verify::Severity::Error)
583 {
584 return Err(refuse(format!(
585 "the backup does not verify{which} ({}: {}) — nothing was changed",
586 problem.code, problem.message
587 )));
588 }
589 }
590
591 let entries: Vec<&ManifestEntry> = parts.iter().flat_map(|part| part.entries.iter()).collect();
594 let mut replaced: BTreeSet<PathBuf> = entries.iter().map(|e| e.relative.clone()).collect();
595 for (part, layout) in parts.iter().zip(layouts) {
596 let part_root = root.join(&part.sub);
597 let sealer = sealer_of(part.encryption.as_ref()).ok().flatten();
598 if let Ok(catalog) = read_catalog_of(layout, sealer.as_deref()) {
599 if let Ok(current) = owned_files(&part_root, layout, &catalog, true, &[]) {
600 replaced.extend(current.into_iter().map(|relative| part.sub.join(relative)));
601 }
602 }
603 }
604 replaced.retain(|relative| root.join(relative).is_file());
605
606 fs::create_dir_all(old)?;
607 let mut moved_out: Vec<PathBuf> = Vec::new();
608 let mut moved_in: Vec<PathBuf> = Vec::new();
609 let swap = (|| -> io::Result<()> {
610 for relative in &replaced {
611 move_file(&root.join(relative), &old.join(relative))?;
612 moved_out.push(relative.clone());
613 }
614 for entry in &entries {
615 move_file(&staged.join(&entry.relative), &root.join(&entry.relative))?;
616 moved_in.push(entry.relative.clone());
617 }
618 Ok(())
619 })();
620 match swap {
621 Ok(()) => {
622 fs::remove_dir_all(old)?;
623 Ok(RestoreResult {
624 dir: root.to_path_buf(),
625 files: entries.len(),
626 bytes: total,
627 replaced: replaced.len(),
628 })
629 }
630 Err(error) => {
631 let rollback = (|| -> io::Result<()> {
632 for relative in &moved_in {
633 fs::remove_file(root.join(relative))?;
634 }
635 for relative in &moved_out {
636 move_file(&old.join(relative), &root.join(relative))?;
637 }
638 Ok(())
639 })();
640 match rollback {
641 Ok(()) => {
642 let _ = fs::remove_dir_all(old);
643 Err(DatabaseError::Io(error))
644 }
645 Err(rollback_error) => Err(refuse(format!(
646 "restore failed ({error}) and putting the previous files back failed too ({rollback_error}) — the previous database is in \"{}\"",
647 old.display()
648 ))),
649 }
650 }
651 }
652}
653
654fn move_file(from: &Path, to: &Path) -> io::Result<()> {
655 if let Some(parent) = to.parent() {
656 fs::create_dir_all(parent)?;
657 }
658 fs::rename(from, to)
659}