Skip to main content

rocketmq_store_api/
checkpoint.rs

1// Copyright 2023 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//! Store-owned release-checkpoint domain contracts.
16//!
17//! These types deliberately mirror the stable wire representation while
18//! remaining independent from `rocketmq-protocol`. Wire/domain conversion is
19//! owned by the Broker maintenance ingress.
20
21use serde::Deserialize;
22use serde::Serialize;
23
24use crate::StoreContractViolation;
25
26/// Current Store checkpoint manifest schema.
27pub const CHECKPOINT_SCHEMA_VERSION: u16 = 1;
28
29/// Store implementation that produced a checkpoint.
30#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
31#[serde(rename_all = "snake_case")]
32pub enum CheckpointBackend {
33    /// Local CommitLog/ConsumeQueue/Index files.
34    Local,
35    /// RocksDB-managed Store state.
36    RocksDb,
37}
38
39/// Consistent Store offsets captured after the checkpoint flush barrier.
40#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
41#[serde(deny_unknown_fields, rename_all = "camelCase")]
42pub struct CheckpointOffsets {
43    /// Exclusive end of data accepted by the primary log.
44    pub appended_offset: i64,
45    /// Exclusive end durably flushed before checkpoint capture.
46    pub durable_offset: i64,
47    /// Highest physical source offset represented by ConsumeQueue.
48    pub consume_queue_offset: i64,
49    /// Highest physical source offset represented by Index.
50    pub index_offset: i64,
51}
52
53impl CheckpointOffsets {
54    /// Validates ordering between append, durable, and derived progress.
55    ///
56    /// # Errors
57    ///
58    /// Returns a typed invariant error for a negative or out-of-order offset.
59    pub fn validate(self) -> Result<(), StoreContractViolation> {
60        if self.appended_offset < 0 || self.durable_offset < 0 || self.consume_queue_offset < 0 || self.index_offset < 0
61        {
62            return Err(StoreContractViolation::CheckpointInvalidOffsets(
63                "checkpoint offsets cannot be negative".to_string(),
64            ));
65        }
66        if self.durable_offset > self.appended_offset {
67            return Err(StoreContractViolation::CheckpointInvalidOffsets(
68                "durable_offset cannot exceed appended_offset".to_string(),
69            ));
70        }
71        if self.consume_queue_offset > self.durable_offset || self.index_offset > self.durable_offset {
72            return Err(StoreContractViolation::CheckpointInvalidOffsets(
73                "derived offsets cannot exceed durable_offset".to_string(),
74            ));
75        }
76        Ok(())
77    }
78}
79
80/// Persistent storage identity that rollback must preserve.
81#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
82#[serde(deny_unknown_fields, rename_all = "camelCase")]
83pub struct CheckpointStorageIdentity {
84    /// Stable persistent-volume or local-volume identity.
85    pub volume_id: String,
86    /// Store/WAL generation expected after restore.
87    pub wal_generation: u64,
88}
89
90impl CheckpointStorageIdentity {
91    fn validate(&self) -> Result<(), StoreContractViolation> {
92        require_identifier("storageIdentity.volumeId", &self.volume_id)?;
93        if self.wal_generation == 0 {
94            return Err(StoreContractViolation::CheckpointInvalidField {
95                field: "storageIdentity.walGeneration",
96                reason: "must be greater than zero".to_string(),
97            });
98        }
99        Ok(())
100    }
101}
102
103/// Identity and integrity metadata for one Store checkpoint artifact.
104#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
105#[serde(deny_unknown_fields, rename_all = "camelCase")]
106pub struct CheckpointArtifact {
107    /// Manifest schema.
108    pub schema_version: u16,
109    /// Globally unique checkpoint ID.
110    pub checkpoint_id: String,
111    /// Set containing this artifact.
112    pub checkpoint_set_id: String,
113    /// Storage/release generation.
114    pub generation: u64,
115    /// Shared write barrier ID.
116    pub barrier_id: String,
117    /// Artifact creation timestamp.
118    pub created_at_unix_millis: u64,
119    /// Uncompressed payload length.
120    pub length_bytes: u64,
121    /// Lowercase SHA-256 of the deterministic artifact payload.
122    pub sha256: String,
123    /// Durable artifact location.
124    pub uri: String,
125}
126
127impl CheckpointArtifact {
128    /// Validates schema, identity, length, checksum, and URI.
129    ///
130    /// # Errors
131    ///
132    /// Returns a typed validation error when the artifact is incomplete.
133    pub fn validate(&self) -> Result<(), StoreContractViolation> {
134        if self.schema_version != CHECKPOINT_SCHEMA_VERSION {
135            return Err(StoreContractViolation::CheckpointSchemaVersion {
136                expected: CHECKPOINT_SCHEMA_VERSION,
137                actual: self.schema_version,
138            });
139        }
140        require_identifier("checkpointId", &self.checkpoint_id)?;
141        require_identifier("checkpointSetId", &self.checkpoint_set_id)?;
142        require_identifier("barrierId", &self.barrier_id)?;
143        if self.generation == 0 {
144            return invalid_field("generation", "must be greater than zero");
145        }
146        if self.created_at_unix_millis == 0 {
147            return invalid_field("createdAtUnixMillis", "must be greater than zero");
148        }
149        if self.length_bytes == 0 {
150            return invalid_field("lengthBytes", "must be greater than zero");
151        }
152        require_sha256(&self.sha256)?;
153        if self.uri.trim().is_empty() || self.uri.bytes().any(|byte| matches!(byte, b'\r' | b'\n')) {
154            return invalid_field("uri", "must be a non-empty single-line URI");
155        }
156        Ok(())
157    }
158}
159
160/// Request to create one Store member checkpoint.
161#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
162#[serde(deny_unknown_fields, rename_all = "camelCase")]
163pub struct CheckpointRequest {
164    /// The checkpoint identifier.
165    pub checkpoint_id: String,
166    /// The checkpoint set identifier.
167    pub checkpoint_set_id: String,
168    /// The generation value.
169    pub generation: u64,
170    /// The barrier identifier.
171    pub barrier_id: String,
172    /// The member identifier.
173    pub member_id: String,
174    /// The offsets value.
175    pub offsets: CheckpointOffsets,
176    /// The storage identity value.
177    pub storage_identity: CheckpointStorageIdentity,
178}
179
180impl CheckpointRequest {
181    /// Validates set binding and pre-flush Store observations.
182    ///
183    /// # Errors
184    ///
185    /// Returns a typed validation error when a required identity, generation,
186    /// offset, or storage identity is invalid.
187    pub fn validate(&self) -> Result<(), StoreContractViolation> {
188        require_identifier("checkpointId", &self.checkpoint_id)?;
189        require_identifier("checkpointSetId", &self.checkpoint_set_id)?;
190        require_identifier("barrierId", &self.barrier_id)?;
191        require_identifier("memberId", &self.member_id)?;
192        if self.generation == 0 {
193            return invalid_field("generation", "must be greater than zero");
194        }
195        self.offsets.validate()?;
196        self.storage_identity.validate()
197    }
198}
199
200/// Checksummed Store checkpoint manifest.
201#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
202#[serde(deny_unknown_fields, rename_all = "camelCase")]
203pub struct CheckpointManifest {
204    /// Shared artifact identity and integrity metadata.
205    pub artifact: CheckpointArtifact,
206    /// Store member bound by the checkpoint set.
207    pub member_id: String,
208    /// Backend that created the artifact.
209    pub backend: CheckpointBackend,
210    /// Offsets observed after all required flushes completed.
211    pub offsets: CheckpointOffsets,
212    /// Persistent storage identity that rollback must retain.
213    pub storage_identity: CheckpointStorageIdentity,
214    /// Explicit proof that WAL files remain part of the checkpoint contract.
215    pub wal_retained: bool,
216    /// Explicit proof that rollback must reuse the existing persistent volume.
217    pub persistent_volume_retained: bool,
218}
219
220impl CheckpointManifest {
221    /// Validates Store checkpoint integrity and rollback invariants.
222    ///
223    /// # Errors
224    ///
225    /// Returns a typed validation error for incomplete artifact metadata,
226    /// invalid offsets/storage identity, or destructive rollback semantics.
227    pub fn validate(&self) -> Result<(), StoreContractViolation> {
228        self.artifact.validate()?;
229        require_identifier("memberId", &self.member_id)?;
230        self.offsets.validate()?;
231        self.storage_identity.validate()?;
232        if !self.wal_retained || !self.persistent_volume_retained {
233            return Err(StoreContractViolation::CheckpointDestructiveRollback);
234        }
235        Ok(())
236    }
237}
238
239/// Result of non-destructive restore verification.
240#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
241#[serde(deny_unknown_fields, rename_all = "camelCase")]
242pub struct CheckpointRestoreVerification {
243    /// The checkpoint identifier.
244    pub checkpoint_id: String,
245    /// The generation value.
246    pub generation: u64,
247    /// The verified at unix duration in milliseconds.
248    pub verified_at_unix_millis: u64,
249    /// Whether checksum verified.
250    pub checksum_verified: bool,
251    /// Whether offsets verified.
252    pub offsets_verified: bool,
253    /// Whether storage identity verified.
254    pub storage_identity_verified: bool,
255    /// Whether wal retained.
256    pub wal_retained: bool,
257    /// Whether persistent volume retained.
258    pub persistent_volume_retained: bool,
259}
260
261impl CheckpointRestoreVerification {
262    /// Validates that restore verification proved every production invariant.
263    ///
264    /// # Errors
265    ///
266    /// Returns a typed validation error when any integrity, offset, WAL, or PVC
267    /// proof is absent.
268    pub fn validate(&self) -> Result<(), StoreContractViolation> {
269        require_identifier("checkpointId", &self.checkpoint_id)?;
270        if self.generation == 0 || self.verified_at_unix_millis == 0 {
271            return invalid_field("generation/verifiedAtUnixMillis", "must be greater than zero");
272        }
273        if !self.checksum_verified
274            || !self.offsets_verified
275            || !self.storage_identity_verified
276            || !self.wal_retained
277            || !self.persistent_volume_retained
278        {
279            return Err(StoreContractViolation::CheckpointRestoreVerificationIncomplete);
280        }
281        Ok(())
282    }
283}
284
285fn require_identifier(field: &'static str, value: &str) -> Result<(), StoreContractViolation> {
286    if value.is_empty()
287        || value.len() > 256
288        || !value
289            .bytes()
290            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':' | b'/' | b'@'))
291    {
292        return invalid_field(field, "must be a canonical identifier");
293    }
294    Ok(())
295}
296
297fn require_sha256(value: &str) -> Result<(), StoreContractViolation> {
298    if value.len() != 64
299        || !value
300            .bytes()
301            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
302    {
303        return invalid_field("sha256", "must be 64 lowercase hexadecimal characters");
304    }
305    Ok(())
306}
307
308fn invalid_field<T>(field: &'static str, reason: impl Into<String>) -> Result<T, StoreContractViolation> {
309    Err(StoreContractViolation::CheckpointInvalidField {
310        field,
311        reason: reason.into(),
312    })
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318
319    #[test]
320    fn domain_json_preserves_the_stable_wire_field_names() {
321        let request = CheckpointRequest {
322            checkpoint_id: "checkpoint-7".to_string(),
323            checkpoint_set_id: "set-7".to_string(),
324            generation: 7,
325            barrier_id: "barrier-42".to_string(),
326            member_id: "broker-a".to_string(),
327            offsets: CheckpointOffsets {
328                appended_offset: 120,
329                durable_offset: 120,
330                consume_queue_offset: 100,
331                index_offset: 100,
332            },
333            storage_identity: CheckpointStorageIdentity {
334                volume_id: "pvc-a".to_string(),
335                wal_generation: 7,
336            },
337        };
338
339        request.validate().expect("valid checkpoint request");
340        let value = serde_json::to_value(request).expect("serialize checkpoint request");
341        assert!(value.get("checkpointId").is_some());
342        assert!(value.get("storageIdentity").is_some());
343        assert!(value.get("checkpoint_id").is_none());
344    }
345
346    #[test]
347    fn destructive_or_unordered_checkpoint_state_is_rejected() {
348        let offsets = CheckpointOffsets {
349            appended_offset: 100,
350            durable_offset: 101,
351            consume_queue_offset: 90,
352            index_offset: 90,
353        };
354        assert!(matches!(
355            offsets.validate(),
356            Err(StoreContractViolation::CheckpointInvalidOffsets(_))
357        ));
358    }
359}