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