allsource_core/infrastructure/persistence/
system_checkpoint.rs1use crate::{
13 domain::entities::Event,
14 error::{AllSourceError, Result},
15 infrastructure::persistence::wal::CoveredSegment,
16};
17use chrono::{DateTime, Utc};
18use serde::{Deserialize, Serialize};
19use std::{
20 collections::BTreeMap,
21 fs::{self, File, OpenOptions},
22 io::Write,
23 path::{Path, PathBuf},
24};
25
26pub const CHECKPOINT_DIR: &str = "checkpoint";
29const FORMAT: u32 = 1;
30const MAGIC: &str = "allsource-system-checkpoint";
31const PREFIX: &str = "checkpoint-";
32const SUFFIX: &str = ".json";
33pub const RETAINED: usize = 2;
36const REJECTED_DIR: &str = "rejected";
37
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
40pub struct FoldedStream {
41 pub format: u32,
42 pub state: serde_json::Value,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct SystemCheckpoint {
47 pub format: u32,
48 pub covered_seq: u64,
51 pub created_at: DateTime<Utc>,
52 pub segments: Vec<CoveredSegment>,
54 pub domain_counts: BTreeMap<String, u64>,
56 pub verbatim: Vec<(u64, Event)>,
58 pub folds: BTreeMap<String, FoldedStream>,
60}
61
62#[derive(Debug, Serialize, Deserialize)]
63struct Footer {
64 magic: String,
65 format: u32,
66 covered_seq: u64,
67 body_len: u64,
68 body_crc32: u32,
69}
70
71fn storage(context: &str, e: impl std::fmt::Display) -> AllSourceError {
72 AllSourceError::StorageError(format!("{context}: {e}"))
73}
74
75fn file_name(covered_seq: u64) -> String {
76 format!("{PREFIX}{covered_seq:016x}{SUFFIX}")
77}
78
79fn covered_seq_of(path: &Path) -> Option<u64> {
80 let name = path.file_name()?.to_str()?;
81 let hex = name.strip_prefix(PREFIX)?.strip_suffix(SUFFIX)?;
82 u64::from_str_radix(hex, 16).ok()
83}
84
85fn list(dir: &Path) -> Result<Vec<(u64, PathBuf)>> {
87 let entries = match fs::read_dir(dir) {
88 Ok(entries) => entries,
89 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
90 Err(e) => return Err(storage("Failed to read checkpoint directory", e)),
91 };
92 let mut found = Vec::new();
93 for entry in entries {
94 let path = entry
95 .map_err(|e| storage("Failed to read checkpoint entry", e))?
96 .path();
97 if let Some(seq) = covered_seq_of(&path) {
98 found.push((seq, path));
99 }
100 }
101 found.sort_by_key(|(seq, _)| std::cmp::Reverse(*seq));
102 Ok(found)
103}
104
105fn sync_dir(dir: &Path) -> Result<()> {
106 File::open(dir)
107 .and_then(|d| d.sync_all())
108 .map_err(|e| storage("Failed to sync checkpoint directory", e))
109}
110
111pub fn read(path: &Path) -> Result<SystemCheckpoint> {
113 let bytes = fs::read(path).map_err(|e| storage("Failed to read checkpoint", e))?;
114 let body_end = bytes
115 .strip_suffix(b"\n")
116 .unwrap_or(&bytes)
117 .iter()
118 .rposition(|b| *b == b'\n')
119 .ok_or_else(|| storage("Checkpoint has no footer", path.display()))?;
120 let footer: Footer = serde_json::from_slice(&bytes[body_end + 1..])
121 .map_err(|e| storage("Checkpoint footer unreadable", e))?;
122 let body = &bytes[..body_end];
123 if footer.magic != MAGIC || footer.format != FORMAT {
124 return Err(storage(
125 "Checkpoint written in an unknown format",
126 format!("{} format {}", footer.magic, footer.format),
127 ));
128 }
129 if footer.body_len != body.len() as u64 || footer.body_crc32 != crc32fast::hash(body) {
130 return Err(storage(
131 "Checkpoint body fails its checksum",
132 path.display(),
133 ));
134 }
135 let checkpoint: SystemCheckpoint =
136 serde_json::from_slice(body).map_err(|e| storage("Checkpoint body unreadable", e))?;
137 if checkpoint.covered_seq != footer.covered_seq
138 || covered_seq_of(path) != Some(footer.covered_seq)
139 {
140 return Err(storage(
141 "Checkpoint sequence disagrees with its name or footer",
142 path.display(),
143 ));
144 }
145 Ok(checkpoint)
146}
147
148pub fn load_latest(dir: &Path) -> Option<SystemCheckpoint> {
150 let files = match list(dir) {
151 Ok(files) => files,
152 Err(e) => {
153 tracing::error!("System checkpoints unreadable, replaying the whole WAL: {e}");
154 return None;
155 }
156 };
157 for (_, path) in files {
158 match read(&path) {
159 Ok(checkpoint) => return Some(checkpoint),
160 Err(e) => tracing::error!("Skipping system checkpoint {}: {e}", path.display()),
161 }
162 }
163 None
164}
165
166pub fn highest_named(dir: &Path) -> u64 {
170 let mut highest = 0;
171 for directory in [dir.to_path_buf(), dir.join(REJECTED_DIR)] {
172 let Ok(entries) = fs::read_dir(&directory) else {
173 continue;
174 };
175 for entry in entries.flatten() {
176 let name = entry.file_name();
177 let name = name.to_string_lossy();
178 let Some(start) = name.find(PREFIX) else {
179 continue;
180 };
181 let hex = name[start + PREFIX.len()..]
182 .split(['.', '-'])
183 .next()
184 .unwrap_or_default();
185 if let Ok(seq) = u64::from_str_radix(hex, 16) {
186 highest = highest.max(seq);
187 }
188 }
189 }
190 highest
191}
192
193pub fn write(dir: &Path, checkpoint: &SystemCheckpoint) -> Result<PathBuf> {
197 fs::create_dir_all(dir).map_err(|e| storage("Failed to create checkpoint directory", e))?;
198 let target = dir.join(file_name(checkpoint.covered_seq));
199 if target.exists() {
200 return Ok(target);
201 }
202 let temporary = dir.join(format!(".{}.tmp", file_name(checkpoint.covered_seq)));
203 let body = serde_json::to_vec(checkpoint).map_err(|e| storage("Checkpoint encode", e))?;
204 let footer = serde_json::to_vec(&Footer {
205 magic: MAGIC.into(),
206 format: FORMAT,
207 covered_seq: checkpoint.covered_seq,
208 body_len: body.len() as u64,
209 body_crc32: crc32fast::hash(&body),
210 })
211 .map_err(|e| storage("Checkpoint footer encode", e))?;
212 {
213 let mut file = OpenOptions::new()
214 .create(true)
215 .write(true)
216 .truncate(true)
217 .open(&temporary)
218 .map_err(|e| storage("Failed to create checkpoint", e))?;
219 file.write_all(&body)
220 .and_then(|()| file.write_all(b"\n"))
221 .and_then(|()| file.write_all(&footer))
222 .and_then(|()| file.write_all(b"\n"))
223 .and_then(|()| file.sync_all())
224 .map_err(|e| storage("Failed to write checkpoint", e))?;
225 }
226 fs::rename(&temporary, &target).map_err(|e| storage("Failed to publish checkpoint", e))?;
227 sync_dir(dir)?;
228 retire_old(dir)?;
229 Ok(target)
230}
231
232fn retire_old(dir: &Path) -> Result<()> {
235 for (_, path) in list(dir)?.into_iter().skip(RETAINED) {
236 if read(&path).is_ok() {
237 fs::remove_file(&path).map_err(|e| storage("Failed to remove checkpoint", e))?;
238 }
239 }
240 let entries = fs::read_dir(dir).map_err(|e| storage("Failed to read checkpoints", e))?;
241 for entry in entries.flatten() {
242 let name = entry.file_name();
243 let name = name.to_string_lossy();
244 if name.starts_with(&format!(".{PREFIX}")) && name.ends_with(".tmp") {
245 let _ = fs::remove_file(entry.path());
246 }
247 }
248 Ok(())
249}
250
251pub fn reject_all(dir: &Path) -> Result<usize> {
254 let rejected = dir.join(REJECTED_DIR);
255 let mut moved = 0;
256 let stamp = Utc::now().format("%Y%m%dT%H%M%S%.6fZ");
257 for (_, path) in list(dir)? {
258 if let Some(name) = path.file_name() {
259 fs::create_dir_all(&rejected)
260 .map_err(|e| storage("Failed to create rejected dir", e))?;
261 let target = rejected.join(format!("{stamp}-{}", name.to_string_lossy()));
262 fs::rename(&path, target).map_err(|e| storage("Failed to reject checkpoint", e))?;
263 moved += 1;
264 }
265 }
266 if moved > 0 {
267 sync_dir(&rejected)?;
268 sync_dir(dir)?;
269 }
270 Ok(moved)
271}
272
273pub const fn format() -> u32 {
274 FORMAT
275}