1use 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
27pub const LANDING_ATTEMPTS: usize = 3;
29
30pub struct LandContext {
32 pub git: GitContext,
34 pub journal: PathBuf,
36 pub on_objects_written: Option<Box<dyn Fn() + Send + Sync>>,
38 pub index_wait: std::time::Duration,
40}
41
42#[derive(Clone, Debug, Eq, PartialEq)]
44pub enum Outcome {
45 Landed { commit: String },
47 RetryPrepare { base: String },
49 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
68fn 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
82fn overlaps(path: &str, changed: &str) -> bool {
84 return path == changed || path.starts_with(&format!("{changed}/")) || changed.starts_with(&format!("{path}/"));
85}
86
87fn 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 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
123fn 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
137fn 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
142fn 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 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
153pub fn land_batch(context: &LandContext, seq: u64, requests: &[CommitRequest]) -> Result<Vec<Outcome>, FailureCode> {
164 return land_batch_announcing(context, seq, requests, &|_| {});
165}
166
167pub 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 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 let unborn: bool = is_zero_object(first.base.as_str());
188 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 if first.reference == "HEAD" && run(&git, repository, &["symbolic-ref", "--quiet", "HEAD"], None)?.succeeded() {
204 return Ok(vec![Outcome::BranchMoved]);
205 }
206 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 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 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 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 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 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 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 let removal: String = if first.commit.is_some() { String::new() } else { format!("delete {scratch}\n") };
316 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 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 attempts_left -= 1;
327 if attempts_left == 0 {
328 return Err(FailureCode::BranchKeepsChanging);
329 }
330 continue;
331 }
332 reach("after-ref");
333 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#[derive(Clone, Debug, Eq, PartialEq)]
349pub struct RecoveryReport {
350 pub seq: u64,
352 pub decision: Recovery,
354}
355
356pub fn recover(context: &LandContext) -> Vec<RecoveryReport> {
367 return recover_selected(context, &|_| { return true; }, true);
368}
369
370pub 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#[cfg(test)]
426#[path = "service_land_tests.rs"]
427mod tests;