Skip to main content

hawdb_storage/
backup.rs

1// Copyright 2026 Nowledge
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::artifact_files::{
16    parse_append_manifest_generation_file, parse_append_segment_generation_file,
17    parse_canonical_adjacency_descriptor_generation_file, parse_canonical_manifest_generation_file,
18    parse_canonical_segment_descriptor_generation_file, parse_generation_file,
19    parse_property_projection_descriptor_generation_file,
20    parse_property_projection_manifest_generation_file,
21    parse_property_spill_descriptor_generation_file, parse_property_spill_manifest_generation_file,
22    parse_relational_index_artifact_generation_file,
23    parse_relational_index_manifest_generation_file, parse_relational_overflow_generation_file,
24    parse_relational_row_generation_file,
25};
26use crate::durability::durable_replace_file;
27use crate::file_io::{self as fs, File, OpenOptions};
28use hawdb_core::{HawDBError, Result};
29use hawdb_integrity::{checksum_u64, IntegrityHasher, Sha256Digest};
30use std::collections::BTreeSet;
31use std::io::{Read, Write};
32use std::path::Path;
33
34pub const BACKUP_MANIFEST_FILE: &str = "backup.hawdb";
35pub const BACKUP_HEADER_V1: &str = "HAWDB_BACKUP_V1";
36pub const STORAGE_MANIFEST_FILE: &str = "manifest.hawdb";
37pub const STABLE_ID_MAPPING_FILE: &str = "stable_ids.hawdb";
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct BackupFileEntry {
41    pub name: String,
42    pub encoded_len: u64,
43    pub encoded_checksum: u64,
44    pub sha256: Sha256Digest,
45}
46
47#[doc(hidden)]
48pub fn validate_new_backup_destination(root: &Path, destination: &Path) -> Result<()> {
49    if destination.exists() {
50        return Err(HawDBError::Storage(format!(
51            "backup destination already exists: {}",
52            destination.display()
53        )));
54    }
55    let file_name = destination.file_name().ok_or_else(|| {
56        HawDBError::Storage("backup destination must have a file name".to_string())
57    })?;
58    let parent = destination.parent().ok_or_else(|| {
59        HawDBError::Storage("backup destination must have a parent directory".to_string())
60    })?;
61    let canonical_parent = parent.canonicalize()?;
62    let destination = canonical_parent.join(file_name);
63    let canonical_root = root.canonicalize()?;
64    if destination.starts_with(&canonical_root) {
65        return Err(HawDBError::Storage(
66            "backup destination cannot be inside the database directory".to_string(),
67        ));
68    }
69    Ok(())
70}
71
72#[doc(hidden)]
73pub fn copy_backup_file(source: &Path, destination: &Path, name: &str) -> Result<BackupFileEntry> {
74    let (encoded_len, encoded_checksum, sha256) = copy_file_with_checksum(source, destination)?;
75    Ok(BackupFileEntry {
76        name: name.to_string(),
77        encoded_len,
78        encoded_checksum,
79        sha256,
80    })
81}
82
83#[doc(hidden)]
84pub fn copy_file_with_checksum(
85    source: &Path,
86    destination: &Path,
87) -> Result<(u64, u64, Sha256Digest)> {
88    let mut source = File::open(source)?;
89    let mut destination = OpenOptions::new()
90        .write(true)
91        .create_new(true)
92        .open(destination)?;
93    let mut integrity = IntegrityHasher::new();
94    let mut total = 0u64;
95    let mut buffer = vec![0u8; 1024 * 1024];
96    loop {
97        let read = source.read(&mut buffer)?;
98        if read == 0 {
99            break;
100        }
101        destination.write_all(&buffer[..read])?;
102        integrity.update(&buffer[..read]);
103        total = total
104            .checked_add(read as u64)
105            .ok_or_else(|| HawDBError::Storage("file byte count overflow".to_string()))?;
106    }
107    destination.sync_all()?;
108    let digest = integrity.finish();
109    Ok((total, digest.crc32c.as_u64(), digest.sha256))
110}
111
112#[doc(hidden)]
113pub fn file_checksum(path: &Path) -> Result<(u64, u64, Sha256Digest)> {
114    let mut file = File::open(path)?;
115    let mut integrity = IntegrityHasher::new();
116    let mut total = 0u64;
117    let mut buffer = vec![0u8; 1024 * 1024];
118    loop {
119        let read = file.read(&mut buffer)?;
120        if read == 0 {
121            break;
122        }
123        integrity.update(&buffer[..read]);
124        total = total
125            .checked_add(read as u64)
126            .ok_or_else(|| HawDBError::Storage("file byte count overflow".to_string()))?;
127    }
128    let digest = integrity.finish();
129    Ok((total, digest.crc32c.as_u64(), digest.sha256))
130}
131
132#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct BackupManifest {
134    pub generation: u64,
135    pub checkpoint_commit_epoch: u64,
136    pub files: Vec<BackupFileEntry>,
137    pub checksum: u64,
138}
139
140impl BackupManifest {
141    pub fn load(path: &Path) -> Result<Self> {
142        const MAX_BACKUP_MANIFEST_BYTES: u64 = 64 * 1024;
143
144        let metadata = fs::metadata(path)?;
145        if metadata.len() > MAX_BACKUP_MANIFEST_BYTES {
146            return Err(HawDBError::Storage(format!(
147                "backup manifest exceeds {MAX_BACKUP_MANIFEST_BYTES} bytes"
148            )));
149        }
150        let text = fs::read_to_string(path)?;
151        let (body, checksum) = split_backup_manifest_checksum(&text)?;
152        let actual = checksum_u64(body.as_bytes());
153        if checksum != actual {
154            return Err(HawDBError::Storage(format!(
155                "backup manifest checksum mismatch: expected {checksum}, got {actual}"
156            )));
157        }
158
159        let mut generation = None;
160        let mut checkpoint_commit_epoch = None;
161        let mut files = Vec::new();
162        let mut names = BTreeSet::new();
163        let mut saw_header = false;
164        for line in body.lines() {
165            if line == BACKUP_HEADER_V1 {
166                if saw_header {
167                    return Err(HawDBError::Storage(
168                        "backup manifest has duplicate headers".to_string(),
169                    ));
170                }
171                saw_header = true;
172                continue;
173            }
174            let fields = line.split('\t').collect::<Vec<_>>();
175            match fields.as_slice() {
176                ["version", "1"] => {}
177                ["generation", raw] => {
178                    if generation
179                        .replace(parse_u64(raw, "backup generation")?)
180                        .is_some()
181                    {
182                        return Err(HawDBError::Storage(
183                            "backup manifest has duplicate generation".to_string(),
184                        ));
185                    }
186                }
187                ["checkpoint_commit_epoch", raw] => {
188                    if checkpoint_commit_epoch
189                        .replace(parse_u64(raw, "backup checkpoint commit epoch")?)
190                        .is_some()
191                    {
192                        return Err(HawDBError::Storage(
193                            "backup manifest has duplicate checkpoint commit epoch".to_string(),
194                        ));
195                    }
196                }
197                ["file", encoded_name, encoded_len, encoded_checksum, sha256] => {
198                    let name = decode_string(encoded_name)?;
199                    validate_backup_file_name(&name)?;
200                    if !names.insert(name.clone()) {
201                        return Err(HawDBError::Storage(format!(
202                            "backup manifest has duplicate file: {name}"
203                        )));
204                    }
205                    files.push(BackupFileEntry {
206                        name,
207                        encoded_len: parse_u64(encoded_len, "backup file length")?,
208                        encoded_checksum: parse_u64(encoded_checksum, "backup file checksum")?,
209                        sha256: sha256.parse().map_err(|error| {
210                            HawDBError::or_stop(&error, || {
211                                HawDBError::Storage(format!(
212                                    "invalid backup file SHA-256 digest: {error}"
213                                ))
214                            })
215                        })?,
216                    });
217                }
218                [""] => {}
219                _ => {
220                    return Err(HawDBError::Storage(format!(
221                        "invalid backup manifest line: {line}"
222                    )));
223                }
224            }
225        }
226        if !saw_header {
227            return Err(HawDBError::Storage(
228                "backup manifest is missing its format header".to_string(),
229            ));
230        }
231        let generation = generation.ok_or_else(|| {
232            HawDBError::Storage("backup manifest is missing generation".to_string())
233        })?;
234        let checkpoint_commit_epoch = checkpoint_commit_epoch.ok_or_else(|| {
235            HawDBError::Storage("backup manifest is missing checkpoint commit epoch".to_string())
236        })?;
237        Ok(Self {
238            generation,
239            checkpoint_commit_epoch,
240            files,
241            checksum,
242        })
243    }
244
245    pub fn write(
246        path: &Path,
247        generation: u64,
248        checkpoint_commit_epoch: u64,
249        files: Vec<BackupFileEntry>,
250    ) -> Result<Self> {
251        let mut body = format!(
252            "{BACKUP_HEADER_V1}\nversion\t1\ngeneration\t{generation}\ncheckpoint_commit_epoch\t{checkpoint_commit_epoch}\n"
253        );
254        for file in &files {
255            body.push_str(&format!(
256                "file\t{}\t{}\t{}\t{}\n",
257                encode_string(&file.name),
258                file.encoded_len,
259                file.encoded_checksum,
260                file.sha256
261            ));
262        }
263        let checksum = checksum_u64(body.as_bytes());
264        let tmp_path = path.with_extension("hawdb.tmp");
265        {
266            let mut file = File::create(&tmp_path)?;
267            file.write_all(format!("{body}checksum\t{checksum}\n").as_bytes())?;
268            file.sync_all()?;
269        }
270        durable_replace_file(&tmp_path, path)?;
271        Ok(Self {
272            generation,
273            checkpoint_commit_epoch,
274            files,
275            checksum,
276        })
277    }
278}
279
280fn split_backup_manifest_checksum(text: &str) -> Result<(&str, u64)> {
281    let marker = "checksum\t";
282    let checksum_offset = text
283        .rfind(marker)
284        .ok_or_else(|| HawDBError::Storage("backup manifest is missing checksum".to_string()))?;
285    let body = &text[..checksum_offset];
286    let checksum_line = text[checksum_offset..].trim_end();
287    if checksum_line.contains('\n') {
288        return Err(HawDBError::Storage(
289            "backup manifest has data after checksum".to_string(),
290        ));
291    }
292    let checksum = parse_u64(
293        checksum_line.strip_prefix(marker).unwrap_or_default(),
294        "backup manifest checksum",
295    )?;
296    Ok((body, checksum))
297}
298
299pub fn validate_backup_file_name(name: &str) -> Result<()> {
300    let allowed = name == STORAGE_MANIFEST_FILE
301        || name == STABLE_ID_MAPPING_FILE
302        || parse_generation_file(name, "stable_ids.").is_some()
303        || parse_generation_file(name, "checkpoint.").is_some()
304        || parse_generation_file(name, "wal.").is_some()
305        || parse_generation_file(name, "relational.").is_some()
306        || parse_generation_file(name, "canonical.").is_some()
307        || parse_canonical_manifest_generation_file(name).is_some()
308        || parse_canonical_segment_descriptor_generation_file(name).is_some()
309        || parse_generation_file(name, "adjacency.").is_some()
310        || parse_canonical_adjacency_descriptor_generation_file(name).is_some()
311        || parse_generation_file(name, "properties.").is_some()
312        || parse_property_spill_manifest_generation_file(name).is_some()
313        || parse_property_spill_descriptor_generation_file(name).is_some()
314        || parse_generation_file(name, "property-index.").is_some()
315        || parse_property_projection_manifest_generation_file(name).is_some()
316        || parse_property_projection_descriptor_generation_file(name).is_some()
317        || parse_relational_index_artifact_generation_file(name).is_some()
318        || parse_relational_index_manifest_generation_file(name).is_some()
319        || parse_relational_row_generation_file(name).is_some()
320        || parse_relational_overflow_generation_file(name).is_some()
321        || parse_append_segment_generation_file(name).is_some()
322        || parse_append_manifest_generation_file(name).is_some();
323    if !allowed || Path::new(name).file_name().and_then(|value| value.to_str()) != Some(name) {
324        return Err(HawDBError::Storage(format!(
325            "backup contains unsupported file name: {name}"
326        )));
327    }
328    Ok(())
329}
330
331fn parse_u64(raw: &str, field: &str) -> Result<u64> {
332    raw.parse()
333        .map_err(|_| HawDBError::Storage(format!("invalid {field}: {raw}")))
334}
335
336fn encode_string(input: &str) -> String {
337    input
338        .as_bytes()
339        .iter()
340        .map(|byte| format!("{byte:02x}"))
341        .collect()
342}
343
344fn decode_string(input: &str) -> Result<String> {
345    if !input.len().is_multiple_of(2) {
346        return Err(HawDBError::Storage(format!(
347            "invalid hex string length: {}",
348            input.len()
349        )));
350    }
351    let mut bytes = Vec::with_capacity(input.len() / 2);
352    for offset in (0..input.len()).step_by(2) {
353        let byte = input
354            .get(offset..offset + 2)
355            .and_then(|pair| u8::from_str_radix(pair, 16).ok())
356            .ok_or_else(|| {
357                HawDBError::Storage(format!("invalid hex string at byte offset {offset}"))
358            })?;
359        bytes.push(byte);
360    }
361    String::from_utf8(bytes).map_err(HawDBError::from_storage_error)
362}
363
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365pub struct StorageBackupReport {
366    pub generation: u64,
367    pub checkpoint_commit_epoch: u64,
368    pub file_count: usize,
369    pub total_bytes: u64,
370    pub manifest_checksum: u64,
371}
372
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub struct StorageRestoreReport {
375    pub generation: u64,
376    pub checkpoint_commit_epoch: u64,
377    pub file_count: usize,
378    pub total_bytes: u64,
379    pub manifest_checksum: u64,
380}
381
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383pub struct StorageScrubReport {
384    pub generation: u64,
385    pub checked_file_count: usize,
386    pub checked_bytes: u64,
387    pub sha256_verified_file_count: usize,
388    pub wal_record_count: usize,
389    pub wal_bytes: u64,
390}
391
392#[cfg(test)]
393mod hex_tests;
394
395#[cfg(test)]
396mod tests {
397    use super::*;
398    use std::sync::atomic::{AtomicU64, Ordering};
399
400    static NEXT_TEST_DIRECTORY: AtomicU64 = AtomicU64::new(1);
401
402    fn test_directory() -> std::path::PathBuf {
403        std::env::temp_dir().join(format!(
404            "hawdb-storage-backup-manifest-{}-{}",
405            std::process::id(),
406            NEXT_TEST_DIRECTORY.fetch_add(1, Ordering::Relaxed)
407        ))
408    }
409
410    #[test]
411    fn backup_manifest_round_trips_protocol_fields() {
412        let directory = test_directory();
413        fs::create_dir_all(&directory).unwrap();
414        let path = directory.join(BACKUP_MANIFEST_FILE);
415        let files = vec![BackupFileEntry {
416            name: "checkpoint.7.hawdb".to_string(),
417            encoded_len: 42,
418            encoded_checksum: 9,
419            sha256: Sha256Digest::from_bytes([3; 32]),
420        }];
421
422        let written = BackupManifest::write(&path, 7, 11, files.clone()).unwrap();
423        let loaded = BackupManifest::load(&path).unwrap();
424
425        assert_eq!(loaded, written);
426        assert_eq!(loaded.files, files);
427        fs::remove_dir_all(directory).unwrap();
428    }
429
430    #[test]
431    fn backup_manifest_rejects_path_traversal() {
432        let error = validate_backup_file_name("../checkpoint.7.hawdb").unwrap_err();
433
434        assert!(error.to_string().contains("unsupported file name"));
435    }
436
437    #[test]
438    fn backup_manifest_rejects_trailing_data_after_checksum() {
439        let body = "HAWDB_BACKUP_V1\nversion\t1\ngeneration\t7\ncheckpoint_commit_epoch\t11\n";
440        let text = format!(
441            "{body}checksum\t{}\nunexpected\n",
442            checksum_u64(body.as_bytes())
443        );
444
445        let error = split_backup_manifest_checksum(&text).unwrap_err();
446
447        assert!(error.to_string().contains("data after checksum"));
448    }
449
450    #[test]
451    fn backup_file_copy_preserves_integrity_and_manifest_entry() {
452        let directory = test_directory();
453        fs::create_dir_all(&directory).unwrap();
454        let source = directory.join("source.hawdb");
455        let destination = directory.join("destination.hawdb");
456        let payload = vec![0x5a; 1024 * 1024 + 17];
457        fs::write(&source, &payload).unwrap();
458
459        let entry = copy_backup_file(&source, &destination, "checkpoint.7.hawdb").unwrap();
460        let source_identity = file_checksum(&source).unwrap();
461        let destination_identity = file_checksum(&destination).unwrap();
462
463        assert_eq!(source_identity, destination_identity);
464        assert_eq!(
465            entry,
466            BackupFileEntry {
467                name: "checkpoint.7.hawdb".to_string(),
468                encoded_len: source_identity.0,
469                encoded_checksum: source_identity.1,
470                sha256: source_identity.2,
471            }
472        );
473        assert_eq!(fs::read(destination).unwrap(), payload);
474        fs::remove_dir_all(directory).unwrap();
475    }
476
477    #[test]
478    fn backup_destination_must_be_new_and_outside_database_root() {
479        let directory = test_directory();
480        let root = directory.join("database");
481        let backup_parent = directory.join("backups");
482        fs::create_dir_all(&root).unwrap();
483        fs::create_dir_all(&backup_parent).unwrap();
484
485        validate_new_backup_destination(&root, &backup_parent.join("backup")).unwrap();
486        let error = validate_new_backup_destination(&root, &root.join("backup")).unwrap_err();
487        assert!(error
488            .to_string()
489            .contains("cannot be inside the database directory"));
490
491        let existing = backup_parent.join("existing");
492        fs::create_dir(&existing).unwrap();
493        let error = validate_new_backup_destination(&root, &existing).unwrap_err();
494        assert!(error.to_string().contains("already exists"));
495        fs::remove_dir_all(directory).unwrap();
496    }
497}