1use super::{format::invalid, PageDevice, RepairPageDevice, PAGE_SIZE};
3use crate::LinkError;
4use std::fs::{File, OpenOptions};
5use std::io::{self, Read, Seek, SeekFrom, Write};
6use std::path::{Path, PathBuf};
7
8pub struct FilePageDevice {
13 files: Vec<File>,
14 owner: Option<File>,
15 lock: PathBuf,
16 closed: bool,
17}
18fn suffix(path: &Path, extension: &str) -> PathBuf {
19 let mut result = path.as_os_str().to_owned();
20 result.push(extension);
21 result.into()
22}
23impl FilePageDevice {
24 pub fn open(path: impl AsRef<Path>) -> Result<Self, LinkError> {
25 let path = std::path::absolute(path)?;
26 let lock = suffix(&path, ".writer");
27 let mut ownership = OpenOptions::new();
28 ownership.write(true).create_new(true);
29 #[cfg(unix)]
30 {
31 use std::os::unix::fs::OpenOptionsExt;
32 ownership.mode(0o600);
33 }
34 let owner = open_file(&lock, &ownership)?;
35 let mut result = Self {
36 files: Vec::new(),
37 owner: Some(owner),
38 lock,
39 closed: false,
40 };
41 let initialize = (|| -> Result<(), LinkError> {
42 for file in [
43 path.clone(),
44 suffix(&path, ".meta0"),
45 suffix(&path, ".meta1"),
46 ] {
47 let mut options = OpenOptions::new();
48 options.read(true).write(true).create(true).truncate(false);
49 #[cfg(unix)]
50 {
51 use std::os::unix::fs::OpenOptionsExt;
52 options.mode(0o600);
53 }
54 result.files.push(open_file(&file, &options)?);
55 }
56 #[cfg(unix)]
57 sync_directory(path.parent().expect("absolute file parent"))?;
58 Ok(())
59 })();
60 if let Err(error) = initialize {
61 if let Err(cleanup) = result.close() {
62 return Err(invalid(&format!("{error}; cleanup failed: {cleanup}")));
63 }
64 return Err(error);
65 }
66 Ok(result)
67 }
68 fn file(&mut self, index: usize) -> Result<&mut File, LinkError> {
69 if self.closed {
70 return Err(invalid("native page device is closed"));
71 }
72 self.files
73 .get_mut(index)
74 .ok_or_else(|| invalid("page device file index"))
75 }
76 #[inline]
77 fn mutation<T>(
78 &mut self,
79 index: usize,
80 _operation: &str,
81 action: impl FnOnce(&mut File) -> io::Result<T>,
82 ) -> Result<T, LinkError> {
83 #[cfg(test)]
84 events::observe(&self.lock, index, _operation, false)?;
85 let result = action(self.file(index)?)?;
86 #[cfg(test)]
87 events::observe(&self.lock, index, _operation, true)?;
88 Ok(result)
89 }
90 pub fn close(&mut self) -> Result<(), LinkError> {
91 let name = self.lock.clone();
92 let mut index = 0;
93 self.close_with(|file| {
94 let result = close_named(&name, index, file);
95 index += 1;
96 result
97 })
98 }
99 pub(super) fn close_with(
100 &mut self,
101 mut close: impl FnMut(File) -> io::Result<()>,
102 ) -> Result<(), LinkError> {
103 if self.closed {
104 return Ok(());
105 }
106 self.closed = true;
107 let mut failures = Vec::new();
108 for file in self.files.drain(..).rev().chain(self.owner.take()) {
109 if let Err(error) = close(file) {
110 failures.push(error.to_string());
111 }
112 }
113 if failures.is_empty() {
116 #[cfg(test)]
117 if let Err(error) = events::boundary(&self.lock, 0, "delete", false) {
118 return Err(error.into());
119 }
120 if let Err(error) = std::fs::remove_file(&self.lock) {
121 failures.push(error.to_string());
122 }
123 #[cfg(test)]
124 if let Err(error) = events::boundary(&self.lock, 0, "delete", true) {
125 failures.push(error.to_string());
126 }
127 }
128 if failures.is_empty() {
129 Ok(())
130 } else {
131 Err(io::Error::other(format!(
132 "native page cleanup failed: {}",
133 failures.join("; ")
134 ))
135 .into())
136 }
137 }
138}
139impl Drop for FilePageDevice {
140 fn drop(&mut self) {
141 let _ = self.close();
142 }
143}
144impl PageDevice for FilePageDevice {
145 fn supports_durable_flush(&self) -> bool {
146 true
147 }
148 fn new_database_id(&mut self) -> Result<[u8; 16], LinkError> {
149 self.file(0)?;
150 let mut identity = [0; 16];
151 getrandom::fill(&mut identity)
152 .map_err(|error| invalid(&format!("database entropy: {error}")))?;
153 Ok(identity)
154 }
155 fn data_length(&mut self) -> Result<u64, LinkError> {
156 Ok(self.file(0)?.metadata()?.len())
157 }
158 fn read_metadata(&mut self, slot: usize) -> Result<Option<Vec<u8>>, LinkError> {
159 if slot > 1 {
160 return Err(invalid("metadata slot"));
161 }
162 let file = self.file(slot + 1)?;
163 match file.metadata()?.len() {
164 0 => Ok(None),
165 128 => {
166 let mut bytes = vec![0; 128];
167 file.rewind()?;
168 file.read_exact(&mut bytes)?;
169 Ok(Some(bytes))
170 }
171 _ => Ok(Some(vec![0])), }
173 }
174 fn write_metadata(&mut self, slot: usize, bytes: &[u8; 128]) -> Result<(), LinkError> {
175 if slot > 1 {
176 return Err(invalid("metadata slot"));
177 }
178 self.file(slot + 1)?.rewind()?;
179 self.mutation(slot + 1, "write", |file| file.write_all(bytes))?;
180 self.mutation(slot + 1, "truncate", |file| file.set_len(128))?;
181 Ok(())
182 }
183 fn sync_metadata(&mut self, slot: usize) -> Result<(), LinkError> {
184 if slot > 1 {
185 return Err(invalid("metadata slot"));
186 }
187 self.mutation(slot + 1, "sync", |file| file.sync_all())?;
188 Ok(())
189 }
190 fn read_page(&mut self, index: u64) -> Result<[u8; PAGE_SIZE], LinkError> {
191 if index >= super::MAX_PAGES {
192 return Err(invalid("physical page address"));
193 }
194 let file = self.file(0)?;
195 file.seek(SeekFrom::Start(index * PAGE_SIZE as u64))?;
196 let mut bytes = [0; PAGE_SIZE];
197 file.read_exact(&mut bytes)?;
198 Ok(bytes)
199 }
200 fn write_page(&mut self, index: u64, bytes: &[u8; PAGE_SIZE]) -> Result<(), LinkError> {
201 if index >= super::MAX_PAGES {
202 return Err(invalid("physical page address"));
203 }
204 let file = self.file(0)?;
205 let position = index * PAGE_SIZE as u64;
206 if file.metadata()?.len() != position {
207 return Err(invalid("native page file changed during ownership"));
208 }
209 file.seek(SeekFrom::Start(position))?;
210 self.mutation(0, "write", |file| file.write_all(bytes))?;
211 Ok(())
212 }
213 fn sync_data(&mut self) -> Result<(), LinkError> {
214 self.mutation(0, "sync", |file| file.sync_all())?;
215 Ok(())
216 }
217 fn truncate_data(&mut self, length: u64) -> Result<(), LinkError> {
218 if length > super::MAX_PAGES * PAGE_SIZE as u64 {
219 return Err(invalid("physical data length"));
220 }
221 self.mutation(0, "truncate", |file| file.set_len(length))?;
222 Ok(())
223 }
224}
225impl RepairPageDevice for FilePageDevice {
226 fn repair_page(&mut self, index: u64, bytes: &[u8; PAGE_SIZE]) -> Result<(), LinkError> {
227 if index >= super::MAX_PAGES {
228 return Err(invalid("physical repair address"));
229 }
230 let file = self.file(0)?;
231 let offset = index * PAGE_SIZE as u64;
232 if file.metadata()?.len() < offset {
233 return Err(invalid("repair would create a hole"));
234 }
235 file.seek(SeekFrom::Start(offset))?;
236 self.mutation(0, "repair", |file| file.write_all(bytes))?;
237 Ok(())
238 }
239}
240
241#[cfg(test)]
242#[path = "file_events.rs"]
243pub(crate) mod events;
244pub(crate) fn open_file(path: &Path, options: &OpenOptions) -> io::Result<File> {
245 #[cfg(test)]
246 {
247 events::open_file(path, || options.open(path))
248 }
249 #[cfg(not(test))]
250 {
251 options.open(path)
252 }
253}
254pub(crate) fn close_named(_path: &Path, _index: usize, file: File) -> io::Result<()> {
255 #[cfg(test)]
256 {
257 events::close_file(_path, _index, file)
258 }
259 #[cfg(not(test))]
260 {
261 close_file(file)
262 }
263}
264#[cfg(unix)]
265pub(crate) fn sync_directory(path: &Path) -> Result<(), LinkError> {
266 let mut options = OpenOptions::new();
267 options.read(true);
268 let directory = open_file(path, &options)?;
269 let sync = (|| -> io::Result<()> {
270 #[cfg(test)]
271 events::boundary(path, 0, "directory-sync", false)?;
272 directory.sync_all()?;
273 #[cfg(test)]
274 events::boundary(path, 0, "directory-sync", true)?;
275 Ok(())
276 })();
277 let close = close_named(path, 0, directory);
278 if sync.is_err() || close.is_err() {
279 return Err(invalid(&format!(
280 "directory sync: {sync:?}; close: {close:?}"
281 )));
282 }
283 Ok(())
284}
285#[cfg(unix)]
286pub(crate) fn close_file(file: File) -> io::Result<()> {
287 use std::os::fd::IntoRawFd;
288 if unsafe { libc::close(file.into_raw_fd()) } == 0 {
291 Ok(())
292 } else {
293 Err(io::Error::last_os_error())
294 }
295}
296#[cfg(windows)]
297pub(crate) fn close_file(file: File) -> io::Result<()> {
298 use std::os::windows::io::IntoRawHandle;
299 if unsafe { windows_sys::Win32::Foundation::CloseHandle(file.into_raw_handle()) } != 0 {
301 Ok(())
302 } else {
303 Err(io::Error::last_os_error())
304 }
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 #[test]
311 fn uncertain_close_preserves_ownership_and_attempts_all_handles() {
312 let dir = tempfile::tempdir().unwrap();
313 let path = dir.path().join("log");
314 let mut device = FilePageDevice::open(&path).unwrap();
315 let mut closed = 0;
316 let error = device
317 .close_with(|file| {
318 close_file(file)?;
319 closed += 1;
320 Err(io::Error::other("injected close"))
321 })
322 .unwrap_err();
323 assert!(error.to_string().contains("injected close"));
324 assert_eq!(closed, 4);
325 assert!(FilePageDevice::open(&path).is_err());
326 device.close().unwrap();
327 assert!(suffix(&path, ".writer").exists());
328 }
329}