Skip to main content

vitrify_cli/cmd/
claim.rs

1//! `vitrify claim|renew|release` — atomic lease transactions.
2//! Each operation is one mainline commit (front-matter edit, journal event,
3//! ledger regen) built in the ephemeral tx worktree `.vitrify/tx-<pid>` and
4//! published atomically by the C-002 CAS/push discipline. Never force.
5
6use std::path::{Path, PathBuf};
7
8use vitrify_core::claims::{self, Op};
9use vitrify_core::config::Overrides;
10use vitrify_core::journal;
11use vitrify_core::model::{self, Instance, UtcTime};
12use vitrify_core::{CoreError, ledger, yamlish};
13
14use crate::cli::ClaimArgs;
15use crate::git::{Git, GitError, resolve_mainline, use_push};
16use crate::out::{J, diag, emit};
17
18/// A published transaction's outcome (the success JSON's fields).
19#[derive(Debug, Clone)]
20pub struct ClaimOutcome {
21    pub unit: String,
22    pub op: Op,
23    pub holder: String,
24    pub claim_seq: i64,
25    pub claim_expires: Option<String>,
26    pub commit: String,
27    pub mainline: String,
28}
29
30/// Monotonic discriminator so in-process transactions never share a tx
31/// worktree.
32static TX_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
33
34/// One mainline transaction at a time within this process. The orchestrator
35/// claims, renews, releases and integrates from several threads; taking
36/// turns keeps them from racing each other for the mainline ref and for the
37/// primary checkout's index. Other processes are arbitrated by the CAS/push.
38static MAINLINE_TX: std::sync::Mutex<()> = std::sync::Mutex::new(());
39
40/// Hold this across the build-and-publish of one mainline commit. Not
41/// re-entrant: [`execute`] takes it itself.
42pub fn tx_lock() -> std::sync::MutexGuard<'static, ()> {
43    MAINLINE_TX.lock().unwrap_or_else(|e| e.into_inner())
44}
45
46/// Under `vitrify run` every published commit moves the primary checkout;
47/// one note per commit would bury the run's own output.
48static QUIET_RESYNC: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
49static WARNED_BEHIND: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
50
51/// Report the primary checkout's fast-forwards only when they stop working.
52pub fn quiet_resync(on: bool) {
53    QUIET_RESYNC.store(on, std::sync::atomic::Ordering::SeqCst);
54}
55
56pub fn run(op: Op, args: &ClaimArgs) -> Result<u8, CoreError> {
57    let outcome = execute(op, args)?;
58    let obj = J::Obj(vec![
59        ("unit".into(), J::s(outcome.unit.clone())),
60        ("op".into(), J::s(op.as_str())),
61        ("holder".into(), J::s(outcome.holder.clone())),
62        ("claim_seq".into(), J::Int(outcome.claim_seq)),
63        (
64            "claim_expires".into(),
65            J::opt_str(outcome.claim_expires.clone()),
66        ),
67        ("commit".into(), J::s(outcome.commit.clone())),
68        ("mainline".into(), J::s(outcome.mainline.clone())),
69    ]);
70    emit(&obj.dumps_default());
71    Ok(0)
72}
73
74/// What a caller that runs many transactions decides once and holds every
75/// one of them to — `vitrify run` does: how commits are published (a run
76/// that began by pushing must never fall back to moving the local branch
77/// because one fetch failed: that would put a claim on a mainline nobody
78/// else sees), and which SDD, by its path under the repository root.
79pub struct Pinned<'a> {
80    pub push: bool,
81    pub sdd_rel: &'a Path,
82}
83
84/// Execute the transaction without printing.
85pub fn execute(op: Op, args: &ClaimArgs) -> Result<ClaimOutcome, CoreError> {
86    execute_with(op, args, None)
87}
88
89/// [`execute`] for the orchestrator: publish mode and SDD as `pinned` says,
90/// whatever `args.sdd` and the state of the remote suggest.
91pub fn execute_pinned(
92    op: Op,
93    args: &ClaimArgs,
94    pinned: &Pinned<'_>,
95) -> Result<ClaimOutcome, CoreError> {
96    execute_with(op, args, Some(pinned))
97}
98
99fn execute_with(
100    op: Op,
101    args: &ClaimArgs,
102    pinned: Option<&Pinned<'_>>,
103) -> Result<ClaimOutcome, CoreError> {
104    let here = Git::new(super::cwd());
105    let primary_path = here.primary_root().map_err(CoreError::from)?;
106    let primary = Git::new(&primary_path);
107
108    let cfg = super::load_config(&Overrides::default())?;
109    let mainline = resolve_mainline(&primary, args.mainline.as_deref(), &cfg.mainline)
110        .map_err(CoreError::from)?;
111
112    let scratch = crate::layout::ensure_scratch(&primary_path)?;
113
114    let _turn = tx_lock();
115    let push = match pinned {
116        Some(p) => p.push,
117        None => use_push(&primary, &mainline).map_err(CoreError::from)?,
118    };
119    let n = TX_COUNTER.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
120    let tx = scratch.join(format!("tx-{}-{n}", std::process::id()));
121
122    let result = attempt_loop(
123        &primary,
124        &tx,
125        push,
126        &mainline,
127        op,
128        args,
129        pinned.map(|p| p.sdd_rel),
130    );
131
132    if tx.exists() {
133        let _ = primary.worktree_remove(&tx);
134    }
135    result
136}
137
138fn attempt_loop(
139    primary: &Git,
140    tx: &Path,
141    push: bool,
142    mainline: &str,
143    op: Op,
144    args: &ClaimArgs,
145    sdd_rel: Option<&Path>,
146) -> Result<ClaimOutcome, CoreError> {
147    let mut lost_race_before = false;
148    for attempt in 0..3 {
149        // -- sync: the head this transaction builds on
150        let base = if push {
151            let _ = primary.fetch_origin(mainline);
152            primary
153                .rev_parse(&format!("refs/remotes/origin/{mainline}"))
154                .map_err(CoreError::from)?
155        } else {
156            primary
157                .rev_parse(&format!("refs/heads/{mainline}"))
158                .map_err(CoreError::from)?
159        };
160        if tx.exists() {
161            let txgit = primary.at(tx);
162            txgit.reset_hard(&base).map_err(CoreError::from)?;
163            txgit.clean_fdq().map_err(CoreError::from)?;
164        } else {
165            primary
166                .worktree_add(tx, &base, true)
167                .map_err(CoreError::from)?;
168        }
169
170        // -- preconditions at this head
171        let inst = load_tx_instance(tx, args.sdd.as_deref(), sdd_rel, &primary.dir)?;
172        let now = UtcTime::now();
173        let plan = claims::plan(
174            &inst,
175            op,
176            &args.unit,
177            &args.holder,
178            args.lease_minutes,
179            now,
180            lost_race_before,
181        )?;
182
183        // -- build the commit: front matter + journal + ledger
184        let unit = inst.unit(&args.unit).unwrap().clone();
185        let handle = inst.handle();
186        model::rewrite_unit_meta(&handle, &unit, |inner| {
187            let mut block = inner.to_string();
188            for (k, v) in &plan.edits {
189                block = yamlish::set_scalar_in_place(&block, k, v);
190            }
191            block
192        })?;
193        let (events, _) = journal::read(&handle)?;
194        let mut event = plan.event.clone();
195        event.seq = events.last().map(|e| e.seq).unwrap_or(0) + 1;
196        event.commit = Some(base[..7.min(base.len())].to_string());
197        journal::append_line(&handle, &journal::render_line(&event))?;
198        let fresh = Instance::load(handle.clone())?;
199        ledger::regen(&fresh, &now.format_date())?;
200
201        let txgit = primary.at(tx);
202        txgit.add_all().map_err(CoreError::from)?;
203        txgit
204            .commit(&plan.commit_message)
205            .map_err(CoreError::from)?;
206        let new = txgit.rev_parse("HEAD").map_err(CoreError::from)?;
207
208        // -- publish atomically
209        let won = if push {
210            // Push from the primary checkout: the commit lives in the shared
211            // object store.
212            match primary.push_cas(&new, mainline) {
213                Ok(()) => {
214                    if let Some(cur) = primary
215                        .verify_ref(&format!("refs/heads/{mainline}"))
216                        .map_err(CoreError::from)?
217                    {
218                        if primary.is_ancestor(&cur, &new).map_err(CoreError::from)? {
219                            // the checkout follows a branch that moved, and
220                            // only then
221                            if primary
222                                .update_ref_cas(&format!("refs/heads/{mainline}"), &new, &cur)
223                                .is_ok()
224                            {
225                                resync_primary(primary, mainline, &cur, &new)?;
226                            }
227                        } else {
228                            diag(&format!(
229                                "warning: local {mainline} diverged from origin; not updating the local branch"
230                            ));
231                        }
232                    }
233                    true
234                }
235                Err(GitError::LostRace { .. }) => false,
236                Err(e) => return Err(e.into()),
237            }
238        } else {
239            match primary.update_ref_cas(&format!("refs/heads/{mainline}"), &new, &base) {
240                Ok(()) => {
241                    resync_primary(primary, mainline, &base, &new)?;
242                    true
243                }
244                Err(GitError::LostRace { .. }) => false,
245                Err(e) => return Err(e.into()),
246            }
247        };
248
249        if won {
250            return Ok(ClaimOutcome {
251                unit: args.unit.clone(),
252                op,
253                holder: args.holder.clone(),
254                claim_seq: plan.claim_seq,
255                claim_expires: plan.claim_expires.clone(),
256                commit: new,
257                mainline: mainline.to_string(),
258            });
259        }
260        lost_race_before = true;
261        diag(&format!(
262            "note: lost publish race on {mainline} (attempt {}); resyncing",
263            attempt + 1
264        ));
265    }
266    Err(CoreError::refusal(
267        5,
268        format!("error: lost race for {} after retries", args.unit),
269    ))
270}
271
272/// Load the instance inside the tx worktree. `--sdd` names the SDD as seen
273/// from wherever the verb runs — the primary checkout or any worktree of it —
274/// so its path relative to that checkout's root is what maps into the tx
275/// tree. A path that lies in neither is refused: resolving it as given
276/// would edit that directory in place instead of the transaction's copy.
277/// `sdd_rel` (the orchestrator's pin) is that relative path already.
278fn load_tx_instance(
279    tx: &Path,
280    sdd_arg: Option<&str>,
281    sdd_rel: Option<&Path>,
282    primary: &Path,
283) -> Result<Instance, CoreError> {
284    if let Some(rel) = sdd_rel {
285        return match super::resolve_sdd_in(tx, rel) {
286            Ok(handle) => Instance::load(handle),
287            Err(CoreError::Refusal { code: 4, .. }) => Err(CoreError::refusal(
288                4,
289                format!(
290                    "error: no SDD at {} at the mainline head — commit the SDD to mainline before claiming",
291                    super::sdd_arg(rel)
292                ),
293            )),
294            Err(e) => Err(e),
295        };
296    }
297    let remapped: Option<String> = match sdd_arg {
298        None => None,
299        Some(arg) => {
300            let mut p = PathBuf::from(arg);
301            if !p.is_absolute() {
302                p = super::cwd().join(&p);
303            }
304            let p = p.canonicalize().unwrap_or(p);
305            // the checkout the verb runs in first: it may itself lie inside
306            // the primary checkout's directory
307            let roots = [super::repo_root(), primary.to_path_buf()];
308            let rel = roots.iter().find_map(|root| {
309                let root = root.canonicalize().unwrap_or_else(|_| root.clone());
310                p.strip_prefix(&root).ok().map(Path::to_path_buf)
311            });
312            match rel {
313                Some(rel) => Some(tx.join(rel).to_string_lossy().to_string()),
314                None => {
315                    return Err(CoreError::refusal(
316                        4,
317                        format!(
318                            "error: --sdd {arg} is not inside this checkout — name the SDD by its path in the repository"
319                        ),
320                    ));
321                }
322            }
323        }
324    };
325    match super::resolve_sdd(tx, remapped.as_deref(), tx) {
326        Ok(handle) => Instance::load(handle),
327        // several SDDs and no --sdd: say so, naming each by the path `--sdd`
328        // takes (the transaction's own location means nothing to the caller)
329        Err(CoreError::Refusal { code: 4, message })
330            if message.starts_with("error: multiple SDDs found") =>
331        {
332            Err(CoreError::refusal(
333                4,
334                message.replace(&format!("{}/", tx.display()), ""),
335            ))
336        }
337        Err(CoreError::Refusal { code: 4, .. }) => Err(CoreError::refusal(
338            4,
339            match sdd_arg {
340                Some(arg) => format!(
341                    "error: --sdd {arg} is not an SDD root at the mainline head — commit the SDD to mainline before claiming"
342                ),
343                None => "error: no SDD found at the mainline head — commit the SDD to mainline before claiming".to_string(),
344            },
345        )),
346        Err(e) => Err(e),
347    }
348}
349
350/// Where a primary checkout that could not follow its branch says so —
351/// `<the commit its files hold> <the commit it was heading for>` — for the
352/// next transaction, of this process or any later one, to catch it up from.
353fn behind_file(primary: &Git) -> PathBuf {
354    primary.dir.join(".vitrify").join("primary-behind")
355}
356
357fn read_behind(primary: &Git) -> Option<(String, String)> {
358    let text = std::fs::read_to_string(behind_file(primary)).ok()?;
359    let mut words = text.split_whitespace();
360    let from = words.next()?.to_string();
361    let target = words.next()?.to_string();
362    Some((from, target))
363}
364
365fn write_behind(primary: &Git, from: &str, target: &str) {
366    if crate::layout::ensure_scratch(&primary.dir).is_ok() {
367        let _ = std::fs::write(behind_file(primary), format!("{from} {target}\n"));
368    }
369}
370
371fn clear_behind(primary: &Git) {
372    let _ = std::fs::remove_file(behind_file(primary));
373}
374
375/// Whether the checkout's index still holds `from`'s version of something
376/// that differs at `head` — that is, has not been brought up to date since
377/// it was left at `from`.
378fn still_behind(primary: &Git, from: &str, head: &str) -> bool {
379    let (Ok(moved), Ok(staged)) = (
380        primary.changed_paths(from, head),
381        primary.index_differs_from(head),
382    ) else {
383        return false; // `from` is no longer a commit here: nothing to catch up from
384    };
385    let staged: std::collections::HashSet<String> = staged.into_iter().collect();
386    moved.iter().any(|p| staged.contains(p))
387}
388
389fn sha7(sha: &str) -> &str {
390    &sha[..7.min(sha.len())]
391}
392
393fn sha12(sha: &str) -> &str {
394    &sha[..12.min(sha.len())]
395}
396
397/// What git said, without the plumbing around it.
398fn git_reason(e: &GitError) -> String {
399    match e {
400        GitError::Failed { stderr, .. } if !stderr.trim().is_empty() => stderr
401            .lines()
402            .map(|l| {
403                l.trim()
404                    .trim_start_matches("error: ")
405                    .trim_start_matches("fatal: ")
406            })
407            .filter(|l| !l.is_empty())
408            .collect::<Vec<_>>()
409            .join(" "),
410        other => other.to_string(),
411    }
412}
413
414/// The command that brings a checkout holding `from` to `new` by hand —
415/// what [`follow`] itself runs.
416fn by_hand(from: &str, new: &str) -> String {
417    format!(
418        "git update-index -q --refresh && git read-tree -m -u {} {}",
419        sha12(from),
420        sha12(new)
421    )
422}
423
424enum Follow {
425    /// Another branch is checked out there: nothing of it moved.
426    NotCheckedOut,
427    Followed,
428    /// It could not follow; the warning to print.
429    Behind(String),
430}
431
432/// Bring the primary checkout's index and files to `new`, when it has
433/// `mainline` checked out. `old` is what the branch pointed at before it
434/// was moved — what the files hold, unless an earlier move could not be
435/// followed (then [`behind_file`] says which commit they do hold).
436///
437/// The move is a fast-forward of index and tree (`read-tree -m -u`): what
438/// the published commits changed is updated and the user's own uncommitted
439/// changes ride along. If one of those — or an untracked file — is in the
440/// way, nothing at all is touched: the checkout stays where it was, a marker
441/// records where, and the next move catches up from there. Never `reset
442/// --hard`, which would overwrite what is in the way.
443fn follow(primary: &Git, mainline: &str, old: &str, new: &str) -> Follow {
444    let by_hand = |from: &str| by_hand(from, new);
445    match primary.current_branch() {
446        Ok(Some(branch)) if branch == mainline => {}
447        Ok(_) => return Follow::NotCheckedOut,
448        Err(e) => {
449            return Follow::Behind(format!(
450                "warning: could not inspect the primary checkout ({}); if it has {mainline} checked out it is now behind — bring it up to date with: {}",
451                git_reason(&e),
452                by_hand(old)
453            ));
454        }
455    }
456    let mut from = old.to_string();
457    if let Some((left_at, _)) = read_behind(primary) {
458        if primary.clean_against(old).unwrap_or(false) || !still_behind(primary, &left_at, old) {
459            clear_behind(primary); // brought up to date by hand since
460        } else {
461            from = left_at;
462        }
463    }
464    if from == new {
465        return Follow::Followed;
466    }
467    match primary.fast_forward_tree(&from, new) {
468        Ok(()) => {
469            clear_behind(primary);
470            Follow::Followed
471        }
472        Err(e) => {
473            write_behind(primary, &from, new);
474            Follow::Behind(format!(
475                "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: {}",
476                sha7(new),
477                git_reason(&e),
478                sha7(&from),
479                by_hand(&from)
480            ))
481        }
482    }
483}
484
485/// After a commit moved `mainline` from `old` to `new`: the primary checkout
486/// follows ([`follow`]). Never fatal — the commit is already published.
487pub fn resync_primary(
488    primary: &Git,
489    mainline: &str,
490    old: &str,
491    new: &str,
492) -> Result<(), CoreError> {
493    use std::sync::atomic::Ordering;
494    let quiet = QUIET_RESYNC.load(Ordering::SeqCst);
495    match follow(primary, mainline, old, new) {
496        Follow::NotCheckedOut => {}
497        Follow::Followed => {
498            WARNED_BEHIND.store(false, Ordering::SeqCst);
499            if !quiet {
500                diag(&format!(
501                    "note: primary checkout fast-forwarded to {}",
502                    sha7(new)
503                ));
504            }
505        }
506        // under `vitrify run`: said once, until it has caught up again
507        Follow::Behind(warning) => {
508            if !(quiet && WARNED_BEHIND.swap(true, Ordering::SeqCst)) {
509                diag(&warning);
510            }
511        }
512    }
513    Ok(())
514}
515
516/// A primary checkout that an earlier commit left behind: try again now.
517/// Returns the warning when it still cannot follow. Like every move of the
518/// checkout, this is one mainline writer's turn ([`tx_lock`]).
519pub fn catch_up_primary(primary: &Git, mainline: &str) -> Option<String> {
520    read_behind(primary)?;
521    let head = primary.rev_parse(&format!("refs/heads/{mainline}")).ok()?;
522    match follow(primary, mainline, &head, &head) {
523        Follow::Behind(warning) => Some(warning),
524        Follow::Followed | Follow::NotCheckedOut => None,
525    }
526}
527
528/// What [`catch_up_primary`] would have to do, without doing it.
529pub fn behind_note(primary: &Git, mainline: &str) -> Option<String> {
530    let (left_at, _) = read_behind(primary)?;
531    if !primary
532        .current_branch()
533        .ok()?
534        .is_some_and(|b| b == mainline)
535    {
536        return None;
537    }
538    let head = primary.rev_parse(&format!("refs/heads/{mainline}")).ok()?;
539    if primary.clean_against(&head).unwrap_or(false) || !still_behind(primary, &left_at, &head) {
540        return None;
541    }
542    Some(format!(
543        "note: the primary checkout is behind {mainline} (it holds {}); a run brings it up to date before it starts — by hand: {}",
544        sha7(&left_at),
545        by_hand(&left_at, &head)
546    ))
547}