Skip to main content

rocketmq_store_api/
timer_snapshot.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
15use rocketmq_error::STORAGE_IO_FAILED;
16use rocketmq_error::STORAGE_REQUEST_INVALID;
17use serde::Deserialize;
18use serde::Serialize;
19use sha2::Digest;
20use sha2::Sha256;
21use std::io::Read;
22use std::path::Path;
23use std::path::PathBuf;
24use thiserror::Error;
25
26use crate::StoreContractViolation;
27use crate::StoreError;
28use crate::StoreOperation;
29
30/// Current Extended Timeline snapshot manifest schema.
31pub const TIMER_SNAPSHOT_SCHEMA_VERSION: u16 = 1;
32
33/// Persistent owner of the large ordered Timeline index. The RocksDB overlay remains present for
34/// state, ready, receipt, and checkpoints in both modes.
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "snake_case")]
37pub enum TimerTimelineIndexKind {
38    /// Ordered Timeline records live in the dedicated RocksDB Timeline CF.
39    #[default]
40    RocksDb,
41    /// Ordered Timeline records live in immutable native runs.
42    Segmented,
43}
44
45impl TimerTimelineIndexKind {
46    fn is_rocksdb(kind: &Self) -> bool {
47        *kind == Self::RocksDb
48    }
49}
50
51/// One immutable file included in an Extended Timeline snapshot.
52#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
53pub struct TimerSnapshotFile {
54    /// Slash-separated path relative to the snapshot artifact root.
55    pub relative_path: String,
56    /// Exact copied length. Appended bytes beyond this length are not part of the snapshot.
57    pub length: u64,
58    /// Lower-case SHA-256 of exactly `length` bytes.
59    pub sha256: String,
60}
61
62/// Versioned handoff contract for Timeline, payload, and both replay streams.
63#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
64pub struct TimerSnapshotManifest {
65    /// Manifest schema version.
66    pub schema_version: u16,
67    /// Monotonic snapshot generation shared by payload and Timeline pins.
68    pub generation: u64,
69    /// First Timer source CQ offset not represented by the snapshot.
70    pub source_cq_cursor: i64,
71    /// First source CommitLog byte not represented by the snapshot.
72    pub source_physical_cursor: i64,
73    /// Conservative due-time cursor represented by the Timeline checkpoint.
74    pub due_time_cursor_ms: i64,
75    /// First final CommitLog byte whose completion fact must be replayed.
76    pub completion_physical_cursor: i64,
77    /// RocksDB sequence captured by the Timeline checkpoint.
78    pub timeline_sequence: u64,
79    /// Durable owner of the large ordered Timeline index.
80    #[serde(default, skip_serializing_if = "TimerTimelineIndexKind::is_rocksdb")]
81    pub timeline_index_kind: TimerTimelineIndexKind,
82    /// Exact archived native manifest generation for a segmented snapshot.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub native_manifest_generation: Option<u64>,
85    /// Exact native durable end paired with `timeline_sequence`.
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub native_durable_end: Option<u64>,
88    /// CRC32C of the archived native manifest.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub native_manifest_checksum: Option<u32>,
91    /// Immutable native manifest and run files for a segmented snapshot.
92    #[serde(default, skip_serializing_if = "Vec::is_empty")]
93    pub native_files: Vec<TimerSnapshotFile>,
94    /// Durable delivery-owner epoch at snapshot creation.
95    pub role_epoch: u64,
96    /// Minimum admission epoch accepted by this Extended group.
97    pub activation_epoch: u64,
98    /// Persisted format/policy fingerprint.
99    pub format_fingerprint: u64,
100    /// Controlled artifact URI for the Timeline RocksDB checkpoint.
101    pub timeline_checkpoint_uri: String,
102    /// Immutable payload files copied into the artifact.
103    pub payload_files: Vec<TimerSnapshotFile>,
104    /// SHA-256 over the canonical manifest fields excluding this value.
105    pub checksum: String,
106}
107
108impl TimerSnapshotManifest {
109    /// Computes and stores the canonical manifest checksum.
110    pub fn seal(&mut self) -> Result<(), StoreContractViolation> {
111        self.checksum = hex::encode(self.digest()?);
112        Ok(())
113    }
114
115    /// Validates shape, cursor monotonicity, file identities, and checksum.
116    pub fn validate(&self) -> Result<(), StoreContractViolation> {
117        if self.schema_version != TIMER_SNAPSHOT_SCHEMA_VERSION {
118            return Err(StoreContractViolation::TimerSnapshotUnsupportedVersion(
119                self.schema_version,
120            ));
121        }
122        match self.timeline_index_kind {
123            TimerTimelineIndexKind::RocksDb => {
124                if self.native_manifest_generation.is_some()
125                    || self.native_durable_end.is_some()
126                    || self.native_manifest_checksum.is_some()
127                    || !self.native_files.is_empty()
128                {
129                    return Err(StoreContractViolation::TimerSnapshotInvalidNativeBinding);
130                }
131            }
132            TimerTimelineIndexKind::Segmented => {
133                if !matches!(self.native_manifest_generation, Some(value) if value > 0)
134                    || !matches!(self.native_durable_end, Some(value) if value > 0)
135                    || !matches!(self.native_manifest_checksum, Some(value) if value > 0)
136                    || self.native_files.is_empty()
137                {
138                    return Err(StoreContractViolation::TimerSnapshotInvalidNativeBinding);
139                }
140            }
141        }
142        if self.generation == 0
143            || self.source_cq_cursor < 0
144            || self.source_physical_cursor < 0
145            || self.due_time_cursor_ms < 0
146            || self.completion_physical_cursor < 0
147            || self.timeline_sequence == 0
148            || self.role_epoch == 0
149            || self.activation_epoch == 0
150            || self.format_fingerprint == 0
151            || self.timeline_checkpoint_uri.is_empty()
152        {
153            return Err(StoreContractViolation::TimerSnapshotInvalidMetadata);
154        }
155        for file in self.payload_files.iter().chain(&self.native_files) {
156            if file.relative_path.is_empty()
157                || file.relative_path.starts_with('/')
158                || file.relative_path.contains('\\')
159                || file.relative_path.split('/').any(|component| {
160                    component.is_empty() || component == "." || component == ".." || component.contains(':')
161                })
162                || file.length == 0
163                || file.sha256.len() != 64
164                || !file.sha256.bytes().all(|byte| byte.is_ascii_hexdigit())
165            {
166                return Err(StoreContractViolation::TimerSnapshotInvalidFile);
167            }
168        }
169        let expected = hex::encode(self.digest()?);
170        if self.checksum != expected {
171            return Err(StoreContractViolation::TimerSnapshotChecksumMismatch);
172        }
173        Ok(())
174    }
175
176    /// Validates every payload and native file against its exact length and SHA-256 identity.
177    ///
178    /// # Errors
179    ///
180    /// Returns [`StoreError`] if a file cannot be opened or read, and preserves
181    /// [`StoreContractViolation::TimerSnapshotArtifactDigestMismatch`] as a
182    /// typed source if its declared identity differs.
183    pub fn validate_artifact_files(&self, artifact_root: impl AsRef<Path>) -> Result<(), StoreError> {
184        self.validate().map_err(snapshot_contract)?;
185        let root = artifact_root.as_ref();
186        for expected in self.payload_files.iter().chain(&self.native_files) {
187            let path = expected
188                .relative_path
189                .split('/')
190                .fold(root.to_path_buf(), |path, component| path.join(component));
191            let mut file = std::fs::File::open(&path)
192                .map_err(|source| snapshot_io("open timer snapshot artifact", &path, source))?;
193            if file
194                .metadata()
195                .map_err(|source| snapshot_io("inspect timer snapshot artifact", &path, source))?
196                .len()
197                != expected.length
198            {
199                return Err(snapshot_contract(
200                    StoreContractViolation::TimerSnapshotArtifactDigestMismatch,
201                ));
202            }
203            let mut hasher = Sha256::new();
204            let mut remaining = expected.length;
205            let mut buffer = [0u8; 64 * 1024];
206            while remaining > 0 {
207                let chunk = usize::try_from(remaining.min(buffer.len() as u64)).unwrap_or(buffer.len());
208                file.read_exact(&mut buffer[..chunk])
209                    .map_err(|source| snapshot_io("read timer snapshot artifact", &path, source))?;
210                hasher.update(&buffer[..chunk]);
211                remaining -= u64::try_from(chunk)
212                    .map_err(|_| snapshot_contract(StoreContractViolation::TimerSnapshotInvalidMetadata))?;
213            }
214            if hex::encode(hasher.finalize()) != expected.sha256 {
215                return Err(snapshot_contract(
216                    StoreContractViolation::TimerSnapshotArtifactDigestMismatch,
217                ));
218            }
219        }
220        Ok(())
221    }
222
223    fn digest(&self) -> Result<[u8; 32], StoreContractViolation> {
224        let mut hasher = Sha256::new();
225        hasher.update(self.schema_version.to_be_bytes());
226        hasher.update(self.generation.to_be_bytes());
227        hasher.update(self.source_cq_cursor.to_be_bytes());
228        hasher.update(self.source_physical_cursor.to_be_bytes());
229        hasher.update(self.due_time_cursor_ms.to_be_bytes());
230        hasher.update(self.completion_physical_cursor.to_be_bytes());
231        hasher.update(self.timeline_sequence.to_be_bytes());
232        if self.timeline_index_kind == TimerTimelineIndexKind::Segmented {
233            hasher.update(b"segmented-timeline-v1");
234            hasher.update(self.native_manifest_generation.unwrap_or_default().to_be_bytes());
235            hasher.update(self.native_durable_end.unwrap_or_default().to_be_bytes());
236            hasher.update(self.native_manifest_checksum.unwrap_or_default().to_be_bytes());
237            update_files(&mut hasher, &self.native_files)?;
238        }
239        hasher.update(self.role_epoch.to_be_bytes());
240        hasher.update(self.activation_epoch.to_be_bytes());
241        hasher.update(self.format_fingerprint.to_be_bytes());
242        update_text(&mut hasher, &self.timeline_checkpoint_uri)?;
243        update_files(&mut hasher, &self.payload_files)?;
244        Ok(hasher.finalize().into())
245    }
246}
247
248fn update_files(hasher: &mut Sha256, files: &[TimerSnapshotFile]) -> Result<(), StoreContractViolation> {
249    let file_count = u32::try_from(files.len()).map_err(|_| StoreContractViolation::TimerSnapshotInvalidMetadata)?;
250    hasher.update(file_count.to_be_bytes());
251    for file in files {
252        update_text(hasher, &file.relative_path)?;
253        hasher.update(file.length.to_be_bytes());
254        update_text(hasher, &file.sha256)?;
255    }
256    Ok(())
257}
258
259fn update_text(hasher: &mut Sha256, value: &str) -> Result<(), StoreContractViolation> {
260    let length = u32::try_from(value.len()).map_err(|_| StoreContractViolation::TimerSnapshotInvalidMetadata)?;
261    hasher.update(length.to_be_bytes());
262    hasher.update(value.as_bytes());
263    Ok(())
264}
265
266#[derive(Debug, Error)]
267#[error("{operation} failed for {path}: {source}")]
268struct TimerSnapshotIoError {
269    operation: &'static str,
270    path: PathBuf,
271    #[source]
272    source: std::io::Error,
273}
274
275fn snapshot_contract(source: StoreContractViolation) -> StoreError {
276    StoreError::new(&STORAGE_REQUEST_INVALID, StoreOperation::Read).with_source(source)
277}
278
279fn snapshot_io(operation: &'static str, path: &Path, source: std::io::Error) -> StoreError {
280    StoreError::new(&STORAGE_IO_FAILED, StoreOperation::Read).with_source(TimerSnapshotIoError {
281        operation,
282        path: path.to_path_buf(),
283        source,
284    })
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    fn manifest() -> TimerSnapshotManifest {
292        let mut manifest = TimerSnapshotManifest {
293            schema_version: TIMER_SNAPSHOT_SCHEMA_VERSION,
294            generation: 3,
295            source_cq_cursor: 10,
296            source_physical_cursor: 1_024,
297            due_time_cursor_ms: 1_800_000_000_000,
298            completion_physical_cursor: 2_048,
299            timeline_sequence: 9,
300            timeline_index_kind: TimerTimelineIndexKind::RocksDb,
301            native_manifest_generation: None,
302            native_durable_end: None,
303            native_manifest_checksum: None,
304            native_files: Vec::new(),
305            role_epoch: 5,
306            activation_epoch: 2,
307            format_fingerprint: 7,
308            timeline_checkpoint_uri: "file:///timer/snapshot/timeline".to_owned(),
309            payload_files: vec![TimerSnapshotFile {
310                relative_path: "payload/day-0000000001/lane-00000/00000000000000000000".to_owned(),
311                length: 128,
312                sha256: "ab".repeat(32),
313            }],
314            checksum: String::new(),
315        };
316        manifest.seal().unwrap();
317        manifest
318    }
319
320    #[test]
321    fn manifest_round_trips_and_detects_cursor_damage() {
322        let manifest = manifest();
323        manifest.validate().unwrap();
324        let encoded = serde_json::to_vec(&manifest).unwrap();
325        let mut decoded: TimerSnapshotManifest = serde_json::from_slice(&encoded).unwrap();
326        assert_eq!(decoded, manifest);
327        decoded.completion_physical_cursor += 1;
328        assert_eq!(
329            decoded.validate(),
330            Err(StoreContractViolation::TimerSnapshotChecksumMismatch)
331        );
332    }
333
334    #[test]
335    fn manifest_rejects_platform_specific_path_escape() {
336        let mut manifest = manifest();
337        manifest.payload_files[0].relative_path = "payload\\..\\outside".to_owned();
338        manifest.seal().unwrap();
339        assert_eq!(
340            manifest.validate(),
341            Err(StoreContractViolation::TimerSnapshotInvalidFile)
342        );
343    }
344}