Skip to main content

agentmux_srv_core/registry/
def_record_lock.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A cross-process lock per shared definition record
5//! (`docs/specs/SPEC_FORK_SLUG_MIGRATION_2026_10_22.md` P0.2).
6//!
7//! Every channel and instance on the host writes these records, each with its
8//! own `DefinitionStore`. An update reads the record, keeps its slug and
9//! former slugs (`keep_slug_and_former_slugs`), and writes it back. Without a
10//! lock spanning all three, another writer can land in between, and the
11//! write-back reverts its slug or drops a former slug it just recorded. The
12//! lock is an OS file lock (`LockFileEx` / `flock`, through `std`) on
13//! `<root>/locks/<id>.lock`, which binds one open handle, so it serializes
14//! writers in this process as well as in others. Lock files are never removed:
15//! deleting one while another writer waits on it would hand two writers two
16//! different locks.
17
18use std::fs::{File, OpenOptions, TryLockError};
19use std::path::Path;
20use std::time::{Duration, Instant};
21
22use super::def_store::DefStoreError;
23
24/// How long a writer waits before giving up with `DefStoreError::Locked`.
25/// A write holds the lock for one small file's read and atomic replace.
26pub(super) const LOCK_TIMEOUT: Duration = Duration::from_secs(5);
27
28const RETRY: Duration = Duration::from_millis(10);
29
30/// Record `id`'s lock, held until the returned file is dropped.
31pub(super) fn lock_record(root: &Path, id: &str, timeout: Duration) -> Result<File, DefStoreError> {
32    let dir = root.join("locks");
33    std::fs::create_dir_all(&dir)?;
34    #[allow(clippy::suspicious_open_options)]
35    let file = OpenOptions::new()
36        .read(true)
37        .write(true)
38        .create(true)
39        .truncate(false)
40        .open(dir.join(format!("{id}.lock")))?;
41    let started = Instant::now();
42    loop {
43        match file.try_lock() {
44            Ok(()) => return Ok(file),
45            Err(TryLockError::WouldBlock) if started.elapsed() < timeout => std::thread::sleep(RETRY),
46            Err(TryLockError::WouldBlock) => {
47                return Err(DefStoreError::Locked {
48                    id: id.to_string(),
49                    waited_ms: started.elapsed().as_millis() as u64,
50                })
51            }
52            Err(TryLockError::Error(e)) => return Err(e.into()),
53        }
54    }
55}
56
57/// The lock name for slug allocation (a uid is a UUID, so it can't collide).
58pub(super) const SLUG_ALLOCATION: &str = "_slug-allocation";
59/// The lock name for seat changes: who reports to whom is one graph.
60pub(super) const SEAT_GRAPH: &str = "_seat-graph";