Skip to main content

git_policy_cli/
service_land.rs

1//! What:
2//!  The service's serialized step: land a batch of prepared commits on a branch, and finish the batches a killed
3//!  service left open.
4//! Why:
5//!  Everything that must happen one commit at a time happens here, in a fixed order, with one durable write: the objects
6//!  of the whole batch are written by one `fast-import`, the intent is journaled, the branch moves by one compare-and-swap,
7//!  the index entries of the named paths are updated, and the intent is marked done
8//!  (`doc/planning/cli-git-resident-service.md`, "The serialized step, group commit, FIFO and backpressure").
9//!
10//! In TS you'd write (pseudocode):
11//! ```ts
12//! const outcomes = await landBatch(context, seq, requests);
13//! ```
14
15use super::service_fault::reach;
16use super::service_head::head_names;
17use super::service_instance::instance_of;
18use super::service_pruned::batch_content_missing;
19use super::service_journal::{Intent, Recovery, list_intents, mark_done, recovery_for, write_intent, OPEN_EXTENSION};
20use super::service_index_lock::{Announce, IndexLock, acquire, remove_stale, try_acquire};
21use super::service_land_follow::{IndexPaths, build_index, classify, remove_conclusion_state, storage_failure};
22use super::service_protocol::{CommitRequest, FailureCode, is_zero_object};
23use super::transaction_git::{GitContext, GitOutput, GitRequest, run_git};
24use std::collections::{BTreeSet, HashMap};
25use std::path::{Path, PathBuf};
26
27/// How many times a batch is built again when the branch moved under it before the failure is reported.
28pub const LANDING_ATTEMPTS: usize = 3;
29
30/// What the service needs to land: how to run Git and where the journal lives.
31pub struct LandContext {
32    /// How to run the real Git, with the bounds of `child_class.rs`.
33    pub git: GitContext,
34    /// Directory of the journal.
35    pub journal: PathBuf,
36    /// Test seam: called after the batch's objects exist and before the branch moves.
37    pub on_objects_written: Option<Box<dyn Fn() + Send + Sync>>,
38    /// How long a landing waits for another program that holds the index lock before it gives up with nothing changed.
39    pub index_wait: std::time::Duration,
40}
41
42/// What became of one request of a batch.
43#[derive(Clone, Debug, Eq, PartialEq)]
44pub enum Outcome {
45    /// The commit is on the branch.
46    Landed { commit: String },
47    /// A named path changed on the branch since the request's base.
48    RetryPrepare { base: String },
49    /// An amend, whose parents are the base's parents, found the branch somewhere else than at its base.
50    BranchMoved,
51}
52
53fn run(git: &GitContext, repository: &Path, arguments: &[&str], input: Option<Vec<u8>>) -> Result<GitOutput, FailureCode> {
54    let mut request: GitRequest = GitRequest::new(repository, arguments);
55    request.input = input;
56    let output: GitOutput = run_git(git, &request).map_err(|_| { return FailureCode::Unavailable; })?;
57    return Ok(output);
58}
59
60fn checked(git: &GitContext, repository: &Path, arguments: &[&str], input: Option<Vec<u8>>) -> Result<String, FailureCode> {
61    let output: GitOutput = run(git, repository, arguments, input)?;
62    if !output.succeeded() {
63        return Err(classify(&output));
64    }
65    return Ok(String::from_utf8_lossy(output.stdout.as_slice()).trim().to_string());
66}
67
68/// A path in the quoted form `fast-import` reads, so no byte of a name can end the line or the field.
69fn quoted(path: &str) -> String {
70    let mut text: String = String::from("\"");
71    for character in path.chars() {
72        match character {
73            '"' => text.push_str("\\\""),
74            '\\' => text.push_str("\\\\"),
75            other => text.push(other),
76        }
77    }
78    text.push('"');
79    return text;
80}
81
82/// Whether two repository paths touch the same file or one contains the other.
83fn overlaps(path: &str, changed: &str) -> bool {
84    return path == changed || path.starts_with(&format!("{changed}/")) || changed.starts_with(&format!("{path}/"));
85}
86
87/// The stream that makes one commit per request on a scratch branch that starts at `old`, or, for an amend, one commit
88///  whose parents are `amended_parents` and whose whole tree is the request's tree.
89fn import_stream(scratch: &str, old: &str, requests: &[&CommitRequest], amended_parents: &[String]) -> Vec<u8> {
90    let mut bytes: Vec<u8> = Vec::new();
91    for (index, request) in requests.iter().enumerate() {
92        bytes.extend(format!("commit {scratch}\nmark :{}\n", index + 1).as_bytes());
93        if let Some(author) = &request.author {
94            bytes.extend(format!("author {author}\n").as_bytes());
95        }
96        bytes.extend(format!("committer {}\ndata {}\n", request.committer, request.message.len()).as_bytes());
97        bytes.extend(request.message.as_bytes());
98        bytes.push(b'\n');
99        if let Some(tree) = request.tree.as_deref().filter(|_| { return request.amend; }) {
100            // An amend replaces the tip: its parents are the base's parents, and its tree is the one the client wrote.
101            for (position, parent) in amended_parents.iter().enumerate() {
102                bytes.extend(format!("{} {parent}\n", if position == 0 { "from" } else { "merge" }).as_bytes());
103            }
104            bytes.extend(format!("M 040000 {tree} \"\"\n").as_bytes());
105            bytes.push(b'\n');
106            continue;
107        }
108        if index == 0 {
109            bytes.extend(format!("from {old}\n").as_bytes());
110        }
111        for change in &request.changes {
112            match &change.blob {
113                Some(blob) => bytes.extend(format!("M {:o} {blob} {}\n", change.mode, quoted(change.path.as_str())).as_bytes()),
114                None => bytes.extend(format!("D {}\n", quoted(change.path.as_str())).as_bytes()),
115            }
116        }
117        bytes.push(b'\n');
118    }
119    bytes.extend(b"done\n");
120    return bytes;
121}
122
123/// The object names `fast-import` recorded for the marks, in request order.
124fn commits_from_marks(text: &str, count: usize) -> Option<Vec<String>> {
125    let mut commits: Vec<Option<String>> = vec![None; count];
126    for line in text.lines() {
127        let mut parts = line.split(' ');
128        let (Some(mark), Some(name)) = (parts.next(), parts.next()) else { continue };
129        let slot: usize = mark.trim_start_matches(':').parse::<usize>().ok()?;
130        if slot >= 1 && slot <= count {
131            commits[slot - 1] = Some(name.to_string());
132        }
133    }
134    return commits.into_iter().collect();
135}
136
137/// The index entries a batch's intent names.
138fn intent_paths(intent: &Intent) -> IndexPaths<'_> {
139    return if intent.derived { IndexPaths::Derived { old: intent.old.as_str() } } else { IndexPaths::Listed(intent.paths.as_slice()) };
140}
141
142/// Finishes what follows the branch move: the conclusion state is removed, then the index entries are updated. Both are
143///  idempotent. Whether both are done.
144fn follow_up(git: &GitContext, repository: &Path, intent: &Intent, lock: IndexLock) -> bool {
145    let cleaned: bool = intent.cleanup.as_ref().is_none_or(|cleanup| { return remove_conclusion_state(git, repository, cleanup); });
146    // The new index is built beside the real one and installed by the release of the lock the landing holds.
147    let Ok(built) = build_index(git, repository, intent.new.as_str(), intent_paths(intent), intent.index.as_path(), intent.seq) else {
148        return false;
149    };
150    return lock.release_with(built.as_path()).is_ok() && cleaned;
151}
152
153/// What:
154///  Lands a batch of requests that share a repository, a common git directory and a branch.
155/// Why:
156///   Requests whose paths changed on the branch since their base are sent back to be prepared again; the others become
157///  one commit each, in order, on the branch, with one journal write and one branch update for all of them.
158///
159/// In TS you'd write (pseudocode):
160/// ```ts
161/// await landBatch(context, seq, requests) // one outcome per request, in order
162/// ```
163pub fn land_batch(context: &LandContext, seq: u64, requests: &[CommitRequest]) -> Result<Vec<Outcome>, FailureCode> {
164    return land_batch_announcing(context, seq, requests, &|_| {});
165}
166
167/// `land_batch`, telling the clients of the batch what it waits for when another program holds the index.
168pub fn land_batch_announcing(context: &LandContext, seq: u64, requests: &[CommitRequest], announce: &dyn Fn(Announce)) -> Result<Vec<Outcome>, FailureCode> {
169    let first: &CommitRequest = requests.first().ok_or(FailureCode::Rejected)?;
170    if requests.iter().any(|request| {
171        return request.repository != first.repository || request.common_dir != first.common_dir || request.reference != first.reference;
172    }) {
173        return Err(FailureCode::Rejected);
174    }
175    // An amend, and a commit built elsewhere, are landed alone: each is only valid while the branch is still at its base,
176    //  which a neighbour in the same batch would change.
177    let alone: bool = requests.iter().any(CommitRequest::lands_alone);
178    if alone && requests.len() != 1 {
179        return Err(FailureCode::Rejected);
180    }
181    let repository: &Path = first.repository.as_path();
182    let git: GitContext = GitContext { common_dir: Some(first.common_dir.clone()), ..context.git.clone() };
183    let scratch: String = format!("refs/worktree/cli-git-service/{seq}");
184    let mut outcomes: Vec<Outcome>;
185    let mut attempts_left: usize = LANDING_ATTEMPTS;
186    // A branch that does not exist yet is prepared against the all-zero name and lands only while it still does not.
187    let unborn: bool = is_zero_object(first.base.as_str());
188    // Git's own order: the index lock is taken before the branch is read or moved and given up when the new index is in place,
189    //  so a foreign `git` that holds it finishes first and this landing builds on what it left. A lock that is not given up
190    //  here (a refusal, a failure) is removed when it goes out of scope, and the index stays as it was.
191    let mut lock: Option<IndexLock> = Some(acquire(first.index.as_path(), seq, context.index_wait, announce).map_err(|failure| { return failure.code; })?);
192    loop {
193        let old: String = match checked(&git, repository, &["rev-parse", "--verify", "--quiet", first.reference.as_str()], None) {
194            Ok(found) => found,
195            Err(_) if unborn => first.base.clone(),
196            Err(code) => return Err(code),
197        };
198        if alone && first.base != old {
199            return Ok(vec![Outcome::BranchMoved]);
200        }
201        // Git's own compare does not refuse a symbolic `HEAD` when it is told not to follow it (measured: it replaces the
202        //  symbolic reference), so a head that became a branch since the commit was prepared is found here, before the move.
203        if first.reference == "HEAD" && run(&git, repository, &["symbolic-ref", "--quiet", "HEAD"], None)?.succeeded() {
204            return Ok(vec![Outcome::BranchMoved]);
205        }
206        // Native Git updates `HEAD`, so a worktree that switched branches while the commit waited fails the commit with nothing
207        //  changed. The named branch would move all the same, and the index built for it would replace the other branch's.
208        if first.reference != "HEAD" && !head_names(&git, repository, first.index.as_path(), first.common_dir.as_path(), first.reference.as_str())? {
209            return Ok(vec![Outcome::BranchMoved; requests.len()]);
210        }
211        let amended_parents: Vec<String> = if alone && !unborn {
212            let listing: String = checked(&git, repository, &["rev-list", "--parents", "--max-count=1", first.base.as_str()], None)?;
213            listing.split_whitespace().skip(1).map(str::to_string).collect()
214        } else {
215            Vec::new()
216        };
217        // One tree comparison per distinct base: the paths that changed on the branch since then.
218        let mut changed_since: HashMap<&str, BTreeSet<String>> = HashMap::new();
219        let mut landing: Vec<(usize, &CommitRequest)> = Vec::new();
220        outcomes = vec![Outcome::RetryPrepare { base: old.clone() }; requests.len()];
221        for (index, request) in requests.iter().enumerate() {
222            if request.base != old && !changed_since.contains_key(request.base.as_str()) {
223                let listing: String = checked(&git, repository, &["diff-tree", "-r", "--name-only", "-z", request.base.as_str(), old.as_str()], None)?;
224                changed_since.insert(request.base.as_str(), listing.split('\0').filter(|name| { return !name.is_empty(); }).map(str::to_string).collect());
225            }
226            let conflicts: bool = request.base != old
227                && request.changes.iter().any(|change| {
228                    return changed_since.get(request.base.as_str()).is_some_and(|names| { return names.iter().any(|name| { return overlaps(change.path.as_str(), name.as_str()); }); });
229                });
230            // A member of this batch that an earlier member overlaps would replace that member's bytes in the stream below. It
231            //  stays in the batch only when it captured the worktree (a batch has one) later than that member, so its bytes
232            //  hold the member's edit; any other request is sent back and merged against the member's landed commit.
233            let shadowed: bool = landing.iter().any(|(_, earlier)| {
234                let later_capture: bool = earlier.captured != 0 && request.captured > earlier.captured;
235                return !later_capture && request.changes.iter().any(|change| { return earlier.changes.iter().any(|member| { return overlaps(change.path.as_str(), member.path.as_str()); }); });
236            });
237            if !conflicts && !shadowed {
238                landing.push((index, request));
239            }
240        }
241        if landing.is_empty() {
242            return Ok(outcomes);
243        }
244        let batch: Vec<&CommitRequest> = landing.iter().map(|(_, request)| { return *request; }).collect();
245        // Content that `git gc --prune=now` removed after the preparation is found before anything is imported or moved: the
246        //  client prepares the commit again, and says so plainly when that is not enough.
247        if batch_content_missing(first.common_dir.as_path(), batch.as_slice()) {
248            return Err(FailureCode::Unavailable);
249        }
250        let (commits, new): (Vec<String>, String) = if let Some(built) = first.commit.as_deref() {
251            // A commit Git built elsewhere lands as it is; it must be a commit with the parents this request's rule gives:
252            //  an amend has the replaced commit's parents, a commit on a branch that did not exist has none, and any other
253            //  commit has the branch tip first (a merge conclusion has the merged commits after it).
254            let listing: GitOutput = run(&git, repository, &["rev-list", "--parents", "--max-count=1", built], None)?;
255            let text: String = String::from_utf8_lossy(listing.stdout.as_slice()).into_owned();
256            let mut words = text.split_whitespace();
257            let named_itself: bool = listing.succeeded() && words.next() == Some(built);
258            let parents: Vec<String> = words.map(str::to_string).collect();
259            let acceptable: bool = if first.amend {
260                parents == amended_parents
261            } else if unborn {
262                parents.is_empty()
263            } else {
264                parents.first() == Some(&first.base)
265            };
266            if !named_itself || !acceptable {
267                return Err(FailureCode::Rejected);
268            }
269            // Git moves a branch to a commit without looking at what the commit holds, so a tree or a blob that a prune took
270            //  while the commit object survived would put a damaged commit on the branch.
271            let connected: Vec<&str> = if unborn { vec!["rev-list", "--objects", "--quiet", built] } else { vec!["rev-list", "--objects", "--quiet", built, "--not", old.as_str()] };
272            if !run(&git, repository, connected.as_slice(), None)?.succeeded() {
273                return Err(FailureCode::Unavailable);
274            }
275            (vec![built.to_string()], built.to_string())
276        } else {
277            let marks: PathBuf = context.journal.join(format!("marks-{seq}"));
278            let marks_argument: String = format!("--export-marks={}", marks.display());
279            checked(&git, repository, &["fast-import", "--quiet", "--done", marks_argument.as_str()], Some(import_stream(scratch.as_str(), old.as_str(), &batch, amended_parents.as_slice())))?;
280            let marks_text: String = std::fs::read_to_string(&marks).map_err(|_| { return FailureCode::Unavailable; })?;
281            let _marks_removed = std::fs::remove_file(&marks);
282            let made: Vec<String> = commits_from_marks(marks_text.as_str(), batch.len()).ok_or(FailureCode::Unavailable)?;
283            let last: String = made.last().cloned().ok_or(FailureCode::Unavailable)?;
284            (made, last)
285        };
286        reach("after-objects");
287        if let Some(seam) = &context.on_objects_written {
288            seam();
289        }
290        // A commit Git built carries no list of changes: its index entries are the paths that differ from the old branch.
291        let derived: bool = first.commit.is_some();
292        let paths: Vec<String> = if derived {
293            Vec::new()
294        } else {
295            batch.iter().flat_map(|request| { return request.changes.iter().map(|change| { return change.path.clone(); }); }).collect()
296        };
297        let intent: Intent = Intent {
298            seq,
299            repository: first.repository.clone(),
300            common_dir: first.common_dir.clone(),
301            reference: first.reference.clone(),
302            old: old.clone(),
303            new: new.clone(),
304            ids: batch.iter().map(|request| { return request.id.clone(); }).collect(),
305            commits: commits.clone(),
306            paths,
307            derived,
308            cleanup: first.cleanup.clone(),
309            index: first.index.clone(),
310            git_dir: first.git_dir.clone(),
311        };
312        write_intent(context.journal.as_path(), &intent).map_err(|error| { return storage_failure(&error); })?;
313        reach("after-intent");
314        // A commit built elsewhere made no scratch branch, so there is none to remove with the move.
315        let removal: String = if first.commit.is_some() { String::new() } else { format!("delete {scratch}\n") };
316        // A detached head is the `HEAD` file itself: it is updated without following a symbolic reference, so a head that
317        //  became a branch since the commit was prepared fails the compare instead of moving that branch.
318        let direct: &str = if first.reference == "HEAD" { "option no-deref\n" } else { "" };
319        let transaction: String = format!("start\n{direct}update {} {new} {old}\n{removal}prepare\ncommit\n", first.reference);
320        let moved: GitOutput = run(&git, repository, &["update-ref", "--stdin"], Some(transaction.into_bytes()))?;
321        if !moved.succeeded() {
322            // The branch moved under the batch: forget the intent and the scratch branch, and build the batch again.
323            let _intent_removed = std::fs::remove_file(super::service_journal::batch_path(context.journal.as_path(), seq, OPEN_EXTENSION));
324            let _deleted = run(&git, repository, &["update-ref", "-d", scratch.as_str()], None);
325            // For an amend, the next round finds the tip away from its base and answers that the branch moved.
326            attempts_left -= 1;
327            if attempts_left == 0 {
328                return Err(FailureCode::BranchKeepsChanging);
329            }
330            continue;
331        }
332        reach("after-ref");
333        // The branch has moved: the commits exist whatever happens to the index, which recovery finishes.
334        let Some(held) = lock.take() else { return Err(FailureCode::Unavailable) };
335        if follow_up(&git, repository, &intent, held) {
336            reach("after-index");
337            let _marked = mark_done(context.journal.as_path(), seq);
338        }
339        for (slot, (index, request)) in landing.iter().enumerate() {
340            outcomes[*index] = Outcome::Landed { commit: commits[slot].clone() };
341            super::service_captures::record_landed(request.common_dir.as_path(), request.repository.as_path(), commits[slot].as_str(), request.captured);
342        }
343        return Ok(outcomes);
344    }
345}
346
347/// One thing a restart did, for the service's log.
348#[derive(Clone, Debug, Eq, PartialEq)]
349pub struct RecoveryReport {
350    /// The batch.
351    pub seq: u64,
352    /// What was decided.
353    pub decision: Recovery,
354}
355
356/// What:
357///  Finishes or drops every batch the journal holds open.
358/// Why:
359///   Runs before the service accepts a connection, and again before each batch (`service_server.rs`), so an index update
360///  that gave up while another program held Git's index lock is finished by the next commit and not only by a restart.
361///
362/// In TS you'd write (pseudocode):
363/// ```ts
364/// await recover(context)
365/// ```
366pub fn recover(context: &LandContext) -> Vec<RecoveryReport> {
367    return recover_selected(context, &|_| { return true; }, true);
368}
369
370/// What:
371///  Finishes or drops the open batches of the worktree one instance serves, found in a journal that other worktrees' batches
372///  may share.
373/// Why:
374///   The single service of the releases before one service per worktree kept one journal for every worktree, in the directory
375///  above each instance's own, and an instance takes over the batches of its worktree there (found by the Git directory the
376///  intent records, which an index outside it, as `GIT_INDEX_FILE` names one, cannot change). A development run may also give several instances one journal. Whatever belongs to
377///  another worktree is left to its instance, and a record that cannot be read is not any instance's to remove.
378///
379/// In TS you'd write (pseudocode):
380/// ```ts
381/// await recoverInstance(context, instance)
382/// ```
383pub fn recover_instance(context: &LandContext, instance: &str) -> Vec<RecoveryReport> {
384    let ours = |intent: &Intent| -> bool { return instance_of(intent.git_dir.as_path()) == instance; };
385    return recover_selected(context, &ours, false);
386}
387
388fn recover_selected(context: &LandContext, selected: &dyn Fn(&Intent) -> bool, remove_unreadable: bool) -> Vec<RecoveryReport> {
389    let mut reports: Vec<RecoveryReport> = Vec::new();
390    for (path, parsed) in list_intents(context.journal.as_path(), OPEN_EXTENSION) {
391        let Some(intent) = parsed else {
392            if remove_unreadable {
393                let _removed = std::fs::remove_file(&path);
394            }
395            continue;
396        };
397        if !selected(&intent) {
398            continue;
399        }
400        let git: GitContext = GitContext { common_dir: Some(intent.common_dir.clone()), ..context.git.clone() };
401        let current: String = checked(&git, intent.repository.as_path(), &["rev-parse", "--verify", intent.reference.as_str()], None).unwrap_or_default();
402        let ancestor: bool = run(&git, intent.repository.as_path(), &["merge-base", "--is-ancestor", intent.new.as_str(), current.as_str()], None)
403            .is_ok_and(|output| { return output.succeeded(); });
404        let decision: Recovery = recovery_for(&intent, current.as_str(), ancestor);
405        match decision {
406            Recovery::Drop => {
407                remove_stale(intent.index.as_path(), intent.seq);
408                let _removed = std::fs::remove_file(&path);
409            }
410            Recovery::Finish => {
411                remove_stale(intent.index.as_path(), intent.seq);
412                if let Some(held) = try_acquire(intent.index.as_path(), intent.seq)
413                    && follow_up(&git, intent.repository.as_path(), &intent, held)
414                {
415                    let _marked = mark_done(context.journal.as_path(), intent.seq);
416                }
417            }
418        }
419        reports.push(RecoveryReport { seq: intent.seq, decision });
420    }
421    return reports;
422}
423
424/// Landing controls stay out of the release executable.
425#[cfg(test)]
426#[path = "service_land_tests.rs"]
427mod tests;