Skip to main content

rocketmq_store_api/
progress.rs

1// Copyright 2026 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Versioned progress contracts for rebuildable stores derived from the CommitLog.
16
17use crate::StoreContractViolation;
18
19/// Current on-disk version of [`DerivedCheckpoint`].
20pub const DERIVED_CHECKPOINT_FORMAT_VERSION: u16 = 1;
21
22/// Fixed byte length of the version-one derived checkpoint format.
23pub 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/// Stable owner of one independently rebuildable derived view.
29#[repr(u8)]
30#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
31pub enum DerivedEngine {
32    /// Represents the consume queue case.
33    ConsumeQueue = 1,
34    /// Represents the index case.
35    Index = 2,
36    /// Represents the rocks db case.
37    RocksDb = 3,
38    /// Represents the tiered case.
39    Tiered = 4,
40    /// Represents the compaction case.
41    Compaction = 5,
42    /// Reconciles final CommitLog timer facts into Extended Timeline receipts.
43    TimerCompletion = 6,
44}
45
46impl DerivedEngine {
47    /// Returns the stable metadata-file component for this engine.
48    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/// Stable idempotency key for one record read from the authoritative CommitLog.
73#[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    /// Creates a record identity after validating its half-open physical range.
82    ///
83    /// # Errors
84    ///
85    /// Returns [`StoreContractViolation`] when `length` is zero or the range overflows.
86    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    /// Returns the source generation that owns the physical offset namespace.
101    pub const fn source_epoch(self) -> u64 {
102        self.source_epoch
103    }
104
105    /// Returns the inclusive starting physical offset.
106    pub const fn physical_offset(self) -> u64 {
107        self.physical_offset
108    }
109
110    /// Returns the encoded record length.
111    pub const fn length(self) -> u32 {
112        self.length
113    }
114
115    /// Returns the exclusive physical end offset.
116    pub const fn end_offset(self) -> u64 {
117        self.physical_offset + self.length as u64
118    }
119}
120
121/// Exclusive CommitLog position durably completed by one derived engine.
122#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
123pub struct DerivedCursor {
124    source_epoch: u64,
125    next_offset: u64,
126}
127
128impl DerivedCursor {
129    /// Creates the initial cursor for one CommitLog source epoch.
130    pub const fn genesis(source_epoch: u64) -> Self {
131        Self {
132            source_epoch,
133            next_offset: 0,
134        }
135    }
136
137    /// Restores a cursor whose next record starts at `next_offset`.
138    pub const fn restore(source_epoch: u64, next_offset: u64) -> Self {
139        Self {
140            source_epoch,
141            next_offset,
142        }
143    }
144
145    /// Returns the source generation that owns this offset namespace.
146    pub const fn source_epoch(self) -> u64 {
147        self.source_epoch
148    }
149
150    /// Returns the exclusive durable cursor and next expected record offset.
151    pub const fn next_offset(self) -> u64 {
152        self.next_offset
153    }
154
155    /// Classifies a replayed record without mutating or persisting this cursor.
156    ///
157    /// # Errors
158    ///
159    /// Returns [`StoreContractViolation`] for a different source epoch, a physical gap, or a record
160    /// that only partially overlaps the committed prefix.
161    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/// Result of classifying a replayed record against a durable cursor.
196#[derive(Clone, Copy, Debug, PartialEq, Eq)]
197pub enum CursorAdvanceDisposition {
198    /// The full record is already within the committed prefix.
199    AlreadyCommitted,
200    /// The record is exactly contiguous and may be applied and committed.
201    Advance(CursorAdvance),
202}
203
204/// Prepared contiguous cursor transition. Creating this value does not imply persistence.
205#[derive(Clone, Copy, Debug, PartialEq, Eq)]
206pub struct CursorAdvance {
207    previous: DerivedCursor,
208    next: DerivedCursor,
209    record: DerivedRecordId,
210}
211
212impl CursorAdvance {
213    /// Returns the cursor that was durable before this transition.
214    pub const fn previous_cursor(self) -> DerivedCursor {
215        self.previous
216    }
217
218    /// Returns the cursor to publish only after durable metadata commit.
219    pub const fn next_cursor(self) -> DerivedCursor {
220        self.next
221    }
222
223    /// Returns the CommitLog identity covered by this transition.
224    pub const fn record(self) -> DerivedRecordId {
225        self.record
226    }
227}
228
229/// Bootstrap representation for migrating an owner that previously stored only an offset.
230///
231/// Version zero has no source epoch. A caller may upgrade it only while it can prove the owning
232/// CommitLog epoch out of band. New writers must persist [`DerivedCheckpoint`] instead.
233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234pub struct LegacyDerivedCursorV0 {
235    next_offset: u64,
236}
237
238impl LegacyDerivedCursorV0 {
239    /// Wraps a previously persisted exclusive physical offset.
240    pub const fn new(next_offset: u64) -> Self {
241        Self { next_offset }
242    }
243
244    /// Returns the legacy exclusive physical offset.
245    pub const fn next_offset(self) -> u64 {
246        self.next_offset
247    }
248}
249
250/// Versioned, payload-free durable metadata for one derived engine.
251#[derive(Clone, Copy, Debug, PartialEq, Eq)]
252pub struct DerivedCheckpoint {
253    engine: DerivedEngine,
254    cursor: DerivedCursor,
255}
256
257impl DerivedCheckpoint {
258    /// Creates the current checkpoint version for one engine.
259    pub const fn new(engine: DerivedEngine, cursor: DerivedCursor) -> Self {
260        Self { engine, cursor }
261    }
262
263    /// Upgrades a proven version-zero offset into the current epoch-aware contract.
264    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    /// Returns the durable format version emitted by [`Self::encode`].
269    pub const fn format_version(self) -> u16 {
270        DERIVED_CHECKPOINT_FORMAT_VERSION
271    }
272
273    /// Returns the sole engine allowed to own this metadata.
274    pub const fn engine(self) -> DerivedEngine {
275        self.engine
276    }
277
278    /// Returns the durable cursor contained in this checkpoint.
279    pub const fn cursor(self) -> DerivedCursor {
280        self.cursor
281    }
282
283    /// Encodes the fixed-size version-one checkpoint.
284    ///
285    /// The format contains magic, version, engine, source epoch, exclusive offset, and CRC32. It
286    /// intentionally contains no message payload, topic, queue, or second WAL record.
287    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    /// Decodes and validates one fixed-size checkpoint for `expected_engine`.
301    ///
302    /// # Errors
303    ///
304    /// Returns [`StoreContractViolation`] for a malformed, corrupted, unsupported, or
305    /// cross-engine checkpoint. Callers must fail readiness rather than guessing a cursor.
306    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}