link_cli/engine/paged/
checkpoint_root.rs1use super::checkpoint_format::Decision;
3use super::format::invalid;
4use super::{PageDevice, PAGE_SIZE};
5use crate::LinkError;
6use std::collections::BTreeMap;
7
8struct Repair {
9 bytes: [u8; 128],
10 source: usize,
11 destinations: Vec<usize>,
12}
13pub struct MirroredCheckpointRoot<D> {
18 devices: [D; 2],
19 flags: u32,
20 repairs: BTreeMap<usize, Repair>,
21 fenced: bool,
22}
23impl<D: PageDevice> MirroredCheckpointRoot<D> {
24 pub fn new(primary: D, secondary: D, bank_flags: u32) -> Result<Self, LinkError> {
26 if bank_flags > 1 || primary.metadata_flags() != 0 || secondary.metadata_flags() != 0 {
27 return Err(invalid(
28 "checkpoint root mirroring requires raw roots and bank mode 0 or 1",
29 ));
30 }
31 Ok(Self {
32 devices: [primary, secondary],
33 flags: 2 | bank_flags,
34 repairs: BTreeMap::new(),
35 fenced: false,
36 })
37 }
38 pub fn into_devices(self) -> [D; 2] {
39 self.devices
40 }
41 fn check(&self) -> Result<(), LinkError> {
42 if self.fenced {
43 Err(invalid(
44 "uncertain checkpoint root is fenced; reopen both devices",
45 ))
46 } else {
47 Ok(())
48 }
49 }
50 fn slot(&self, slot: usize) -> Result<(), LinkError> {
51 self.check()?;
52 if slot > 1 {
53 Err(invalid("checkpoint root metadata slot"))
54 } else {
55 Ok(())
56 }
57 }
58 fn mutate(
59 &mut self,
60 action: impl FnOnce(&mut Self) -> Result<(), LinkError>,
61 ) -> Result<(), LinkError> {
62 self.check()?;
63 let result = action(self);
64 if result.is_err() {
65 self.fenced = true;
66 }
67 result
68 }
69 fn both(
70 &mut self,
71 mut action: impl FnMut(&mut D) -> Result<(), LinkError>,
72 ) -> Result<(), LinkError> {
73 self.mutate(|s| {
74 for device in &mut s.devices {
75 action(device)?;
76 }
77 Ok(())
78 })
79 }
80}
81impl<D: PageDevice> PageDevice for MirroredCheckpointRoot<D> {
82 fn metadata_flags(&self) -> u32 {
83 self.flags
84 }
85 fn supports_durable_flush(&self) -> bool {
86 self.devices.iter().all(PageDevice::supports_durable_flush)
87 }
88 fn new_database_id(&mut self) -> Result<[u8; 16], LinkError> {
89 self.check()?;
90 self.devices[0].new_database_id()
91 }
92 fn data_length(&mut self) -> Result<u64, LinkError> {
93 self.check()?;
94 for device in &mut self.devices {
95 if device.data_length()? != 0 {
96 return Err(invalid("checkpoint root data must be empty"));
97 }
98 }
99 Ok(0)
100 }
101 fn read_metadata(&mut self, slot: usize) -> Result<Option<Vec<u8>>, LinkError> {
102 self.slot(slot)?;
103 let mut failed = false;
104 let raw = self.devices.each_mut().map(|device| {
105 device.read_metadata(slot).unwrap_or_else(|_| {
106 failed = true;
107 Some(vec![0])
108 })
109 });
110 let states = [
111 Decision::decode(raw[0].as_deref().unwrap_or_default(), slot, self.flags)?,
112 Decision::decode(raw[1].as_deref().unwrap_or_default(), slot, self.flags)?,
113 ];
114 if let [Some(a), Some(b)] = &states {
115 if a.identity != b.identity || a.epoch.abs_diff(b.epoch) > 2 {
116 return Err(invalid("conflicting checkpoint root copies"));
117 }
118 }
119 let source = match &states {
120 [None, None] => {
121 let absent = raw
122 .each_ref()
123 .map(|b| b.as_deref().is_none_or(<[u8]>::is_empty));
124 return match absent {
125 [true, true] => {
126 self.repairs.remove(&slot);
127 Ok(None)
128 }
129 [false, true] if !failed => {
134 self.repairs.remove(&slot);
135 Ok(raw[0].clone())
136 }
137 _ => Err(invalid("both checkpoint root copies are unreadable")),
138 };
139 }
140 [Some(_), None] => 0,
141 [None, Some(_)] => 1,
142 [Some(a), Some(b)] => usize::from(b.epoch > a.epoch),
143 };
144 let bytes: [u8; 128] = raw[source]
145 .as_deref()
146 .expect("valid root bytes")
147 .try_into()
148 .expect("fixed root size");
149 let destinations = (0..2)
150 .filter(|&i| raw[i].as_deref() != Some(bytes.as_slice()))
151 .collect();
152 self.repairs.insert(
153 slot,
154 Repair {
155 bytes,
156 source,
157 destinations,
158 },
159 );
160 Ok(Some(bytes.to_vec()))
161 }
162 fn complete_recovery(&mut self) -> Result<(), LinkError> {
163 self.mutate(|s| {
164 for (&slot, repair) in &s.repairs {
166 if !repair.destinations.is_empty()
167 && s.devices[repair.source].read_metadata(slot)?.as_deref()
168 != Some(repair.bytes.as_slice())
169 {
170 return Err(invalid("checkpoint root repair source changed"));
171 }
172 }
173 for (&slot, repair) in &s.repairs {
174 for &side in &repair.destinations {
175 s.devices[side].write_metadata(slot, &repair.bytes)?;
176 s.devices[side].sync_metadata(slot)?;
177 }
178 }
179 s.repairs.clear();
180 Ok(())
181 })
182 }
183 fn write_metadata(&mut self, slot: usize, bytes: &[u8; 128]) -> Result<(), LinkError> {
184 self.slot(slot)?;
185 if Decision::decode(bytes, slot, self.flags)?.is_none() {
186 return Err(invalid("invalid checkpoint root publication"));
187 }
188 self.mutate(|s| {
191 let [primary, secondary] = &mut s.devices;
192 primary.write_metadata(slot, bytes)?;
193 primary.sync_metadata(slot)?;
194 secondary.write_metadata(slot, bytes)
195 })?;
196 self.repairs.remove(&slot);
197 Ok(())
198 }
199 fn sync_metadata(&mut self, slot: usize) -> Result<(), LinkError> {
202 self.slot(slot)?;
203 self.mutate(|s| s.devices[1].sync_metadata(slot))
204 }
205 fn sync_data(&mut self) -> Result<(), LinkError> {
206 self.both(PageDevice::sync_data)
207 }
208 fn truncate_data(&mut self, length: u64) -> Result<(), LinkError> {
209 self.check()?;
210 if length != 0 {
211 return Err(invalid("checkpoint root data must be empty"));
212 }
213 self.both(|device| device.truncate_data(0))
214 }
215 fn read_page(&mut self, _index: u64) -> Result<[u8; PAGE_SIZE], LinkError> {
216 self.check()?;
217 Err(invalid("checkpoint root has no data pages"))
218 }
219 fn write_page(&mut self, _index: u64, _bytes: &[u8; PAGE_SIZE]) -> Result<(), LinkError> {
220 self.check()?;
221 Err(invalid("checkpoint root has no data pages"))
222 }
223}