Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/client/src/lock.ts?format=json
182 linesFirst import 96% · review 4% · infra-split 1%Last change infra-split in version 37, 4 versions changed it
1// One writer at a time for a folder's own records (#51, as git's index.lock).
2// Recording and applying a sync rewrite .avcs/ (known copies, modes.json,
3// blobs.json); two at once, in different processes, could leave a known copy
4// out of step with the folder. They take .avcs/lock. A command waits a moment
5// for the lock (a hook holds it for about 100 ms), then fails with a
6// sentence; the command hook never waits, and leaves the edit for the next
7// record.
8//
9// The lock is never there without its contents: they're written to a file of
10// the taker's own and linked into place, which fails if a lock exists
11// already. Its holder renews it every RENEW_MS, so a lock not
12// renewed for LOCK_STALE_MS was left behind, whatever process now has its
13// id; a long record or sync is never taken over while it writes. Taking one
14// over goes through a rename aside, which only one process can win.
16import { closeSync, linkSync, openSync, readFileSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
17import { basename, join } from "node:path";
18import { UsageError } from "./args.ts";
19import { LOCK_FILE, LOCK_STALE_MS, type LockInfo } from "./core.ts";
20import { fromEnv } from "./env-names.ts";
21import { writeFileAtomic } from "./folder.ts";
22import { stateDir } from "./state-dir.ts";
24/** How long a command waits for the lock before it says who holds it. */
25const WAIT_MS = 3000;
26/** How often a holder renews its lock. */
27const RENEW_MS = 20_000;
29/** Locks this process holds, by folder, and how deep: a locked call inside another one doesn't wait for itself. */
30const held = new Map<string, { depth: number; renew: ReturnType<typeof setInterval> }>();
32const lockPath = (root: string): string => join(stateDir(root), LOCK_FILE);
34function readInfo(path: string): LockInfo | undefined {
35 try {
36 return JSON.parse(readFileSync(path, "utf8")) as LockInfo;
37 } catch {
38 return undefined;
39 }
42/**
43 * Whether a lock is still held: renewed lately and its process running. A
44 * lock that can't be read (written in place by an older client, caught
45 * between creating and writing) is held until its file is LOCK_STALE_MS old.
46 */
47function live(path: string, info: LockInfo | undefined, now: number): boolean {
48 if (!info || typeof info.pid !== "number" || typeof info.time !== "number") {
49 try {
50 return now - statSync(path).mtimeMs <= LOCK_STALE_MS;
51 } catch {
52 return false;
53 }
54 }
55 if (now - info.time > LOCK_STALE_MS) return false;
56 try {
57 process.kill(info.pid, 0);
58 return true;
59 } catch (e) {
60 // EPERM: it runs, as another user.
61 return (e as NodeJS.ErrnoException).code === "EPERM";
62 }
65/** Put `info` at `path` only if nothing is there: a file of our own, linked into place. */
66function create(path: string, info: LockInfo): "taken" | "exists" | "no folder" {
67 const mine = `${path}.${process.pid}.${Math.random().toString(36).slice(2)}`;
68 try {
69 const fd = openSync(mine, "wx");
70 writeSync(fd, JSON.stringify(info));
71 closeSync(fd);
72 } catch (e) {
73 if ((e as NodeJS.ErrnoException).code === "ENOENT") return "no folder";
74 throw e;
75 }
76 try {
77 linkSync(mine, path);
78 return "taken";
79 } catch (e) {
80 if ((e as NodeJS.ErrnoException).code === "EEXIST") return "exists";
81 throw e;
82 } finally {
83 rmSync(mine, { force: true });
84 }
87/** Take the lock if it's free (or left behind): true, false while someone holds it, or 'no folder' before init. */
88function take(root: string, what: string): boolean | "no folder" {
89 const path = lockPath(root);
90 for (let tries = 0; tries < 3; tries++) {
91 const made = create(path, { pid: process.pid, time: Date.now(), what });
92 if (made !== "exists") return made === "taken" ? true : "no folder";
93 const there = readInfo(path);
94 if (live(path, there, Date.now())) return false;
95 // Left behind: move it aside. Only one taker's rename finds it.
96 const aside = `${path}.left.${process.pid}`;
97 try {
98 renameSync(path, aside);
99 } catch {
100 continue;
101 }
102 // A quicker taker may have put a fresh lock there between our read and our rename: give it back.
103 const moved = readInfo(aside);
104 if (moved && (moved.pid !== there?.pid || moved.time !== there?.time) && live(aside, moved, Date.now())) {
105 try {
106 linkSync(aside, path);
107 } catch {
108 // Someone else took it meanwhile; either way it isn't ours.
109 }
110 rmSync(aside, { force: true });
111 return false;
112 }
113 rmSync(aside, { force: true });
114 }
115 return false;
118/** Hold the lock for this process: renewed every RENEW_MS until let go. */
119function hold(root: string, what: string): void {
120 const renew = setInterval(() => {
121 // Only while it's still ours; written aside and renamed in, so a reader never sees half of it.
122 if (readInfo(lockPath(root))?.pid !== process.pid) return;
123 try {
124 writeFileAtomic(lockPath(root), JSON.stringify({ pid: process.pid, time: Date.now(), what } satisfies LockInfo));
125 } catch {
126 // The next renewal tries again.
127 }
128 }, RENEW_MS);
129 renew.unref();
130 held.set(root, { depth: 1, renew });
133function letGo(root: string): void {
134 const h = held.get(root);
135 if (!h || --h.depth > 0) return;
136 clearInterval(h.renew);
137 held.delete(root);
138 if (readInfo(lockPath(root))?.pid === process.pid) rmSync(lockPath(root), { force: true });
141/** Run `fn` holding the folder's lock, waiting a moment for another holder; then a sentence saying who holds it. */
142export async function withFolderLock<T>(root: string, what: string, fn: () => Promise<T>): Promise<T> {
143 const mine = held.get(root);
144 if (mine) mine.depth++;
145 else {
146 // ABSO_LOCK_WAIT_MS shortens the wait in tests.
147 const until = Date.now() + (Number(fromEnv(process.env, "LOCK_WAIT_MS")) || WAIT_MS);
148 for (;;) {
149 const got = take(root, what);
150 if (got === "no folder") return fn(); // no .avcs/ yet (init): nothing to protect
151 if (got) break;
152 if (Date.now() >= until) {
153 const info = readInfo(lockPath(root));
154 const since = info ? new Date(info.time).toISOString().slice(11, 19) : "?";
155 throw new UsageError(
156 `another abso command (${info?.what ?? "one"}, process ${info?.pid ?? "?"}, since ${since} UTC) is changing this folder's records; run this again when it has finished. If none is running, delete ${basename(stateDir(root))}/lock.`,
157 );
158 }
159 await new Promise((ok) => setTimeout(ok, 50));
160 }
161 hold(root, what);
162 }
163 try {
164 return await fn();
165 } finally {
166 letGo(root);
167 }
170/** For the command hook, which never waits: the lock and a way to let it go, or undefined while someone else holds it. */
171export function tryFolderLock(root: string, what: string): (() => void) | undefined {
172 const mine = held.get(root);
173 if (mine) {
174 mine.depth++;
175 return () => letGo(root);
176 }
177 const got = take(root, what);
178 if (got === "no folder") return () => {};
179 if (!got) return undefined;
180 hold(root, what);
181 return () => letGo(root);