| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Journals: one fixed-size entry per record appended to an open segment, so |
| 5 | //! readers find new objects without reading payloads (format spec, section 7). |
| 6 | //! |
| 7 | //! ```text |
| 8 | //! [32] id | u64 offset | u32 stored_len | u8 kind | u8 codec | u16 0 |
| 9 | //! u64 raw_len | u32 record crc | u32 entry crc |
| 10 | //! ``` |
| 11 | //! |
| 12 | //! Each entry is 64 bytes, starts at a multiple of 64, and carries a CRC of |
| 13 | //! its first 60 bytes. The only writer is the segment's lease holder, which |
| 14 | //! writes an entry after the record it describes. An entry that fails its CRC |
| 15 | //! was cut short by a crash (or damaged) and is skipped. A new lease holder |
| 16 | //! resumes right after the last valid entry, overwriting any torn tail. |
| 17 | //! |
| 18 | //! An entry whose CRC holds but that names an object kind or a codec this |
| 19 | //! version does not know, or sets its reserved field, is not torn: a newer |
| 20 | //! version of braid wrote it. Reading such a journal fails, so that this |
| 21 | //! version never takes the segment over and writes over what it does not |
| 22 | //! understand. |
| 23 | |
| 24 | use std::fs::File; |
| 25 | use std::path::Path; |
| 26 | |
| 27 | use braid_format::{Kind, ObjectId}; |
| 28 | |
| 29 | use crate::error::{Error, io_error}; |
| 30 | use crate::fsutil::read_range; |
| 31 | use crate::record::{CODEC_CHUNKED, CODEC_MAX, CODEC_RAW, Header, array}; |
| 32 | |
| 33 | /// Why a journal slot or an index location holds no entry this version |
| 34 | /// can use. |
| 35 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 36 | pub(crate) enum Unusable { |
| 37 | /// Torn by a crash, or damaged: it fails its CRC, or holds values no |
| 38 | /// writer produces. |
| 39 | Invalid, |
| 40 | /// Whole, but it names an object kind or a codec this version does not |
| 41 | /// know, or sets its reserved field: a newer version of braid wrote it. |
| 42 | Newer, |
| 43 | } |
| 44 | |
| 45 | /// Bytes per journal entry. |
| 46 | pub(crate) const ENTRY_LEN: u64 = 64; |
| 47 | |
| 48 | /// Where a record is and what it holds. Journals and indexes store the same |
| 49 | /// fields. |
| 50 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 51 | pub(crate) struct Entry { |
| 52 | /// The object's id. |
| 53 | pub id: ObjectId, |
| 54 | /// Where the record starts in its segment. |
| 55 | pub offset: u64, |
| 56 | /// Bytes of payload in the record. |
| 57 | pub stored_len: u32, |
| 58 | /// What the object is. |
| 59 | pub kind: Kind, |
| 60 | /// How the payload is stored. |
| 61 | pub codec: u8, |
| 62 | /// Bytes of the object once decoded. |
| 63 | pub raw_len: u64, |
| 64 | /// The record's CRC. |
| 65 | pub crc: u32, |
| 66 | } |
| 67 | |
| 68 | impl Entry { |
| 69 | /// The entry for a record at `offset`. |
| 70 | pub fn new(offset: u64, header: &Header, crc: u32) -> Self { |
| 71 | Self { |
| 72 | id: header.id, |
| 73 | offset, |
| 74 | stored_len: header.stored_len, |
| 75 | kind: header.kind, |
| 76 | codec: header.codec, |
| 77 | raw_len: header.raw_len, |
| 78 | crc, |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /// The header the record must have. |
| 83 | pub fn header(&self) -> Header { |
| 84 | Header { |
| 85 | kind: self.kind, |
| 86 | codec: self.codec, |
| 87 | stored_len: self.stored_len, |
| 88 | raw_len: self.raw_len, |
| 89 | id: self.id, |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | /// Where the record ends, padding included. |
| 94 | pub fn end(&self) -> u64 { |
| 95 | self.offset + self.header().record_len() |
| 96 | } |
| 97 | |
| 98 | /// The 64 bytes of a journal entry. |
| 99 | pub fn encode(&self) -> [u8; ENTRY_LEN as usize] { |
| 100 | self.encode_in(0) |
| 101 | } |
| 102 | |
| 103 | /// The 64 bytes of an entry of a version 2 index: a journal entry whose |
| 104 | /// reserved field holds the number of its segment in the index. |
| 105 | pub fn encode_in(&self, segment: u16) -> [u8; ENTRY_LEN as usize] { |
| 106 | let mut out = [0u8; ENTRY_LEN as usize]; |
| 107 | out[0..32].copy_from_slice(self.id.as_bytes()); |
| 108 | out[32..40].copy_from_slice(&self.offset.to_le_bytes()); |
| 109 | out[40..44].copy_from_slice(&self.stored_len.to_le_bytes()); |
| 110 | out[44] = self.kind.code(); |
| 111 | out[45] = self.codec; |
| 112 | out[46..48].copy_from_slice(&segment.to_le_bytes()); |
| 113 | out[48..56].copy_from_slice(&self.raw_len.to_le_bytes()); |
| 114 | out[56..60].copy_from_slice(&self.crc.to_le_bytes()); |
| 115 | let entry_crc = crc32c::crc32c(&out[..60]); |
| 116 | out[60..64].copy_from_slice(&entry_crc.to_le_bytes()); |
| 117 | out |
| 118 | } |
| 119 | |
| 120 | /// Decodes a journal entry. |
| 121 | pub fn decode(bytes: &[u8]) -> Result<Self, Unusable> { |
| 122 | Self::check_crc(bytes)?; |
| 123 | Self::from_fields(&bytes[0..32], &bytes[32..60]) |
| 124 | } |
| 125 | |
| 126 | /// Decodes an entry of a version 2 index, and the number of its |
| 127 | /// segment in the index. |
| 128 | pub fn decode_in(bytes: &[u8]) -> Result<(Self, u16), Unusable> { |
| 129 | Self::check_crc(bytes)?; |
| 130 | let segment = u16::from_le_bytes(array(&bytes[46..48])); |
| 131 | let mut fields: [u8; 28] = array(&bytes[32..60]); |
| 132 | fields[14..16].fill(0); |
| 133 | Ok((Self::from_fields(&bytes[0..32], &fields)?, segment)) |
| 134 | } |
| 135 | |
| 136 | fn check_crc(bytes: &[u8]) -> Result<(), Unusable> { |
| 137 | if bytes.len() != ENTRY_LEN as usize |
| 138 | || crc32c::crc32c(&bytes[..60]) != u32::from_le_bytes(array(&bytes[60..64])) |
| 139 | { |
| 140 | return Err(Unusable::Invalid); |
| 141 | } |
| 142 | Ok(()) |
| 143 | } |
| 144 | |
| 145 | /// Builds an entry from an id and the 28 bytes that follow it in a journal |
| 146 | /// entry (`offset` to `record crc`), checking the values. |
| 147 | pub fn from_fields(id: &[u8], fields: &[u8]) -> Result<Self, Unusable> { |
| 148 | let codec = fields[13]; |
| 149 | if codec > CODEC_MAX || u16::from_le_bytes(array(&fields[14..16])) != 0 { |
| 150 | return Err(Unusable::Newer); |
| 151 | } |
| 152 | let entry = Self { |
| 153 | id: ObjectId::from_bytes(array(id)), |
| 154 | offset: u64::from_le_bytes(array(&fields[0..8])), |
| 155 | stored_len: u32::from_le_bytes(array(&fields[8..12])), |
| 156 | kind: Kind::from_code(fields[12]).ok_or(Unusable::Newer)?, |
| 157 | codec, |
| 158 | raw_len: u64::from_le_bytes(array(&fields[16..24])), |
| 159 | crc: u32::from_le_bytes(array(&fields[24..28])), |
| 160 | }; |
| 161 | let valid = (entry.codec != CODEC_RAW || entry.raw_len == u64::from(entry.stored_len)) |
| 162 | && (entry.codec != CODEC_CHUNKED || entry.kind == Kind::Blob) |
| 163 | && entry.offset.is_multiple_of(crate::record::ALIGN) |
| 164 | && entry |
| 165 | .offset |
| 166 | .checked_add(entry.header().record_len()) |
| 167 | .is_some(); |
| 168 | if valid { |
| 169 | Ok(entry) |
| 170 | } else { |
| 171 | Err(Unusable::Invalid) |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// The valid entries of a journal from some offset on. |
| 177 | #[derive(Debug, Default)] |
| 178 | pub(crate) struct Read { |
| 179 | /// Valid entries, in the order they were written. |
| 180 | pub entries: Vec<Entry>, |
| 181 | /// Where the entry after the last valid one starts: where reading resumes |
| 182 | /// next time, and where a new lease holder writes. |
| 183 | pub end: u64, |
| 184 | /// Slots that failed their CRC, partial slots included. |
| 185 | pub invalid: u64, |
| 186 | } |
| 187 | |
| 188 | /// Reads the entries of `file`, the journal at `path`, from `from`, a |
| 189 | /// multiple of 64, to its end. Fails with [`Error::NewerStore`] at the |
| 190 | /// first entry a newer version of braid wrote. |
| 191 | pub(crate) fn read(file: &File, from: u64, path: &Path) -> Result<Read, Error> { |
| 192 | let len = file.metadata().map_err(io_error("read", path))?.len(); |
| 193 | let mut read = Read { |
| 194 | end: from, |
| 195 | ..Read::default() |
| 196 | }; |
| 197 | if len <= from { |
| 198 | return Ok(read); |
| 199 | } |
| 200 | let bytes = read_range(file, from, len - from).map_err(io_error("read", path))?; |
| 201 | let mut pending_invalid = 0; |
| 202 | for (i, slot) in bytes.chunks(ENTRY_LEN as usize).enumerate() { |
| 203 | match Entry::decode(slot) { |
| 204 | Ok(entry) => { |
| 205 | read.entries.push(entry); |
| 206 | read.end = from + (i as u64 + 1) * ENTRY_LEN; |
| 207 | read.invalid += pending_invalid; |
| 208 | pending_invalid = 0; |
| 209 | } |
| 210 | Err(Unusable::Invalid) => pending_invalid += 1, |
| 211 | Err(Unusable::Newer) => { |
| 212 | return Err(Error::NewerStore { |
| 213 | path: path.to_path_buf(), |
| 214 | detail: format!( |
| 215 | "its entry at byte {} names an object kind or codec, or sets a \ |
| 216 | field, that this version does not know", |
| 217 | from + i as u64 * ENTRY_LEN |
| 218 | ), |
| 219 | }); |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | read.invalid += pending_invalid; |
| 224 | Ok(read) |
| 225 | } |
| 226 | |
| 227 | #[cfg(test)] |
| 228 | mod tests { |
| 229 | use std::fs::OpenOptions; |
| 230 | |
| 231 | use super::*; |
| 232 | use crate::fsutil::write_all_at; |
| 233 | use crate::record; |
| 234 | |
| 235 | fn entry(n: u8) -> Entry { |
| 236 | let payload = vec![n; usize::from(n) * 10]; |
| 237 | let id = ObjectId::hash(Kind::Blob, &payload); |
| 238 | let encoded = record::encode(Kind::Blob, id, &payload).unwrap(); |
| 239 | Entry::new(u64::from(n) * 1024, &encoded.header, encoded.crc) |
| 240 | } |
| 241 | |
| 242 | #[test] |
| 243 | fn round_trip() { |
| 244 | for n in 0..20 { |
| 245 | let entry = entry(n); |
| 246 | assert_eq!(Entry::decode(&entry.encode()), Ok(entry)); |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | /// Sets a byte of an entry and fixes its CRC, as a newer writer would |
| 251 | /// write it. |
| 252 | fn newer(at: usize, value: u8) -> [u8; 64] { |
| 253 | let mut bytes = entry(5).encode(); |
| 254 | bytes[at] = value; |
| 255 | let crc = crc32c::crc32c(&bytes[..60]); |
| 256 | bytes[60..64].copy_from_slice(&crc.to_le_bytes()); |
| 257 | bytes |
| 258 | } |
| 259 | |
| 260 | #[test] |
| 261 | fn entries_from_a_newer_version_stop_the_read() { |
| 262 | // An unknown codec, an unknown kind, the reserved field set. |
| 263 | for (at, value) in [(45, 5u8), (45, 0xff), (44, 9), (46, 1), (47, 0x80)] { |
| 264 | assert_eq!( |
| 265 | Entry::decode(&newer(at, value)), |
| 266 | Err(Unusable::Newer), |
| 267 | "byte {at}" |
| 268 | ); |
| 269 | } |
| 270 | // A whole entry with values no writer produces is damage, not news. |
| 271 | let mut misaligned = entry(5).encode(); |
| 272 | misaligned[32] = 3; |
| 273 | let crc = crc32c::crc32c(&misaligned[..60]); |
| 274 | misaligned[60..64].copy_from_slice(&crc.to_le_bytes()); |
| 275 | assert_eq!(Entry::decode(&misaligned), Err(Unusable::Invalid)); |
| 276 | |
| 277 | let dir = tempfile::tempdir().unwrap(); |
| 278 | let path = dir.path().join("j"); |
| 279 | let file = OpenOptions::new() |
| 280 | .read(true) |
| 281 | .write(true) |
| 282 | .create(true) |
| 283 | .truncate(true) |
| 284 | .open(&path) |
| 285 | .unwrap(); |
| 286 | write_all_at(&file, &entry(0).encode(), 0).unwrap(); |
| 287 | write_all_at(&file, &newer(45, 5), ENTRY_LEN).unwrap(); |
| 288 | let err = read(&file, 0, &path).unwrap_err(); |
| 289 | assert!(matches!(err, Error::NewerStore { .. }), "{err}"); |
| 290 | assert!(err.to_string().contains("byte 64"), "{err}"); |
| 291 | // From after it, the rest reads as usual. |
| 292 | assert!( |
| 293 | read(&file, 2 * ENTRY_LEN, &path) |
| 294 | .unwrap() |
| 295 | .entries |
| 296 | .is_empty() |
| 297 | ); |
| 298 | } |
| 299 | |
| 300 | #[test] |
| 301 | fn layout_matches_the_spec() { |
| 302 | let entry = entry(3); |
| 303 | let bytes = entry.encode(); |
| 304 | assert_eq!(&bytes[0..32], entry.id.as_bytes()); |
| 305 | assert_eq!(&bytes[32..40], &3072u64.to_le_bytes()); |
| 306 | assert_eq!(&bytes[40..44], &entry.stored_len.to_le_bytes()); |
| 307 | assert_eq!(bytes[44], 1); |
| 308 | assert_eq!(bytes[45], entry.codec); |
| 309 | assert_eq!(&bytes[46..48], &[0, 0]); |
| 310 | assert_eq!(&bytes[48..56], &30u64.to_le_bytes()); |
| 311 | assert_eq!(&bytes[56..60], &entry.crc.to_le_bytes()); |
| 312 | assert_eq!(&bytes[60..64], &crc32c::crc32c(&bytes[..60]).to_le_bytes()); |
| 313 | } |
| 314 | |
| 315 | #[test] |
| 316 | fn index_entries_carry_their_segment() { |
| 317 | let entry = entry(4); |
| 318 | let bytes = entry.encode_in(0x0102); |
| 319 | assert_eq!(&bytes[46..48], &[0x02, 0x01]); |
| 320 | assert_eq!(Entry::decode_in(&bytes), Ok((entry, 0x0102))); |
| 321 | // In a journal the field is reserved. |
| 322 | assert_eq!(Entry::decode(&bytes), Err(Unusable::Newer)); |
| 323 | assert_eq!(Entry::decode_in(&entry.encode()), Ok((entry, 0))); |
| 324 | let mut damaged = bytes; |
| 325 | damaged[47] ^= 1; |
| 326 | assert_eq!(Entry::decode_in(&damaged), Err(Unusable::Invalid)); |
| 327 | } |
| 328 | |
| 329 | #[test] |
| 330 | fn every_flipped_byte_is_caught() { |
| 331 | let bytes = entry(7).encode(); |
| 332 | for i in 0..bytes.len() { |
| 333 | let mut damaged = bytes; |
| 334 | damaged[i] ^= 0x40; |
| 335 | assert_eq!(Entry::decode(&damaged), Err(Unusable::Invalid), "byte {i}"); |
| 336 | } |
| 337 | assert_eq!(Entry::decode(&[0u8; 64]), Err(Unusable::Invalid)); |
| 338 | assert_eq!(Entry::decode(&bytes[..63]), Err(Unusable::Invalid)); |
| 339 | } |
| 340 | |
| 341 | #[test] |
| 342 | fn reading_skips_torn_and_damaged_slots() { |
| 343 | let dir = tempfile::tempdir().unwrap(); |
| 344 | let path = dir.path().join("j"); |
| 345 | let file = OpenOptions::new() |
| 346 | .read(true) |
| 347 | .write(true) |
| 348 | .create(true) |
| 349 | .truncate(true) |
| 350 | .open(&path) |
| 351 | .unwrap(); |
| 352 | for n in 0..4u8 { |
| 353 | write_all_at(&file, &entry(n).encode(), u64::from(n) * ENTRY_LEN).unwrap(); |
| 354 | } |
| 355 | // Damage the second entry, and leave half an entry at the end. |
| 356 | write_all_at(&file, &[0xff], ENTRY_LEN + 5).unwrap(); |
| 357 | write_all_at(&file, &entry(9).encode()[..30], 4 * ENTRY_LEN).unwrap(); |
| 358 | |
| 359 | let all = read(&file, 0, &path).unwrap(); |
| 360 | assert_eq!(all.entries, vec![entry(0), entry(2), entry(3)]); |
| 361 | assert_eq!(all.end, 4 * ENTRY_LEN); |
| 362 | assert_eq!(all.invalid, 2); |
| 363 | |
| 364 | let tail = read(&file, 3 * ENTRY_LEN, &path).unwrap(); |
| 365 | assert_eq!(tail.entries, vec![entry(3)]); |
| 366 | assert_eq!(tail.end, 4 * ENTRY_LEN); |
| 367 | |
| 368 | let nothing = read(&file, 4 * ENTRY_LEN, &path).unwrap(); |
| 369 | assert!(nothing.entries.is_empty()); |
| 370 | assert_eq!(nothing.end, 4 * ENTRY_LEN); |
| 371 | assert_eq!(nothing.invalid, 1); |
| 372 | } |
| 373 | } |