synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-coord / src / lib.rs
| 1 | //! Shared agent coordination plane (claims, presence, whispers) compatible with the Crumb |
| 2 | //! RFC-0002 store, kept outside Synapse history. |
| 3 | //! |
| 4 | //! This crate is a Rust implementation of the RFC-0002 common coordination plane of |
| 5 | //! `tools/crumb/crumb.c` (aien-architecture 29780e5) that works on the **same store** the C |
| 6 | //! tool uses, so agents claiming through `crumb` in Git worktrees and agents claiming through |
| 7 | //! Synapse see one lock set. It never calls Git: the store root and the workspace are passed |
| 8 | //! in explicitly. See `README.md` for the design and the compatibility contract. |
| 9 | //! |
| 10 | //! Coordination state is ephemeral. It is never written into Synapse history, is never an |
| 11 | //! evidence receipt, and is never an authority for publication. |
| 12 | |
| 13 | pub mod board; |
| 14 | pub mod identity; |
| 15 | pub mod json; |
| 16 | pub mod record; |
| 17 | pub mod time; |
| 18 | |
| 19 | pub use identity::{ |
| 20 | resolve_coord_root, ResolvedRoot, RootSource, StoreId, STORE_ID_FILE, STORE_ID_FORMAT, |
| 21 | }; |
| 22 | pub use record::{read_record_file, RecordRefusal, MAX_MARKER_BYTES, MAX_RECORD_BYTES}; |
| 23 | |
| 24 | use json::J; |
| 25 | use std::fs::{self, File, OpenOptions}; |
| 26 | use std::io::Write; |
| 27 | use std::os::unix::fs::OpenOptionsExt; |
| 28 | use std::os::unix::io::AsRawFd; |
| 29 | use std::path::{Path, PathBuf}; |
| 30 | use std::sync::{Arc, Mutex, MutexGuard}; |
| 31 | |
| 32 | /// RFC-0001 schema version stamped into new directory records (`SCHEMA` in crumb.c). |
| 33 | pub const SCHEMA: &str = "1.0.0"; |
| 34 | /// Rolling history entries kept per directory record (`HISTORY_CAP`). |
| 35 | pub const HISTORY_CAP: usize = 20; |
| 36 | /// Default presence (scent) lifetime in seconds (`SCENT_TTL`). |
| 37 | pub const SCENT_TTL: i64 = 3600; |
| 38 | /// Default claim (lock) lifetime in seconds (`LOCK_TTL`). |
| 39 | pub const LOCK_TTL: i64 = 1800; |
| 40 | /// Whispers older than this many seconds are pruned (`WHISPER_RETENTION`). |
| 41 | pub const WHISPER_RETENTION: i64 = 24 * 3600; |
| 42 | |
| 43 | /// Everything that can go wrong. The C tool `die`s with exit 1 on all of these. |
| 44 | #[derive(Debug)] |
| 45 | pub enum CoordError { |
| 46 | Io { |
| 47 | path: PathBuf, |
| 48 | source: std::io::Error, |
| 49 | }, |
| 50 | /// A record file exists but is not a JSON object. Like crumb.c, refuse rather than overwrite. |
| 51 | CorruptRecord { |
| 52 | path: PathBuf, |
| 53 | }, |
| 54 | /// A store file is not a regular file, is a symlink, or is over its size cap (issue |
| 55 | /// #58). Handled like [`CoordError::CorruptRecord`]: refused, never opened in a blocking |
| 56 | /// way, never followed, never overwritten. See [`record`]. |
| 57 | RefusedRecord { |
| 58 | path: PathBuf, |
| 59 | reason: RecordRefusal, |
| 60 | }, |
| 61 | /// A path normalizes to somewhere above the repository root. |
| 62 | EscapesRoot { |
| 63 | path: String, |
| 64 | }, |
| 65 | /// An absolute target that is not inside this workspace. |
| 66 | OutsideWorkspace { |
| 67 | path: String, |
| 68 | workspace: String, |
| 69 | }, |
| 70 | BadPriority(String), |
| 71 | BadAction(String), |
| 72 | /// A relative target named from a subdirectory with no tree to resolve it against. |
| 73 | AmbiguousWithoutTree { |
| 74 | target: String, |
| 75 | dir: String, |
| 76 | }, |
| 77 | BadTtl(i64), |
| 78 | /// Opened expecting a registered store identity, but the root has no `STORE_ID` |
| 79 | /// marker: most likely a misconfigured root (a split coordination store). |
| 80 | StoreIdMissing { |
| 81 | root: PathBuf, |
| 82 | }, |
| 83 | /// Opened expecting one store identity, but the root's marker names another store. |
| 84 | StoreIdMismatch { |
| 85 | root: PathBuf, |
| 86 | expected: StoreId, |
| 87 | found: StoreId, |
| 88 | }, |
| 89 | /// `STORE_ID` exists but is not a v1 marker. Refused, never rewritten. |
| 90 | StoreIdUnreadable { |
| 91 | path: PathBuf, |
| 92 | reason: String, |
| 93 | }, |
| 94 | /// [`resolve_coord_root`] could not choose a root the way crumb.c would. |
| 95 | RootUnresolved(String), |
| 96 | } |
| 97 | |
| 98 | impl std::fmt::Display for CoordError { |
| 99 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 100 | match self { |
| 101 | CoordError::Io { path, source } => write!(f, "{}: {source}", path.display()), |
| 102 | CoordError::CorruptRecord { path } => { |
| 103 | write!( |
| 104 | f, |
| 105 | "{} is not valid JSON; fix or move it aside", |
| 106 | path.display() |
| 107 | ) |
| 108 | } |
| 109 | CoordError::RefusedRecord { path, reason } => write!( |
| 110 | f, |
| 111 | "{} {reason}; refusing to read it (fix or move it aside)", |
| 112 | path.display() |
| 113 | ), |
| 114 | CoordError::EscapesRoot { path } => write!(f, "target {path} escapes the repository"), |
| 115 | CoordError::OutsideWorkspace { path, workspace } => { |
| 116 | write!(f, "target {path} is outside the repository {workspace}") |
| 117 | } |
| 118 | CoordError::AmbiguousWithoutTree { target, dir } => write!( |
| 119 | f, |
| 120 | "target {target} named from {dir} is ambiguous without a tree; name it from the root (dir .) or pass an absolute path" |
| 121 | ), |
| 122 | CoordError::BadPriority(p) => { |
| 123 | write!(f, "priority must be low|normal|high|critical (got {p})") |
| 124 | } |
| 125 | CoordError::BadAction(a) => { |
| 126 | write!( |
| 127 | f, |
| 128 | "action must be create|modify|delete|audit|test|build (got {a})" |
| 129 | ) |
| 130 | } |
| 131 | CoordError::BadTtl(t) => write!(f, "bad ttl: {t}"), |
| 132 | CoordError::StoreIdMissing { root } => write!( |
| 133 | f, |
| 134 | "coordination store {} has no {STORE_ID_FILE} marker; refusing (expected a registered store: check CRUMB_COORD_ROOT / crumb.coordinationRoot / --store)", |
| 135 | root.display() |
| 136 | ), |
| 137 | CoordError::StoreIdMismatch { |
| 138 | root, |
| 139 | expected, |
| 140 | found, |
| 141 | } => write!( |
| 142 | f, |
| 143 | "coordination store {} is store {found}, expected {expected}; refusing (split coordination roots)", |
| 144 | root.display() |
| 145 | ), |
| 146 | CoordError::StoreIdUnreadable { path, reason } => { |
| 147 | write!(f, "{} is not a store identity marker: {reason}", path.display()) |
| 148 | } |
| 149 | CoordError::RootUnresolved(r) => write!(f, "cannot resolve coordination root: {r}"), |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | impl std::error::Error for CoordError {} |
| 155 | |
| 156 | fn io_err(path: &Path) -> impl FnOnce(std::io::Error) -> CoordError + '_ { |
| 157 | move |source| CoordError::Io { |
| 158 | path: path.to_path_buf(), |
| 159 | source, |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /// `norm_path`: collapse `.`, `..` and repeated `/`. `None` when the path escapes the root. |
| 164 | /// A leading `/` is dropped, as in the C tool (`strtok` on `/`). |
| 165 | pub fn norm_path(s: &str) -> Option<String> { |
| 166 | let mut st: Vec<&str> = Vec::new(); |
| 167 | for tok in s.split('/').filter(|t| !t.is_empty()) { |
| 168 | match tok { |
| 169 | "." => {} |
| 170 | ".." => { |
| 171 | st.pop()?; |
| 172 | } |
| 173 | t => st.push(t), |
| 174 | } |
| 175 | } |
| 176 | if st.is_empty() { |
| 177 | Some(".".to_string()) |
| 178 | } else { |
| 179 | Some(st.join("/")) |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// `key_dir`: the directory record a key belongs to (`.` for top-level keys). |
| 184 | pub fn key_dir(key: &str) -> String { |
| 185 | match key.rfind('/') { |
| 186 | Some(i) => key[..i].to_string(), |
| 187 | None => ".".to_string(), |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | /// `agent_path` file stem: every byte outside `[A-Za-z0-9._-]` becomes `_`. |
| 192 | pub fn agent_file_stem(agent: &str) -> String { |
| 193 | agent |
| 194 | .bytes() |
| 195 | .map(|c| { |
| 196 | if c.is_ascii_alphanumeric() || c == b'.' || c == b'-' || c == b'_' { |
| 197 | c as char |
| 198 | } else { |
| 199 | '_' |
| 200 | } |
| 201 | }) |
| 202 | .collect() |
| 203 | } |
| 204 | |
| 205 | /// `session_id`: `CRUMB_SESSION` if set and non-empty, else `agent@host`. Never a PID alone. |
| 206 | pub fn default_session(agent: &str) -> String { |
| 207 | if let Ok(s) = std::env::var("CRUMB_SESSION") { |
| 208 | if !s.is_empty() { |
| 209 | return s; |
| 210 | } |
| 211 | } |
| 212 | let mut buf = [0u8; 256]; |
| 213 | // SAFETY: buf is valid for 256 bytes; gethostname writes at most len bytes. |
| 214 | let rc = unsafe { libc::gethostname(buf.as_mut_ptr().cast(), buf.len()) }; |
| 215 | let host = if rc == 0 { |
| 216 | buf[255] = 0; |
| 217 | let n = buf.iter().position(|&c| c == 0).unwrap_or(buf.len()); |
| 218 | String::from_utf8_lossy(&buf[..n]).into_owned() |
| 219 | } else { |
| 220 | "unknown-host".to_string() |
| 221 | }; |
| 222 | format!("{agent}@{host}") |
| 223 | } |
| 224 | |
| 225 | /// Answers "does this repository-relative path exist?" for target-key resolution |
| 226 | /// (`exists_at` in crumb.c). A Git worktree answers from the filesystem; a Synapse |
| 227 | /// workspace answers from its snapshot. |
| 228 | pub trait PathOracle: Send + Sync { |
| 229 | fn exists(&self, rel: &str) -> bool; |
| 230 | /// [`PathOracle::exists`], with a lookup that could not be answered returned as an |
| 231 | /// error instead of read as "absent". Target-key resolution uses this: a transient |
| 232 | /// lookup failure must not key a file differently from a process that could see it |
| 233 | /// (two keys for one file would let two agents hold it). The default is |
| 234 | /// `Ok(self.exists(rel))`, for oracles that cannot fail (a snapshot, [`NoOracle`]). |
| 235 | fn lookup(&self, rel: &str) -> std::io::Result<bool> { |
| 236 | Ok(self.exists(rel)) |
| 237 | } |
| 238 | /// False for an oracle that cannot see the tree. Relative targets named from a |
| 239 | /// subdirectory are then refused: crumb.c would resolve them by file existence, so a |
| 240 | /// blind guess could key one file twice and let two agents hold it. |
| 241 | fn sees_tree(&self) -> bool { |
| 242 | true |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | /// Filesystem oracle (`lstat(top/rel)`), what crumb.c uses. |
| 247 | pub struct FsOracle(pub PathBuf); |
| 248 | impl PathOracle for FsOracle { |
| 249 | /// `lstat(top/rel) == 0`, crumb.c's `exists_at`: any error reads as absent here. Key |
| 250 | /// resolution uses [`PathOracle::lookup`], which does not. |
| 251 | fn exists(&self, rel: &str) -> bool { |
| 252 | record::lstat(&self.0.join(rel)).is_ok() |
| 253 | } |
| 254 | /// Absent only when the path cannot name a file for any process: `ENOENT`, `ENOTDIR` |
| 255 | /// (a component is not a directory), `ENAMETOOLONG`, `ELOOP` (a looping component). |
| 256 | /// Every other error (`EIO`, `EACCES`, ...) may hide a file another process sees, so |
| 257 | /// it is returned and the key is not guessed. |
| 258 | fn lookup(&self, rel: &str) -> std::io::Result<bool> { |
| 259 | match record::lstat(&self.0.join(rel)) { |
| 260 | Ok(_) => Ok(true), |
| 261 | Err(e) |
| 262 | if e.kind() == std::io::ErrorKind::NotFound |
| 263 | || matches!( |
| 264 | e.raw_os_error(), |
| 265 | Some(libc::ENOTDIR | libc::ENAMETOOLONG | libc::ELOOP) |
| 266 | ) => |
| 267 | { |
| 268 | Ok(false) |
| 269 | } |
| 270 | Err(e) => Err(e), |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | /// Oracle that knows no files: keys then depend only on the strings given (see README). |
| 276 | pub struct NoOracle; |
| 277 | impl PathOracle for NoOracle { |
| 278 | fn exists(&self, _rel: &str) -> bool { |
| 279 | false |
| 280 | } |
| 281 | fn sees_tree(&self) -> bool { |
| 282 | false |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | /// Holder metadata written into lock and agent records. RFC-0002: branch, worktree path, |
| 287 | /// HEAD and base are holder metadata, never part of a resource's identity. |
| 288 | #[derive(Clone, Debug, Default)] |
| 289 | pub struct Holder { |
| 290 | /// `branch` field. Git: short branch name or `(detached)`. Synapse: the lane/ref name. |
| 291 | pub branch: String, |
| 292 | /// `head` field. Git: 12-hex short commit. Synapse: first 12 hex of the ChangesetId. |
| 293 | pub head: String, |
| 294 | /// `base` field. Git: 12-hex merge-base with origin/main. Synapse: first 12 hex of the base ChangesetId. |
| 295 | pub base: String, |
| 296 | /// Extra `synapse_revision` field (full ChangesetId hex). Absent for Git holders. |
| 297 | pub synapse_revision: Option<String>, |
| 298 | /// Explicit session id; `None` means [`default_session`]. |
| 299 | pub session: Option<String>, |
| 300 | } |
| 301 | |
| 302 | impl Holder { |
| 303 | /// Metadata for an agent working in a Git worktree (what crumb.c records). |
| 304 | pub fn git(branch: &str, head: &str, base: &str) -> Holder { |
| 305 | Holder { |
| 306 | branch: branch.to_string(), |
| 307 | head: head.to_string(), |
| 308 | base: base.to_string(), |
| 309 | ..Holder::default() |
| 310 | } |
| 311 | } |
| 312 | /// Metadata for an agent working in Synapse. `revision` and `base` are full ChangesetId |
| 313 | /// hex strings; `head`/`base` get the same 12-character short form crumb.c uses so the |
| 314 | /// C tool's displays stay readable, and the full id is kept in `synapse_revision`. |
| 315 | pub fn synapse(lane: &str, revision: &str, base: &str) -> Holder { |
| 316 | let short = |s: &str| s.chars().take(12).collect::<String>(); |
| 317 | Holder { |
| 318 | branch: lane.to_string(), |
| 319 | head: short(revision), |
| 320 | base: short(base), |
| 321 | synapse_revision: Some(revision.to_string()), |
| 322 | session: None, |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | /// Where an agent is working: a workspace identity plus the files it can see. |
| 328 | pub struct Workspace { |
| 329 | /// Absolute path label stored in `worktree` (crumb.c: `git rev-parse --show-toplevel`). |
| 330 | /// For Synapse, the workspace directory the agent materialized, or any stable absolute |
| 331 | /// label; absolute targets are accepted only under it. |
| 332 | pub top: String, |
| 333 | pub holder: Holder, |
| 334 | pub oracle: Box<dyn PathOracle>, |
| 335 | } |
| 336 | |
| 337 | impl Workspace { |
| 338 | /// A Git worktree checkout at `top` (filesystem oracle). |
| 339 | pub fn worktree(top: impl Into<String>, holder: Holder) -> Workspace { |
| 340 | let top = top.into(); |
| 341 | Workspace { |
| 342 | oracle: Box::new(FsOracle(PathBuf::from(&top))), |
| 343 | top, |
| 344 | holder, |
| 345 | } |
| 346 | } |
| 347 | /// A workspace with a caller-supplied oracle (e.g. a Synapse snapshot). |
| 348 | pub fn with_oracle( |
| 349 | top: impl Into<String>, |
| 350 | holder: Holder, |
| 351 | oracle: Box<dyn PathOracle>, |
| 352 | ) -> Workspace { |
| 353 | Workspace { |
| 354 | top: top.into(), |
| 355 | holder, |
| 356 | oracle, |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | /// Repository-relative directory for a `dir` argument (relative or absolute under `top`). |
| 361 | pub fn rel_dir(&self, dir: &str) -> Result<String, CoordError> { |
| 362 | if dir.starts_with('/') { |
| 363 | let t = self.top.trim_end_matches('/'); |
| 364 | if dir == t { |
| 365 | return Ok(".".into()); |
| 366 | } |
| 367 | let rest = dir |
| 368 | .strip_prefix(t) |
| 369 | .and_then(|r| r.strip_prefix('/')) |
| 370 | .ok_or_else(|| CoordError::OutsideWorkspace { |
| 371 | path: dir.into(), |
| 372 | workspace: self.top.clone(), |
| 373 | })?; |
| 374 | return norm_path(rest).ok_or_else(|| CoordError::EscapesRoot { path: dir.into() }); |
| 375 | } |
| 376 | norm_path(dir).ok_or_else(|| CoordError::EscapesRoot { path: dir.into() }) |
| 377 | } |
| 378 | |
| 379 | /// `target_key`: repository-relative key for a target named from directory `rel`. |
| 380 | /// `<rel>/<target>` if that exists, else `<target>` from the root if that exists, else |
| 381 | /// the repository-relative form when the target contains `/`, else `<rel>/<target>`. |
| 382 | pub fn target_key(&self, target: &str, rel: &str) -> Result<String, CoordError> { |
| 383 | if target.starts_with('/') { |
| 384 | let t = self.top.trim_end_matches('/'); |
| 385 | let rest = target |
| 386 | .strip_prefix(t) |
| 387 | .and_then(|r| r.strip_prefix('/')) |
| 388 | .ok_or_else(|| CoordError::OutsideWorkspace { |
| 389 | path: target.into(), |
| 390 | workspace: self.top.clone(), |
| 391 | })?; |
| 392 | return norm_path(rest).ok_or_else(|| CoordError::EscapesRoot { |
| 393 | path: target.into(), |
| 394 | }); |
| 395 | } |
| 396 | if rel != "." && !self.oracle.sees_tree() { |
| 397 | return Err(CoordError::AmbiguousWithoutTree { |
| 398 | target: target.into(), |
| 399 | dir: rel.into(), |
| 400 | }); |
| 401 | } |
| 402 | let joined = if rel != "." { |
| 403 | format!("{rel}/{target}") |
| 404 | } else { |
| 405 | target.to_string() |
| 406 | }; |
| 407 | let c1 = norm_path(&joined); |
| 408 | let c2 = norm_path(target); |
| 409 | // A lookup that cannot be answered refuses the key instead of reading as absent. |
| 410 | let exists = |c: &str| -> Result<bool, CoordError> { |
| 411 | if c == "." { |
| 412 | return Ok(false); |
| 413 | } |
| 414 | self.oracle.lookup(c).map_err(|source| CoordError::Io { |
| 415 | path: Path::new(&self.top).join(c), |
| 416 | source, |
| 417 | }) |
| 418 | }; |
| 419 | if let Some(c) = c1.as_deref() { |
| 420 | if exists(c)? { |
| 421 | return Ok(c.to_string()); |
| 422 | } |
| 423 | } |
| 424 | if let Some(c) = c2.as_deref() { |
| 425 | if exists(c)? { |
| 426 | return Ok(c.to_string()); |
| 427 | } |
| 428 | } |
| 429 | if target.contains('/') { |
| 430 | if let Some(c) = c2.clone() { |
| 431 | return Ok(c); |
| 432 | } |
| 433 | } |
| 434 | c1.or(c2).ok_or_else(|| CoordError::EscapesRoot { |
| 435 | path: target.into(), |
| 436 | }) |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | /// Close actions accepted by `crumb close`. |
| 441 | pub const ACTIONS: [&str; 6] = ["create", "modify", "delete", "audit", "test", "build"]; |
| 442 | /// Whisper priorities accepted by `crumb whisper`. |
| 443 | pub const PRIORITIES: [&str; 4] = ["low", "normal", "high", "critical"]; |
| 444 | |
| 445 | /// A lock as stored under `locks` in a directory record. |
| 446 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 447 | pub struct LockView { |
| 448 | pub key: String, |
| 449 | pub holder: String, |
| 450 | pub session: String, |
| 451 | pub intent: String, |
| 452 | pub worktree: String, |
| 453 | pub branch: String, |
| 454 | pub head: String, |
| 455 | pub acquired_at: String, |
| 456 | pub ttl_seconds: i64, |
| 457 | pub synapse_revision: Option<String>, |
| 458 | pub imported_from: Option<String>, |
| 459 | } |
| 460 | |
| 461 | impl LockView { |
| 462 | fn from(key: &str, e: &J) -> LockView { |
| 463 | let s = |k: &str| e.str_of(k).unwrap_or_default(); |
| 464 | LockView { |
| 465 | key: key.to_string(), |
| 466 | holder: s("holder"), |
| 467 | session: s("session"), |
| 468 | intent: s("intent"), |
| 469 | worktree: s("worktree"), |
| 470 | branch: s("branch"), |
| 471 | head: s("head"), |
| 472 | acquired_at: s("acquired_at"), |
| 473 | ttl_seconds: e.long_of("ttl_seconds", LOCK_TTL), |
| 474 | synapse_revision: e.str_of("synapse_revision"), |
| 475 | imported_from: e.str_of("imported_from"), |
| 476 | } |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | /// A live agent presence record (`agents/<agent>.json`). |
| 481 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 482 | pub struct AgentView { |
| 483 | pub agent: String, |
| 484 | pub session: String, |
| 485 | pub focus: String, |
| 486 | pub dir: String, |
| 487 | pub worktree: String, |
| 488 | pub branch: String, |
| 489 | pub head: String, |
| 490 | pub updated_at: String, |
| 491 | /// Seconds since `updated_at`, -1 when unparseable. |
| 492 | pub heartbeat_age: i64, |
| 493 | pub synapse_revision: Option<String>, |
| 494 | } |
| 495 | |
| 496 | /// A whisper addressed to the sniffing agent or broadcast. |
| 497 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 498 | pub struct WhisperView { |
| 499 | pub from: String, |
| 500 | pub to: Option<String>, |
| 501 | pub message: String, |
| 502 | pub timestamp: String, |
| 503 | pub priority: Option<String>, |
| 504 | pub target_file: Option<String>, |
| 505 | } |
| 506 | |
| 507 | /// Result of a claim. |
| 508 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 509 | pub enum ClaimOutcome { |
| 510 | Claimed { |
| 511 | key: String, |
| 512 | }, |
| 513 | /// Someone else holds an unexpired lock on the key (crumb.c exit code 2). |
| 514 | Blocked { |
| 515 | key: String, |
| 516 | holder: Box<LockView>, |
| 517 | }, |
| 518 | } |
| 519 | |
| 520 | /// Result of a close. |
| 521 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 522 | pub enum CloseOutcome { |
| 523 | Closed { |
| 524 | key: String, |
| 525 | lock_was_held: bool, |
| 526 | }, |
| 527 | /// The key is held by another agent (crumb.c exit code 2). |
| 528 | Refused { |
| 529 | key: String, |
| 530 | holder: String, |
| 531 | }, |
| 532 | } |
| 533 | |
| 534 | /// Read-side view of the plane, the data behind `crumb sniff`. |
| 535 | #[derive(Clone, Debug, Default)] |
| 536 | pub struct Sniff { |
| 537 | pub store: PathBuf, |
| 538 | pub agents: Vec<AgentView>, |
| 539 | pub locks: Vec<LockView>, |
| 540 | /// Other workspaces seen in records: (worktree, agents there, conflicting keys under `dir`). |
| 541 | pub other_workspaces: Vec<(String, Vec<String>, Vec<String>)>, |
| 542 | pub whispers: Vec<WhisperView>, |
| 543 | /// The store's identity marker; `None` until a mutating open has created it. |
| 544 | pub store_id: Option<StoreId>, |
| 545 | } |
| 546 | |
| 547 | type Clock = Arc<dyn Fn() -> i64 + Send + Sync>; |
| 548 | |
| 549 | /// A coordination store at an explicit root (crumb.c: `<git-common-dir>/crumb/v1` or |
| 550 | /// `CRUMB_COORD_ROOT`). Layout: `dirs/<rel>.json` (`dirs/_root.json` for `.`), |
| 551 | /// `agents/<agent>.json`, `continuations/`, `ledger/`, and the transaction lock file `.lock`. |
| 552 | #[derive(Clone)] |
| 553 | pub struct CoordStore { |
| 554 | root: PathBuf, |
| 555 | clock: Clock, |
| 556 | /// Registered identity this handle insists on (see [`CoordStore::open_expecting`]). |
| 557 | expected: Option<StoreId>, |
| 558 | } |
| 559 | |
| 560 | impl std::fmt::Debug for CoordStore { |
| 561 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 562 | f.debug_struct("CoordStore") |
| 563 | .field("root", &self.root) |
| 564 | .field("expected", &self.expected) |
| 565 | .finish() |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | struct Rec { |
| 570 | path: PathBuf, |
| 571 | root: J, |
| 572 | before: Vec<u8>, |
| 573 | agent: bool, |
| 574 | dead: bool, |
| 575 | } |
| 576 | |
| 577 | /// POSIX record locks belong to the process, not the thread, and are dropped when the |
| 578 | /// process closes *any* descriptor for the file. One process-wide mutex therefore |
| 579 | /// serializes transactions inside this process; the `fcntl` lock serializes processes |
| 580 | /// (including crumb.c). |
| 581 | static IN_PROCESS: Mutex<()> = Mutex::new(()); |
| 582 | |
| 583 | struct Txn<'a> { |
| 584 | store: &'a CoordStore, |
| 585 | recs: Vec<Rec>, |
| 586 | now: i64, |
| 587 | lock: Option<(File, MutexGuard<'static, ()>)>, |
| 588 | } |
| 589 | |
| 590 | impl CoordStore { |
| 591 | /// Open a store without an identity expectation. The first mutating transaction (or |
| 592 | /// [`CoordStore::ensure_store_id`]) creates the `STORE_ID` marker if it is absent. |
| 593 | pub fn open(root: impl Into<PathBuf>) -> CoordStore { |
| 594 | CoordStore { |
| 595 | root: root.into(), |
| 596 | clock: Arc::new(time::system_now), |
| 597 | expected: None, |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | /// Open a store that must carry the identity `expected` (the id Synapse registered for |
| 602 | /// this repository). Refuses now, and again inside every later transaction, with |
| 603 | /// [`CoordError::StoreIdMissing`] when the root has no marker and |
| 604 | /// [`CoordError::StoreIdMismatch`] when it names another store. Such a handle never |
| 605 | /// creates a marker, so a misconfigured root is never silently adopted. |
| 606 | pub fn open_expecting( |
| 607 | root: impl Into<PathBuf>, |
| 608 | expected: StoreId, |
| 609 | ) -> Result<CoordStore, CoordError> { |
| 610 | let mut s = CoordStore::open(root); |
| 611 | s.expected = Some(expected); |
| 612 | s.check_expected()?; |
| 613 | Ok(s) |
| 614 | } |
| 615 | |
| 616 | /// The identity this handle insists on, if any. |
| 617 | pub fn expected_store_id(&self) -> Option<StoreId> { |
| 618 | self.expected |
| 619 | } |
| 620 | |
| 621 | /// Read the store's identity marker without creating it (`None` if absent). |
| 622 | pub fn store_id(&self) -> Result<Option<StoreId>, CoordError> { |
| 623 | identity::read_marker(&self.root) |
| 624 | } |
| 625 | |
| 626 | /// The store's identity, creating the marker under the store lock if absent (for an |
| 627 | /// expecting handle: verified, never created). Use this to register a store. |
| 628 | pub fn ensure_store_id(&self) -> Result<StoreId, CoordError> { |
| 629 | let t = self.begin(true)?; |
| 630 | let id = self.store_id()?.ok_or_else(|| CoordError::StoreIdMissing { |
| 631 | root: self.root.clone(), |
| 632 | })?; |
| 633 | t.commit()?; |
| 634 | Ok(id) |
| 635 | } |
| 636 | |
| 637 | fn check_expected(&self) -> Result<(), CoordError> { |
| 638 | let Some(expected) = self.expected else { |
| 639 | return Ok(()); |
| 640 | }; |
| 641 | match identity::read_marker(&self.root)? { |
| 642 | None => Err(CoordError::StoreIdMissing { |
| 643 | root: self.root.clone(), |
| 644 | }), |
| 645 | Some(found) if found != expected => Err(CoordError::StoreIdMismatch { |
| 646 | root: self.root.clone(), |
| 647 | expected, |
| 648 | found, |
| 649 | }), |
| 650 | Some(_) => Ok(()), |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | /// Replace the clock (Unix seconds). For tests of expiry. |
| 655 | pub fn with_clock(mut self, clock: impl Fn() -> i64 + Send + Sync + 'static) -> CoordStore { |
| 656 | self.clock = Arc::new(clock); |
| 657 | self |
| 658 | } |
| 659 | |
| 660 | pub fn root(&self) -> &Path { |
| 661 | &self.root |
| 662 | } |
| 663 | |
| 664 | fn dir_path(&self, rel: &str) -> PathBuf { |
| 665 | if rel == "." { |
| 666 | self.root.join("dirs/_root.json") |
| 667 | } else { |
| 668 | self.root.join("dirs").join(format!("{rel}.json")) |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | fn agent_path(&self, agent: &str) -> PathBuf { |
| 673 | self.root |
| 674 | .join("agents") |
| 675 | .join(format!("{}.json", agent_file_stem(agent))) |
| 676 | } |
| 677 | |
| 678 | fn begin(&self, mutate: bool) -> Result<Txn<'_>, CoordError> { |
| 679 | let mut t = Txn { |
| 680 | store: self, |
| 681 | recs: Vec::new(), |
| 682 | now: (self.clock)(), |
| 683 | lock: None, |
| 684 | }; |
| 685 | // An expecting handle refuses a wrong root before creating anything in it. |
| 686 | self.check_expected()?; |
| 687 | if !mutate { |
| 688 | return Ok(t); |
| 689 | } |
| 690 | for sub in ["dirs", "agents", "continuations", "ledger"] { |
| 691 | let d = self.root.join(sub); |
| 692 | fs::create_dir_all(&d).map_err(io_err(&d))?; |
| 693 | } |
| 694 | let guard = IN_PROCESS.lock().unwrap_or_else(|e| e.into_inner()); |
| 695 | let lp = self.root.join(".lock"); |
| 696 | let f = OpenOptions::new() |
| 697 | .read(true) |
| 698 | .write(true) |
| 699 | .create(true) |
| 700 | .truncate(false) |
| 701 | .mode(0o644) |
| 702 | .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) |
| 703 | .open(&lp) |
| 704 | .map_err(|e| match e.raw_os_error() { |
| 705 | Some(libc::ELOOP) => CoordError::RefusedRecord { |
| 706 | path: lp.clone(), |
| 707 | reason: RecordRefusal::Symlink, |
| 708 | }, |
| 709 | // A directory planted as `.lock` is a refused store file, not an I/O error. |
| 710 | Some(libc::EISDIR) => CoordError::RefusedRecord { |
| 711 | path: lp.clone(), |
| 712 | reason: RecordRefusal::NotRegular("directory"), |
| 713 | }, |
| 714 | _ => io_err(&lp)(e), |
| 715 | })?; |
| 716 | // The lock file is a store file too: a FIFO or device planted as `.lock` is refused. |
| 717 | let m = f.metadata().map_err(io_err(&lp))?; |
| 718 | if let Some(reason) = record::refusal_for(&m.file_type()) { |
| 719 | return Err(CoordError::RefusedRecord { path: lp, reason }); |
| 720 | } |
| 721 | // SAFETY: zeroed flock is a valid "whole file from offset 0" request. |
| 722 | let mut fl: libc::flock = unsafe { std::mem::zeroed() }; |
| 723 | fl.l_type = libc::F_WRLCK as _; |
| 724 | fl.l_whence = libc::SEEK_SET as _; |
| 725 | loop { |
| 726 | // SAFETY: f is open for the duration of the call; fl is a valid flock. |
| 727 | let rc = unsafe { libc::fcntl(f.as_raw_fd(), libc::F_SETLKW, &fl) }; |
| 728 | if rc == 0 { |
| 729 | break; |
| 730 | } |
| 731 | let e = std::io::Error::last_os_error(); |
| 732 | if e.raw_os_error() != Some(libc::EINTR) { |
| 733 | return Err(CoordError::Io { |
| 734 | path: lp, |
| 735 | source: e, |
| 736 | }); |
| 737 | } |
| 738 | } |
| 739 | t.lock = Some((f, guard)); |
| 740 | // Under the lock: re-check the expectation (the marker could have changed since), |
| 741 | // or create the marker on this store's first mutating open. |
| 742 | if self.expected.is_some() { |
| 743 | self.check_expected()?; |
| 744 | } else { |
| 745 | identity::ensure_marker_locked(&self.root)?; |
| 746 | } |
| 747 | Ok(t) |
| 748 | } |
| 749 | } |
| 750 | |
| 751 | /// `sweep` (RFC-0001 SPEC 5.4): drop expired scents and locks, and whispers past retention. |
| 752 | fn sweep(root: &mut J, now: i64) { |
| 753 | if let Some(J::Obj(sc)) = root.get_mut("active_scents") { |
| 754 | sc.retain(|(_, v)| { |
| 755 | let u = time::parse_iso(v.bytes_of("updated_at")); |
| 756 | !(u < 0 || now - u > v.long_of("ttl_seconds", SCENT_TTL)) |
| 757 | }); |
| 758 | } |
| 759 | if let Some(J::Obj(lk)) = root.get_mut("locks") { |
| 760 | lk.retain(|(_, v)| { |
| 761 | let u = time::parse_iso(v.bytes_of("acquired_at")); |
| 762 | !(u < 0 || now - u > v.long_of("ttl_seconds", LOCK_TTL)) |
| 763 | }); |
| 764 | } |
| 765 | if let Some(J::Arr(wh)) = root.get_mut("whispers") { |
| 766 | wh.retain(|v| { |
| 767 | let u = time::parse_iso(v.bytes_of("timestamp")); |
| 768 | !(u >= 0 && now - u > WHISPER_RETENTION) |
| 769 | }); |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | fn has_lock_by(root: &J, agent: &str) -> bool { |
| 774 | match root.get("locks") { |
| 775 | Some(J::Obj(m)) => m |
| 776 | .iter() |
| 777 | .any(|(_, v)| v.str_of("holder").as_deref() == Some(agent)), |
| 778 | _ => false, |
| 779 | } |
| 780 | } |
| 781 | |
| 782 | /// Flush a directory, making the entries created, renamed or removed in it durable. A |
| 783 | /// durability boundary: the caller must not report success (a receipt, an ACK, a written |
| 784 | /// record) when this fails, because a power loss could then undo the entry. |
| 785 | /// |
| 786 | /// Opened like every other store file: never following a final link, never blocking (a |
| 787 | /// FIFO planted in place of a directory cannot stall the writer), and only if it really is |
| 788 | /// a directory. Every open or sync error is returned, with one documented exception: an |
| 789 | /// `fsync` answered with `EINVAL` means the file system does not support syncing a |
| 790 | /// directory at all (Linux `fsync(2)`: "fd is bound to a special file ... which does not |
| 791 | /// support synchronization"; PostgreSQL's `fsync_fname` tolerates the same case), so there |
| 792 | /// is nothing more this process can do and it is treated as done. |
| 793 | /// |
| 794 | /// Test-only fault injection through `SYNAPSE_COORD_FAULT`: `dir-sync-eio` makes the |
| 795 | /// sync fail with `EIO`, `dir-sync-einval` with `EINVAL` (unset in normal use). |
| 796 | fn fsync_dir(dir: &Path) -> Result<(), CoordError> { |
| 797 | let f = OpenOptions::new() |
| 798 | .read(true) |
| 799 | .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC) |
| 800 | .open(dir) |
| 801 | .map_err(io_err(dir))?; |
| 802 | let r = match std::env::var("SYNAPSE_COORD_FAULT").as_deref() { |
| 803 | Ok("dir-sync-eio") => Err(std::io::Error::from_raw_os_error(libc::EIO)), |
| 804 | Ok("dir-sync-einval") => Err(std::io::Error::from_raw_os_error(libc::EINVAL)), |
| 805 | _ => f.sync_all(), |
| 806 | }; |
| 807 | match r { |
| 808 | Ok(()) => Ok(()), |
| 809 | Err(e) if e.raw_os_error() == Some(libc::EINVAL) => Ok(()), |
| 810 | Err(e) => Err(io_err(dir)(e)), |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | /// `durable_write`: write `<path>.tmp<pid>`, fsync, rename over `path`, fsync the directory. |
| 815 | /// A crash before the rename leaves the old record intact and a `*.tmp<pid>` file that no |
| 816 | /// reader ever loads (only names ending in `.json` are records). |
| 817 | /// |
| 818 | /// Refuses (typed [`CoordError::RefusedRecord`]) to replace anything but a regular file, and |
| 819 | /// to write a record over [`MAX_RECORD_BYTES`], which readers would refuse. |
| 820 | fn durable_write(root: &Path, path: &Path, data: &[u8]) -> Result<(), CoordError> { |
| 821 | if data.len() as u64 > MAX_RECORD_BYTES { |
| 822 | return Err(CoordError::RefusedRecord { |
| 823 | path: path.to_path_buf(), |
| 824 | reason: RecordRefusal::TooLarge { |
| 825 | limit: MAX_RECORD_BYTES, |
| 826 | }, |
| 827 | }); |
| 828 | } |
| 829 | record::check_real_parents(root, path)?; |
| 830 | record::check_replaceable(path)?; |
| 831 | let dd = path.parent().unwrap_or(Path::new(".")); |
| 832 | fs::create_dir_all(dd).map_err(io_err(dd))?; |
| 833 | let mut tmp = path.as_os_str().to_owned(); |
| 834 | tmp.push(format!(".tmp{}", std::process::id())); |
| 835 | let tmp = PathBuf::from(tmp); |
| 836 | { |
| 837 | let mut f = record::create_temp(&tmp)?; |
| 838 | f.write_all(data).map_err(io_err(&tmp))?; |
| 839 | f.sync_all().map_err(io_err(&tmp))?; |
| 840 | } |
| 841 | fault_point("before-rename"); |
| 842 | fs::rename(&tmp, path).map_err(io_err(path))?; |
| 843 | // The rename is only durable once the directory is: no success before that. A failed |
| 844 | // sync leaves the new record visible, so a caller with an "already applied" path (a |
| 845 | // retry that finds the record as it wanted it and writes nothing) must sync the |
| 846 | // directory again itself before it reports success (the board's `ack`, |
| 847 | // `subscribe`, `deliver` of an existing cursor, compaction). |
| 848 | fsync_dir(dd) |
| 849 | } |
| 850 | |
| 851 | /// Test-only fault injection: `SYNAPSE_COORD_FAULT=<point>` aborts the process at that point |
| 852 | /// (used by the crash-mid-write test through the CLI binary). Unset in normal use. |
| 853 | fn fault_point(point: &str) { |
| 854 | if std::env::var("SYNAPSE_COORD_FAULT").as_deref() == Ok(point) { |
| 855 | std::process::abort(); |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | /// List record names under `dir`, recursively, without opening any entry. Entry types come |
| 860 | /// from the directory entry (`d_type`, falling back to `lstat`), so nothing is followed: |
| 861 | /// real subdirectories are walked, symlinked directories are not (crumb.c follows them with |
| 862 | /// `stat`; not following also rules out a symlink loop). Every name ending in `.json` that |
| 863 | /// is not a directory is returned, whatever its type; [`record::read_bounded`] then refuses |
| 864 | /// a non-regular one without opening it, so a planted FIFO is reported, never read. |
| 865 | /// |
| 866 | /// Complete or an error: callers decide from the list that no other record holds a lock |
| 867 | /// (`close` drops an agent's presence when it holds no other lock; `sniff` reports the |
| 868 | /// live locks), so only an absent directory (a new store has no `dirs/` yet, or a |
| 869 | /// subdirectory removed since it was listed) is empty, and an entry that vanished between |
| 870 | /// the listing and its type lookup is skipped. Every other listing, entry or type error is |
| 871 | /// returned, never a shorter list. |
| 872 | fn collect_json(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), CoordError> { |
| 873 | let rd = match record::list_dir(dir) { |
| 874 | Ok(rd) => rd, |
| 875 | Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), |
| 876 | Err(e) => return Err(io_err(dir)(e)), |
| 877 | }; |
| 878 | let mut ents = Vec::new(); |
| 879 | for e in rd { |
| 880 | let e = e.map_err(io_err(dir))?; |
| 881 | let full = e.path(); |
| 882 | match e.file_type() { |
| 883 | Ok(ft) => ents.push((full, ft.is_dir())), |
| 884 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} |
| 885 | Err(err) => return Err(io_err(&full)(err)), |
| 886 | } |
| 887 | } |
| 888 | ents.sort_by(|a, b| a.0.cmp(&b.0)); |
| 889 | for (full, is_dir) in ents { |
| 890 | if is_dir { |
| 891 | collect_json(&full, out)?; |
| 892 | } else if let Some(n) = full.file_name().and_then(|n| n.to_str()) { |
| 893 | if n.len() > 5 && n.ends_with(".json") { |
| 894 | out.push(full); |
| 895 | } |
| 896 | } |
| 897 | } |
| 898 | Ok(()) |
| 899 | } |
| 900 | |
| 901 | impl Txn<'_> { |
| 902 | /// `rec_load`: load (once) and prepare a record. `label` is the directory for dir records. |
| 903 | fn load(&mut self, path: &Path, agent: bool, label: Option<&str>) -> Result<usize, CoordError> { |
| 904 | if let Some(i) = self.recs.iter().position(|r| r.path == path) { |
| 905 | return Ok(i); |
| 906 | } |
| 907 | // Never read through a symlinked directory: listing does not follow one, so a record |
| 908 | // behind it would be invisible to prune yet loadable and writable here. |
| 909 | record::check_real_parents(&self.store.root, path)?; |
| 910 | let (mut j, existed) = match record::read_bounded(path, MAX_RECORD_BYTES)? { |
| 911 | Some(bytes) => match json::parse(&bytes) { |
| 912 | Some(j) if j.is_obj() => (j, true), |
| 913 | _ => { |
| 914 | return Err(CoordError::CorruptRecord { |
| 915 | path: path.to_path_buf(), |
| 916 | }) |
| 917 | } |
| 918 | }, |
| 919 | None => (J::obj(), false), |
| 920 | }; |
| 921 | if !agent { |
| 922 | if j.get("schema_version").is_none() { |
| 923 | j.set("schema_version", J::str(SCHEMA)); |
| 924 | } |
| 925 | if j.get("directory").is_none() { |
| 926 | j.set("directory", J::str(label.unwrap_or("."))); |
| 927 | } |
| 928 | } |
| 929 | let before = j.dump(); |
| 930 | let mut dead = false; |
| 931 | if agent { |
| 932 | let u = time::parse_iso(j.bytes_of("updated_at")); |
| 933 | if existed && (u < 0 || self.now - u > j.long_of("ttl_seconds", SCENT_TTL)) { |
| 934 | dead = true; |
| 935 | } |
| 936 | } else { |
| 937 | sweep(&mut j, self.now); |
| 938 | } |
| 939 | self.recs.push(Rec { |
| 940 | path: path.to_path_buf(), |
| 941 | root: j, |
| 942 | before, |
| 943 | agent, |
| 944 | dead, |
| 945 | }); |
| 946 | Ok(self.recs.len() - 1) |
| 947 | } |
| 948 | |
| 949 | fn dir_rec(&mut self, rel: &str) -> Result<usize, CoordError> { |
| 950 | let p = self.store.dir_path(rel); |
| 951 | self.load(&p, false, Some(rel)) |
| 952 | } |
| 953 | |
| 954 | fn agent_rec(&mut self, agent: &str) -> Result<usize, CoordError> { |
| 955 | let p = self.store.agent_path(agent); |
| 956 | self.load(&p, true, None) |
| 957 | } |
| 958 | |
| 959 | /// `txn_prune`: load every record so expired entries drop out (written back on commit). |
| 960 | fn prune(&mut self) -> Result<(), CoordError> { |
| 961 | let dd = self.store.root.join("dirs"); |
| 962 | let mut f = Vec::new(); |
| 963 | collect_json(&dd, &mut f)?; |
| 964 | for p in f { |
| 965 | let rel = p |
| 966 | .strip_prefix(&dd) |
| 967 | .ok() |
| 968 | .and_then(|r| r.to_str()) |
| 969 | .map(|r| r[..r.len() - 5].to_string()) |
| 970 | .unwrap_or_default(); |
| 971 | let label = if rel == "_root" { "." } else { rel.as_str() }; |
| 972 | self.load(&p, false, Some(label))?; |
| 973 | } |
| 974 | let mut g = Vec::new(); |
| 975 | collect_json(&self.store.root.join("agents"), &mut g)?; |
| 976 | for p in g { |
| 977 | self.load(&p, true, None)?; |
| 978 | } |
| 979 | Ok(()) |
| 980 | } |
| 981 | |
| 982 | /// `txn_end(commit = 1)`: unlink dead agent records, durably write changed records, |
| 983 | /// then release the OS lock. |
| 984 | fn commit(mut self) -> Result<(), CoordError> { |
| 985 | for r in &self.recs { |
| 986 | if r.dead { |
| 987 | // Best effort, as in crumb.c: presence is advisory and no lock lives in an |
| 988 | // agent record, so one left behind only shows the agent until its TTL ends. |
| 989 | if fs::remove_file(&r.path).is_ok() { |
| 990 | fsync_dir(r.path.parent().unwrap_or(Path::new(".")))?; |
| 991 | } |
| 992 | continue; |
| 993 | } |
| 994 | let now = r.root.dump(); |
| 995 | if now != r.before { |
| 996 | durable_write(&self.store.root, &r.path, &now)?; |
| 997 | } |
| 998 | } |
| 999 | self.lock.take(); |
| 1000 | Ok(()) |
| 1001 | } |
| 1002 | |
| 1003 | fn agent_set( |
| 1004 | &mut self, |
| 1005 | ws: &Workspace, |
| 1006 | agent: &str, |
| 1007 | focus: &str, |
| 1008 | rel: &str, |
| 1009 | ttl: i64, |
| 1010 | ) -> Result<(), CoordError> { |
| 1011 | let i = self.agent_rec(agent)?; |
| 1012 | let mut e = J::obj(); |
| 1013 | e.set("agent", J::str(agent)); |
| 1014 | e.set("session", J::str(&session_of(ws, agent))); |
| 1015 | e.set("focus", J::str(focus)); |
| 1016 | e.set("dir", J::str(rel)); |
| 1017 | holder_fields(&mut e, ws); |
| 1018 | e.set("updated_at", J::str(&time::iso(self.now))); |
| 1019 | e.set("ttl_seconds", J::num(ttl)); |
| 1020 | if let Some(r) = &ws.holder.synapse_revision { |
| 1021 | e.set("synapse_revision", J::str(r)); |
| 1022 | } |
| 1023 | let r = &mut self.recs[i]; |
| 1024 | r.dead = false; |
| 1025 | r.root = e; |
| 1026 | Ok(()) |
| 1027 | } |
| 1028 | |
| 1029 | fn agent_has_lock(&self, agent: &str) -> bool { |
| 1030 | self.recs |
| 1031 | .iter() |
| 1032 | .any(|r| !r.agent && has_lock_by(&r.root, agent)) |
| 1033 | } |
| 1034 | } |
| 1035 | |
| 1036 | fn session_of(ws: &Workspace, agent: &str) -> String { |
| 1037 | ws.holder |
| 1038 | .session |
| 1039 | .clone() |
| 1040 | .unwrap_or_else(|| default_session(agent)) |
| 1041 | } |
| 1042 | |
| 1043 | fn holder_fields(e: &mut J, ws: &Workspace) { |
| 1044 | e.set("worktree", J::str(&ws.top)); |
| 1045 | e.set("branch", J::str(&ws.holder.branch)); |
| 1046 | e.set("head", J::str(&ws.holder.head)); |
| 1047 | e.set("base", J::str(&ws.holder.base)); |
| 1048 | } |
| 1049 | |
| 1050 | fn whisper_add( |
| 1051 | root: &mut J, |
| 1052 | now: i64, |
| 1053 | from: &str, |
| 1054 | to: Option<&str>, |
| 1055 | msg: &str, |
| 1056 | prio: Option<&str>, |
| 1057 | tf: Option<&str>, |
| 1058 | ) { |
| 1059 | let mut e = J::obj(); |
| 1060 | e.set("from", J::str(from)); |
| 1061 | if let Some(to) = to.filter(|t| *t != "-") { |
| 1062 | e.set("to", J::str(to)); |
| 1063 | } |
| 1064 | e.set("message", J::str(msg)); |
| 1065 | if let Some(tf) = tf.filter(|t| !t.is_empty()) { |
| 1066 | e.set("target_file", J::str(tf)); |
| 1067 | } |
| 1068 | e.set("timestamp", J::str(&time::iso(now))); |
| 1069 | if let Some(p) = prio.filter(|p| !p.is_empty()) { |
| 1070 | e.set("priority", J::str(p)); |
| 1071 | } |
| 1072 | root.arr_of("whispers").push(e); |
| 1073 | } |
| 1074 | |
| 1075 | fn history_add(root: &mut J, now: i64, agent: &str, action: &str, target: &str, intent: &str) { |
| 1076 | let mut e = J::obj(); |
| 1077 | e.set("agent", J::str(agent)); |
| 1078 | e.set("action", J::str(action)); |
| 1079 | e.set("target", J::str(target)); |
| 1080 | e.set("intent", J::str(intent)); |
| 1081 | e.set("vector", J::str("")); |
| 1082 | e.set("timestamp", J::str(&time::iso(now))); |
| 1083 | let h = root.arr_of("history"); |
| 1084 | h.push(e); |
| 1085 | if h.len() > HISTORY_CAP { |
| 1086 | let d = h.len() - HISTORY_CAP; |
| 1087 | h.drain(..d); |
| 1088 | } |
| 1089 | } |
| 1090 | |
| 1091 | impl CoordStore { |
| 1092 | /// `crumb claim`: take the advisory lock on `target` (named from directory `dir`). |
| 1093 | /// `ttl` defaults to [`LOCK_TTL`]. Re-claiming one's own lock refreshes it. |
| 1094 | pub fn claim( |
| 1095 | &self, |
| 1096 | ws: &Workspace, |
| 1097 | agent: &str, |
| 1098 | dir: &str, |
| 1099 | target: &str, |
| 1100 | intent: &str, |
| 1101 | ttl: Option<i64>, |
| 1102 | ) -> Result<ClaimOutcome, CoordError> { |
| 1103 | let ttl = check_ttl(ttl, LOCK_TTL)?; |
| 1104 | let rel = ws.rel_dir(dir)?; |
| 1105 | let key = ws.target_key(target, &rel)?; |
| 1106 | let td = key_dir(&key); |
| 1107 | let mut t = self.begin(true)?; |
| 1108 | t.prune()?; |
| 1109 | let ti = t.dir_rec(&td)?; |
| 1110 | let now = t.now; |
| 1111 | let locks = t.recs[ti].root.obj_of("locks"); |
| 1112 | if let Some(cur) = locks.get(&key) { |
| 1113 | if let Some(h) = cur.str_of("holder") { |
| 1114 | if h != agent { |
| 1115 | let holder = LockView::from(&key, cur); |
| 1116 | t.commit()?; |
| 1117 | return Ok(ClaimOutcome::Blocked { |
| 1118 | key, |
| 1119 | holder: Box::new(holder), |
| 1120 | }); |
| 1121 | } |
| 1122 | } |
| 1123 | } |
| 1124 | let mut e = J::obj(); |
| 1125 | e.set("holder", J::str(agent)); |
| 1126 | e.set("session", J::str(&session_of(ws, agent))); |
| 1127 | e.set("target", J::str(&key)); |
| 1128 | e.set("intent", J::str(intent)); |
| 1129 | holder_fields(&mut e, ws); |
| 1130 | e.set("acquired_at", J::str(&time::iso(now))); |
| 1131 | e.set("ttl_seconds", J::num(ttl)); |
| 1132 | if let Some(r) = &ws.holder.synapse_revision { |
| 1133 | e.set("synapse_revision", J::str(r)); |
| 1134 | } |
| 1135 | locks.set(&key, e); |
| 1136 | t.agent_set(ws, agent, intent, &rel, SCENT_TTL.max(ttl))?; |
| 1137 | t.commit()?; |
| 1138 | Ok(ClaimOutcome::Claimed { key }) |
| 1139 | } |
| 1140 | |
| 1141 | /// `crumb update`: refresh this agent's presence. `ttl` defaults to [`SCENT_TTL`]. |
| 1142 | pub fn update( |
| 1143 | &self, |
| 1144 | ws: &Workspace, |
| 1145 | agent: &str, |
| 1146 | dir: &str, |
| 1147 | focus: &str, |
| 1148 | ttl: Option<i64>, |
| 1149 | ) -> Result<(), CoordError> { |
| 1150 | let ttl = check_ttl(ttl, SCENT_TTL)?; |
| 1151 | let rel = ws.rel_dir(dir)?; |
| 1152 | let mut t = self.begin(true)?; |
| 1153 | t.prune()?; |
| 1154 | t.agent_set(ws, agent, focus, &rel, ttl)?; |
| 1155 | t.commit() |
| 1156 | } |
| 1157 | |
| 1158 | /// `crumb whisper`: leave a message in the record of directory `dir`. `to = None` or |
| 1159 | /// `Some("-")` broadcasts. |
| 1160 | #[allow(clippy::too_many_arguments)] |
| 1161 | pub fn whisper( |
| 1162 | &self, |
| 1163 | ws: &Workspace, |
| 1164 | from: &str, |
| 1165 | dir: &str, |
| 1166 | to: Option<&str>, |
| 1167 | msg: &str, |
| 1168 | priority: Option<&str>, |
| 1169 | target_file: Option<&str>, |
| 1170 | ) -> Result<(), CoordError> { |
| 1171 | if let Some(p) = priority.filter(|p| !p.is_empty()) { |
| 1172 | if !PRIORITIES.contains(&p) { |
| 1173 | return Err(CoordError::BadPriority(p.into())); |
| 1174 | } |
| 1175 | } |
| 1176 | let rel = ws.rel_dir(dir)?; |
| 1177 | let mut t = self.begin(true)?; |
| 1178 | t.prune()?; |
| 1179 | let i = t.dir_rec(&rel)?; |
| 1180 | let now = t.now; |
| 1181 | whisper_add( |
| 1182 | &mut t.recs[i].root, |
| 1183 | now, |
| 1184 | from, |
| 1185 | to, |
| 1186 | msg, |
| 1187 | priority, |
| 1188 | target_file, |
| 1189 | ); |
| 1190 | t.commit() |
| 1191 | } |
| 1192 | |
| 1193 | /// `crumb close`: release the lock, append a history vector, optionally whisper. |
| 1194 | /// The agent's presence record is removed when it holds no other lock. |
| 1195 | pub fn close( |
| 1196 | &self, |
| 1197 | ws: &Workspace, |
| 1198 | agent: &str, |
| 1199 | dir: &str, |
| 1200 | target: &str, |
| 1201 | action: &str, |
| 1202 | msg: Option<&str>, |
| 1203 | ) -> Result<CloseOutcome, CoordError> { |
| 1204 | if !ACTIONS.contains(&action) { |
| 1205 | return Err(CoordError::BadAction(action.into())); |
| 1206 | } |
| 1207 | let rel = ws.rel_dir(dir)?; |
| 1208 | let key = ws.target_key(target, &rel)?; |
| 1209 | let td = key_dir(&key); |
| 1210 | let mut t = self.begin(true)?; |
| 1211 | t.prune()?; |
| 1212 | let ti = t.dir_rec(&td)?; |
| 1213 | let now = t.now; |
| 1214 | let root = &mut t.recs[ti].root; |
| 1215 | let cur = root.obj_of("locks").get(&key).cloned(); |
| 1216 | let mut intent = String::new(); |
| 1217 | if let Some(cur) = &cur { |
| 1218 | if let Some(h) = cur.str_of("holder") { |
| 1219 | if h != agent { |
| 1220 | t.commit()?; |
| 1221 | return Ok(CloseOutcome::Refused { key, holder: h }); |
| 1222 | } |
| 1223 | } |
| 1224 | if let Some(i) = cur.str_of("intent") { |
| 1225 | intent = i; |
| 1226 | } |
| 1227 | } |
| 1228 | history_add(root, now, agent, action, &key, &intent); |
| 1229 | if cur.is_some() { |
| 1230 | root.obj_of("locks").del(&key); |
| 1231 | } |
| 1232 | if !t.agent_has_lock(agent) { |
| 1233 | let ai = t.agent_rec(agent)?; |
| 1234 | t.recs[ai].dead = true; |
| 1235 | } |
| 1236 | if let Some(m) = msg.filter(|m| !m.is_empty()) { |
| 1237 | whisper_add( |
| 1238 | &mut t.recs[ti].root, |
| 1239 | now, |
| 1240 | agent, |
| 1241 | None, |
| 1242 | m, |
| 1243 | Some("normal"), |
| 1244 | Some(&key), |
| 1245 | ); |
| 1246 | } |
| 1247 | t.commit()?; |
| 1248 | Ok(CloseOutcome::Closed { |
| 1249 | key, |
| 1250 | lock_was_held: cur.is_some(), |
| 1251 | }) |
| 1252 | } |
| 1253 | |
| 1254 | /// `crumb sniff` (shared-plane part): live agents, live locks, other workspaces with |
| 1255 | /// conflicts under `dir`, and whispers in `dir` addressed to `agent` or broadcast. |
| 1256 | /// Read-only: takes no lock and writes nothing (expired entries are hidden in memory). |
| 1257 | pub fn sniff(&self, ws: &Workspace, agent: &str, dir: &str) -> Result<Sniff, CoordError> { |
| 1258 | let rel = ws.rel_dir(dir)?; |
| 1259 | let mut t = self.begin(false)?; |
| 1260 | t.prune()?; |
| 1261 | let now = t.now; |
| 1262 | let mut s = Sniff { |
| 1263 | store: self.root.clone(), |
| 1264 | store_id: self.store_id()?, |
| 1265 | ..Sniff::default() |
| 1266 | }; |
| 1267 | for r in t |
| 1268 | .recs |
| 1269 | .iter() |
| 1270 | .filter(|r| r.agent && !r.dead && r.root.get("updated_at").is_some()) |
| 1271 | { |
| 1272 | let e = &r.root; |
| 1273 | let st = |k: &str| e.str_of(k).unwrap_or_default(); |
| 1274 | let u = time::parse_iso(e.bytes_of("updated_at")); |
| 1275 | s.agents.push(AgentView { |
| 1276 | agent: st("agent"), |
| 1277 | session: st("session"), |
| 1278 | focus: st("focus"), |
| 1279 | dir: st("dir"), |
| 1280 | worktree: st("worktree"), |
| 1281 | branch: st("branch"), |
| 1282 | head: st("head"), |
| 1283 | updated_at: st("updated_at"), |
| 1284 | heartbeat_age: if u < 0 { -1 } else { now - u }, |
| 1285 | synapse_revision: e.str_of("synapse_revision"), |
| 1286 | }); |
| 1287 | } |
| 1288 | for r in t.recs.iter().filter(|r| !r.agent) { |
| 1289 | if let Some(J::Obj(m)) = r.root.get("locks") { |
| 1290 | for (k, v) in m { |
| 1291 | s.locks.push(LockView::from(&String::from_utf8_lossy(k), v)); |
| 1292 | } |
| 1293 | } |
| 1294 | } |
| 1295 | let mut others: Vec<String> = s |
| 1296 | .agents |
| 1297 | .iter() |
| 1298 | .map(|a| a.worktree.clone()) |
| 1299 | .chain(s.locks.iter().map(|l| l.worktree.clone())) |
| 1300 | .filter(|w| !w.is_empty() && *w != ws.top) |
| 1301 | .collect(); |
| 1302 | others.sort(); |
| 1303 | others.dedup(); |
| 1304 | for w in others { |
| 1305 | let agents = s |
| 1306 | .agents |
| 1307 | .iter() |
| 1308 | .filter(|a| a.worktree == w) |
| 1309 | .map(|a| a.agent.clone()) |
| 1310 | .collect(); |
| 1311 | let conflicts = s |
| 1312 | .locks |
| 1313 | .iter() |
| 1314 | .filter(|l| l.worktree == w) |
| 1315 | .filter(|l| rel == "." || l.key.starts_with(&format!("{rel}/"))) |
| 1316 | .map(|l| l.key.clone()) |
| 1317 | .collect(); |
| 1318 | s.other_workspaces.push((w, agents, conflicts)); |
| 1319 | } |
| 1320 | let di = t.dir_rec(&rel)?; |
| 1321 | if let Some(J::Arr(wh)) = t.recs[di].root.get("whispers") { |
| 1322 | for w in wh { |
| 1323 | let to = w.str_of("to"); |
| 1324 | if to.as_deref().is_some_and(|to| to != agent) { |
| 1325 | continue; |
| 1326 | } |
| 1327 | s.whispers.push(WhisperView { |
| 1328 | from: w.str_of("from").unwrap_or_else(|| "?".into()), |
| 1329 | to, |
| 1330 | message: w.str_of("message").unwrap_or_default(), |
| 1331 | timestamp: w.str_of("timestamp").unwrap_or_default(), |
| 1332 | priority: w.str_of("priority"), |
| 1333 | target_file: w.str_of("target_file"), |
| 1334 | }); |
| 1335 | } |
| 1336 | } |
| 1337 | Ok(s) |
| 1338 | } |
| 1339 | } |
| 1340 | |
| 1341 | fn check_ttl(ttl: Option<i64>, dflt: i64) -> Result<i64, CoordError> { |
| 1342 | match ttl { |
| 1343 | None => Ok(dflt), |
| 1344 | Some(t) if t < 0 => Err(CoordError::BadTtl(t)), |
| 1345 | Some(t) => Ok(t), |
| 1346 | } |
| 1347 | } |
| 1348 | |
| 1349 | impl Sniff { |
| 1350 | /// Text rendering in the shape of crumb.c's sniff sections (for humans and scripts). |
| 1351 | pub fn render(&self, ws: &Workspace, agent: &str) -> String { |
| 1352 | use std::fmt::Write as _; |
| 1353 | let mut o = String::new(); |
| 1354 | let _ = writeln!(o, "shared coordination: ACTIVE"); |
| 1355 | let _ = writeln!(o, " common root: {}", self.store.display()); |
| 1356 | match &self.store_id { |
| 1357 | Some(id) => writeln!(o, " store id: {id}"), |
| 1358 | None => writeln!(o, " store id: (none yet)"), |
| 1359 | } |
| 1360 | .ok(); |
| 1361 | let _ = writeln!( |
| 1362 | o, |
| 1363 | " this workspace: {} [{} {}] as {agent}", |
| 1364 | ws.top, ws.holder.branch, ws.holder.head |
| 1365 | ); |
| 1366 | let _ = writeln!(o, "ACTIVE AGENTS"); |
| 1367 | if self.agents.is_empty() { |
| 1368 | let _ = writeln!(o, " (none)"); |
| 1369 | } |
| 1370 | for a in &self.agents { |
| 1371 | let _ = writeln!( |
| 1372 | o, |
| 1373 | " agent {:<16} branch {} focus: {} heartbeat {}s ago [{}]", |
| 1374 | a.agent, a.branch, a.focus, a.heartbeat_age, a.worktree |
| 1375 | ); |
| 1376 | } |
| 1377 | let _ = writeln!(o, "LOCKS"); |
| 1378 | if self.locks.is_empty() { |
| 1379 | let _ = writeln!(o, " (none)"); |
| 1380 | } |
| 1381 | for l in &self.locks { |
| 1382 | let imp = l |
| 1383 | .imported_from |
| 1384 | .as_deref() |
| 1385 | .map(|f| format!(" imported from {f}")) |
| 1386 | .unwrap_or_default(); |
| 1387 | let _ = writeln!( |
| 1388 | o, |
| 1389 | " lock {:<16} held by {} [{}]: {} [{}]{imp}", |
| 1390 | l.key, l.holder, l.branch, l.intent, l.acquired_at |
| 1391 | ); |
| 1392 | } |
| 1393 | let _ = writeln!(o, "OTHER WORKSPACES"); |
| 1394 | if self.other_workspaces.is_empty() { |
| 1395 | let _ = writeln!(o, " (none)"); |
| 1396 | } |
| 1397 | for (w, agents, conflicts) in &self.other_workspaces { |
| 1398 | let a = if agents.is_empty() { |
| 1399 | "no agents".to_string() |
| 1400 | } else { |
| 1401 | format!("agent {}", agents.join(", ")) |
| 1402 | }; |
| 1403 | let c = if conflicts.is_empty() { |
| 1404 | "; conflicts: none".to_string() |
| 1405 | } else { |
| 1406 | format!("; CONFLICT: {}", conflicts.join(", ")) |
| 1407 | }; |
| 1408 | let _ = writeln!(o, " {w}: {a}{c}"); |
| 1409 | } |
| 1410 | let _ = writeln!(o, "WHISPERS"); |
| 1411 | if self.whispers.is_empty() { |
| 1412 | let _ = writeln!(o, " (none)"); |
| 1413 | } |
| 1414 | for w in &self.whispers { |
| 1415 | let p = w |
| 1416 | .priority |
| 1417 | .as_deref() |
| 1418 | .map(|p| format!(" {p}")) |
| 1419 | .unwrap_or_default(); |
| 1420 | let _ = writeln!( |
| 1421 | o, |
| 1422 | " whisper {} -> {}: {} [{}{p}]", |
| 1423 | w.from, |
| 1424 | w.to.as_deref().unwrap_or("all"), |
| 1425 | w.message, |
| 1426 | w.timestamp |
| 1427 | ); |
| 1428 | } |
| 1429 | o |
| 1430 | } |
| 1431 | } |
| 1432 | |
| 1433 | #[cfg(test)] |
| 1434 | mod tests { |
| 1435 | use super::*; |
| 1436 | |
| 1437 | #[test] |
| 1438 | fn norm_path_rules() { |
| 1439 | assert_eq!(norm_path("a/./b//c").as_deref(), Some("a/b/c")); |
| 1440 | assert_eq!(norm_path("src/../src/./x.c").as_deref(), Some("src/x.c")); |
| 1441 | assert_eq!(norm_path("./").as_deref(), Some(".")); |
| 1442 | assert_eq!(norm_path("/abs/x").as_deref(), Some("abs/x")); |
| 1443 | assert_eq!(norm_path("../x"), None); |
| 1444 | assert_eq!(norm_path("a/../../x"), None); |
| 1445 | } |
| 1446 | |
| 1447 | #[test] |
| 1448 | fn key_dir_and_agent_stem() { |
| 1449 | assert_eq!(key_dir("src/a.c"), "src"); |
| 1450 | assert_eq!(key_dir("a.c"), "."); |
| 1451 | assert_eq!(agent_file_stem("lane A/b@c"), "lane_A_b_c"); |
| 1452 | } |
| 1453 | } |