Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 6.8 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Reading segments front to back: for fsck, for checking records before a
5//! segment is sealed, and for rebuilding a damaged index.
6
7use std::fs::File;
8use std::io;
9
10use crate::fsutil::read_exact_at;
11use crate::journal::Entry;
12use crate::record::{ALIGN, Checked, HEADER_LEN, check, parse_header};
13
14/// Bytes read at a time when walking a file in order.
15const CHUNK: u64 = 1 << 20;
16
17/// A buffered view of a file for reads that mostly move forward.
18#[derive(Debug)]
19pub(crate) struct Window<'a> {
20 file: &'a File,
21 len: u64,
22 start: u64,
23 buf: Vec<u8>,
24}
25
26impl<'a> Window<'a> {
27 /// A view of the first `len` bytes of `file`.
28 pub fn new(file: &'a File, len: u64) -> Self {
29 Self {
30 file,
31 len,
32 start: 0,
33 buf: Vec::new(),
34 }
35 }
36
37 /// The `n` bytes at `offset`, or `None` if they run past the end.
38 pub fn bytes(&mut self, offset: u64, n: u64) -> io::Result<Option<&[u8]>> {
39 let Some(end) = offset.checked_add(n).filter(|end| *end <= self.len) else {
40 return Ok(None);
41 };
42 if offset < self.start || end > self.start + self.buf.len() as u64 {
43 let want = n.max(CHUNK).min(self.len - offset);
44 let want =
45 usize::try_from(want).map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?;
46 self.buf.resize(want, 0);
47 read_exact_at(self.file, &mut self.buf, offset)?;
48 self.start = offset;
49 }
50 let at = (offset - self.start) as usize;
51 Ok(Some(&self.buf[at..at + n as usize]))
52 }
53}
54
55/// What a scan found.
56#[derive(Debug, Default)]
57pub(crate) struct Scan {
58 /// Records whose header and CRC are valid.
59 pub records: u64,
60 /// Bytes that are not part of any valid record.
61 pub junk: u64,
62}
63
64/// Calls `visit(offset, record)` for every record of the first `len` bytes
65/// of a segment whose header and CRC are valid, in order.
66///
67/// Bytes that do not start a valid record are the remains of a write cut
68/// short by a crash, or damage. They are skipped 8 bytes at a time, looking
69/// for the next sync word, and counted as junk. A valid record is stepped
70/// over whole, so a payload that happens to contain records is never
71/// mistaken for them.
72pub(crate) fn scan(
73 file: &File,
74 len: u64,
75 mut visit: impl FnMut(u64, &Checked<'_>),
76) -> io::Result<Scan> {
77 let mut window = Window::new(file, len);
78 let mut scan = Scan::default();
79 let mut offset = 0u64;
80 while offset < len {
81 let header = match window.bytes(offset, HEADER_LEN as u64)? {
82 Some(bytes) => parse_header(bytes).ok(),
83 None => None,
84 };
85 let mut record_len = None;
86 if let Some(header) = header
87 && let Some(bytes) = window.bytes(offset, header.unpadded_len())?
88 && let Ok(record) = check(bytes)
89 {
90 visit(offset, &record);
91 record_len = Some(record.header.record_len());
92 }
93 match record_len {
94 Some(record_len) => {
95 scan.records += 1;
96 offset += record_len;
97 }
98 None => {
99 let step = ALIGN.min(len - offset);
100 scan.junk += step;
101 offset += step;
102 }
103 }
104 }
105 Ok(scan)
106}
107
108/// Whether a valid record matching `entry` is where the entry says.
109pub(crate) fn matches(window: &mut Window<'_>, entry: &Entry) -> io::Result<bool> {
110 let header = entry.header();
111 Ok(match window.bytes(entry.offset, header.unpadded_len())? {
112 Some(bytes) => {
113 matches!(check(bytes), Ok(found) if found.header == header && found.crc == entry.crc)
114 }
115 None => false,
116 })
117}
118
119#[cfg(test)]
120mod tests {
121 use std::fs::OpenOptions;
122
123 use braid_format::{Kind, ObjectId};
124
125 use super::*;
126 use crate::fsutil::write_all_at;
127 use crate::record::encode;
128
129 #[test]
130 fn finds_records_around_junk() {
131 let dir = tempfile::tempdir().unwrap();
132 let file = OpenOptions::new()
133 .read(true)
134 .write(true)
135 .create(true)
136 .truncate(true)
137 .open(dir.path().join("s"))
138 .unwrap();
139 let payloads: Vec<Vec<u8>> = vec![
140 b"first".to_vec(),
141 b"second, a little longer and repeated ".repeat(10),
142 b"third".to_vec(),
143 ];
144 let records: Vec<_> = payloads
145 .iter()
146 .map(|p| encode(Kind::Blob, ObjectId::hash(Kind::Blob, p), p).unwrap())
147 .collect();
148
149 // first record, half of a record cut short, then the others.
150 let mut offset = 0u64;
151 let mut expected = Vec::new();
152 write_all_at(&file, &records[0].bytes, offset).unwrap();
153 expected.push(offset);
154 offset += records[0].bytes.len() as u64;
155 let torn = &records[1].bytes[..records[1].bytes.len() / 2];
156 write_all_at(&file, torn, offset).unwrap();
157 offset = crate::record::align(offset + torn.len() as u64);
158 for record in &records[1..] {
159 write_all_at(&file, &record.bytes, offset).unwrap();
160 expected.push(offset);
161 offset += record.bytes.len() as u64;
162 }
163
164 let mut seen = Vec::new();
165 let scan = scan(&file, offset, |at, record| {
166 seen.push((at, record.header.id))
167 })
168 .unwrap();
169 assert_eq!(scan.records, 3);
170 assert_eq!(seen.iter().map(|(at, _)| *at).collect::<Vec<_>>(), expected);
171 assert_eq!(
172 seen.iter().map(|(_, id)| *id).collect::<Vec<_>>(),
173 records.iter().map(|r| r.header.id).collect::<Vec<_>>()
174 );
175 assert_eq!(scan.junk, crate::record::align(torn.len() as u64));
176 }
177
178 #[test]
179 fn records_inside_payloads_are_not_scanned() {
180 // A blob that is itself a valid record, stored raw.
181 let inner_payload = b"inner";
182 let inner = encode(
183 Kind::Blob,
184 ObjectId::hash(Kind::Blob, inner_payload),
185 inner_payload,
186 )
187 .unwrap();
188 let mut outer_payload = vec![0u8; 4];
189 outer_payload.extend_from_slice(&inner.bytes);
190 let outer = encode(
191 Kind::Blob,
192 ObjectId::hash(Kind::Blob, &outer_payload),
193 &outer_payload,
194 )
195 .unwrap();
196
197 let dir = tempfile::tempdir().unwrap();
198 let file = OpenOptions::new()
199 .read(true)
200 .write(true)
201 .create(true)
202 .truncate(true)
203 .open(dir.path().join("s"))
204 .unwrap();
205 write_all_at(&file, &outer.bytes, 0).unwrap();
206 let mut ids = Vec::new();
207 let scan = scan(&file, outer.bytes.len() as u64, |_, record| {
208 ids.push(record.header.id)
209 })
210 .unwrap();
211 assert_eq!(ids, vec![outer.header.id]);
212 assert_eq!(scan.junk, 0);
213 }
214}