1use 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
30pub 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
40pub 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
64fn 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
110pub 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
125pub 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
149fn 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 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}