1use std::io::Write;
14use std::path::{Path, PathBuf};
15
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19use crate::backend::rpc_types::ForkSlugPlan;
20
21pub const JOURNAL_FILE: &str = "journal.jsonl";
22const VERSION: u32 = 1;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
26pub enum Step {
27 S1,
28 S2,
29 S3,
30 S4,
31 S5,
32 S6,
33 S7,
34 S8,
35}
36
37pub const STEPS: [Step; 8] = [Step::S1, Step::S2, Step::S3, Step::S4, Step::S5, Step::S6, Step::S7, Step::S8];
38
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct BackupEntry {
42 pub original: String,
43 pub copy: String,
45 pub sha256: String,
46 pub database: bool,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51pub struct Fingerprint {
52 pub path: String,
53 pub digest: String,
55 pub mtime_ms: i64,
58}
59
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61#[serde(tag = "t", rename_all = "snake_case")]
62pub enum Record {
63 Header { version: u32, started_at: i64, retired_at: i64, plan: ForkSlugPlan, backups: Vec<BackupEntry> },
64 Intent { uid: String, step: Step, before: Value },
65 Done { uid: String, step: Step, changes: Vec<String> },
66 Verified { uid: String },
67 Failed { uid: String, error: String },
68 Skipped { uid: String, reason: String },
71 Finished { at: i64, after: Vec<Fingerprint> },
72 Undo { uid: String, step: Step },
73 Undone { uid: String, step: Step, changes: Vec<String> },
74 RolledBack { at: i64, mode: String },
75}
76
77pub struct Journal {
79 pub path: PathBuf,
80 pub records: Vec<Record>,
81}
82
83impl Journal {
84 pub fn create(dir: &Path, started_at: i64, retired_at: i64, plan: ForkSlugPlan, backups: Vec<BackupEntry>) -> Result<Journal, String> {
86 let mut j = Journal { path: dir.join(JOURNAL_FILE), records: Vec::new() };
87 j.append(Record::Header { version: VERSION, started_at, retired_at, plan, backups })?;
88 sync_dir(dir);
90 Ok(j)
91 }
92
93 pub fn open(path: &Path) -> Result<Journal, String> {
100 Self::load(path, true)
101 }
102
103 pub fn read(path: &Path) -> Result<Journal, String> {
107 Self::load(path, false)
108 }
109
110 fn load(path: &Path, repair: bool) -> Result<Journal, String> {
111 let bytes = std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
112 let mut keep = bytes.len();
113 let body = bytes.strip_suffix(b"\n").unwrap_or(&bytes);
115 let start = body.iter().rposition(|b| *b == b'\n').map_or(0, |i| i + 1);
116 let last = &body[start..];
117 if !last.iter().all(u8::is_ascii_whitespace) && serde_json::from_slice::<Record>(last).is_err() {
118 keep = start;
119 tracing::warn!(journal = %path.display(), discarded = last.len(), "fork slug migration: discarded a torn last journal record");
120 }
121 if repair && keep < bytes.len() {
122 let f = std::fs::OpenOptions::new().write(true).open(path).map_err(|e| format!("{}: {e}", path.display()))?;
123 f.set_len(keep as u64).map_err(|e| format!("{}: {e}", path.display()))?;
124 f.sync_all().map_err(|e| format!("{}: {e}", path.display()))?;
125 }
126 let text = String::from_utf8_lossy(&bytes[..keep]);
127 let mut records = Vec::new();
128 for (i, line) in text.lines().enumerate().filter(|(_, l)| !l.trim().is_empty()) {
129 let record = serde_json::from_str::<Record>(line).map_err(|e| format!("{} line {}: {e}", path.display(), i + 1))?;
130 records.push(record);
131 }
132 match records.first() {
133 Some(Record::Header { version, .. }) if *version <= VERSION => {}
134 _ => return Err(format!("{} has no header this build reads", path.display())),
135 }
136 Ok(Journal { path: path.to_path_buf(), records })
137 }
138
139 pub fn dir(&self) -> PathBuf {
140 self.path.parent().map(Path::to_path_buf).unwrap_or_default()
141 }
142
143 pub fn append(&mut self, record: Record) -> Result<(), String> {
148 use std::io::{Read, Seek, SeekFrom};
149 let err = |e: std::io::Error| format!("{}: {e}", self.path.display());
150 let mut line = serde_json::to_string(&record).map_err(|e| e.to_string())?;
151 line.push('\n');
152 let mut opts = std::fs::OpenOptions::new();
153 opts.create(true).read(true).append(true);
154 #[cfg(unix)]
156 {
157 use std::os::unix::fs::OpenOptionsExt as _;
158 opts.mode(0o600);
159 }
160 let mut f = opts.open(&self.path).map_err(err)?;
161 let len = f.metadata().map_err(err)?.len();
162 if len > 0 {
163 let mut last = [0u8; 1];
164 f.seek(SeekFrom::Start(len - 1)).map_err(err)?;
165 f.read_exact(&mut last).map_err(err)?;
166 if last[0] != b'\n' {
167 line.insert(0, '\n');
168 }
169 }
170 f.write_all(line.as_bytes()).map_err(err)?;
171 f.sync_all().map_err(err)?;
172 self.records.push(record);
173 Ok(())
174 }
175
176 pub fn header(&self) -> (i64, &ForkSlugPlan, &[BackupEntry]) {
177 match &self.records[0] {
178 Record::Header { retired_at, plan, backups, .. } => (*retired_at, plan, backups),
179 _ => unreachable!("open and create both start with a header"),
180 }
181 }
182
183 pub fn intent(&self, uid: &str, step: Step) -> Option<&Value> {
185 self.records.iter().find_map(|r| match r {
186 Record::Intent { uid: u, step: s, before } if u == uid && *s == step => Some(before),
187 _ => None,
188 })
189 }
190
191 pub fn done(&self, uid: &str, step: Step) -> bool {
192 self.records.iter().any(|r| matches!(r, Record::Done { uid: u, step: s, .. } if u == uid && *s == step))
193 }
194
195 pub fn skipped(&self, uid: &str) -> Option<&str> {
196 self.records.iter().find_map(|r| match r {
197 Record::Skipped { uid: u, reason } if u == uid => Some(reason.as_str()),
198 _ => None,
199 })
200 }
201
202 pub fn verified(&self, uid: &str) -> bool {
203 self.records.iter().any(|r| matches!(r, Record::Verified { uid: u } if u == uid))
204 }
205
206 pub fn undone(&self, uid: &str, step: Step) -> bool {
207 self.records.iter().any(|r| matches!(r, Record::Undone { uid: u, step: s, .. } if u == uid && *s == step))
208 }
209
210 pub fn finished(&self) -> Option<&[Fingerprint]> {
211 self.records.iter().find_map(|r| match r {
212 Record::Finished { after, .. } => Some(after.as_slice()),
213 _ => None,
214 })
215 }
216
217 pub fn rolled_back(&self) -> bool {
218 self.records.iter().any(|r| matches!(r, Record::RolledBack { .. }))
219 }
220
221 pub fn intents(&self) -> Vec<(String, Step, Value)> {
223 self.records
224 .iter()
225 .filter_map(|r| match r {
226 Record::Intent { uid, step, before } => Some((uid.clone(), *step, before.clone())),
227 _ => None,
228 })
229 .collect()
230 }
231
232 pub fn changes(&self, uid: &str) -> Vec<String> {
234 self.records
235 .iter()
236 .filter_map(|r| match r {
237 Record::Done { uid: u, step, changes } if u == uid => Some(changes.iter().map(move |c| format!("{step:?}: {c}"))),
238 _ => None,
239 })
240 .flatten()
241 .collect()
242 }
243
244 pub fn last_failure(&self) -> Option<String> {
245 let failed = self.records.iter().rposition(|r| matches!(r, Record::Failed { .. }))?;
246 let later_progress = self.records[failed + 1..].iter().any(|r| matches!(r, Record::Done { .. } | Record::Verified { .. }));
247 match &self.records[failed] {
248 Record::Failed { uid, error } if !later_progress => Some(format!("{uid}: {error}")),
249 _ => None,
250 }
251 }
252}
253
254#[cfg(unix)]
258fn sync_dir(dir: &Path) {
259 if let Ok(d) = std::fs::File::open(dir) {
260 let _ = d.sync_all();
261 }
262}
263
264#[cfg(not(unix))]
265fn sync_dir(_dir: &Path) {}
266
267pub fn journals(backups: &Path) -> Vec<PathBuf> {
269 let Ok(dirs) = std::fs::read_dir(backups) else { return Vec::new() };
270 let mut out: Vec<PathBuf> = dirs
271 .flatten()
272 .filter(|d| d.file_name().to_string_lossy().starts_with("slug-migration-"))
273 .map(|d| d.path().join(JOURNAL_FILE))
274 .filter(|p| p.is_file())
275 .collect();
276 out.sort();
277 out.reverse();
278 out
279}