1use serde::Deserialize;
22use serde::Serialize;
23
24use crate::StoreContractViolation;
25
26pub const CHECKPOINT_SCHEMA_VERSION: u16 = 1;
28
29#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
31#[serde(rename_all = "snake_case")]
32pub enum CheckpointStoreKind {
33 Local,
35 RocksDb,
37}
38
39#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
41#[serde(deny_unknown_fields, rename_all = "camelCase")]
42pub struct CheckpointOffsets {
43 pub appended_offset: i64,
45 pub durable_offset: i64,
47 pub consume_queue_offset: i64,
49 pub index_offset: i64,
51}
52
53impl CheckpointOffsets {
54 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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
82#[serde(deny_unknown_fields, rename_all = "camelCase")]
83pub struct CheckpointStorageIdentity {
84 pub volume_id: String,
86 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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
105#[serde(deny_unknown_fields, rename_all = "camelCase")]
106pub struct CheckpointArtifact {
107 pub schema_version: u16,
109 pub checkpoint_id: String,
111 pub checkpoint_set_id: String,
113 pub generation: u64,
115 pub barrier_id: String,
117 pub created_at_unix_millis: u64,
119 pub length_bytes: u64,
121 pub sha256: String,
123 pub uri: String,
125}
126
127impl CheckpointArtifact {
128 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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
162#[serde(deny_unknown_fields, rename_all = "camelCase")]
163pub struct CheckpointRequest {
164 pub checkpoint_id: String,
166 pub checkpoint_set_id: String,
168 pub generation: u64,
170 pub barrier_id: String,
172 pub member_id: String,
174 pub offsets: CheckpointOffsets,
176 pub storage_identity: CheckpointStorageIdentity,
178}
179
180impl CheckpointRequest {
181 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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
202#[serde(deny_unknown_fields, rename_all = "camelCase")]
203pub struct CheckpointManifest {
204 pub artifact: CheckpointArtifact,
206 pub member_id: String,
208 #[serde(rename = "backend")]
211 pub store_kind: CheckpointStoreKind,
212 pub offsets: CheckpointOffsets,
214 pub storage_identity: CheckpointStorageIdentity,
216 pub wal_retained: bool,
218 pub persistent_volume_retained: bool,
220}
221
222impl CheckpointManifest {
223 pub fn validate(&self) -> Result<(), StoreContractViolation> {
230 self.artifact.validate()?;
231 require_identifier("memberId", &self.member_id)?;
232 self.offsets.validate()?;
233 self.storage_identity.validate()?;
234 if !self.wal_retained || !self.persistent_volume_retained {
235 return Err(StoreContractViolation::CheckpointDestructiveRollback);
236 }
237 Ok(())
238 }
239}
240
241#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
243#[serde(deny_unknown_fields, rename_all = "camelCase")]
244pub struct CheckpointRestoreVerification {
245 pub checkpoint_id: String,
247 pub generation: u64,
249 pub verified_at_unix_millis: u64,
251 pub checksum_verified: bool,
253 pub offsets_verified: bool,
255 pub storage_identity_verified: bool,
257 pub wal_retained: bool,
259 pub persistent_volume_retained: bool,
261}
262
263impl CheckpointRestoreVerification {
264 pub fn validate(&self) -> Result<(), StoreContractViolation> {
271 require_identifier("checkpointId", &self.checkpoint_id)?;
272 if self.generation == 0 || self.verified_at_unix_millis == 0 {
273 return invalid_field("generation/verifiedAtUnixMillis", "must be greater than zero");
274 }
275 if !self.checksum_verified
276 || !self.offsets_verified
277 || !self.storage_identity_verified
278 || !self.wal_retained
279 || !self.persistent_volume_retained
280 {
281 return Err(StoreContractViolation::CheckpointRestoreVerificationIncomplete);
282 }
283 Ok(())
284 }
285}
286
287fn require_identifier(field: &'static str, value: &str) -> Result<(), StoreContractViolation> {
288 if value.is_empty()
289 || value.len() > 256
290 || !value
291 .bytes()
292 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':' | b'/' | b'@'))
293 {
294 return invalid_field(field, "must be a canonical identifier");
295 }
296 Ok(())
297}
298
299fn require_sha256(value: &str) -> Result<(), StoreContractViolation> {
300 if value.len() != 64
301 || !value
302 .bytes()
303 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
304 {
305 return invalid_field("sha256", "must be 64 lowercase hexadecimal characters");
306 }
307 Ok(())
308}
309
310fn invalid_field<T>(field: &'static str, reason: impl Into<String>) -> Result<T, StoreContractViolation> {
311 Err(StoreContractViolation::CheckpointInvalidField {
312 field,
313 reason: reason.into(),
314 })
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320
321 #[test]
322 fn checkpoint_manifest_json_preserves_store_kind() {
323 for (store_kind, name) in [
324 (CheckpointStoreKind::Local, "local"),
325 (CheckpointStoreKind::RocksDb, "rocks_db"),
326 ] {
327 let value = serde_json::json!({
328 "artifact": {
329 "schemaVersion": 1,
330 "checkpointId": "checkpoint-7",
331 "checkpointSetId": "set-7",
332 "generation": 7,
333 "barrierId": "barrier-42",
334 "createdAtUnixMillis": 1_800_000_000_000_u64,
335 "lengthBytes": 512,
336 "sha256": "a".repeat(64),
337 "uri": "file:///checkpoints/checkpoint-7"
338 },
339 "memberId": "broker-a",
340 "backend": name,
341 "offsets": {
342 "appendedOffset": 120,
343 "durableOffset": 120,
344 "consumeQueueOffset": 100,
345 "indexOffset": 100
346 },
347 "storageIdentity": { "volumeId": "pvc-a", "walGeneration": 7 },
348 "walRetained": true,
349 "persistentVolumeRetained": true
350 });
351 let manifest: CheckpointManifest = serde_json::from_value(value.clone()).unwrap();
352 assert_eq!(manifest.store_kind, store_kind);
353 assert_eq!(serde_json::to_value(manifest).unwrap(), value);
354 }
355 }
356
357 #[test]
358 fn domain_json_preserves_the_stable_wire_field_names() {
359 let request = CheckpointRequest {
360 checkpoint_id: "checkpoint-7".to_string(),
361 checkpoint_set_id: "set-7".to_string(),
362 generation: 7,
363 barrier_id: "barrier-42".to_string(),
364 member_id: "broker-a".to_string(),
365 offsets: CheckpointOffsets {
366 appended_offset: 120,
367 durable_offset: 120,
368 consume_queue_offset: 100,
369 index_offset: 100,
370 },
371 storage_identity: CheckpointStorageIdentity {
372 volume_id: "pvc-a".to_string(),
373 wal_generation: 7,
374 },
375 };
376
377 request.validate().expect("valid checkpoint request");
378 let value = serde_json::to_value(request).expect("serialize checkpoint request");
379 assert!(value.get("checkpointId").is_some());
380 assert!(value.get("storageIdentity").is_some());
381 assert!(value.get("checkpoint_id").is_none());
382 }
383
384 #[test]
385 fn destructive_or_unordered_checkpoint_state_is_rejected() {
386 let offsets = CheckpointOffsets {
387 appended_offset: 100,
388 durable_offset: 101,
389 consume_queue_offset: 90,
390 index_offset: 90,
391 };
392 assert!(matches!(
393 offsets.validate(),
394 Err(StoreContractViolation::CheckpointInvalidOffsets(_))
395 ));
396 }
397}