1use crate::StoreContractViolation;
18
19pub const DERIVED_CHECKPOINT_FORMAT_VERSION: u16 = 1;
21
22pub const DERIVED_CHECKPOINT_ENCODED_LEN: usize = 32;
24
25const CHECKPOINT_MAGIC: [u8; 8] = *b"RMQDCUR\0";
26const CHECKSUM_OFFSET: usize = DERIVED_CHECKPOINT_ENCODED_LEN - 4;
27
28#[repr(u8)]
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
31pub enum DerivedEngine {
32 ConsumeQueue = 1,
34 Index = 2,
36 RocksDb = 3,
38 Tiered = 4,
40 Compaction = 5,
42 TimerCompletion = 6,
44}
45
46impl DerivedEngine {
47 pub const fn as_str(self) -> &'static str {
49 match self {
50 Self::ConsumeQueue => "consume_queue",
51 Self::Index => "index",
52 Self::RocksDb => "rocksdb",
53 Self::Tiered => "tiered",
54 Self::Compaction => "compaction",
55 Self::TimerCompletion => "timer_completion",
56 }
57 }
58
59 const fn from_code(code: u8) -> Option<Self> {
60 match code {
61 1 => Some(Self::ConsumeQueue),
62 2 => Some(Self::Index),
63 3 => Some(Self::RocksDb),
64 4 => Some(Self::Tiered),
65 5 => Some(Self::Compaction),
66 6 => Some(Self::TimerCompletion),
67 _ => None,
68 }
69 }
70}
71
72#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
74pub struct DerivedRecordId {
75 source_epoch: u64,
76 physical_offset: u64,
77 length: u32,
78}
79
80impl DerivedRecordId {
81 pub const fn try_new(source_epoch: u64, physical_offset: u64, length: u32) -> Result<Self, StoreContractViolation> {
87 if length == 0 {
88 return Err(StoreContractViolation::DerivedRecordEmpty);
89 }
90 if physical_offset.checked_add(length as u64).is_none() {
91 return Err(StoreContractViolation::DerivedRecordRangeOverflow);
92 }
93 Ok(Self {
94 source_epoch,
95 physical_offset,
96 length,
97 })
98 }
99
100 pub const fn source_epoch(self) -> u64 {
102 self.source_epoch
103 }
104
105 pub const fn physical_offset(self) -> u64 {
107 self.physical_offset
108 }
109
110 pub const fn length(self) -> u32 {
112 self.length
113 }
114
115 pub const fn end_offset(self) -> u64 {
117 self.physical_offset + self.length as u64
118 }
119}
120
121#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
123pub struct DerivedCursor {
124 source_epoch: u64,
125 next_offset: u64,
126}
127
128impl DerivedCursor {
129 pub const fn genesis(source_epoch: u64) -> Self {
131 Self {
132 source_epoch,
133 next_offset: 0,
134 }
135 }
136
137 pub const fn restore(source_epoch: u64, next_offset: u64) -> Self {
139 Self {
140 source_epoch,
141 next_offset,
142 }
143 }
144
145 pub const fn source_epoch(self) -> u64 {
147 self.source_epoch
148 }
149
150 pub const fn next_offset(self) -> u64 {
152 self.next_offset
153 }
154
155 pub const fn prepare(self, record: DerivedRecordId) -> Result<CursorAdvanceDisposition, StoreContractViolation> {
162 if record.source_epoch != self.source_epoch {
163 return Err(StoreContractViolation::DerivedCursorSourceEpochMismatch {
164 expected: self.source_epoch,
165 actual: record.source_epoch,
166 });
167 }
168
169 let record_end = record.end_offset();
170 if record_end <= self.next_offset {
171 return Ok(CursorAdvanceDisposition::AlreadyCommitted);
172 }
173 if record.physical_offset < self.next_offset {
174 return Err(StoreContractViolation::DerivedCursorPartialOverlap {
175 committed: self.next_offset,
176 record_start: record.physical_offset,
177 record_end,
178 });
179 }
180 if record.physical_offset > self.next_offset {
181 return Err(StoreContractViolation::DerivedCursorGap {
182 expected: self.next_offset,
183 actual: record.physical_offset,
184 });
185 }
186
187 Ok(CursorAdvanceDisposition::Advance(CursorAdvance {
188 previous: self,
189 next: Self::restore(self.source_epoch, record_end),
190 record,
191 }))
192 }
193}
194
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
197pub enum CursorAdvanceDisposition {
198 AlreadyCommitted,
200 Advance(CursorAdvance),
202}
203
204#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub struct CursorAdvance {
207 previous: DerivedCursor,
208 next: DerivedCursor,
209 record: DerivedRecordId,
210}
211
212impl CursorAdvance {
213 pub const fn previous_cursor(self) -> DerivedCursor {
215 self.previous
216 }
217
218 pub const fn next_cursor(self) -> DerivedCursor {
220 self.next
221 }
222
223 pub const fn record(self) -> DerivedRecordId {
225 self.record
226 }
227}
228
229#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234pub struct LegacyDerivedCursorV0 {
235 next_offset: u64,
236}
237
238impl LegacyDerivedCursorV0 {
239 pub const fn new(next_offset: u64) -> Self {
241 Self { next_offset }
242 }
243
244 pub const fn next_offset(self) -> u64 {
246 self.next_offset
247 }
248}
249
250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
252pub struct DerivedCheckpoint {
253 engine: DerivedEngine,
254 cursor: DerivedCursor,
255}
256
257impl DerivedCheckpoint {
258 pub const fn new(engine: DerivedEngine, cursor: DerivedCursor) -> Self {
260 Self { engine, cursor }
261 }
262
263 pub const fn upgrade_legacy(engine: DerivedEngine, source_epoch: u64, legacy: LegacyDerivedCursorV0) -> Self {
265 Self::new(engine, DerivedCursor::restore(source_epoch, legacy.next_offset))
266 }
267
268 pub const fn format_version(self) -> u16 {
270 DERIVED_CHECKPOINT_FORMAT_VERSION
271 }
272
273 pub const fn engine(self) -> DerivedEngine {
275 self.engine
276 }
277
278 pub const fn cursor(self) -> DerivedCursor {
280 self.cursor
281 }
282
283 pub fn encode(self) -> [u8; DERIVED_CHECKPOINT_ENCODED_LEN] {
288 let mut encoded = [0_u8; DERIVED_CHECKPOINT_ENCODED_LEN];
289 encoded[..8].copy_from_slice(&CHECKPOINT_MAGIC);
290 encoded[8..10].copy_from_slice(&DERIVED_CHECKPOINT_FORMAT_VERSION.to_be_bytes());
291 encoded[10] = self.engine as u8;
292 encoded[11] = 0;
293 encoded[12..20].copy_from_slice(&self.cursor.source_epoch.to_be_bytes());
294 encoded[20..28].copy_from_slice(&self.cursor.next_offset.to_be_bytes());
295 let checksum = crc32(&encoded[..CHECKSUM_OFFSET]);
296 encoded[CHECKSUM_OFFSET..].copy_from_slice(&checksum.to_be_bytes());
297 encoded
298 }
299
300 pub fn decode(encoded: &[u8], expected_engine: DerivedEngine) -> Result<Self, StoreContractViolation> {
307 if encoded.len() != DERIVED_CHECKPOINT_ENCODED_LEN {
308 return Err(StoreContractViolation::DerivedCheckpointInvalidLength {
309 expected: DERIVED_CHECKPOINT_ENCODED_LEN,
310 actual: encoded.len(),
311 });
312 }
313 if encoded[..8] != CHECKPOINT_MAGIC {
314 return Err(StoreContractViolation::DerivedCheckpointInvalidMagic);
315 }
316
317 let version = u16::from_be_bytes([encoded[8], encoded[9]]);
318 if version != DERIVED_CHECKPOINT_FORMAT_VERSION {
319 return Err(StoreContractViolation::DerivedCheckpointUnsupportedVersion(version));
320 }
321 if encoded[11] != 0 {
322 return Err(StoreContractViolation::DerivedCheckpointInvalidReservedByte(
323 encoded[11],
324 ));
325 }
326
327 let engine = DerivedEngine::from_code(encoded[10])
328 .ok_or(StoreContractViolation::DerivedCheckpointUnknownEngine(encoded[10]))?;
329 if engine != expected_engine {
330 return Err(StoreContractViolation::DerivedCheckpointEngineMismatch {
331 expected: expected_engine,
332 actual: engine,
333 });
334 }
335
336 let expected_checksum = u32::from_be_bytes([
337 encoded[CHECKSUM_OFFSET],
338 encoded[CHECKSUM_OFFSET + 1],
339 encoded[CHECKSUM_OFFSET + 2],
340 encoded[CHECKSUM_OFFSET + 3],
341 ]);
342 let actual_checksum = crc32(&encoded[..CHECKSUM_OFFSET]);
343 if actual_checksum != expected_checksum {
344 return Err(StoreContractViolation::DerivedCheckpointChecksumMismatch);
345 }
346
347 let source_epoch = u64::from_be_bytes([
348 encoded[12],
349 encoded[13],
350 encoded[14],
351 encoded[15],
352 encoded[16],
353 encoded[17],
354 encoded[18],
355 encoded[19],
356 ]);
357 let next_offset = u64::from_be_bytes([
358 encoded[20],
359 encoded[21],
360 encoded[22],
361 encoded[23],
362 encoded[24],
363 encoded[25],
364 encoded[26],
365 encoded[27],
366 ]);
367 Ok(Self::new(engine, DerivedCursor::restore(source_epoch, next_offset)))
368 }
369}
370
371fn crc32(bytes: &[u8]) -> u32 {
372 let mut crc = u32::MAX;
373 for byte in bytes {
374 crc ^= u32::from(*byte);
375 for _ in 0..8 {
376 let mask = (crc & 1).wrapping_neg();
377 crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
378 }
379 }
380 !crc
381}