Skip to main content

link_cli/engine/paged/
mirrored.rs

1//! Optional two-copy repair; never repairs before the complete prefix validates.
2use super::{
3    format::{invalid, page_hash, u64_at, Metadata},
4    PageDevice, RepairPageDevice, MAX_PAGES, PAGE_SIZE,
5};
6use crate::LinkError;
7use std::collections::BTreeMap;
8struct Repair {
9    expected: u64,
10    source: usize,
11    destination: usize,
12}
13struct MetaRepair {
14    bytes: [u8; 128],
15    sides: Vec<usize>,
16}
17/// Owns two exclusive repair-capable devices. Extraction does not flush records.
18/// Both data syncs precede any metadata write; both decision syncs precede ACK.
19pub struct MirroredPageDevice<D> {
20    devices: [D; 2],
21    pages: BTreeMap<u64, Repair>,
22    metadata: BTreeMap<usize, MetaRepair>,
23    fenced: bool,
24}
25fn checked(page: &[u8; PAGE_SIZE], expected: u64) -> bool {
26    page_hash(page) == expected && u64_at(page, 56) == expected
27}
28impl<D: RepairPageDevice> MirroredPageDevice<D> {
29    pub fn new(primary: D, secondary: D) -> Self {
30        Self {
31            devices: [primary, secondary],
32            pages: BTreeMap::new(),
33            metadata: BTreeMap::new(),
34            fenced: false,
35        }
36    }
37    pub fn into_devices(self) -> [D; 2] {
38        self.devices
39    }
40    fn check(&self) -> Result<(), LinkError> {
41        if self.fenced {
42            Err(invalid(
43                "uncertain mirror owner is fenced; reopen both devices",
44            ))
45        } else {
46            Ok(())
47        }
48    }
49    fn mutate(
50        &mut self,
51        action: impl FnOnce(&mut Self) -> Result<(), LinkError>,
52    ) -> Result<(), LinkError> {
53        self.check()?;
54        let result = action(self);
55        if result.is_err() {
56            self.fenced = true;
57        }
58        result
59    }
60    fn both(
61        &mut self,
62        mut action: impl FnMut(&mut D) -> Result<(), LinkError>,
63    ) -> Result<(), LinkError> {
64        self.mutate(|s| {
65            for d in &mut s.devices {
66                action(d)?;
67            }
68            Ok(())
69        })
70    }
71}
72impl<D: RepairPageDevice> PageDevice for MirroredPageDevice<D> {
73    fn metadata_flags(&self) -> u32 {
74        1
75    }
76    fn supports_durable_flush(&self) -> bool {
77        self.devices.iter().all(PageDevice::supports_durable_flush)
78    }
79    fn new_database_id(&mut self) -> Result<[u8; 16], LinkError> {
80        self.check()?;
81        self.devices[0].new_database_id()
82    }
83    fn data_length(&mut self) -> Result<u64, LinkError> {
84        self.check()?;
85        let mut length = 0;
86        for d in &mut self.devices {
87            let n = d.data_length()?;
88            if n > MAX_PAGES * PAGE_SIZE as u64 {
89                return Err(invalid("mirror physical length"));
90            }
91            length = length.max(n);
92        }
93        Ok(length)
94    }
95    fn read_metadata(&mut self, slot: usize) -> Result<Option<Vec<u8>>, LinkError> {
96        self.check()?;
97        if slot > 1 {
98            return Err(invalid("mirror metadata slot"));
99        }
100        let mut failed = false;
101        let raw = self.devices.each_mut().map(|d| {
102            d.read_metadata(slot).unwrap_or_else(|_| {
103                failed = true;
104                Some(vec![0])
105            })
106        });
107        let states = [
108            Metadata::decode(raw[0].as_deref().unwrap_or_default(), 1)?,
109            Metadata::decode(raw[1].as_deref().unwrap_or_default(), 1)?,
110        ];
111        if let [Some(a), Some(b)] = &states {
112            if a.identity != b.identity || (a.generation == b.generation && raw[0] != raw[1]) {
113                return Err(invalid("conflicting mirror metadata copies"));
114            }
115        }
116        let side = match &states {
117            [None, None] => {
118                let absent = raw
119                    .each_ref()
120                    .map(|b| b.as_deref().is_none_or(<[u8]>::is_empty));
121                return match absent {
122                    [true, true] => Ok(None),
123                    // The secondary copy is written only after the primary
124                    // copy is durable. A torn primary next to a secondary
125                    // that was never written is a decision that power loss
126                    // interrupted before it was acknowledged: like one
127                    // device, report the invalid bytes so the other slot
128                    // is used. Garbage in both copies needs a second fault
129                    // and is refused.
130                    [false, true] if !failed => {
131                        self.metadata.remove(&slot);
132                        Ok(raw[0].clone())
133                    }
134                    _ => Err(invalid("both mirror metadata copies are unreadable")),
135                };
136            }
137            [Some(_), None] => 0,
138            [None, Some(_)] => 1,
139            [Some(a), Some(b)] => usize::from(b.generation >= a.generation),
140        };
141        let bytes = raw[side].as_ref().expect("decoded metadata").clone();
142        let sides = (0..2)
143            .filter(|&i| raw[i].as_ref() != Some(&bytes))
144            .collect();
145        self.metadata.insert(
146            slot,
147            MetaRepair {
148                bytes: bytes.clone().try_into().expect("fixed metadata"),
149                sides,
150            },
151        );
152        Ok(Some(bytes))
153    }
154    fn read_page(&mut self, _index: u64) -> Result<[u8; PAGE_SIZE], LinkError> {
155        Err(invalid("expected page checksum is required for mirror"))
156    }
157    fn read_checked_page(
158        &mut self,
159        index: u64,
160        expected: u64,
161    ) -> Result<[u8; PAGE_SIZE], LinkError> {
162        self.check()?;
163        let copies = self.devices.each_mut().map(|d| d.read_page(index).ok());
164        let valid = copies
165            .each_ref()
166            .map(|p| p.as_ref().is_some_and(|p| checked(p, expected)));
167        if !valid.iter().any(|v| *v) {
168            return Err(invalid(
169                "neither mirror page copy matches expected checksum",
170            ));
171        }
172        if valid == [true, true] && copies[0] != copies[1] {
173            return Err(invalid("conflicting mirror page copies"));
174        }
175        let source = usize::from(!valid[0]);
176        if valid != [true, true] {
177            self.pages.insert(
178                index,
179                Repair {
180                    expected,
181                    source,
182                    destination: 1 - source,
183                },
184            );
185        }
186        Ok(copies[source].expect("validated page"))
187    }
188    fn complete_recovery(&mut self) -> Result<(), LinkError> {
189        self.mutate(|s| {
190            for (&index, repair) in &s.pages {
191                let page = s.devices[repair.source].read_page(index)?;
192                if !checked(&page, repair.expected) {
193                    return Err(invalid("mirror repair source changed"));
194                }
195                s.devices[repair.destination].repair_page(index, &page)?;
196            }
197            if !s.pages.is_empty() {
198                for d in &mut s.devices {
199                    d.sync_data()?;
200                }
201            }
202            for (&slot, repair) in &s.metadata {
203                for &side in &repair.sides {
204                    s.devices[side].write_metadata(slot, &repair.bytes)?;
205                    s.devices[side].sync_metadata(slot)?;
206                }
207            }
208            s.pages.clear();
209            s.metadata.clear();
210            Ok(())
211        })
212    }
213    fn write_page(&mut self, index: u64, bytes: &[u8; PAGE_SIZE]) -> Result<(), LinkError> {
214        self.both(|d| d.write_page(index, bytes))
215    }
216    fn sync_data(&mut self) -> Result<(), LinkError> {
217        self.both(PageDevice::sync_data)
218    }
219    fn write_metadata(&mut self, slot: usize, bytes: &[u8; 128]) -> Result<(), LinkError> {
220        // The secondary copy is written only after the primary copy is
221        // durable, so power loss tears at most one copy of a decision.
222        self.mutate(|s| {
223            let [primary, secondary] = &mut s.devices;
224            primary.write_metadata(slot, bytes)?;
225            primary.sync_metadata(slot)?;
226            secondary.write_metadata(slot, bytes)
227        })
228    }
229    /// Only the secondary copy can be unsynced: `write_metadata` and repair
230    /// sync the primary copy before anything else is written.
231    fn sync_metadata(&mut self, slot: usize) -> Result<(), LinkError> {
232        self.mutate(|s| s.devices[1].sync_metadata(slot))
233    }
234    fn truncate_data(&mut self, length: u64) -> Result<(), LinkError> {
235        self.both(|d| d.truncate_data(length))
236    }
237}
238#[cfg(all(feature = "native-pages", any(unix, windows)))]
239impl MirroredPageDevice<super::FilePageDevice> {
240    /// Acquires both native `.writer` files, never stealing existing ownership.
241    pub fn open(path: impl AsRef<std::path::Path>) -> Result<Self, LinkError> {
242        let path = path.as_ref();
243        let mut secondary = path.as_os_str().to_owned();
244        secondary.push(".mirror");
245        let mut primary = super::FilePageDevice::open(path)?;
246        match super::FilePageDevice::open(std::path::Path::new(&secondary)) {
247            Ok(second) => Ok(Self::new(primary, second)),
248            Err(error) => {
249                if let Err(cleanup) = primary.close() {
250                    return Err(invalid(&format!(
251                        "{error}; mirror cleanup failed: {cleanup}"
252                    )));
253                }
254                Err(error)
255            }
256        }
257    }
258    /// Attempts both closes; uncertain underlying ownership files remain fenced.
259    pub fn close(&mut self) -> Result<(), LinkError> {
260        self.close_with(super::FilePageDevice::close)
261    }
262    fn close_with(
263        &mut self,
264        mut close: impl FnMut(&mut super::FilePageDevice) -> Result<(), LinkError>,
265    ) -> Result<(), LinkError> {
266        self.fenced = true;
267        let failures: Vec<_> = self
268            .devices
269            .iter_mut()
270            .rev()
271            .filter_map(|d| close(d).err().map(|e| e.to_string()))
272            .collect();
273        if failures.is_empty() {
274            Ok(())
275        } else {
276            Err(invalid(&format!(
277                "mirror cleanup failed: {}",
278                failures.join("; ")
279            )))
280        }
281    }
282}
283
284#[cfg(all(test, feature = "native-pages", any(unix, windows)))]
285mod tests {
286    use super::*;
287    #[test]
288    fn both_close_errors_preserve_fences_and_attempt_all_handles_once() {
289        let dir = tempfile::tempdir().unwrap();
290        let path = dir.path().join("journal");
291        let mut pair = MirroredPageDevice::open(&path).unwrap();
292        let mut closed = 0;
293        let error = pair
294            .close_with(|device| {
295                device.close_with(|file| {
296                    drop(file);
297                    closed += 1;
298                    Err(std::io::Error::other("injected close"))
299                })
300            })
301            .unwrap_err();
302        assert_eq!(closed, 8);
303        assert_eq!(error.to_string().matches("injected close").count(), 8);
304        assert!(dir.path().join("journal.writer").exists());
305        assert!(dir.path().join("journal.mirror.writer").exists());
306        assert!(MirroredPageDevice::open(&path).is_err());
307        assert!(pair.sync_data().is_err());
308        pair.close().unwrap();
309        assert!(dir.path().join("journal.writer").exists());
310        assert!(dir.path().join("journal.mirror.writer").exists());
311    }
312}