1use std::path::Path;
4use std::process::{Command, Stdio};
5
6use crate::format::{Names, WRITE};
7use crate::git;
8
9#[derive(Clone, Copy, Debug, PartialEq)]
16pub enum Mirror {
17 Fresh,
19 NoOrigin,
21 Deleted,
23 Undeletable,
25 Unreachable,
27 TimedOut,
29 Unwritable,
32}
33
34impl Mirror {
35 pub fn as_str(self) -> &'static str {
36 match self {
37 Mirror::Fresh => "fetched",
38 Mirror::NoOrigin => "no-origin",
39 Mirror::Deleted => "absent",
40 Mirror::Undeletable => "undeletable",
41 Mirror::Unreachable | Mirror::TimedOut => "unreachable",
42 Mirror::Unwritable => "unwritable",
43 }
44 }
45 pub fn judged(self) -> bool {
46 matches!(self, Mirror::Fresh | Mirror::NoOrigin)
47 }
48}
49
50fn drop_mirror(root: &Path, loud: &mut Vec<String>, notes_ref: &str) -> Mirror {
52 let full = format!("refs/notes/{notes_ref}");
53 let Some(oid) = git::stdout_in(root, &["rev-parse", "--verify", "--quiet", &full]) else {
54 return Mirror::Deleted;
55 };
56 if git::succeeds_in(root, &["update-ref", "-d", &full, &oid]) {
57 loud.push(format!(
58 "origin has no {full}; deleted the local mirror (was {oid}); restore: git update-ref {full} {oid}"
59 ));
60 Mirror::Deleted
61 } else {
62 Mirror::Undeletable
63 }
64}
65
66pub(crate) const TMP_NS: &str = "refs/greensummit-tmp/";
70
71fn sweep_tmp_refs(root: &Path) {
76 let Some(refs) = git::stdout_in(root, &["for-each-ref", "--format=%(refname)", TMP_NS]) else {
77 return;
78 };
79 let me = std::process::id().to_string();
80 for r in refs.lines() {
81 let Some(pid) = r
82 .strip_prefix(TMP_NS)
83 .and_then(|rest| rest.split('/').next())
84 .filter(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
85 else {
86 continue;
87 };
88 if pid != me && process_gone(pid) {
89 let _ = git::succeeds_in(root, &["update-ref", "-d", r]);
90 }
91 }
92}
93
94fn process_gone(pid: &str) -> bool {
97 if !cfg!(unix) {
98 return false;
99 }
100 Command::new("kill")
101 .args(["-0", pid])
102 .env("LC_ALL", "C")
103 .stdin(Stdio::null())
104 .stdout(Stdio::null())
105 .stderr(Stdio::piped())
106 .output()
107 .is_ok_and(|o| {
108 !o.status.success()
109 && String::from_utf8_lossy(&o.stderr)
110 .to_lowercase()
111 .contains("no such process")
112 })
113}
114
115fn adopt(root: &Path, notes_ref: &str, tmp: &str, old: Option<&str>) -> Mirror {
121 let full = format!("refs/notes/{notes_ref}");
122 let Some(new) = git::stdout_in(root, &["rev-parse", "--verify", "--quiet", tmp]) else {
123 return Mirror::Unwritable;
124 };
125 if git::succeeds_in(root, &["update-ref", &full, &new, old.unwrap_or("")]) {
126 return Mirror::Fresh;
127 }
128 match git::stdout_in(root, &["rev-parse", "--verify", "--quiet", &full]) {
129 Some(now) if now == new => Mirror::Fresh,
130 _ => Mirror::Unwritable,
131 }
132}
133
134pub fn sync_mirrors(root: &Path, loud: &mut Vec<String>) -> (Mirror, Mirror) {
141 let synced = sync_mirrors_of(root, &WRITE);
142 loud.extend(synced.loud);
143 (synced.notes, synced.inputs)
144}
145
146#[derive(Debug, Clone, PartialEq)]
150#[non_exhaustive]
151pub struct Synced {
152 pub notes: Mirror,
153 pub inputs: Mirror,
154 pub loud: Vec<String>,
155}
156
157impl Synced {
158 pub fn origin_silent(&self) -> Option<Mirror> {
162 if self.notes == Mirror::TimedOut || self.inputs == Mirror::TimedOut {
163 Some(Mirror::TimedOut)
164 } else if self.notes == Mirror::Unreachable && self.inputs == Mirror::Unreachable {
165 Some(Mirror::Unreachable)
166 } else {
167 None
168 }
169 }
170}
171
172pub fn sync_mirrors_of(root: &Path, names: &Names) -> Synced {
176 let mut loud = Vec::new();
179 if !git::succeeds_in(root, &["remote", "get-url", "origin"]) {
180 return Synced {
181 notes: Mirror::NoOrigin,
182 inputs: Mirror::NoOrigin,
183 loud,
184 };
185 }
186 sweep_tmp_refs(root);
187 let pid = std::process::id();
188 let full = |r: &str| format!("refs/notes/{r}");
189 let tmp = |r: &str| format!("{TMP_NS}{pid}/{r}");
190 let spec = |r: &str| format!("+{}:{}", full(r), tmp(r));
191 for r in [names.notes_ref, names.inputs_ref] {
196 let _ = git::succeeds_in(root, &["update-ref", "-d", &tmp(r)]);
197 if let Some(lock) = git::stdout_in(
198 root,
199 &["rev-parse", "--git-path", &format!("{}.lock", tmp(r))],
200 ) {
201 let _ = std::fs::remove_file(root.join(lock));
203 }
204 }
205 let old_main = git::stdout_in(
206 root,
207 &["rev-parse", "--verify", "--quiet", &full(names.notes_ref)],
208 );
209 let old_inputs = git::stdout_in(
210 root,
211 &["rev-parse", "--verify", "--quiet", &full(names.inputs_ref)],
212 );
213 let adopt_both = || {
214 (
215 adopt(
216 root,
217 names.notes_ref,
218 &tmp(names.notes_ref),
219 old_main.as_deref(),
220 ),
221 adopt(
222 root,
223 names.inputs_ref,
224 &tmp(names.inputs_ref),
225 old_inputs.as_deref(),
226 ),
227 )
228 };
229 let states = match git::remote(
230 root,
231 &[
232 "fetch",
233 "--quiet",
234 "origin",
235 &spec(names.notes_ref),
236 &spec(names.inputs_ref),
237 ],
238 ) {
239 git::Remote::Done(0, _) => adopt_both(),
240 git::Remote::TimedOut => (Mirror::TimedOut, Mirror::TimedOut),
242 _ => match git::remote(
243 root,
244 &[
245 "ls-remote",
246 "--exit-code",
247 "origin",
248 &full(names.notes_ref),
249 &full(names.inputs_ref),
250 ],
251 ) {
252 git::Remote::Done(0, listing) => {
253 let listed = |r: &str| {
254 let f = full(r);
255 listing
256 .lines()
257 .any(|l| l.split_whitespace().nth(1) == Some(f.as_str()))
258 };
259 let (has_main, has_inputs) = (listed(names.notes_ref), listed(names.inputs_ref));
260 let mut want = Vec::new();
261 if has_main {
262 want.push(spec(names.notes_ref));
263 }
264 if has_inputs {
265 want.push(spec(names.inputs_ref));
266 }
267 let fetched = if want.is_empty() {
268 None
269 } else {
270 let mut args = vec!["fetch", "--quiet", "origin"];
271 args.extend(want.iter().map(String::as_str));
272 Some(git::remote(root, &args))
273 };
274 let one = |present: bool, r: &str, old: Option<&str>, loud: &mut Vec<String>| {
275 if !present {
276 return drop_mirror(root, loud, r);
277 }
278 match &fetched {
279 Some(git::Remote::Done(0, _)) => adopt(root, r, &tmp(r), old),
280 Some(git::Remote::TimedOut) => Mirror::TimedOut,
281 _ => Mirror::Unreachable,
282 }
283 };
284 let notes_mirror = one(has_main, names.notes_ref, old_main.as_deref(), &mut loud);
285 let inputs_mirror = one(
286 has_inputs,
287 names.inputs_ref,
288 old_inputs.as_deref(),
289 &mut loud,
290 );
291 (notes_mirror, inputs_mirror)
292 }
293 git::Remote::Done(2, _) => (
294 drop_mirror(root, &mut loud, names.notes_ref),
295 drop_mirror(root, &mut loud, names.inputs_ref),
296 ),
297 git::Remote::TimedOut => (Mirror::TimedOut, Mirror::TimedOut),
298 _ => (Mirror::Unreachable, Mirror::Unreachable),
299 },
300 };
301 for r in [names.notes_ref, names.inputs_ref] {
302 let _ = git::succeeds_in(root, &["update-ref", "-d", &tmp(r)]);
303 }
304 let (notes, inputs) = states;
305 Synced {
306 notes,
307 inputs,
308 loud,
309 }
310}
311
312pub struct Publish<'a> {
319 pub remote: &'a str,
321 pub attempts: u32,
323 pub pause: bool,
326 pub identity: Option<(&'a str, &'a str)>,
329 pub push_env: &'a [(&'a str, &'a str)],
332}
333
334#[derive(Debug, Clone, PartialEq, Eq)]
336#[non_exhaustive]
337pub enum Published {
338 Pushed,
340 AlreadyPresent,
342 Local,
344 PushFailed,
346 Error,
348}
349
350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
357#[non_exhaustive]
358pub enum PushFailure {
359 Raced,
360 Unreachable,
361 Refused,
362}
363
364pub fn classify_push(stderr: &str) -> PushFailure {
369 const RACED: [&str; 5] = [
370 "non-fast-forward",
371 "fetch first",
372 "stale info",
373 "cannot lock ref",
374 "failed to lock",
375 ];
376 const UNREACHABLE: [&str; 5] = [
377 "Could not resolve host",
378 "Connection refused",
379 "Connection timed out",
380 "unable to access",
381 "Could not read from remote repository",
382 ];
383 let own = |l: &&str| {
384 let l = l.trim_start();
385 l.starts_with("fatal:") || l.starts_with("ssh:") || l.starts_with("error:")
386 };
387 if RACED.iter().any(|m| stderr.contains(m)) {
388 PushFailure::Raced
389 } else if stderr
390 .lines()
391 .filter(own)
392 .any(|l| UNREACHABLE.iter().any(|m| l.contains(m)))
393 {
394 PushFailure::Unreachable
395 } else {
396 PushFailure::Refused
397 }
398}
399
400fn notes_git(root: &Path, identity: Option<(&str, &str)>) -> Command {
402 let mut cmd = Command::new("git");
403 cmd.current_dir(root).stdin(Stdio::null());
404 if let Some((name, email)) = identity {
405 cmd.args([
406 "-c",
407 &format!("user.name={name}"),
408 "-c",
409 &format!("user.email={email}"),
410 ]);
411 }
412 cmd
413}
414
415fn append(
419 root: &Path,
420 identity: Option<(&str, &str)>,
421 notes_ref: &str,
422 object: &str,
423 block: &str,
424) -> Option<bool> {
425 let existing =
426 git::stdout_in(root, &["notes", "--ref", notes_ref, "show", object]).unwrap_or_default();
427 if existing.contains(block.trim_end()) {
428 return Some(false);
429 }
430 notes_git(root, identity)
431 .args(["notes", "--ref", notes_ref, "append", "-m", block, object])
432 .stdout(Stdio::null())
433 .stderr(Stdio::null())
434 .status()
435 .ok()?
436 .success()
437 .then_some(true)
438}
439
440pub fn publish(
455 root: &Path,
456 how: &Publish,
457 notes_ref: &str,
458 items: &[(String, String)],
459 log: &mut Vec<String>,
460) -> Published {
461 let full = format!("refs/notes/{notes_ref}");
462 let tref = format!("greensummit-publish-{}-{notes_ref}", std::process::id());
463 let tfull = format!("refs/notes/{tref}");
464 let mut attempt = 0;
465 let outcome = loop {
466 attempt += 1;
467 let _ = git::succeeds_in(root, &["update-ref", "-d", &tfull]);
468 let _ = git::succeeds_in(
471 root,
472 &["fetch", "--quiet", how.remote, &format!("+{full}:{tfull}")],
473 );
474 let mut appended = false;
475 for (object, block) in items {
476 match append(root, how.identity, &tref, object, block) {
477 Some(true) => appended = true,
478 Some(false) => {}
479 None => return cleanup(root, &tfull, Published::Error),
480 }
481 }
482 if !appended {
483 break Published::AlreadyPresent;
484 }
485 let out = Command::new("git")
486 .current_dir(root)
487 .args(["push", "--quiet", how.remote, &format!("{tfull}:{full}")])
488 .envs(how.push_env.iter().copied())
489 .stdin(Stdio::null())
490 .stdout(Stdio::null())
491 .output();
492 let Ok(out) = out else {
493 log.push(format!("push of {full} could not run git"));
494 break Published::PushFailed;
495 };
496 if out.status.success() {
497 if how.remote == "origin" {
498 let _ = git::succeeds_in(root, &["update-ref", &full, &tfull]);
499 }
500 break Published::Pushed;
501 }
502 let why = scrub(&String::from_utf8_lossy(&out.stderr));
503 match classify_push(&why) {
504 PushFailure::Raced if attempt < how.attempts => {
505 log.push(format!(
506 "push of {full} rejected, another job attested this tree meanwhile; retrying"
507 ));
508 if how.pause {
509 std::thread::sleep(std::time::Duration::from_secs(
510 u64::from(attempt) + u64::from(std::process::id() % 3),
511 ));
512 }
513 }
514 PushFailure::Raced => {
515 log.push(format!("gave up on {full} after {attempt} attempts: {why}"));
516 break Published::PushFailed;
517 }
518 _ => {
519 log.push(format!("push of {full} refused: {why}"));
520 break Published::PushFailed;
521 }
522 }
523 };
524 cleanup(root, &tfull, outcome)
525}
526
527fn cleanup(root: &Path, tfull: &str, outcome: Published) -> Published {
528 let _ = git::succeeds_in(root, &["update-ref", "-d", tfull]);
529 outcome
530}
531
532pub(crate) fn scrub(stderr: &str) -> String {
534 let mut out = String::new();
535 for word in stderr.split_whitespace() {
536 if !out.is_empty() {
537 out.push(' ');
538 }
539 match word.find("://") {
540 Some(i) => {
541 let (scheme, rest) = word.split_at(i + 3);
542 let host_start = match rest.find('/') {
543 Some(slash) => rest[..slash].rfind('@').map(|a| a + 1).unwrap_or(0),
544 None => rest.rfind('@').map(|a| a + 1).unwrap_or(0),
545 };
546 out.push_str(scheme);
547 out.push_str(&rest[host_start..]);
548 }
549 None => out.push_str(word),
550 }
551 }
552 out
553}
554
555pub fn publish_local(
558 root: &Path,
559 identity: Option<(&str, &str)>,
560 notes_ref: &str,
561 items: &[(String, String)],
562) -> Published {
563 let mut appended = false;
564 for (object, block) in items {
565 match append(root, identity, notes_ref, object, block) {
566 Some(true) => appended = true,
567 Some(false) => {}
568 None => return Published::Error,
569 }
570 }
571 if appended {
572 Published::Local
573 } else {
574 Published::AlreadyPresent
575 }
576}