1use zerocopy::{
26 FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned,
27 little_endian::{U32, U64},
28};
29
30use crate::db::LogPosition;
31use crate::error::Error;
32use crate::sector::LogId;
33
34pub const SPOOL_CURSOR_MAGIC: [u8; 4] = *b"SPC1";
36
37pub const SPOOL_CURSOR_VERSION: u8 = 1;
39
40pub const CURSOR_RECORD_SIZE: usize = 60;
42
43const CURSOR_CRC_COVERAGE: usize = CURSOR_RECORD_SIZE - 4;
45
46pub const CURSOR_SECTORS: u8 = 2;
49
50const CURSOR_CRC: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISCSI);
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57#[cfg_attr(feature = "defmt", derive(defmt::Format))]
58pub enum CursorKind {
59 Intent,
61 Commit,
63}
64
65pub const CURSOR_KIND_INTENT: u8 = 0xA1;
67pub const CURSOR_KIND_COMMIT: u8 = 0xC0;
69
70impl CursorKind {
71 fn from_raw(raw: u8) -> Option<Self> {
72 match raw {
73 CURSOR_KIND_INTENT => Some(Self::Intent),
74 CURSOR_KIND_COMMIT => Some(Self::Commit),
75 _ => None,
76 }
77 }
78
79 fn to_raw(self) -> u8 {
80 match self {
81 Self::Intent => CURSOR_KIND_INTENT,
82 Self::Commit => CURSOR_KIND_COMMIT,
83 }
84 }
85}
86
87#[derive(FromBytes, IntoBytes, KnownLayout, Immutable, Unaligned, Clone, Copy)]
94#[repr(C, packed)]
95pub struct SpoolCursorWire {
96 pub magic: [u8; 4],
98 pub version: u8,
100 pub kind: u8,
102 pub reserved: [u8; 2],
104 pub source_log_id: U32,
106 pub source_epoch: U32,
112 pub batch_id: U32,
121 pub from_sequence: U32,
123 pub from_offset: U32,
125 pub upto_sequence: U32,
127 pub upto_offset: U32,
129 pub entry_count: U32,
131 pub dest_sequence: U32,
133 pub dest_offset: U32,
135 pub last_timestamp: U64,
137 pub record_crc: U32,
139}
140
141impl SpoolCursorWire {
142 #[allow(clippy::too_many_arguments)]
144 pub fn new(
145 kind: CursorKind,
146 source_log_id: Option<LogId>,
147 source_epoch: u32,
148 batch_id: u32,
149 from: LogPosition,
150 upto: LogPosition,
151 entry_count: u32,
152 dest: LogPosition,
153 last_timestamp: u64,
154 ) -> Self {
155 let mut record = Self {
156 magic: SPOOL_CURSOR_MAGIC,
157 version: SPOOL_CURSOR_VERSION,
158 kind: kind.to_raw(),
159 reserved: [0; 2],
160 source_log_id: U32::new(source_log_id.map_or(0, LogId::get)),
161 source_epoch: U32::new(source_epoch),
162 batch_id: U32::new(batch_id),
163 from_sequence: U32::new(from.sequence),
164 from_offset: U32::new(from.offset),
165 upto_sequence: U32::new(upto.sequence),
166 upto_offset: U32::new(upto.offset),
167 entry_count: U32::new(entry_count),
168 dest_sequence: U32::new(dest.sequence),
169 dest_offset: U32::new(dest.offset),
170 last_timestamp: U64::new(last_timestamp),
171 record_crc: U32::new(0),
172 };
173 record.record_crc = U32::new(record.compute_crc());
174 record
175 }
176
177 fn compute_crc(&self) -> u32 {
178 CURSOR_CRC.checksum(&self.as_bytes()[..CURSOR_CRC_COVERAGE])
179 }
180
181 pub fn is_valid(&self) -> bool {
183 self.magic == SPOOL_CURSOR_MAGIC
184 && self.version == SPOOL_CURSOR_VERSION
185 && CursorKind::from_raw(self.kind).is_some()
186 && self.record_crc.get() == self.compute_crc()
187 }
188
189 pub fn kind(&self) -> Option<CursorKind> {
191 CursorKind::from_raw(self.kind)
192 }
193
194 pub fn from(&self) -> LogPosition {
196 LogPosition {
197 sequence: self.from_sequence.get(),
198 offset: self.from_offset.get(),
199 }
200 }
201
202 pub fn upto(&self) -> LogPosition {
204 LogPosition {
205 sequence: self.upto_sequence.get(),
206 offset: self.upto_offset.get(),
207 }
208 }
209
210 pub fn dest(&self) -> LogPosition {
212 LogPosition {
213 sequence: self.dest_sequence.get(),
214 offset: self.dest_offset.get(),
215 }
216 }
217
218 pub fn resume_point(&self) -> LogPosition {
229 match self.kind() {
230 Some(CursorKind::Commit) => self.upto(),
231 _ => self.from(),
232 }
233 }
234}
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
241#[cfg_attr(feature = "defmt", derive(defmt::Format))]
242pub struct CursorRegion {
243 base: u32,
244 sector_size: u32,
245 page_size: u32,
246}
247
248impl CursorRegion {
249 pub fn new(base: u32, sector_size: u32, page_size: u32) -> Result<Self, Error> {
256 if page_size < CURSOR_RECORD_SIZE as u32
257 || sector_size == 0
258 || page_size == 0
259 || !sector_size.is_multiple_of(page_size)
260 || sector_size / page_size < 2
261 {
262 return Err(Error::InvalidConfig);
263 }
264 let span = sector_size
265 .checked_mul(CURSOR_SECTORS as u32)
266 .ok_or(Error::Overflow)?;
267 base.checked_add(span).ok_or(Error::Overflow)?;
268 Ok(Self {
269 base,
270 sector_size,
271 page_size,
272 })
273 }
274
275 pub fn slots_per_sector(&self) -> u32 {
277 self.sector_size / self.page_size
278 }
279
280 pub fn total_size(&self) -> u32 {
282 self.sector_size * CURSOR_SECTORS as u32
283 }
284
285 pub fn base(&self) -> u32 {
287 self.base
288 }
289
290 pub fn end(&self) -> u32 {
292 self.base + self.total_size()
293 }
294
295 pub fn sector_offset(&self, sector: u8) -> u32 {
302 (sector % CURSOR_SECTORS) as u32 * self.sector_size
303 }
304
305 pub fn sector_range(&self, sector: u8) -> (u32, u32) {
313 let from = self.sector_offset(sector);
314 (from, from + self.sector_size)
315 }
316
317 pub fn slot_offset(&self, sector: u8, slot: u32) -> u32 {
320 self.sector_offset(sector) + slot * self.page_size
321 }
322
323 pub fn slots(&self) -> impl Iterator<Item = SlotAddress> + '_ {
330 let region = *self;
331 (0..CURSOR_SECTORS).flat_map(move |sector| {
332 (0..region.slots_per_sector()).map(move |slot| SlotAddress {
333 sector,
334 slot,
335 offset: region.slot_offset(sector, slot),
336 })
337 })
338 }
339}
340
341#[derive(Debug, Clone, Copy, PartialEq, Eq)]
343#[cfg_attr(feature = "defmt", derive(defmt::Format))]
344pub struct SlotAddress {
345 pub sector: u8,
347 pub slot: u32,
349 pub offset: u32,
351}
352
353#[cfg(test)]
354mod tests {
355 use super::*;
356
357 #[test]
358 fn record_size_matches_the_constant() {
359 assert_eq!(CURSOR_RECORD_SIZE, core::mem::size_of::<SpoolCursorWire>());
360 }
361
362 fn sample(kind: CursorKind) -> SpoolCursorWire {
363 SpoolCursorWire::new(
364 kind,
365 LogId::new(0xABCD),
366 7,
367 42,
368 LogPosition {
369 sequence: 3,
370 offset: 100,
371 },
372 LogPosition {
373 sequence: 3,
374 offset: 500,
375 },
376 17,
377 LogPosition {
378 sequence: 9,
379 offset: 28,
380 },
381 123_456,
382 )
383 }
384
385 #[test]
386 fn round_trips_through_bytes() {
387 let record = sample(CursorKind::Commit);
388 let bytes = record.as_bytes().to_vec();
389 let parsed = SpoolCursorWire::read_from_bytes(&bytes).unwrap();
390 assert!(parsed.is_valid());
391 assert_eq!(parsed.kind(), Some(CursorKind::Commit));
392 assert_eq!(parsed.batch_id.get(), 42);
393 assert_eq!(parsed.source_epoch.get(), 7);
394 assert_eq!(parsed.from().offset, 100);
395 assert_eq!(parsed.upto().offset, 500);
396 assert_eq!(parsed.dest().sequence, 9);
397 assert_eq!(parsed.last_timestamp.get(), 123_456);
398 }
399
400 #[test]
401 fn a_single_flipped_bit_fails_the_crc() {
402 let record = sample(CursorKind::Commit);
403 let mut bytes = record.as_bytes().to_vec();
404 bytes[20] ^= 0x01;
405 let parsed = SpoolCursorWire::read_from_bytes(&bytes).unwrap();
406 assert!(!parsed.is_valid(), "a torn record must not be trusted");
407 }
408
409 #[test]
410 fn an_erased_page_is_not_a_record() {
411 let bytes = [0xFFu8; CURSOR_RECORD_SIZE];
412 let parsed = SpoolCursorWire::read_from_bytes(&bytes).unwrap();
413 assert!(!parsed.is_valid());
414 assert_eq!(parsed.kind(), None);
415 }
416
417 #[test]
418 fn a_zeroed_page_is_not_a_record() {
419 let bytes = [0x00u8; CURSOR_RECORD_SIZE];
420 let parsed = SpoolCursorWire::read_from_bytes(&bytes).unwrap();
421 assert!(!parsed.is_valid());
422 }
423
424 #[test]
425 fn resume_point_trusts_commits_and_distrusts_intents() {
426 let commit = sample(CursorKind::Commit);
427 assert_eq!(commit.resume_point(), commit.upto());
428
429 let intent = sample(CursorKind::Intent);
430 assert_eq!(
431 intent.resume_point(),
432 intent.from(),
433 "an intent proves only where the batch started"
434 );
435 }
436
437 #[test]
438 fn region_rejects_geometry_that_cannot_hold_records() {
439 assert!(CursorRegion::new(0, 4096, 32).is_err());
441 assert!(CursorRegion::new(0, 4000, 256).is_err());
443 assert!(CursorRegion::new(0, 256, 256).is_err());
445 assert!(CursorRegion::new(u32::MAX - 1024, 4096, 256).is_err());
447 }
448
449 #[test]
450 fn region_addresses_are_laid_out_as_documented() {
451 let region = CursorRegion::new(0x1000, 4096, 256).unwrap();
452 assert_eq!(region.slots_per_sector(), 16);
453 assert_eq!(region.total_size(), 8192);
454 assert_eq!(region.base(), 0x1000);
455 assert_eq!(region.end(), 0x1000 + 8192);
456 assert_eq!(region.sector_offset(0), 0);
459 assert_eq!(region.sector_offset(1), 4096);
460 assert_eq!(region.slot_offset(0, 0), 0);
461 assert_eq!(region.slot_offset(0, 3), 3 * 256);
462 assert_eq!(region.slot_offset(1, 15), 4096 + 15 * 256);
463 assert!(region.base() + region.slot_offset(1, 15) < region.end());
465 }
466
467 #[test]
468 fn a_sector_range_covers_exactly_one_cursor_sector() {
469 let region = CursorRegion::new(0x1000, 4096, 256).unwrap();
470 assert_eq!(region.sector_range(0), (0, 4096));
471 assert_eq!(region.sector_range(1), (4096, 8192));
472 assert_eq!(region.sector_range(1).1, region.total_size());
475 }
476
477 #[test]
478 fn the_slot_iterator_visits_every_slot_once_in_address_order() {
479 let region = CursorRegion::new(0x1000, 4096, 256).unwrap();
480
481 let mut visited = 0u32;
482 let mut previous: Option<SlotAddress> = None;
483 for at in region.slots() {
484 assert_eq!(at.offset, region.slot_offset(at.sector, at.slot));
485 if let Some(before) = previous {
487 assert!(before.offset < at.offset);
488 }
489 previous = Some(at);
490 visited += 1;
491 }
492
493 assert_eq!(visited, 2 * region.slots_per_sector());
494 assert_eq!(
495 region.slots().next().unwrap(),
496 SlotAddress {
497 sector: 0,
498 slot: 0,
499 offset: 0
500 }
501 );
502 assert_eq!(
503 previous.unwrap(),
504 SlotAddress {
505 sector: 1,
506 slot: 15,
507 offset: 4096 + 15 * 256
508 }
509 );
510 }
511}