Skip to main content

link_cli/engine/paged/
file_checkpoint.rs

1//! Selected native ownership of the root and both fixed checkpoint banks.
2use super::{
3    format::invalid, CheckpointPagedLog, FilePageDevice, MirroredCheckpointRoot,
4    MirroredPageDevice, PageDevice, RepairPageDevice, MAX_PAGES, PAGE_SIZE,
5};
6use crate::{LinkError, ReplaceableTransitionLogStore, TransitionLogStore};
7use std::{
8    path::{Path, PathBuf},
9    sync::{Arc, Mutex},
10};
11
12// Retain independent raw owners across fallible portable construction. Dropping
13// a partially constructed bank must not hide its explicit cleanup errors.
14#[derive(Clone)]
15struct Lease(Arc<Mutex<FilePageDevice>>);
16impl Lease {
17    fn open(path: &Path) -> Result<Self, LinkError> {
18        Ok(Self(Arc::new(Mutex::new(FilePageDevice::open(path)?))))
19    }
20    fn io<T>(
21        &self,
22        action: impl FnOnce(&mut FilePageDevice) -> Result<T, LinkError>,
23    ) -> Result<T, LinkError> {
24        let mut device = self
25            .0
26            .lock()
27            .map_err(|_| invalid("native checkpoint device mutex is poisoned"))?;
28        action(&mut device)
29    }
30}
31impl PageDevice for Lease {
32    fn supports_durable_flush(&self) -> bool {
33        true
34    }
35    fn new_database_id(&mut self) -> Result<[u8; 16], LinkError> {
36        self.io(PageDevice::new_database_id)
37    }
38    fn data_length(&mut self) -> Result<u64, LinkError> {
39        self.io(PageDevice::data_length)
40    }
41    fn read_metadata(&mut self, slot: usize) -> Result<Option<Vec<u8>>, LinkError> {
42        self.io(|device| device.read_metadata(slot))
43    }
44    fn write_metadata(&mut self, slot: usize, bytes: &[u8; 128]) -> Result<(), LinkError> {
45        self.io(|device| device.write_metadata(slot, bytes))
46    }
47    fn sync_metadata(&mut self, slot: usize) -> Result<(), LinkError> {
48        self.io(|device| device.sync_metadata(slot))
49    }
50    fn read_page(&mut self, index: u64) -> Result<[u8; PAGE_SIZE], LinkError> {
51        self.io(|device| device.read_page(index))
52    }
53    fn write_page(&mut self, index: u64, bytes: &[u8; PAGE_SIZE]) -> Result<(), LinkError> {
54        self.io(|device| device.write_page(index, bytes))
55    }
56    fn sync_data(&mut self) -> Result<(), LinkError> {
57        self.io(PageDevice::sync_data)
58    }
59    fn truncate_data(&mut self, length: u64) -> Result<(), LinkError> {
60        self.io(|device| device.truncate_data(length))
61    }
62}
63impl RepairPageDevice for Lease {
64    fn repair_page(&mut self, index: u64, bytes: &[u8; PAGE_SIZE]) -> Result<(), LinkError> {
65        self.io(|device| device.repair_page(index, bytes))
66    }
67}
68
69enum NativeDevice {
70    Single(Lease),
71    Mirrored(Box<MirroredPageDevice<Lease>>),
72    Root(Box<MirroredCheckpointRoot<Lease>>),
73}
74impl NativeDevice {
75    fn device(&mut self) -> &mut dyn PageDevice {
76        match self {
77            Self::Single(device) => device,
78            Self::Mirrored(device) => &mut **device,
79            Self::Root(device) => &mut **device,
80        }
81    }
82}
83impl PageDevice for NativeDevice {
84    fn metadata_flags(&self) -> u32 {
85        match self {
86            Self::Single(_) => 0,
87            Self::Mirrored(_) => 1,
88            Self::Root(device) => device.metadata_flags(),
89        }
90    }
91    fn supports_durable_flush(&self) -> bool {
92        true
93    }
94    fn new_database_id(&mut self) -> Result<[u8; 16], LinkError> {
95        self.device().new_database_id()
96    }
97    fn data_length(&mut self) -> Result<u64, LinkError> {
98        self.device().data_length()
99    }
100    fn read_metadata(&mut self, slot: usize) -> Result<Option<Vec<u8>>, LinkError> {
101        self.device().read_metadata(slot)
102    }
103    fn write_metadata(&mut self, slot: usize, bytes: &[u8; 128]) -> Result<(), LinkError> {
104        self.device().write_metadata(slot, bytes)
105    }
106    fn sync_metadata(&mut self, slot: usize) -> Result<(), LinkError> {
107        self.device().sync_metadata(slot)
108    }
109    fn read_page(&mut self, index: u64) -> Result<[u8; PAGE_SIZE], LinkError> {
110        self.device().read_page(index)
111    }
112    fn read_checked_page(
113        &mut self,
114        index: u64,
115        expected: u64,
116    ) -> Result<[u8; PAGE_SIZE], LinkError> {
117        self.device().read_checked_page(index, expected)
118    }
119    fn complete_recovery(&mut self) -> Result<(), LinkError> {
120        self.device().complete_recovery()
121    }
122    fn write_page(&mut self, index: u64, bytes: &[u8; PAGE_SIZE]) -> Result<(), LinkError> {
123        self.device().write_page(index, bytes)
124    }
125    fn sync_data(&mut self) -> Result<(), LinkError> {
126        self.device().sync_data()
127    }
128    fn truncate_data(&mut self, length: u64) -> Result<(), LinkError> {
129        self.device().truncate_data(length)
130    }
131}
132
133/// Independently selected root and bank copies. Defaults retain the existing
134/// single-root, single-bank mode and its file/I/O costs.
135#[derive(Clone, Copy, Debug)]
136pub struct FileCheckpointOptions {
137    pub mirrored_banks: bool,
138    pub mirrored_root: bool,
139    pub max_pages: u64,
140}
141impl Default for FileCheckpointOptions {
142    fn default() -> Self {
143        Self {
144            mirrored_banks: false,
145            mirrored_root: false,
146            max_pages: MAX_PAGES,
147        }
148    }
149}
150
151/// Owns native devices at `path`, `.bank0` and `.bank1`, with independently
152/// selected `.mirror` copies of the root and banks. Acquires every writer fence
153/// before validation or repair.
154/// Close never flushes pending records; it attempts every device in reverse
155/// order, root last. Uncertain cleanup retains the affected native writer fence.
156pub struct FileCheckpointPagedLog {
157    inner: Option<CheckpointPagedLog<NativeDevice, NativeDevice>>,
158    owners: Vec<Lease>,
159}
160fn suffix(path: &Path, extension: &str) -> PathBuf {
161    let mut result = path.as_os_str().to_owned();
162    result.push(extension);
163    result.into()
164}
165impl FileCheckpointPagedLog {
166    pub fn with_options(
167        path: impl AsRef<Path>,
168        options: FileCheckpointOptions,
169    ) -> Result<Self, LinkError> {
170        Self::build_selected(path.as_ref(), options, Lease::open, |_, device| {
171            device.close()
172        })
173    }
174    pub fn open(path: impl AsRef<Path>, mirrored_banks: bool) -> Result<Self, LinkError> {
175        Self::with_max_pages(path, mirrored_banks, MAX_PAGES)
176    }
177    pub fn with_max_pages(
178        path: impl AsRef<Path>,
179        mirrored_banks: bool,
180        max_pages: u64,
181    ) -> Result<Self, LinkError> {
182        Self::build(
183            path.as_ref(),
184            mirrored_banks,
185            max_pages,
186            Lease::open,
187            |_, device| device.close(),
188        )
189    }
190    fn build(
191        path: &Path,
192        mirrored: bool,
193        max_pages: u64,
194        open: impl FnMut(&Path) -> Result<Lease, LinkError>,
195        close: impl FnMut(usize, &mut FilePageDevice) -> Result<(), LinkError>,
196    ) -> Result<Self, LinkError> {
197        Self::build_selected(
198            path,
199            FileCheckpointOptions {
200                mirrored_banks: mirrored,
201                max_pages,
202                ..Default::default()
203            },
204            open,
205            close,
206        )
207    }
208    fn build_selected(
209        path: &Path,
210        options: FileCheckpointOptions,
211        mut open: impl FnMut(&Path) -> Result<Lease, LinkError>,
212        close: impl FnMut(usize, &mut FilePageDevice) -> Result<(), LinkError>,
213    ) -> Result<Self, LinkError> {
214        let mut owners = Vec::new();
215        let result = (|| {
216            let mut acquire = |name: &Path| {
217                let lease = open(name)?;
218                owners.push(lease.clone());
219                Ok::<_, LinkError>(lease)
220            };
221            let primary_root = acquire(path)?;
222            let secondary_root = if options.mirrored_root {
223                Some(acquire(&suffix(path, ".mirror"))?)
224            } else {
225                None
226            };
227            let mut bank = |index| {
228                let name = suffix(path, &format!(".bank{index}"));
229                let primary = acquire(&name)?;
230                Ok::<_, LinkError>(if options.mirrored_banks {
231                    NativeDevice::Mirrored(Box::new(MirroredPageDevice::new(
232                        primary,
233                        acquire(&suffix(&name, ".mirror"))?,
234                    )))
235                } else {
236                    NativeDevice::Single(primary)
237                })
238            };
239            let banks = [bank(0)?, bank(1)?];
240            let root = match secondary_root {
241                Some(secondary) => NativeDevice::Root(Box::new(MirroredCheckpointRoot::new(
242                    primary_root,
243                    secondary,
244                    u32::from(options.mirrored_banks),
245                )?)),
246                None => NativeDevice::Single(primary_root),
247            };
248            CheckpointPagedLog::with_max_pages(root, banks, options.max_pages)
249        })();
250        match result {
251            Ok(inner) => Ok(Self {
252                inner: Some(inner),
253                owners,
254            }),
255            Err(cause) => match Self::close_owned(&mut owners, close) {
256                Ok(()) => Err(cause),
257                Err(cleanup) => Err(invalid(&format!(
258                    "{cause}; native checkpoint initialization cleanup failed: {cleanup}"
259                ))),
260            },
261        }
262    }
263    fn inner(&mut self) -> Result<&mut CheckpointPagedLog<NativeDevice, NativeDevice>, LinkError> {
264        self.inner
265            .as_mut()
266            .ok_or_else(|| invalid("native checkpoint log is closed"))
267    }
268    pub fn epoch(&self) -> Result<u64, LinkError> {
269        self.inner
270            .as_ref()
271            .map(CheckpointPagedLog::epoch)
272            .ok_or_else(|| invalid("native checkpoint log is closed"))
273    }
274    fn close_owned(
275        owners: &mut Vec<Lease>,
276        mut close: impl FnMut(usize, &mut FilePageDevice) -> Result<(), LinkError>,
277    ) -> Result<(), LinkError> {
278        let mut errors = Vec::new();
279        for (index, owner) in owners.drain(..).enumerate().rev() {
280            // Recovery of a poisoned guard is only for closing every handle.
281            let mut device = owner.0.lock().unwrap_or_else(|cause| cause.into_inner());
282            if let Err(cause) = close(index, &mut device) {
283                errors.push(cause.to_string());
284            }
285        }
286        if errors.is_empty() {
287            Ok(())
288        } else {
289            Err(invalid(&format!(
290                "native checkpoint cleanup failed: {}",
291                errors.join("; ")
292            )))
293        }
294    }
295    fn close_with(
296        &mut self,
297        close: impl FnMut(usize, &mut FilePageDevice) -> Result<(), LinkError>,
298    ) -> Result<(), LinkError> {
299        self.inner = None;
300        Self::close_owned(&mut self.owners, close)
301    }
302    pub fn close(&mut self) -> Result<(), LinkError> {
303        self.close_with(|_, device| device.close())
304    }
305}
306impl Drop for FileCheckpointPagedLog {
307    fn drop(&mut self) {
308        let _ = self.close();
309    }
310}
311impl TransitionLogStore for FileCheckpointPagedLog {
312    fn supports_durable_flush(&self) -> bool {
313        true
314    }
315    fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
316        self.inner()?.read_log_entries()
317    }
318    fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
319        self.inner()?.append_log_entry(entry)
320    }
321    fn flush_log(&mut self) -> Result<(), LinkError> {
322        self.inner()?.flush_log()
323    }
324}
325impl ReplaceableTransitionLogStore for FileCheckpointPagedLog {
326    fn replace_log_entries(&mut self, entries: &[String]) -> Result<bool, LinkError> {
327        self.inner()?.replace_log_entries(entries)
328    }
329}
330
331#[cfg(test)]
332#[path = "file_checkpoint_tests.rs"]
333mod tests;
334
335#[cfg(test)]
336#[path = "file_checkpoint_process_tests.rs"]
337mod process_tests;