use crate::StoreContractViolation;
pub const DERIVED_CHECKPOINT_FORMAT_VERSION: u16 = 1;
pub const DERIVED_CHECKPOINT_ENCODED_LEN: usize = 32;
const CHECKPOINT_MAGIC: [u8; 8] = *b"RMQDCUR\0";
const CHECKSUM_OFFSET: usize = DERIVED_CHECKPOINT_ENCODED_LEN - 4;
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum DerivedEngine {
ConsumeQueue = 1,
Index = 2,
RocksDb = 3,
Tiered = 4,
Compaction = 5,
TimerCompletion = 6,
}
impl DerivedEngine {
pub const fn as_str(self) -> &'static str {
match self {
Self::ConsumeQueue => "consume_queue",
Self::Index => "index",
Self::RocksDb => "rocksdb",
Self::Tiered => "tiered",
Self::Compaction => "compaction",
Self::TimerCompletion => "timer_completion",
}
}
const fn from_code(code: u8) -> Option<Self> {
match code {
1 => Some(Self::ConsumeQueue),
2 => Some(Self::Index),
3 => Some(Self::RocksDb),
4 => Some(Self::Tiered),
5 => Some(Self::Compaction),
6 => Some(Self::TimerCompletion),
_ => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DerivedRecordId {
source_epoch: u64,
physical_offset: u64,
length: u32,
}
impl DerivedRecordId {
pub const fn try_new(source_epoch: u64, physical_offset: u64, length: u32) -> Result<Self, StoreContractViolation> {
if length == 0 {
return Err(StoreContractViolation::DerivedRecordEmpty);
}
if physical_offset.checked_add(length as u64).is_none() {
return Err(StoreContractViolation::DerivedRecordRangeOverflow);
}
Ok(Self {
source_epoch,
physical_offset,
length,
})
}
pub const fn source_epoch(self) -> u64 {
self.source_epoch
}
pub const fn physical_offset(self) -> u64 {
self.physical_offset
}
pub const fn length(self) -> u32 {
self.length
}
pub const fn end_offset(self) -> u64 {
self.physical_offset + self.length as u64
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DerivedCursor {
source_epoch: u64,
next_offset: u64,
}
impl DerivedCursor {
pub const fn genesis(source_epoch: u64) -> Self {
Self {
source_epoch,
next_offset: 0,
}
}
pub const fn restore(source_epoch: u64, next_offset: u64) -> Self {
Self {
source_epoch,
next_offset,
}
}
pub const fn source_epoch(self) -> u64 {
self.source_epoch
}
pub const fn next_offset(self) -> u64 {
self.next_offset
}
pub const fn prepare(self, record: DerivedRecordId) -> Result<CursorAdvanceDisposition, StoreContractViolation> {
if record.source_epoch != self.source_epoch {
return Err(StoreContractViolation::DerivedCursorSourceEpochMismatch {
expected: self.source_epoch,
actual: record.source_epoch,
});
}
let record_end = record.end_offset();
if record_end <= self.next_offset {
return Ok(CursorAdvanceDisposition::AlreadyCommitted);
}
if record.physical_offset < self.next_offset {
return Err(StoreContractViolation::DerivedCursorPartialOverlap {
committed: self.next_offset,
record_start: record.physical_offset,
record_end,
});
}
if record.physical_offset > self.next_offset {
return Err(StoreContractViolation::DerivedCursorGap {
expected: self.next_offset,
actual: record.physical_offset,
});
}
Ok(CursorAdvanceDisposition::Advance(CursorAdvance {
previous: self,
next: Self::restore(self.source_epoch, record_end),
record,
}))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CursorAdvanceDisposition {
AlreadyCommitted,
Advance(CursorAdvance),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CursorAdvance {
previous: DerivedCursor,
next: DerivedCursor,
record: DerivedRecordId,
}
impl CursorAdvance {
pub const fn previous_cursor(self) -> DerivedCursor {
self.previous
}
pub const fn next_cursor(self) -> DerivedCursor {
self.next
}
pub const fn record(self) -> DerivedRecordId {
self.record
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LegacyDerivedCursorV0 {
next_offset: u64,
}
impl LegacyDerivedCursorV0 {
pub const fn new(next_offset: u64) -> Self {
Self { next_offset }
}
pub const fn next_offset(self) -> u64 {
self.next_offset
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DerivedCheckpoint {
engine: DerivedEngine,
cursor: DerivedCursor,
}
impl DerivedCheckpoint {
pub const fn new(engine: DerivedEngine, cursor: DerivedCursor) -> Self {
Self { engine, cursor }
}
pub const fn upgrade_legacy(engine: DerivedEngine, source_epoch: u64, legacy: LegacyDerivedCursorV0) -> Self {
Self::new(engine, DerivedCursor::restore(source_epoch, legacy.next_offset))
}
pub const fn format_version(self) -> u16 {
DERIVED_CHECKPOINT_FORMAT_VERSION
}
pub const fn engine(self) -> DerivedEngine {
self.engine
}
pub const fn cursor(self) -> DerivedCursor {
self.cursor
}
pub fn encode(self) -> [u8; DERIVED_CHECKPOINT_ENCODED_LEN] {
let mut encoded = [0_u8; DERIVED_CHECKPOINT_ENCODED_LEN];
encoded[..8].copy_from_slice(&CHECKPOINT_MAGIC);
encoded[8..10].copy_from_slice(&DERIVED_CHECKPOINT_FORMAT_VERSION.to_be_bytes());
encoded[10] = self.engine as u8;
encoded[11] = 0;
encoded[12..20].copy_from_slice(&self.cursor.source_epoch.to_be_bytes());
encoded[20..28].copy_from_slice(&self.cursor.next_offset.to_be_bytes());
let checksum = crc32(&encoded[..CHECKSUM_OFFSET]);
encoded[CHECKSUM_OFFSET..].copy_from_slice(&checksum.to_be_bytes());
encoded
}
pub fn decode(encoded: &[u8], expected_engine: DerivedEngine) -> Result<Self, StoreContractViolation> {
if encoded.len() != DERIVED_CHECKPOINT_ENCODED_LEN {
return Err(StoreContractViolation::DerivedCheckpointInvalidLength {
expected: DERIVED_CHECKPOINT_ENCODED_LEN,
actual: encoded.len(),
});
}
if encoded[..8] != CHECKPOINT_MAGIC {
return Err(StoreContractViolation::DerivedCheckpointInvalidMagic);
}
let version = u16::from_be_bytes([encoded[8], encoded[9]]);
if version != DERIVED_CHECKPOINT_FORMAT_VERSION {
return Err(StoreContractViolation::DerivedCheckpointUnsupportedVersion(version));
}
if encoded[11] != 0 {
return Err(StoreContractViolation::DerivedCheckpointInvalidReservedByte(
encoded[11],
));
}
let engine = DerivedEngine::from_code(encoded[10])
.ok_or(StoreContractViolation::DerivedCheckpointUnknownEngine(encoded[10]))?;
if engine != expected_engine {
return Err(StoreContractViolation::DerivedCheckpointEngineMismatch {
expected: expected_engine,
actual: engine,
});
}
let expected_checksum = u32::from_be_bytes([
encoded[CHECKSUM_OFFSET],
encoded[CHECKSUM_OFFSET + 1],
encoded[CHECKSUM_OFFSET + 2],
encoded[CHECKSUM_OFFSET + 3],
]);
let actual_checksum = crc32(&encoded[..CHECKSUM_OFFSET]);
if actual_checksum != expected_checksum {
return Err(StoreContractViolation::DerivedCheckpointChecksumMismatch);
}
let source_epoch = u64::from_be_bytes([
encoded[12],
encoded[13],
encoded[14],
encoded[15],
encoded[16],
encoded[17],
encoded[18],
encoded[19],
]);
let next_offset = u64::from_be_bytes([
encoded[20],
encoded[21],
encoded[22],
encoded[23],
encoded[24],
encoded[25],
encoded[26],
encoded[27],
]);
Ok(Self::new(engine, DerivedCursor::restore(source_epoch, next_offset)))
}
}
fn crc32(bytes: &[u8]) -> u32 {
let mut crc = u32::MAX;
for byte in bytes {
crc ^= u32::from(*byte);
for _ in 0..8 {
let mask = (crc & 1).wrapping_neg();
crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
}
}
!crc
}