Skip to main content

git_policy_cli/
service_journal.rs

1//! What:
2//!  The resident service's journal: one file per batch of commits, with the one durable write the batch needs, and the
3//!  decision a restart makes about a batch it finds open.
4//! Why:
5//!  The branch moves only after the intent is on disk, so after any kill the journal and the branch say whether the
6//!  batch landed; a restart finishes the one step that may be missing (the index update) or drops the intent, and a
7//!  request that landed is remembered by its identity so a retry is answered, not landed twice
8//!  (`doc/planning/cli-git-resident-service.md`, "Durability and crash recovery").
9//!
10//! In TS you'd write (pseudocode):
11//! ```ts
12//! await writeIntent(dir, intent); // file fsync, rename, directory fsync: the batch's only synchronous write
13//! ```
14
15use super::repo_read_layout::dot_git_target;
16use super::service_protocol::Cleanup;
17use std::collections::HashMap;
18use std::fs::{self, File};
19use std::io::Write;
20use std::path::{Path, PathBuf};
21
22/// Extension of an intent whose batch may be unfinished.
23pub const OPEN_EXTENSION: &str = "intent";
24
25/// Extension of a finished batch, kept so its request identities are remembered.
26pub const DONE_EXTENSION: &str = "done";
27
28/// Extension of a file being written; never read as an intent.
29const TEMPORARY_EXTENSION: &str = "tmp";
30
31/// What:
32///  What the service decided to do for a batch, written before the branch moves.
33/// Why:
34///   Enough to finish the batch after a kill: where the branch was, where it goes, which requests, which index paths.
35///
36/// In TS you'd write (pseudocode):
37/// ```ts
38/// type Intent = { seq; repository; commonDir; reference; old; new; ids; paths };
39/// ```
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub struct Intent {
42    /// Number of the batch, unique and increasing within one journal.
43    pub seq: u64,
44    /// Worktree root whose index the batch updates.
45    pub repository: PathBuf,
46    /// Common git directory.
47    pub common_dir: PathBuf,
48    /// The branch.
49    pub reference: String,
50    /// The branch before the batch.
51    pub old: String,
52    /// The branch after the batch.
53    pub new: String,
54    /// Identities of the requests in the batch.
55    pub ids: Vec<String>,
56    /// The commit each request became, in the same order as the identities.
57    pub commits: Vec<String>,
58    /// Paths whose index entries the batch updates.
59    pub paths: Vec<String>,
60    /// Whether the index entries to update are the paths that differ between `old` and `new`, read from the repository
61    ///  when they are needed (a commit Git built has no list of changes to carry, and its names are bytes).
62    pub derived: bool,
63    /// The conclusion state the landing removes after the branch moved; nothing for any other batch.
64    pub cleanup: Option<Cleanup>,
65    /// The real index whose lock the landing held, so a restart can remove its own stale lock and finish the index.
66    pub index: PathBuf,
67    /// The worktree's own Git directory, which names the instance that serves the batch; an intent written before it was
68    ///  recorded reads as the Git directory of its repository's worktree.
69    pub git_dir: PathBuf,
70}
71
72/// What a restart does with an open intent.
73#[derive(Clone, Copy, Debug, Eq, PartialEq)]
74pub enum Recovery {
75    /// The batch never landed; forget the intent.
76    Drop,
77    /// The batch landed; make sure the index shows it, then remember the identities.
78    Finish,
79}
80
81/// What:
82///  The decision for an open intent from the branch's current value.
83/// Why:
84///   The branch is the commit point: still at the old value means nothing happened, at the new value or past it
85///  (`new_is_ancestor_of_current`) means the batch landed, anywhere else means it cannot land now.
86///
87/// In TS you'd write (pseudocode):
88/// ```ts
89/// recoveryFor(intent, current, newIsAncestorOfCurrent)
90/// ```
91pub fn recovery_for(intent: &Intent, current: &str, new_is_ancestor_of_current: bool) -> Recovery {
92    if current == intent.new || (current != intent.old && new_is_ancestor_of_current) {
93        return Recovery::Finish;
94    }
95    return Recovery::Drop;
96}
97
98/// The text of an intent: `key=value` lines, tabs between list items.
99pub fn intent_text(intent: &Intent) -> String {
100    let cleanup: String = intent.cleanup.as_ref().map_or_else(String::new, |found| {
101        return format!("{}\t{}\t{}", found.git_dir.display(), found.scratch.display(), u8::from(found.reftable));
102    });
103    return format!(
104        "seq={}\nrepository={}\ncommon={}\nref={}\nold={}\nnew={}\nids={}\ncommits={}\npaths={}\nderived={}\ncleanup={}\nindex={}\ngitdir={}\n",
105        intent.seq,
106        intent.repository.display(),
107        intent.common_dir.display(),
108        intent.reference,
109        intent.old,
110        intent.new,
111        intent.ids.join("\t"),
112        intent.commits.join("\t"),
113        intent.paths.join("\t"),
114        u8::from(intent.derived),
115        cleanup,
116        intent.index.display(),
117        intent.git_dir.display(),
118    );
119}
120
121/// What:
122///  The worktree's own Git directory, read from the worktree's `.git` entry: the entry itself when it is a directory, the
123///  directory a `gitdir:` file names for a linked worktree, and `.git` under the worktree when it cannot be read.
124/// Why:
125///   An intent written before it recorded its Git directory has only the repository to name the worktree by; the worktree's
126///  instance is the hash of this directory, so the recovery that finds the intent must resolve it the way a commit does.
127///
128/// In TS you'd write (pseudocode):
129/// ```ts
130/// gitDirOfWorktree('/work/repo') // '/work/repo/.git', or '/work/main/.git/worktrees/repo' for a linked worktree
131/// ```
132fn git_dir_of_worktree(repository: &Path) -> PathBuf {
133    return match dot_git_target(repository) {
134        Some(Some((git_dir, _))) => git_dir,
135        Some(None) | None => repository.join(".git"),
136    };
137}
138
139/// What:
140///  Reads an intent's text.
141/// Why:
142///   A damaged file is no intent: recovery drops it.
143///
144/// In TS you'd write (pseudocode):
145/// ```ts
146/// parseIntent(text) // undefined when damaged
147/// ```
148pub fn parse_intent(text: &str) -> Option<Intent> {
149    let value = |key: &str| -> Option<&str> { return text.lines().find_map(|line| { return line.strip_prefix(key)?.strip_prefix('='); }); };
150    let list = |key: &str| -> Option<Vec<String>> {
151        return Some(value(key)?.split('\t').filter(|item| { return !item.is_empty(); }).map(str::to_string).collect());
152    };
153    let index: PathBuf = value("index").map_or_else(|| { return PathBuf::from(value("repository").unwrap_or("")).join(".git").join("index"); }, PathBuf::from);
154    let repository: PathBuf = PathBuf::from(value("repository")?);
155    // An intent written before the Git directory was recorded names its worktree by the repository it was made for, never
156    //  by the directory its index sits in, which `GIT_INDEX_FILE` can put anywhere.
157    let worktree_git_dir: PathBuf = value("gitdir").map_or_else(|| { return git_dir_of_worktree(repository.as_path()); }, PathBuf::from);
158    return Some(Intent {
159        seq: value("seq")?.parse().ok()?,
160        repository,
161        common_dir: PathBuf::from(value("common")?),
162        reference: value("ref")?.to_string(),
163        old: value("old")?.to_string(),
164        new: value("new")?.to_string(),
165        ids: list("ids")?,
166        commits: list("commits")?,
167        paths: list("paths")?,
168        // Intents written before these fields existed name neither.
169        derived: value("derived") == Some("1"),
170        index,
171        git_dir: worktree_git_dir,
172        cleanup: value("cleanup").and_then(|entry| {
173            let mut parts = entry.split('\t');
174            let (git_dir, scratch, reftable) = (parts.next()?, parts.next()?, parts.next()?);
175            return Some(Cleanup { git_dir: PathBuf::from(git_dir), scratch: PathBuf::from(scratch), reftable: reftable == "1" });
176        }),
177    });
178}
179
180/// The path of a batch's file with an extension.
181pub fn batch_path(dir: &Path, seq: u64, extension: &str) -> PathBuf {
182    return dir.join(format!("{seq}.{extension}"));
183}
184
185/// What:
186///  Writes an intent durably: the file is synced, renamed into place, and the directory is synced.
187/// Why:
188///   This is the only synchronous write of a batch, whatever its size.
189///
190/// In TS you'd write (pseudocode):
191/// ```ts
192/// await writeIntent(dir, intent)
193/// ```
194pub fn write_intent(dir: &Path, intent: &Intent) -> std::io::Result<()> {
195    let temporary: PathBuf = batch_path(dir, intent.seq, TEMPORARY_EXTENSION);
196    let mut file: File = File::create(&temporary)?;
197    file.write_all(intent_text(intent).as_bytes())?;
198    file.sync_all()?;
199    fs::rename(&temporary, batch_path(dir, intent.seq, OPEN_EXTENSION))?;
200    return File::open(dir)?.sync_all();
201}
202
203/// Marks a batch finished. Not synced: if the mark is lost a restart redoes an idempotent step.
204pub fn mark_done(dir: &Path, seq: u64) -> std::io::Result<()> {
205    return fs::rename(batch_path(dir, seq, OPEN_EXTENSION), batch_path(dir, seq, DONE_EXTENSION));
206}
207
208/// What:
209///  The intents in the journal with an extension, in batch order, and the temporary files removed on the way.
210/// Why:
211///   Recovery reads the open ones; startup reads the done ones for the request identities.
212///
213/// In TS you'd write (pseudocode):
214/// ```ts
215/// listIntents(dir, 'intent')
216/// ```
217pub fn list_intents(dir: &Path, extension: &str) -> Vec<(PathBuf, Option<Intent>)> {
218    let Ok(entries) = fs::read_dir(dir) else {
219        return Vec::new();
220    };
221    let mut found: Vec<(PathBuf, Option<Intent>)> = Vec::new();
222    for entry in entries.flatten() {
223        let path: PathBuf = entry.path();
224        match path.extension().and_then(|text| { return text.to_str(); }) {
225            Some(TEMPORARY_EXTENSION) => {
226                let _removed = fs::remove_file(&path);
227            }
228            Some(found_extension) if found_extension == extension => {
229                let parsed: Option<Intent> = fs::read_to_string(&path).ok().and_then(|text| { return parse_intent(text.as_str()); });
230                found.push((path, parsed));
231            }
232            _ => {}
233        }
234    }
235    found.sort_by_key(|(path, intent)| {
236        return intent.as_ref().map_or_else(|| { return path.to_string_lossy().len() as u64; }, |parsed| { return parsed.seq; });
237    });
238    return found;
239}
240
241/// How many finished batches a journal keeps. A request is answered as already landed only when its own client sends it again
242///  after a broken connection: at most `RECONNECTS` times, each after a pause of milliseconds and a wait for a service to
243///  start of at most `START_WAIT` (`service_client.rs`), so the resend of a landed request arrives within seconds of the
244///  landing. A service lands a batch in the time of a few Git processes, so this many batches reach back past any such resend.
245pub const DONE_RETAINED: usize = 1024;
246
247/// What:
248///  Removes the files of the oldest finished batches, keeping the newest `retained`, and gives how many it removed.
249/// Why:
250///   A finished batch's file is only memory of the request identities it landed. Nothing else removed them, so a journal grew by
251///  a file per batch for as long as the worktree lived. Batch numbers increase with time, so the oldest are the smallest.
252///  Only files named as a batch number with the finished extension are touched, and a file that cannot be removed is left.
253///
254/// In TS you'd write (pseudocode):
255/// ```ts
256/// await pruneDone(dir, DONE_RETAINED) // 3: removed the three oldest
257/// ```
258pub fn prune_done(dir: &Path, retained: usize) -> usize {
259    let Ok(entries) = fs::read_dir(dir) else {
260        return 0;
261    };
262    let mut finished: Vec<(u64, PathBuf)> = entries
263        .flatten()
264        .filter_map(|entry| {
265            let path: PathBuf = entry.path();
266            if path.extension()? != DONE_EXTENSION || !entry.file_type().ok()?.is_file() {
267                return None;
268            }
269            let seq: u64 = path.file_stem()?.to_str()?.parse().ok()?;
270            return Some((seq, path));
271        })
272        .collect();
273    finished.sort_by_key(|(seq, _)| { return std::cmp::Reverse(*seq); });
274    return finished.into_iter().skip(retained).filter(|(_, path)| { return fs::remove_file(path).is_ok(); }).count();
275}
276
277/// The request identities of every finished batch, each with the commit it became.
278pub fn landed_commits(dir: &Path) -> HashMap<String, String> {
279    let mut landed: HashMap<String, String> = HashMap::new();
280    for (_, intent) in list_intents(dir, DONE_EXTENSION) {
281        if let Some(parsed) = intent {
282            landed.extend(parsed.ids.into_iter().zip(parsed.commits));
283        }
284    }
285    return landed;
286}
287
288/// Journal controls stay out of the release executable.
289#[cfg(test)]
290#[path = "service_journal_tests.rs"]
291mod tests;