Skip to main content

antfly_embedded/
files.rs

1// Copyright 2026 Antfly, Inc.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Free functions and `Database` methods that read or write Lite database
17//! files directly (backup to disk, restore, path-level integrity checks).
18//! Mirrors `go/pkg/embedded/files.go` and the file-oriented helpers in
19//! `go/pkg/embedded/maintenance.go`.
20
21use std::path::Path;
22
23use antfly_embedded_sys::{self as sys, antfly_buffer};
24
25use crate::db::{Database, validate_abi};
26use crate::error::{Error, Result};
27use crate::ffi::{borrow_slice, check, path_has_suffix, path_to_cstring, take_buffer};
28use crate::options::{RestoreOptions, Storage};
29
30/// Runs Lite integrity checks for `path` without opening a database handle
31/// and returns the JSON result.
32pub fn check_file_json(path: impl AsRef<Path>) -> Result<Vec<u8>> {
33    validate_abi()?;
34    let c_path = path_to_cstring(path.as_ref())?;
35    let mut out = antfly_buffer::default();
36    check(unsafe { sys::antfly_lite_check_file_json(c_path.as_ptr(), &mut out) })?;
37    Ok(unsafe { take_buffer(out) })
38}
39
40/// Opens `src_path` read-only, copies a stable Lite snapshot to
41/// `dest_path`, and returns the JSON result. Neither path is required to
42/// end in `.aflite`; see [`crate::maintenance::copy_stable_snapshot_file`]
43/// for the suffix-checked, typed convenience.
44pub fn copy_stable_snapshot_file_json(
45    src_path: impl AsRef<Path>,
46    dest_path: impl AsRef<Path>,
47    replace: bool,
48) -> Result<Vec<u8>> {
49    validate_abi()?;
50    let c_src = path_to_cstring(src_path.as_ref())?;
51    let c_dest = path_to_cstring(dest_path.as_ref())?;
52    let mut out = antfly_buffer::default();
53    check(unsafe {
54        sys::antfly_lite_copy_stable_snapshot_file_json(
55            c_src.as_ptr(),
56            c_dest.as_ptr(),
57            replace,
58            &mut out,
59        )
60    })?;
61    Ok(unsafe { take_buffer(out) })
62}
63
64/// Builds an `antfly_open_options` with only `storage_kind` set from
65/// `storage`, matching the Go binding's `restoreCOptions`: the destination's
66/// storage kind is the only option restore needs from the caller, and the
67/// restored database is otherwise opened with defaults.
68fn restore_c_options(storage: Storage) -> Result<sys::antfly_open_options> {
69    let mut c_opts: sys::antfly_open_options = unsafe { std::mem::zeroed() };
70    check(unsafe { sys::antfly_open_options_init(&mut c_opts) })?;
71    c_opts.storage_kind = storage.as_u32();
72    Ok(c_opts)
73}
74
75fn restore_to_file(path: &Path, backup: &[u8], opts: &RestoreOptions) -> Result<()> {
76    let c_opts = restore_c_options(opts.storage)?;
77    let c_path = path_to_cstring(path)?;
78    let mut out = antfly_buffer::default();
79    check(unsafe {
80        sys::antfly_restore_backup_json(
81            c_path.as_ptr(),
82            &c_opts,
83            borrow_slice(backup),
84            opts.replace,
85            &mut out,
86        )
87    })?;
88    unsafe { sys::antfly_buffer_free(&mut out) };
89    Ok(())
90}
91
92fn restore_file_to_file(path: &Path, backup_path: &Path, opts: &RestoreOptions) -> Result<()> {
93    let c_opts = restore_c_options(opts.storage)?;
94    let c_path = path_to_cstring(path)?;
95    let c_backup_path = path_to_cstring(backup_path)?;
96    let mut out = antfly_buffer::default();
97    check(unsafe {
98        sys::antfly_restore_backup_file_json(
99            c_path.as_ptr(),
100            &c_opts,
101            c_backup_path.as_ptr(),
102            opts.replace,
103            &mut out,
104        )
105    })?;
106    unsafe { sys::antfly_buffer_free(&mut out) };
107    Ok(())
108}
109
110/// Creates a database at `path` from a portable Antfly backup archive, of
111/// the storage kind `opts.storage` selects. A backup of either kind
112/// restores into either kind. `path` must end in `.aflite` when
113/// `opts.storage` is [`Storage::Lite`] and `backup` must be non-empty.
114/// [`Error::OutcomeUnknown`] means the destination was published but crash
115/// durability could not be confirmed; inspect it and do not retry
116/// automatically.
117pub fn restore(path: impl AsRef<Path>, backup: &[u8], opts: &RestoreOptions) -> Result<()> {
118    let path = path.as_ref();
119    if backup.is_empty() || (opts.storage == Storage::Lite && !path_has_suffix(path, ".aflite")) {
120        return Err(Error::InvalidArgument);
121    }
122    restore_to_file(path, backup, opts)
123}
124
125/// [`restore`] reading the archive from `backup_path` (which must end in
126/// `.afb`). For `.aflite` destinations it streams with bounded memory use.
127/// [`Error::Busy`] means the source changed during streaming or the
128/// source/destination is concurrently locked; retry after the files are
129/// stable and no writer is active. [`Error::Unsupported`] means the source
130/// filesystem lacks required advisory locking; copy the archive to a
131/// supported local filesystem. [`Error::OutcomeUnknown`] means the
132/// destination was published but crash durability could not be confirmed;
133/// inspect it and do not retry automatically.
134pub fn restore_file(
135    path: impl AsRef<Path>,
136    backup_path: impl AsRef<Path>,
137    opts: &RestoreOptions,
138) -> Result<()> {
139    let path = path.as_ref();
140    let backup_path = backup_path.as_ref();
141    if !path_has_suffix(backup_path, ".afb")
142        || (opts.storage == Storage::Lite && !path_has_suffix(path, ".aflite"))
143    {
144        return Err(Error::InvalidArgument);
145    }
146    restore_file_to_file(path, backup_path, opts)
147}
148
149/// Writes `data` to `path` atomically: a temp file in the same directory is
150/// written, `fsync`'d, and renamed into place. I/O failures are reported as
151/// [`Error::Internal`] (they are not `antfly_error_code` values).
152fn write_file_atomically(path: &Path, data: &[u8]) -> Result<()> {
153    let dir = path
154        .parent()
155        .filter(|p| !p.as_os_str().is_empty())
156        .unwrap_or_else(|| Path::new("."));
157    let file_name = path
158        .file_name()
159        .and_then(|n| n.to_str())
160        .ok_or(Error::InvalidArgument)?;
161    let tmp_path = dir.join(format!(
162        ".{file_name}.{}.{}.tmp",
163        std::process::id(),
164        std::time::SystemTime::now()
165            .duration_since(std::time::UNIX_EPOCH)
166            .map(|d| d.as_nanos())
167            .unwrap_or_default()
168    ));
169
170    let write_result = (|| -> std::io::Result<()> {
171        use std::io::Write;
172        let mut file = std::fs::OpenOptions::new()
173            .write(true)
174            .create(true)
175            .truncate(true)
176            .open(&tmp_path)?;
177        file.write_all(data)?;
178        #[cfg(unix)]
179        {
180            use std::os::unix::fs::PermissionsExt;
181            file.set_permissions(std::fs::Permissions::from_mode(0o600))?;
182        }
183        file.sync_all()
184    })();
185
186    if write_result.is_err() {
187        let _ = std::fs::remove_file(&tmp_path);
188        return Err(Error::Internal);
189    }
190
191    std::fs::rename(&tmp_path, path).map_err(|_| {
192        let _ = std::fs::remove_file(&tmp_path);
193        Error::Internal
194    })
195}
196
197impl Database {
198    /// Writes a portable Antfly backup archive for this database to `path`,
199    /// which must end in `.afb`.
200    pub fn backup_to_file(&self, path: impl AsRef<Path>) -> Result<()> {
201        let path = path.as_ref();
202        if !path_has_suffix(path, ".afb") {
203            return Err(Error::InvalidArgument);
204        }
205        let backup = self.backup()?;
206        write_file_atomically(path, &backup)
207    }
208}