1#[cfg(all(feature = "native-pages", any(unix, windows)))]
4mod file;
5#[cfg(all(
6 test,
7 feature = "native-pages",
8 feature = "physical-lsm",
9 any(unix, windows)
10))]
11pub(crate) use file::events;
12#[cfg(all(feature = "native-pages", feature = "physical-lsm", unix))]
13pub(crate) use file::sync_directory;
14#[cfg(all(feature = "native-pages", any(unix, windows)))]
15pub use file::FilePageDevice;
16#[cfg(all(feature = "native-pages", feature = "physical-lsm", any(unix, windows)))]
17pub(crate) use file::{close_named, open_file};
18#[cfg(all(feature = "native-pages", any(unix, windows)))]
19mod file_checkpoint;
20#[cfg(all(feature = "native-pages", any(unix, windows)))]
21pub use file_checkpoint::{FileCheckpointOptions, FileCheckpointPagedLog};
22mod checkpoint;
23mod checkpoint_format;
24mod checkpoint_inspect;
25mod checkpoint_root;
26pub use checkpoint_root::MirroredCheckpointRoot;
27mod format;
28pub use checkpoint::CheckpointPagedLog;
29mod mirrored;
30#[cfg(feature = "sorted-tables")]
31mod sorted_table;
32use crate::{LinkError, TransitionLogStore};
33use format::{
34 invalid, page_hash, portable, put, u32_at, u64_at, Metadata, CELLS, EXTERNAL, PAGE_MAGIC,
35 PAYLOAD,
36};
37pub use format::{MAX_PAGES, PAGE_SIZE};
38pub use mirrored::MirroredPageDevice;
39#[cfg(feature = "sorted-tables")]
40pub use sorted_table::{SortedJournalEntry, SortedJournalTable, SortedTableOptions};
41
42pub trait PageDevice {
45 fn metadata_flags(&self) -> u32 {
47 0
48 }
49 fn read_checked_page(
50 &mut self,
51 index: u64,
52 _expected: u64,
53 ) -> Result<[u8; PAGE_SIZE], LinkError> {
54 self.read_page(index)
55 }
56 fn complete_recovery(&mut self) -> Result<(), LinkError> {
58 Ok(())
59 }
60 fn supports_durable_flush(&self) -> bool {
61 false
62 }
63 fn new_database_id(&mut self) -> Result<[u8; 16], LinkError>;
64 fn data_length(&mut self) -> Result<u64, LinkError>;
65 fn read_metadata(&mut self, slot: usize) -> Result<Option<Vec<u8>>, LinkError>;
66 fn write_metadata(&mut self, slot: usize, bytes: &[u8; 128]) -> Result<(), LinkError>;
67 fn sync_metadata(&mut self, slot: usize) -> Result<(), LinkError>;
68 fn read_page(&mut self, index: u64) -> Result<[u8; PAGE_SIZE], LinkError>;
69 fn write_page(&mut self, index: u64, bytes: &[u8; PAGE_SIZE]) -> Result<(), LinkError>;
70 fn sync_data(&mut self) -> Result<(), LinkError>;
71 fn truncate_data(&mut self, length: u64) -> Result<(), LinkError>;
72}
73
74pub trait RepairPageDevice: PageDevice {
77 fn repair_page(&mut self, index: u64, bytes: &[u8; PAGE_SIZE]) -> Result<(), LinkError>;
78}
79
80pub struct PagedLog<D> {
85 device: D,
86 state: Metadata,
87 pending: Vec<String>,
88 pending_rows: u64,
89 fenced: bool,
90 max_pages: u64,
91}
92impl<D: PageDevice> PagedLog<D> {
93 pub fn open(device: D) -> Result<Self, LinkError> {
94 Self::with_max_pages(device, MAX_PAGES)
95 }
96 pub fn with_max_pages(mut device: D, max_pages: u64) -> Result<Self, LinkError> {
97 if max_pages == 0 || max_pages > MAX_PAGES {
98 return Err(invalid("invalid native page limit"));
99 }
100 let flags = device.metadata_flags();
101 if flags > 1 {
102 return Err(invalid("unsupported device mode"));
103 }
104 let raw = [device.read_metadata(0)?, device.read_metadata(1)?];
105 let mut valid = Vec::new();
106 for bytes in &raw {
107 if let Some(state) = Metadata::decode(bytes.as_deref().unwrap_or_default(), flags)? {
108 valid.push(state);
109 }
110 }
111 let state = if valid.is_empty() {
112 if raw.iter().flatten().any(|bytes| !bytes.is_empty()) || device.data_length()? != 0 {
113 return Err(invalid("no valid metadata decision"));
114 }
115 let state = Metadata::empty(device.new_database_id()?, flags);
116 device.sync_data()?;
117 device.write_metadata(0, &state.encode())?;
118 device.sync_metadata(0)?;
119 state
120 } else {
121 if valid.len() == 2
122 && (valid[0].identity != valid[1].identity
123 || (valid[0].generation == valid[1].generation && raw[0] != raw[1]))
124 {
125 return Err(invalid("conflicting metadata decisions"));
126 }
127 valid
128 .into_iter()
129 .max_by_key(|state| state.generation)
130 .expect("nonempty decisions")
131 };
132 if state.pages > max_pages {
133 return Err(invalid("committed pages exceed selected limit"));
134 }
135 let length = device.data_length()?;
136 let committed = state.pages * PAGE_SIZE as u64;
137 if length < committed {
138 return Err(invalid("truncated committed pages"));
139 }
140 read_committed(&mut device, &state, false)?;
141 device.complete_recovery()?;
142 if length > committed {
143 device.truncate_data(committed)?;
144 device.sync_data()?;
145 }
146 Ok(Self {
147 device,
148 state,
149 pending: Vec::new(),
150 pending_rows: 0,
151 fenced: false,
152 max_pages,
153 })
154 }
155 pub fn into_device(self) -> D {
156 self.device
157 }
158 fn check(&self) -> Result<(), LinkError> {
159 if self.fenced {
160 Err(invalid(
161 "uncertain native page owner is fenced; reopen the log",
162 ))
163 } else {
164 Ok(())
165 }
166 }
167}
168impl<D: PageDevice> TransitionLogStore for PagedLog<D> {
169 fn supports_durable_flush(&self) -> bool {
170 self.device.supports_durable_flush()
171 }
172 fn append_log_entry(&mut self, entry: &str) -> Result<(), LinkError> {
173 self.check()?;
174 if entry.contains(['\r', '\n']) {
175 return Err(invalid("journal records cannot contain line breaks"));
176 }
177 let rows = entry.len().div_ceil(7) as u64 + 1;
178 if self.state.pages + (self.pending_rows + rows).div_ceil(CELLS) > self.max_pages {
179 return Err(invalid("native page address space exhausted"));
180 }
181 self.pending.push(entry.to_owned());
182 self.pending_rows += rows;
183 Ok(())
184 }
185 fn read_log_entries(&mut self) -> Result<Vec<String>, LinkError> {
186 self.check()?;
187 match read_committed(&mut self.device, &self.state, true).and_then(|records| {
188 self.device.complete_recovery()?;
189 Ok(records)
190 }) {
191 Ok(mut records) => {
192 records.extend(self.pending.iter().cloned());
193 Ok(records)
194 }
195 Err(error) => {
196 self.fenced = true;
197 Err(error)
198 }
199 }
200 }
201 fn flush_log(&mut self) -> Result<(), LinkError> {
202 self.check()?;
203 if self.pending.is_empty() {
204 return Ok(());
205 }
206 self.fenced = true;
207 let mut next = self.state.clone();
208 next.generation += 1;
209 let mut writer = Writer {
210 device: &mut self.device,
211 state: &mut next,
212 page: [0; PAGE_SIZE],
213 count: 0,
214 };
215 for entry in &self.pending {
216 let mut string = 0;
217 for chunk in entry.as_bytes().chunks(7).rev() {
218 let mut payload = 0_u64;
219 for (i, byte) in chunk.iter().enumerate() {
220 payload |= u64::from(*byte) << (i * 8);
221 }
222 string = writer.cell(EXTERNAL | ((chunk.len() as u64) << 56) | payload, string)?;
223 }
224 let root = writer.cell(string, writer.state.root)?;
225 writer.state.root = root;
226 writer.state.records += 1;
227 }
228 writer.finish()?;
229 self.device.sync_data()?;
230 let slot = (next.generation % 2) as usize;
231 self.device.write_metadata(slot, &next.encode())?;
232 self.device.sync_metadata(slot)?;
233 self.state = next;
234 self.pending.clear();
235 self.pending_rows = 0;
236 self.fenced = false;
237 Ok(())
238 }
239}
240struct Writer<'a, D> {
241 device: &'a mut D,
242 state: &'a mut Metadata,
243 page: [u8; PAGE_SIZE],
244 count: usize,
245}
246impl<D: PageDevice> Writer<'_, D> {
247 fn cell(&mut self, source: u64, target: u64) -> Result<u64, LinkError> {
248 if self.count == CELLS as usize {
249 self.finish()?;
250 }
251 let id = self.state.pages * CELLS + self.count as u64 + 1;
252 put(&mut self.page, 64 + self.count * 16, source);
253 put(&mut self.page, 72 + self.count * 16, target);
254 self.count += 1;
255 self.state.rows += 1;
256 Ok(id)
257 }
258 fn finish(&mut self) -> Result<(), LinkError> {
259 self.page[..8].copy_from_slice(PAGE_MAGIC);
260 self.page[8..24].copy_from_slice(&self.state.identity);
261 put(&mut self.page, 24, self.state.pages);
262 put(&mut self.page, 32, self.state.generation);
263 self.page[40..44].copy_from_slice(&(self.count as u32).to_le_bytes());
264 put(&mut self.page, 48, self.state.last_hash);
265 self.state.last_hash = page_hash(&self.page);
266 put(&mut self.page, 56, self.state.last_hash);
267 self.device.write_page(self.state.pages, &self.page)?;
268 self.state.pages += 1;
269 self.page.fill(0);
270 self.count = 0;
271 Ok(())
272 }
273}
274struct Cursor<'a, D> {
275 device: &'a mut D,
276 state: &'a Metadata,
277 index: i64,
278 generation: u64,
279 expected: u64,
280 page: [u8; PAGE_SIZE],
281 count: usize,
282 consumed: u64,
283}
284impl<D: PageDevice> Cursor<'_, D> {
285 fn load(&mut self) -> Result<(), LinkError> {
286 self.page = self
287 .device
288 .read_checked_page(self.index as u64, self.expected)?;
289 let page = &self.page;
290 let actual = page_hash(page);
291 if &page[..8] != PAGE_MAGIC
292 || page[8..24] != self.state.identity
293 || u64_at(page, 24) != self.index as u64
294 || actual != self.expected
295 || actual != u64_at(page, 56)
296 {
297 return Err(invalid("page checksum or identity"));
298 }
299 let created = u64_at(page, 32);
300 if created == 0
301 || created > self.generation
302 || created < self.generation - 1
303 || (self.index as u64 == self.state.pages - 1 && created != self.generation)
304 || (self.index == 0 && created != 1)
305 {
306 return Err(invalid("page generation"));
307 }
308 self.generation = created;
309 self.count = u32_at(page, 40) as usize;
310 self.expected = u64_at(page, 48);
311 if self.count == 0
312 || self.count > CELLS as usize
313 || u32_at(page, 44) != 0
314 || page[64 + self.count * 16..].iter().any(|v| *v != 0)
315 || (self.index == 0 && self.expected != 0)
316 {
317 return Err(invalid("page count or padding"));
318 }
319 Ok(())
320 }
321 fn current(&self) -> u64 {
322 if self.index < 0 {
323 0
324 } else {
325 self.index as u64 * CELLS + self.count as u64
326 }
327 }
328 fn take(&mut self, wanted: u64) -> Result<(u64, u64), LinkError> {
329 if wanted == 0 || wanted != self.current() {
330 return Err(invalid("noncanonical doublet reference"));
331 }
332 let offset = 64 + (self.count - 1) * 16;
333 let result = (
334 u64_at(&self.page, offset),
335 portable(u64_at(&self.page, offset + 8))?,
336 );
337 self.consumed += 1;
338 self.count -= 1;
339 if self.count == 0 {
340 self.index -= 1;
341 if self.index >= 0 {
342 self.load()?;
343 }
344 }
345 Ok(result)
346 }
347}
348fn read_committed<D: PageDevice>(
349 device: &mut D,
350 state: &Metadata,
351 retain: bool,
352) -> Result<Vec<String>, LinkError> {
353 let mut result = Vec::new();
354 if state.pages == 0 {
355 return Ok(result);
356 }
357 let mut cursor = Cursor {
358 device,
359 state,
360 index: (state.pages - 1) as i64,
361 generation: state.generation,
362 expected: state.last_hash,
363 page: [0; PAGE_SIZE],
364 count: 0,
365 consumed: 0,
366 };
367 cursor.load()?;
368 let mut root = state.root;
369 let mut records = 0;
370 while root != 0 {
371 let (source, previous) = cursor.take(root)?;
372 let mut string = portable(source)?;
373 let mut bytes = Vec::new();
374 while string != 0 {
375 let (external, next) = cursor.take(string)?;
376 let length = ((external >> 56) & 7) as usize;
377 let payload = external & PAYLOAD;
378 if external & EXTERNAL == 0
379 || external & 0x7800000000000000 != 0
380 || length == 0
381 || payload >> (length * 8) != 0
382 || (next != 0 && length != 7)
383 {
384 return Err(invalid("string doublet"));
385 }
386 bytes.extend_from_slice(&payload.to_le_bytes()[..length]);
387 string = next;
388 }
389 let text = String::from_utf8(bytes).map_err(|_| invalid("record UTF-8"))?;
390 if text.contains(['\r', '\n']) {
391 return Err(invalid("record delimiter"));
392 }
393 if previous != cursor.current() {
394 return Err(invalid("record predecessor"));
395 }
396 if retain {
397 result.push(text);
398 }
399 root = previous;
400 records += 1;
401 }
402 if cursor.current() != 0 || cursor.consumed != state.rows || records != state.records {
403 return Err(invalid("record counts"));
404 }
405 result.reverse();
406 Ok(result)
407}