1use std::path::{Path, PathBuf};
7
8use vitrify_core::claims::{self, Op};
9use vitrify_core::config::Overrides;
10use vitrify_core::graph::{self, Node};
11use vitrify_core::journal;
12use vitrify_core::model::{self, Instance, UtcTime};
13use vitrify_core::{CoreError, ledger, yamlish};
14
15use crate::cli::ClaimArgs;
16use crate::git::{Git, GitError, resolve_mainline, use_push};
17use crate::out::{J, diag, emit};
18
19#[derive(Debug, Clone)]
21pub struct ClaimOutcome {
22 pub unit: String,
23 pub op: Op,
24 pub holder: String,
25 pub claim_seq: i64,
26 pub claim_expires: Option<String>,
27 pub commit: String,
28 pub mainline: String,
29}
30
31static TX_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
34
35static MAINLINE_TX: std::sync::Mutex<()> = std::sync::Mutex::new(());
40
41pub fn tx_lock() -> std::sync::MutexGuard<'static, ()> {
44 MAINLINE_TX.lock().unwrap_or_else(|e| e.into_inner())
45}
46
47static QUIET_RESYNC: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
50static WARNED_BEHIND: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
51
52pub fn quiet_resync(on: bool) {
54 QUIET_RESYNC.store(on, std::sync::atomic::Ordering::SeqCst);
55}
56
57pub fn run(op: Op, args: &ClaimArgs) -> Result<u8, CoreError> {
58 let outcome = execute(op, args)?;
59 let obj = J::Obj(vec![
60 ("unit".into(), J::s(outcome.unit.clone())),
61 ("op".into(), J::s(op.as_str())),
62 ("holder".into(), J::s(outcome.holder.clone())),
63 ("claim_seq".into(), J::Int(outcome.claim_seq)),
64 (
65 "claim_expires".into(),
66 J::opt_str(outcome.claim_expires.clone()),
67 ),
68 ("commit".into(), J::s(outcome.commit.clone())),
69 ("mainline".into(), J::s(outcome.mainline.clone())),
70 ]);
71 emit(&obj.dumps_default());
72 Ok(0)
73}
74
75pub struct Pinned<'a> {
81 pub push: bool,
82 pub sdd_rel: &'a Path,
83}
84
85pub fn execute(op: Op, args: &ClaimArgs) -> Result<ClaimOutcome, CoreError> {
87 execute_with(op, args, None)
88}
89
90pub fn execute_pinned(
93 op: Op,
94 args: &ClaimArgs,
95 pinned: &Pinned<'_>,
96) -> Result<ClaimOutcome, CoreError> {
97 execute_with(op, args, Some(pinned))
98}
99
100fn execute_with(
101 op: Op,
102 args: &ClaimArgs,
103 pinned: Option<&Pinned<'_>>,
104) -> Result<ClaimOutcome, CoreError> {
105 let here = Git::new(super::cwd());
106 let primary_path = here.primary_root().map_err(CoreError::from)?;
107 let primary = Git::new(&primary_path);
108
109 let cfg = super::load_config(&Overrides::default())?;
110 let mainline = resolve_mainline(&primary, args.mainline.as_deref(), &cfg.mainline)
111 .map_err(CoreError::from)?;
112
113 let scratch = crate::layout::ensure_scratch(&primary_path)?;
114
115 let _turn = tx_lock();
116 let push = match pinned {
117 Some(p) => p.push,
118 None => use_push(&primary, &mainline).map_err(CoreError::from)?,
119 };
120 let n = TX_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
121 let tx = scratch.join(format!("tx-{}-{n}", std::process::id()));
122
123 let result = attempt_loop(
124 &primary,
125 &tx,
126 push,
127 &mainline,
128 op,
129 args,
130 pinned.map(|p| p.sdd_rel),
131 );
132
133 if tx.exists() {
134 let _ = primary.worktree_remove(&tx);
135 }
136 result
137}
138
139fn attempt_loop(
140 primary: &Git,
141 tx: &Path,
142 push: bool,
143 mainline: &str,
144 op: Op,
145 args: &ClaimArgs,
146 sdd_rel: Option<&Path>,
147) -> Result<ClaimOutcome, CoreError> {
148 let mut lost_race_before = false;
149 for attempt in 0..3 {
150 let base = if push {
152 let _ = primary.fetch_origin(mainline);
153 primary
154 .rev_parse(&format!("refs/remotes/origin/{mainline}"))
155 .map_err(CoreError::from)?
156 } else {
157 primary
158 .rev_parse(&format!("refs/heads/{mainline}"))
159 .map_err(CoreError::from)?
160 };
161 if tx.exists() {
162 let txgit = primary.at(tx);
163 txgit.reset_hard(&base).map_err(CoreError::from)?;
164 txgit.clean_fdq().map_err(CoreError::from)?;
165 } else {
166 primary
167 .worktree_add(tx, &base, true)
168 .map_err(CoreError::from)?;
169 }
170
171 let inst = load_tx_instance(tx, args.sdd.as_deref(), sdd_rel, &primary.dir)?;
173 let now = UtcTime::now();
174 let unit_graph = if super::reaches_out(&inst) {
177 Some(super::repo_graph(tx, Some(&inst))?)
178 } else {
179 None
180 };
181 let node = Node::new(graph::slug_of(&inst), args.unit.as_str());
182 let no_graph = |_: &str| None;
183 let resolve: model::Resolve = match &unit_graph {
184 Some(g) => &g.resolver(&node),
185 None => &no_graph,
186 };
187 let plan = claims::plan_with(
188 &inst,
189 op,
190 &args.unit,
191 &args.holder,
192 args.lease_minutes,
193 now,
194 lost_race_before,
195 resolve,
196 )?;
197
198 let unit = inst.unit(&args.unit).unwrap().clone();
200 let handle = inst.handle();
201 model::rewrite_unit_meta(&handle, &unit, |inner| {
202 let mut block = inner.to_string();
203 for (k, v) in &plan.edits {
204 block = yamlish::set_scalar_in_place(&block, k, v);
205 }
206 block
207 })?;
208 let (events, _) = journal::read(&handle)?;
209 let mut event = plan.event.clone();
210 event.seq = events.last().map(|e| e.seq).unwrap_or(0) + 1;
211 event.commit = Some(base[..7.min(base.len())].to_string());
212 journal::append_line(&handle, &journal::render_line(&event))?;
213 let fresh = Instance::load(handle.clone())?;
214 ledger::regen(&fresh, &now.format_date())?;
215
216 let txgit = primary.at(tx);
217 txgit.add_all().map_err(CoreError::from)?;
218 txgit
219 .commit(&plan.commit_message)
220 .map_err(CoreError::from)?;
221 let new = txgit.rev_parse("HEAD").map_err(CoreError::from)?;
222
223 let won = publish_commit(primary, push, mainline, &new, &base)?;
225
226 if won {
227 return Ok(ClaimOutcome {
228 unit: args.unit.clone(),
229 op,
230 holder: args.holder.clone(),
231 claim_seq: plan.claim_seq,
232 claim_expires: plan.claim_expires.clone(),
233 commit: new,
234 mainline: mainline.to_string(),
235 });
236 }
237 lost_race_before = true;
238 diag(&format!(
239 "note: lost publish race on {mainline} (attempt {}); resyncing",
240 attempt + 1
241 ));
242 }
243 Err(CoreError::refusal(
244 5,
245 format!("error: lost race for {} after retries", args.unit),
246 ))
247}
248
249fn publish_commit(
253 primary: &Git,
254 push: bool,
255 mainline: &str,
256 new: &str,
257 base: &str,
258) -> Result<bool, CoreError> {
259 if push {
260 match primary.push_cas(new, mainline) {
263 Ok(()) => {
264 if let Some(cur) = primary
265 .verify_ref(&format!("refs/heads/{mainline}"))
266 .map_err(CoreError::from)?
267 {
268 if primary.is_ancestor(&cur, new).map_err(CoreError::from)? {
269 if primary
272 .update_ref_cas(&format!("refs/heads/{mainline}"), new, &cur)
273 .is_ok()
274 {
275 resync_primary(primary, mainline, &cur, new)?;
276 }
277 } else {
278 diag(&format!(
279 "warning: local {mainline} diverged from origin; not updating the local branch"
280 ));
281 }
282 }
283 Ok(true)
284 }
285 Err(GitError::LostRace { .. }) => Ok(false),
286 Err(e) => Err(e.into()),
287 }
288 } else {
289 match primary.update_ref_cas(&format!("refs/heads/{mainline}"), new, base) {
290 Ok(()) => {
291 resync_primary(primary, mainline, base, new)?;
292 Ok(true)
293 }
294 Err(GitError::LostRace { .. }) => Ok(false),
295 Err(e) => Err(e.into()),
296 }
297 }
298}
299
300#[derive(Debug, Clone)]
302pub struct BatchClaim {
303 pub sdd_rel: PathBuf,
305 pub unit: String,
306 pub holder: String,
307}
308
309pub fn claim_many(
319 primary: &Git,
320 push: bool,
321 mainline: &str,
322 lease_minutes: i64,
323 claims: &[BatchClaim],
324) -> Result<Vec<Result<ClaimOutcome, CoreError>>, CoreError> {
325 let mut out: Vec<Option<Result<ClaimOutcome, CoreError>>> =
326 claims.iter().map(|_| None).collect();
327 if claims.is_empty() {
328 return Ok(Vec::new());
329 }
330 let scratch = crate::layout::ensure_scratch(&primary.dir)?;
331 let _turn = tx_lock();
332 let n = TX_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
333 let tx = scratch.join(format!("tx-{}-{n}", std::process::id()));
334 let result = (|| -> Result<(), CoreError> {
335 let mut lost_race_before = false;
336 for attempt in 0..3 {
337 let base = if push {
338 let _ = primary.fetch_origin(mainline);
339 primary
340 .rev_parse(&format!("refs/remotes/origin/{mainline}"))
341 .map_err(CoreError::from)?
342 } else {
343 primary
344 .rev_parse(&format!("refs/heads/{mainline}"))
345 .map_err(CoreError::from)?
346 };
347 if tx.exists() {
348 let txgit = primary.at(&tx);
349 txgit.reset_hard(&base).map_err(CoreError::from)?;
350 txgit.clean_fdq().map_err(CoreError::from)?;
351 } else {
352 primary
353 .worktree_add(&tx, &base, true)
354 .map_err(CoreError::from)?;
355 }
356 let now = UtcTime::now();
357 let mut planned: Vec<(usize, claims::TxPlan, String)> = Vec::new();
358 for (i, c) in claims.iter().enumerate() {
359 if out[i].is_some() {
360 continue; }
362 let inst = load_tx_instance(&tx, None, Some(&c.sdd_rel), &primary.dir)?;
364 let unit_graph = if super::reaches_out(&inst) {
365 Some(super::repo_graph(&tx, Some(&inst))?)
366 } else {
367 None
368 };
369 let node = Node::new(graph::slug_of(&inst), c.unit.as_str());
370 let no_graph = |_: &str| None;
371 let resolve: model::Resolve = match &unit_graph {
372 Some(g) => &g.resolver(&node),
373 None => &no_graph,
374 };
375 let plan = match claims::plan_with(
376 &inst,
377 Op::Claim,
378 &c.unit,
379 &c.holder,
380 lease_minutes,
381 now,
382 lost_race_before,
383 resolve,
384 ) {
385 Ok(plan) => plan,
386 Err(e) if e.exit_code() == 4 => {
387 out[i] = Some(Err(e));
389 continue;
390 }
391 Err(e) => return Err(e),
392 };
393 let Some(unit) = inst.unit(&c.unit).cloned() else {
394 continue;
395 };
396 let handle = inst.handle();
397 model::rewrite_unit_meta(&handle, &unit, |inner| {
398 let mut block = inner.to_string();
399 for (k, v) in &plan.edits {
400 block = yamlish::set_scalar_in_place(&block, k, v);
401 }
402 block
403 })?;
404 let (events, _) = journal::read(&handle)?;
405 let mut event = plan.event.clone();
406 event.seq = events.last().map(|e| e.seq).unwrap_or(0) + 1;
407 event.commit = Some(base[..7.min(base.len())].to_string());
408 journal::append_line(&handle, &journal::render_line(&event))?;
409 let fresh = Instance::load(handle.clone())?;
410 ledger::regen(&fresh, &now.format_date())?;
411 planned.push((i, plan, graph::slug_of(&fresh).to_string()));
412 }
413 if planned.is_empty() {
414 return Ok(());
415 }
416 let one_sdd = planned.iter().all(|(_, _, s)| *s == planned[0].2);
419 let message = match planned.as_slice() {
420 [(_, plan, _)] => plan.commit_message.clone(),
421 many => format!(
422 "sdd: claim {}",
423 many.iter()
424 .map(|(i, p, slug)| if one_sdd {
425 format!("{} (c{})", claims[*i].unit, p.claim_seq)
426 } else {
427 format!("{slug} {} (c{})", claims[*i].unit, p.claim_seq)
428 })
429 .collect::<Vec<_>>()
430 .join(", ")
431 ),
432 };
433 let txgit = primary.at(&tx);
434 txgit.add_all().map_err(CoreError::from)?;
435 txgit.commit(&message).map_err(CoreError::from)?;
436 let new = txgit.rev_parse("HEAD").map_err(CoreError::from)?;
437 if publish_commit(primary, push, mainline, &new, &base)? {
438 for (i, plan, _) in planned {
439 out[i] = Some(Ok(ClaimOutcome {
440 unit: claims[i].unit.clone(),
441 op: Op::Claim,
442 holder: claims[i].holder.clone(),
443 claim_seq: plan.claim_seq,
444 claim_expires: plan.claim_expires.clone(),
445 commit: new.clone(),
446 mainline: mainline.to_string(),
447 }));
448 }
449 return Ok(());
450 }
451 lost_race_before = true;
452 diag(&format!(
453 "note: lost publish race on {mainline} (attempt {}); resyncing",
454 attempt + 1
455 ));
456 }
457 Ok(())
458 })();
459 if tx.exists() {
460 let _ = primary.worktree_remove(&tx);
461 }
462 result?;
463 Ok(out
464 .into_iter()
465 .zip(claims)
466 .map(|(r, c)| {
467 r.unwrap_or_else(|| {
468 Err(CoreError::refusal(
469 5,
470 format!("error: lost race for {} after retries", c.unit),
471 ))
472 })
473 })
474 .collect())
475}
476
477fn load_tx_instance(
484 tx: &Path,
485 sdd_arg: Option<&str>,
486 sdd_rel: Option<&Path>,
487 primary: &Path,
488) -> Result<Instance, CoreError> {
489 if let Some(rel) = sdd_rel {
490 return match super::resolve_sdd_in(tx, rel) {
491 Ok(handle) => Instance::load(handle),
492 Err(CoreError::Refusal { code: 4, .. }) => Err(CoreError::refusal(
493 4,
494 format!(
495 "error: no SDD at {} at the mainline head — commit the SDD to mainline before claiming",
496 super::sdd_arg(rel)
497 ),
498 )),
499 Err(e) => Err(e),
500 };
501 }
502 let remapped: Option<String> = match sdd_arg {
503 None => None,
504 Some(arg) => {
505 let mut p = PathBuf::from(arg);
506 if !p.is_absolute() {
507 p = super::cwd().join(&p);
508 }
509 let p = p.canonicalize().unwrap_or(p);
510 let roots = [super::repo_root(), primary.to_path_buf()];
513 let rel = roots.iter().find_map(|root| {
514 let root = root.canonicalize().unwrap_or_else(|_| root.clone());
515 p.strip_prefix(&root).ok().map(Path::to_path_buf)
516 });
517 match rel {
518 Some(rel) => Some(tx.join(rel).to_string_lossy().to_string()),
519 None => {
520 return Err(CoreError::refusal(
521 4,
522 format!(
523 "error: --sdd {arg} is not inside this checkout — name the SDD by its path in the repository"
524 ),
525 ));
526 }
527 }
528 }
529 };
530 match super::resolve_sdd(tx, remapped.as_deref(), tx) {
531 Ok(handle) => Instance::load(handle),
532 Err(CoreError::Refusal { code: 4, message })
535 if message.starts_with("error: multiple SDDs found") =>
536 {
537 Err(CoreError::refusal(
538 4,
539 message.replace(&format!("{}/", tx.display()), ""),
540 ))
541 }
542 Err(CoreError::Refusal { code: 4, .. }) => Err(CoreError::refusal(
543 4,
544 match sdd_arg {
545 Some(arg) => format!(
546 "error: --sdd {arg} is not an SDD root at the mainline head — commit the SDD to mainline before claiming"
547 ),
548 None => "error: no SDD found at the mainline head — commit the SDD to mainline before claiming".to_string(),
549 },
550 )),
551 Err(e) => Err(e),
552 }
553}
554
555fn behind_file(primary: &Git) -> PathBuf {
559 primary.dir.join(".vitrify").join("primary-behind")
560}
561
562fn read_behind(primary: &Git) -> Option<(String, String)> {
563 let text = std::fs::read_to_string(behind_file(primary)).ok()?;
564 let mut words = text.split_whitespace();
565 let from = words.next()?.to_string();
566 let target = words.next()?.to_string();
567 Some((from, target))
568}
569
570fn write_behind(primary: &Git, from: &str, target: &str) {
571 if crate::layout::ensure_scratch(&primary.dir).is_ok() {
572 let _ = std::fs::write(behind_file(primary), format!("{from} {target}\n"));
573 }
574}
575
576fn clear_behind(primary: &Git) {
577 let _ = std::fs::remove_file(behind_file(primary));
578}
579
580fn still_behind(primary: &Git, from: &str, head: &str) -> bool {
584 let (Ok(moved), Ok(staged)) = (
585 primary.changed_paths(from, head),
586 primary.index_differs_from(head),
587 ) else {
588 return false; };
590 let staged: std::collections::HashSet<String> = staged.into_iter().collect();
591 moved.iter().any(|p| staged.contains(p))
592}
593
594fn sha7(sha: &str) -> &str {
595 &sha[..7.min(sha.len())]
596}
597
598fn sha12(sha: &str) -> &str {
599 &sha[..12.min(sha.len())]
600}
601
602fn git_reason(e: &GitError) -> String {
604 match e {
605 GitError::Failed { stderr, .. } if !stderr.trim().is_empty() => stderr
606 .lines()
607 .map(|l| {
608 l.trim()
609 .trim_start_matches("error: ")
610 .trim_start_matches("fatal: ")
611 })
612 .filter(|l| !l.is_empty())
613 .collect::<Vec<_>>()
614 .join(" "),
615 other => other.to_string(),
616 }
617}
618
619fn by_hand(from: &str, new: &str) -> String {
622 format!(
623 "git update-index -q --refresh && git read-tree -m -u {} {}",
624 sha12(from),
625 sha12(new)
626 )
627}
628
629enum Follow {
630 NotCheckedOut,
632 Followed,
633 Behind(String),
635}
636
637fn follow(primary: &Git, mainline: &str, old: &str, new: &str) -> Follow {
649 let by_hand = |from: &str| by_hand(from, new);
650 match primary.current_branch() {
651 Ok(Some(branch)) if branch == mainline => {}
652 Ok(_) => return Follow::NotCheckedOut,
653 Err(e) => {
654 return Follow::Behind(format!(
655 "warning: could not inspect the primary checkout ({}); if it has {mainline} checked out it is now behind — bring it up to date with: {}",
656 git_reason(&e),
657 by_hand(old)
658 ));
659 }
660 }
661 let mut from = old.to_string();
662 if let Some((left_at, _)) = read_behind(primary) {
663 if primary.clean_against(old).unwrap_or(false) || !still_behind(primary, &left_at, old) {
664 clear_behind(primary); } else {
666 from = left_at;
667 }
668 }
669 if from == new {
670 return Follow::Followed;
671 }
672 match primary.fast_forward_tree(&from, new) {
673 Ok(()) => {
674 clear_behind(primary);
675 Follow::Followed
676 }
677 Err(e) => {
678 write_behind(primary, &from, new);
679 Follow::Behind(format!(
680 "warning: the primary checkout could not follow {mainline} to {}: {}\n It still holds {} and is behind {mainline} — commit nothing from it until it has caught up.\n Clear what is in the way and it catches up at the next commit vitrify publishes, or now with: {}",
681 sha7(new),
682 git_reason(&e),
683 sha7(&from),
684 by_hand(&from)
685 ))
686 }
687 }
688}
689
690pub fn resync_primary(
693 primary: &Git,
694 mainline: &str,
695 old: &str,
696 new: &str,
697) -> Result<(), CoreError> {
698 use std::sync::atomic::Ordering;
699 let quiet = QUIET_RESYNC.load(Ordering::SeqCst);
700 match follow(primary, mainline, old, new) {
701 Follow::NotCheckedOut => {}
702 Follow::Followed => {
703 WARNED_BEHIND.store(false, Ordering::SeqCst);
704 if !quiet {
705 diag(&format!(
706 "note: primary checkout fast-forwarded to {}",
707 sha7(new)
708 ));
709 }
710 }
711 Follow::Behind(warning) => {
713 if !(quiet && WARNED_BEHIND.swap(true, Ordering::SeqCst)) {
714 diag(&warning);
715 }
716 }
717 }
718 Ok(())
719}
720
721pub fn catch_up_primary(primary: &Git, mainline: &str) -> Option<String> {
725 read_behind(primary)?;
726 let head = primary.rev_parse(&format!("refs/heads/{mainline}")).ok()?;
727 match follow(primary, mainline, &head, &head) {
728 Follow::Behind(warning) => Some(warning),
729 Follow::Followed | Follow::NotCheckedOut => None,
730 }
731}
732
733pub fn behind_note(primary: &Git, mainline: &str) -> Option<String> {
735 let (left_at, _) = read_behind(primary)?;
736 if !primary
737 .current_branch()
738 .ok()?
739 .is_some_and(|b| b == mainline)
740 {
741 return None;
742 }
743 let head = primary.rev_parse(&format!("refs/heads/{mainline}")).ok()?;
744 if primary.clean_against(&head).unwrap_or(false) || !still_behind(primary, &left_at, &head) {
745 return None;
746 }
747 Some(format!(
748 "note: the primary checkout is behind {mainline} (it holds {}); a run brings it up to date before it starts — by hand: {}",
749 sha7(&left_at),
750 by_hand(&left_at, &head)
751 ))
752}