Skip to main content

wal_backup/replication/
manifest.rs

1use chrono::Utc;
2use serde::{Deserialize, Serialize};
3
4/// A compacted L1 file that merges multiple L0 segments into one.
5/// L1 files cover a contiguous range of WAL frames and are used
6/// during restore to reduce the number of GET requests.
7#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
8pub struct L1File {
9    /// Object key in the bucket (e.g. "wal/salt/00000001-00005000.l1")
10    pub key: String,
11    /// First frame in the L1 range (inclusive)
12    pub start_frame: u32,
13    /// Last frame in the L1 range (inclusive)
14    pub end_frame: u32,
15    /// Number of L0 segments that were merged to create this L1
16    pub source_count: u32,
17    /// SHA256 checksum of the L1 file content ("sha256:...")
18    /// None for backward compatibility with existing manifests.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub checksum: Option<String>,
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct Manifest {
25    pub version: u32,
26    pub generation: u64,
27    pub snapshot: Option<String>,
28    pub snapshot_checksum: Option<String>,
29    pub current_salt_1: u32,
30    pub current_salt_2: u32,
31    pub page_size: u32,
32    pub shipped_frames: u32,
33    pub db_size: u64,
34    pub last_updated: String,
35    /// ETag of the manifest object in the bucket. Used for conditional writes.
36    /// None means the manifest doesn't exist yet (fresh start) or we don't know the etag.
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub etag: Option<String>,
39    /// Compacted L1 files. These merge multiple L0 segments into fewer,
40    /// larger files for efficient restore. L0 segments covered by an L1
41    /// file can be safely deleted by GC.
42    #[serde(default, skip_serializing_if = "Vec::is_empty")]
43    pub l1_files: Vec<L1File>,
44    /// The highest frame covered by any L1 file. L0 segments with
45    /// end_frame <= this value are candidates for GC after compaction.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub l1_max_frame: Option<u32>,
48    /// SHA256 checksums of L0 segment files, keyed by object key.
49    /// Used during restore to verify segment integrity before replay.
50    /// Empty for backward compatibility with existing manifests.
51    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
52    pub segment_checksums: std::collections::HashMap<String, String>,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum ConflictLevel {
57    None,
58    LocalAhead,
59    RemoteAhead,
60}
61
62impl Manifest {
63    pub fn new(salt_1: u32, salt_2: u32, page_size: u32) -> Self {
64        Manifest {
65            version: 1,
66            generation: 0,
67            snapshot: None,
68            snapshot_checksum: None,
69            current_salt_1: salt_1,
70            current_salt_2: salt_2,
71            page_size,
72            shipped_frames: 0,
73            db_size: 0,
74            last_updated: Utc::now().to_rfc3339(),
75            etag: None,
76            l1_files: Vec::new(),
77            l1_max_frame: None,
78            segment_checksums: std::collections::HashMap::new(),
79        }
80    }
81
82    pub fn update_snapshot(
83        &mut self,
84        snapshot_path: String,
85        checksum: String,
86        salt_1: u32,
87        salt_2: u32,
88        page_size: u32,
89        db_size: u64,
90    ) {
91        self.snapshot = Some(snapshot_path);
92        self.snapshot_checksum = Some(checksum);
93        self.current_salt_1 = salt_1;
94        self.current_salt_2 = salt_2;
95        self.page_size = page_size;
96        self.shipped_frames = 0;
97        self.db_size = db_size;
98        self.last_updated = Utc::now().to_rfc3339();
99        // After a snapshot, all L1 files are stale (they reference the old salt).
100        // The snapshot resets shipped_frames to 0, so L1 files covering
101        // the old frame range are no longer needed for restore.
102        self.l1_files.clear();
103        self.l1_max_frame = None;
104        // Prune segment checksums for the old salt prefix since those segments
105        // belong to the previous generation and will never be restored.
106        // Keep checksums for the new salt so new segments can still be verified.
107        let old_salt_prefix = format!("wal/{:08x}{:08x}/", salt_1, salt_2);
108        self.segment_checksums
109            .retain(|key, _| !key.starts_with(&old_salt_prefix));
110    }
111
112    pub fn update_shipped_frames(&mut self, frames: u32) {
113        self.shipped_frames = frames;
114        self.generation = self.generation.saturating_add(1);
115        self.last_updated = Utc::now().to_rfc3339();
116    }
117
118    pub fn conflict_level(&self, remote: &Manifest) -> ConflictLevel {
119        if remote.generation > self.generation {
120            ConflictLevel::RemoteAhead
121        } else if self.generation > remote.generation {
122            ConflictLevel::LocalAhead
123        } else {
124            // Equal generation means both manifests are at the same point.
125            // No conflict — both are consistent.
126            ConflictLevel::None
127        }
128    }
129
130    pub fn check_conflict(&self, remote: &Manifest) -> bool {
131        self.conflict_level(remote) != ConflictLevel::None
132    }
133
134    pub fn salt_string(&self) -> String {
135        format!("{}-{}", self.current_salt_1, self.current_salt_2)
136    }
137
138    pub fn is_different_salt(&self, salt_1: u32, salt_2: u32) -> bool {
139        self.current_salt_1 != salt_1 || self.current_salt_2 != salt_2
140    }
141
142    pub fn segment_prefix(&self) -> String {
143        format!("wal/{}/", self.salt_string())
144    }
145
146    /// Returns the highest frame covered by any L1 file, or 0 if no L1 files exist.
147    /// L0 segments with end_frame <= this value are fully covered by compaction
148    /// and can be safely deleted by GC.
149    pub fn l1_max_frame_value(&self) -> u32 {
150        self.l1_max_frame.unwrap_or(0)
151    }
152
153    /// Add an L1 file to the manifest and update l1_max_frame.
154    pub fn add_l1_file(&mut self, l1: L1File) {
155        let end = l1.end_frame;
156        self.l1_files.push(l1);
157        self.l1_max_frame = Some(end.max(self.l1_max_frame.unwrap_or(0)));
158        self.last_updated = Utc::now().to_rfc3339();
159    }
160
161    /// Update the ETag after reading it from the bucket (e.g. from GET response headers).
162    pub fn set_etag(&mut self, etag: String) {
163        self.etag = Some(etag);
164    }
165
166    /// Set last_updated from an RFC3339 string. For test use.
167    /// Panics if the string is not valid RFC3339.
168    pub fn set_last_updated_str(&mut self, ts: &str) {
169        self.last_updated = ts
170            .parse()
171            .expect("set_last_updated_str: invalid RFC3339 timestamp");
172    }
173
174    /// Create a manifest with a specific last_updated timestamp. For test use.
175    /// Panics if the string is not valid RFC3339.
176    pub fn with_last_updated(salt_1: u32, salt_2: u32, page_size: u32, ts: &str) -> Self {
177        let mut m = Self::new(salt_1, salt_2, page_size);
178        m.last_updated = ts
179            .parse()
180            .expect("with_last_updated: invalid RFC3339 timestamp");
181        m
182    }
183
184    pub fn serialize(&self) -> crate::error::Result<Vec<u8>> {
185        serde_json::to_vec(self).map_err(crate::error::Error::Serialization)
186    }
187
188    pub fn deserialize(data: &[u8]) -> crate::error::Result<Self> {
189        // First parse into a raw JSON value so we can inspect the version field
190        // before committing to the full deserialization. This lets us return a
191        // clear error for unsupported manifest versions rather than silently
192        // producing wrong data.
193        let raw: serde_json::Value =
194            serde_json::from_slice(data).map_err(crate::error::Error::Serialization)?;
195        if let Some(v) = raw.get("version").and_then(|v| v.as_u64()) {
196            if v != 1 {
197                return Err(crate::error::Error::Other(format!(
198                    "unsupported manifest version {} (only version 1 is supported)",
199                    v
200                )));
201            }
202        }
203        serde_json::from_slice(data).map_err(crate::error::Error::Serialization)
204    }
205}
206
207pub const MANIFEST_KEY: &str = "manifest.json";