1use 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
30pub const TIMER_SNAPSHOT_SCHEMA_VERSION: u16 = 1;
32
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "snake_case")]
37pub enum TimerTimelineIndexKind {
38 #[default]
40 RocksDb,
41 Segmented,
43}
44
45impl TimerTimelineIndexKind {
46 fn is_rocksdb(kind: &Self) -> bool {
47 *kind == Self::RocksDb
48 }
49}
50
51#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
53pub struct TimerSnapshotFile {
54 pub relative_path: String,
56 pub length: u64,
58 pub sha256: String,
60}
61
62#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
64pub struct TimerSnapshotManifest {
65 pub schema_version: u16,
67 pub generation: u64,
69 pub source_cq_cursor: i64,
71 pub source_physical_cursor: i64,
73 pub due_time_cursor_ms: i64,
75 pub completion_physical_cursor: i64,
77 pub timeline_sequence: u64,
79 #[serde(default, skip_serializing_if = "TimerTimelineIndexKind::is_rocksdb")]
81 pub timeline_index_kind: TimerTimelineIndexKind,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub native_manifest_generation: Option<u64>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub native_durable_end: Option<u64>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub native_manifest_checksum: Option<u32>,
91 #[serde(default, skip_serializing_if = "Vec::is_empty")]
93 pub native_files: Vec<TimerSnapshotFile>,
94 pub role_epoch: u64,
96 pub activation_epoch: u64,
98 pub format_fingerprint: u64,
100 pub timeline_checkpoint_uri: String,
102 pub payload_files: Vec<TimerSnapshotFile>,
104 pub checksum: String,
106}
107
108impl TimerSnapshotManifest {
109 pub fn seal(&mut self) -> Result<(), StoreContractViolation> {
111 self.checksum = hex::encode(self.digest()?);
112 Ok(())
113 }
114
115 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 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}