use rocketmq_error::STORAGE_IO_FAILED;
use rocketmq_error::STORAGE_REQUEST_INVALID;
use serde::Deserialize;
use serde::Serialize;
use sha2::Digest;
use sha2::Sha256;
use std::io::Read;
use std::path::Path;
use std::path::PathBuf;
use thiserror::Error;
use crate::StoreContractViolation;
use crate::StoreError;
use crate::StoreOperation;
pub const TIMER_SNAPSHOT_SCHEMA_VERSION: u16 = 1;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TimerTimelineIndexKind {
#[default]
RocksDb,
Segmented,
}
impl TimerTimelineIndexKind {
fn is_rocksdb(kind: &Self) -> bool {
*kind == Self::RocksDb
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimerSnapshotFile {
pub relative_path: String,
pub length: u64,
pub sha256: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimerSnapshotManifest {
pub schema_version: u16,
pub generation: u64,
pub source_cq_cursor: i64,
pub source_physical_cursor: i64,
pub due_time_cursor_ms: i64,
pub completion_physical_cursor: i64,
pub timeline_sequence: u64,
#[serde(default, skip_serializing_if = "TimerTimelineIndexKind::is_rocksdb")]
pub timeline_index_kind: TimerTimelineIndexKind,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub native_manifest_generation: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub native_durable_end: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub native_manifest_checksum: Option<u32>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub native_files: Vec<TimerSnapshotFile>,
pub role_epoch: u64,
pub activation_epoch: u64,
pub format_fingerprint: u64,
pub timeline_checkpoint_uri: String,
pub payload_files: Vec<TimerSnapshotFile>,
pub checksum: String,
}
impl TimerSnapshotManifest {
pub fn seal(&mut self) -> Result<(), StoreContractViolation> {
self.checksum = hex::encode(self.digest()?);
Ok(())
}
pub fn validate(&self) -> Result<(), StoreContractViolation> {
if self.schema_version != TIMER_SNAPSHOT_SCHEMA_VERSION {
return Err(StoreContractViolation::TimerSnapshotUnsupportedVersion(
self.schema_version,
));
}
match self.timeline_index_kind {
TimerTimelineIndexKind::RocksDb => {
if self.native_manifest_generation.is_some()
|| self.native_durable_end.is_some()
|| self.native_manifest_checksum.is_some()
|| !self.native_files.is_empty()
{
return Err(StoreContractViolation::TimerSnapshotInvalidNativeBinding);
}
}
TimerTimelineIndexKind::Segmented => {
if !matches!(self.native_manifest_generation, Some(value) if value > 0)
|| !matches!(self.native_durable_end, Some(value) if value > 0)
|| !matches!(self.native_manifest_checksum, Some(value) if value > 0)
|| self.native_files.is_empty()
{
return Err(StoreContractViolation::TimerSnapshotInvalidNativeBinding);
}
}
}
if self.generation == 0
|| self.source_cq_cursor < 0
|| self.source_physical_cursor < 0
|| self.due_time_cursor_ms < 0
|| self.completion_physical_cursor < 0
|| self.timeline_sequence == 0
|| self.role_epoch == 0
|| self.activation_epoch == 0
|| self.format_fingerprint == 0
|| self.timeline_checkpoint_uri.is_empty()
{
return Err(StoreContractViolation::TimerSnapshotInvalidMetadata);
}
for file in self.payload_files.iter().chain(&self.native_files) {
if file.relative_path.is_empty()
|| file.relative_path.starts_with('/')
|| file.relative_path.contains('\\')
|| file.relative_path.split('/').any(|component| {
component.is_empty() || component == "." || component == ".." || component.contains(':')
})
|| file.length == 0
|| file.sha256.len() != 64
|| !file.sha256.bytes().all(|byte| byte.is_ascii_hexdigit())
{
return Err(StoreContractViolation::TimerSnapshotInvalidFile);
}
}
let expected = hex::encode(self.digest()?);
if self.checksum != expected {
return Err(StoreContractViolation::TimerSnapshotChecksumMismatch);
}
Ok(())
}
pub fn validate_artifact_files(&self, artifact_root: impl AsRef<Path>) -> Result<(), StoreError> {
self.validate().map_err(snapshot_contract)?;
let root = artifact_root.as_ref();
for expected in self.payload_files.iter().chain(&self.native_files) {
let path = expected
.relative_path
.split('/')
.fold(root.to_path_buf(), |path, component| path.join(component));
let mut file = std::fs::File::open(&path)
.map_err(|source| snapshot_io("open timer snapshot artifact", &path, source))?;
if file
.metadata()
.map_err(|source| snapshot_io("inspect timer snapshot artifact", &path, source))?
.len()
!= expected.length
{
return Err(snapshot_contract(
StoreContractViolation::TimerSnapshotArtifactDigestMismatch,
));
}
let mut hasher = Sha256::new();
let mut remaining = expected.length;
let mut buffer = [0u8; 64 * 1024];
while remaining > 0 {
let chunk = usize::try_from(remaining.min(buffer.len() as u64)).unwrap_or(buffer.len());
file.read_exact(&mut buffer[..chunk])
.map_err(|source| snapshot_io("read timer snapshot artifact", &path, source))?;
hasher.update(&buffer[..chunk]);
remaining -= u64::try_from(chunk)
.map_err(|_| snapshot_contract(StoreContractViolation::TimerSnapshotInvalidMetadata))?;
}
if hex::encode(hasher.finalize()) != expected.sha256 {
return Err(snapshot_contract(
StoreContractViolation::TimerSnapshotArtifactDigestMismatch,
));
}
}
Ok(())
}
fn digest(&self) -> Result<[u8; 32], StoreContractViolation> {
let mut hasher = Sha256::new();
hasher.update(self.schema_version.to_be_bytes());
hasher.update(self.generation.to_be_bytes());
hasher.update(self.source_cq_cursor.to_be_bytes());
hasher.update(self.source_physical_cursor.to_be_bytes());
hasher.update(self.due_time_cursor_ms.to_be_bytes());
hasher.update(self.completion_physical_cursor.to_be_bytes());
hasher.update(self.timeline_sequence.to_be_bytes());
if self.timeline_index_kind == TimerTimelineIndexKind::Segmented {
hasher.update(b"segmented-timeline-v1");
hasher.update(self.native_manifest_generation.unwrap_or_default().to_be_bytes());
hasher.update(self.native_durable_end.unwrap_or_default().to_be_bytes());
hasher.update(self.native_manifest_checksum.unwrap_or_default().to_be_bytes());
update_files(&mut hasher, &self.native_files)?;
}
hasher.update(self.role_epoch.to_be_bytes());
hasher.update(self.activation_epoch.to_be_bytes());
hasher.update(self.format_fingerprint.to_be_bytes());
update_text(&mut hasher, &self.timeline_checkpoint_uri)?;
update_files(&mut hasher, &self.payload_files)?;
Ok(hasher.finalize().into())
}
}
fn update_files(hasher: &mut Sha256, files: &[TimerSnapshotFile]) -> Result<(), StoreContractViolation> {
let file_count = u32::try_from(files.len()).map_err(|_| StoreContractViolation::TimerSnapshotInvalidMetadata)?;
hasher.update(file_count.to_be_bytes());
for file in files {
update_text(hasher, &file.relative_path)?;
hasher.update(file.length.to_be_bytes());
update_text(hasher, &file.sha256)?;
}
Ok(())
}
fn update_text(hasher: &mut Sha256, value: &str) -> Result<(), StoreContractViolation> {
let length = u32::try_from(value.len()).map_err(|_| StoreContractViolation::TimerSnapshotInvalidMetadata)?;
hasher.update(length.to_be_bytes());
hasher.update(value.as_bytes());
Ok(())
}
#[derive(Debug, Error)]
#[error("{operation} failed for {path}: {source}")]
struct TimerSnapshotIoError {
operation: &'static str,
path: PathBuf,
#[source]
source: std::io::Error,
}
fn snapshot_contract(source: StoreContractViolation) -> StoreError {
StoreError::new(&STORAGE_REQUEST_INVALID, StoreOperation::Read).with_source(source)
}
fn snapshot_io(operation: &'static str, path: &Path, source: std::io::Error) -> StoreError {
StoreError::new(&STORAGE_IO_FAILED, StoreOperation::Read).with_source(TimerSnapshotIoError {
operation,
path: path.to_path_buf(),
source,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn manifest() -> TimerSnapshotManifest {
let mut manifest = TimerSnapshotManifest {
schema_version: TIMER_SNAPSHOT_SCHEMA_VERSION,
generation: 3,
source_cq_cursor: 10,
source_physical_cursor: 1_024,
due_time_cursor_ms: 1_800_000_000_000,
completion_physical_cursor: 2_048,
timeline_sequence: 9,
timeline_index_kind: TimerTimelineIndexKind::RocksDb,
native_manifest_generation: None,
native_durable_end: None,
native_manifest_checksum: None,
native_files: Vec::new(),
role_epoch: 5,
activation_epoch: 2,
format_fingerprint: 7,
timeline_checkpoint_uri: "file:///timer/snapshot/timeline".to_owned(),
payload_files: vec![TimerSnapshotFile {
relative_path: "payload/day-0000000001/lane-00000/00000000000000000000".to_owned(),
length: 128,
sha256: "ab".repeat(32),
}],
checksum: String::new(),
};
manifest.seal().unwrap();
manifest
}
#[test]
fn manifest_round_trips_and_detects_cursor_damage() {
let manifest = manifest();
manifest.validate().unwrap();
let encoded = serde_json::to_vec(&manifest).unwrap();
let mut decoded: TimerSnapshotManifest = serde_json::from_slice(&encoded).unwrap();
assert_eq!(decoded, manifest);
decoded.completion_physical_cursor += 1;
assert_eq!(
decoded.validate(),
Err(StoreContractViolation::TimerSnapshotChecksumMismatch)
);
}
#[test]
fn manifest_rejects_platform_specific_path_escape() {
let mut manifest = manifest();
manifest.payload_files[0].relative_path = "payload\\..\\outside".to_owned();
manifest.seal().unwrap();
assert_eq!(
manifest.validate(),
Err(StoreContractViolation::TimerSnapshotInvalidFile)
);
}
}