@dibssoftware/dibs 0.0.178 → 0.0.180
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +40 -2
- package/README.md +49 -196
- package/bin/dibs-guard.mjs +10 -1
- package/bin/dibs.mjs +72 -31
- package/docs/benchmarks.md +1 -1
- package/docs/files.md +1 -1
- package/docs/guard.md +6 -0
- package/docs/machines.md +1 -1
- package/docs/questions.md +7 -3
- package/docs/reference.md +157 -0
- package/docs/relay.md +9 -7
- package/docs/releasing.md +11 -8
- package/docs/scheduling.md +6 -6
- package/docs/windows.md +14 -0
- package/package.json +2 -1
- package/skills/dibs/SKILL.md +104 -83
- package/src/acquire.mjs +102 -34
- package/src/agents.mjs +7 -22
- package/src/alerts.mjs +157 -57
- package/src/answers.mjs +2 -2
- package/src/board.mjs +3 -4
- package/src/broker.mjs +26 -11
- package/src/commands.mjs +39 -14
- package/src/config.mjs +27 -6
- package/src/cool.mjs +104 -9
- package/src/diskwarn.mjs +32 -35
- package/src/events.mjs +13 -2
- package/src/files.mjs +52 -67
- package/src/guard.mjs +52 -6
- package/src/guardd.mjs +97 -0
- package/src/guardw.mjs +19 -0
- package/src/hogs.mjs +18 -5
- package/src/later.mjs +20 -25
- package/src/lock.mjs +292 -0
- package/src/measure.mjs +9 -4
- package/src/news.mjs +101 -0
- package/src/notes.mjs +171 -0
- package/src/notices.mjs +52 -13
- package/src/ondemand.mjs +6 -3
- package/src/override.mjs +60 -14
- package/src/plain.mjs +7 -4
- package/src/platform.mjs +165 -35
- package/src/preempt.mjs +54 -6
- package/src/primer.mjs +43 -15
- package/src/proc.mjs +39 -8
- package/src/progress.mjs +33 -4
- package/src/questions.mjs +8 -22
- package/src/relay.mjs +10 -22
- package/src/remote.mjs +12 -8
- package/src/schedule.mjs +182 -44
- package/src/serve.mjs +22 -3
- package/src/service.mjs +4 -3
- package/src/state.mjs +139 -47
- package/src/stats.mjs +3 -2
- package/src/talk.mjs +335 -73
- package/src/trust.mjs +7 -1
- package/src/util.mjs +28 -2
- package/src/version.mjs +1 -1
- package/src/web.mjs +19 -27
- package/src/worker.mjs +2 -1
package/src/later.mjs
CHANGED
|
@@ -24,7 +24,8 @@ import { short, takeAgent, talkKey } from './files.mjs';
|
|
|
24
24
|
import { noteAs } from './talk.mjs';
|
|
25
25
|
import { named, about, minutes } from './plain.mjs';
|
|
26
26
|
import { bold, dim, columns } from './style.mjs';
|
|
27
|
-
import {
|
|
27
|
+
import { underLock, commit } from './lock.mjs';
|
|
28
|
+
import { clock, deadline, die, dur, log, ms, now, say, sleep, fakeFull, LEAN } from './util.mjs';
|
|
28
29
|
|
|
29
30
|
const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dibs.mjs');
|
|
30
31
|
export const DIR = path.join(HOME, 'later');
|
|
@@ -41,8 +42,7 @@ const MAX_AHEAD = 7 * 864e5;
|
|
|
41
42
|
const TICK = 1000;
|
|
42
43
|
// Started this long after its time, a job says it ran late (the machine was asleep, or no runner was up).
|
|
43
44
|
const LATE = 60e3;
|
|
44
|
-
// Writes take milliseconds
|
|
45
|
-
const LOCK_STALE = 5000;
|
|
45
|
+
// Writes take milliseconds: a live holder past this is stuck on something else, and the caller hears so.
|
|
46
46
|
const LOCK_WAIT = 15e3;
|
|
47
47
|
// Finished jobs and their logs stay a week for dibs later list, up to KEEP_DONE of them.
|
|
48
48
|
const KEEP_FOR = 7 * 864e5;
|
|
@@ -50,7 +50,14 @@ const KEEP_DONE = 200;
|
|
|
50
50
|
// What a scheduled command gets from the scheduler's environment. TMPDIR, USER
|
|
51
51
|
// and SHELL too, since Xcode and many scripts break without them. Anything
|
|
52
52
|
// else (a token, say) only with --env, by name.
|
|
53
|
-
const ENV_KEEP = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'USER', 'SHELL', 'TMPDIR']
|
|
53
|
+
const ENV_KEEP = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'USER', 'SHELL', 'TMPDIR']
|
|
54
|
+
// Windows itself: without SystemRoot and the rest, PowerShell, cmd.exe and
|
|
55
|
+
// os.tmpdir() break or crawl. Without PSModuleAnalysisCachePath, where a
|
|
56
|
+
// machine set one, every PowerShell dibs starts rebuilds its module cache, and
|
|
57
|
+
// on a GitHub runner the scheduled run never got past its first (2026-11-03).
|
|
58
|
+
.concat(OS === 'windows' ? ['SystemRoot', 'SystemDrive', 'windir', 'ComSpec', 'PATHEXT', 'TEMP', 'TMP', 'USERPROFILE', 'USERNAME',
|
|
59
|
+
'HOMEDRIVE', 'HOMEPATH', 'APPDATA', 'LOCALAPPDATA', 'ProgramData', 'ProgramFiles', 'ProgramFiles(x86)', 'CommonProgramFiles',
|
|
60
|
+
'NUMBER_OF_PROCESSORS', 'PROCESSOR_ARCHITECTURE', 'OS', 'PSModulePath', 'PSModuleAnalysisCachePath'] : []);
|
|
54
61
|
// dibs's own settings reach the run from the runner (DIBS_HOME above all);
|
|
55
62
|
// these say who is calling, and the run sets its own.
|
|
56
63
|
const DIBS_WHO = new Set(['DIBS_AGENT', 'DIBS_AS', 'DIBS_REMOTE_JOB', 'DIBS_LEASE', 'DIBS_OWNER', 'DIBS_LATER_JOB']);
|
|
@@ -61,31 +68,17 @@ const notEnv = k => k.startsWith('DIBS_') || k.startsWith('CLAUDE_CODE_') || AGE
|
|
|
61
68
|
const ACTIVE = new Set(['scheduled', 'started']);
|
|
62
69
|
|
|
63
70
|
function locked(fn) {
|
|
64
|
-
|
|
65
|
-
const t0 = now();
|
|
66
|
-
for (;;) {
|
|
67
|
-
try { fs.mkdirSync(LOCK); break; } catch (e) {
|
|
68
|
-
if (e.code !== 'EEXIST') throw e;
|
|
69
|
-
try { if (now() - fs.statSync(LOCK).mtimeMs > LOCK_STALE) fs.rmSync(LOCK, { recursive: true, force: true }); } catch {}
|
|
70
|
-
if (now() - t0 > LOCK_WAIT) throw Object.assign(new Error(`${LOCK} stayed locked for ${LOCK_WAIT / 1000}s; remove it if no dibs is running. Nothing was changed.`), { exit: 75 });
|
|
71
|
-
sleepSync(5 + Math.random() * 10);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
try {
|
|
71
|
+
const r = underLock(LOCK, h => {
|
|
75
72
|
const s = load();
|
|
76
73
|
const before = JSON.stringify(s);
|
|
77
74
|
reap(s);
|
|
78
75
|
const out = fn(s);
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
fakeFull('state');
|
|
82
|
-
fs.writeFileSync(`${FILE}.tmp`, JSON.stringify(s, null, 1), { mode: 0o600 });
|
|
83
|
-
fs.renameSync(`${FILE}.tmp`, FILE);
|
|
84
|
-
}
|
|
76
|
+
// --env values may be tokens: only this user reads the file.
|
|
77
|
+
if (JSON.stringify(s) !== before) commit(h, FILE, JSON.stringify(s, null, 1), { mode: 0o600, fake: () => fakeFull('state') });
|
|
85
78
|
return out;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
|
|
79
|
+
}, { wait: LOCK_WAIT, files: [FILE] });
|
|
80
|
+
if (!r) throw Object.assign(new Error(`${LOCK} is held by a dibs that's still running, and stayed held for ${LOCK_WAIT / 1000}s. Nothing was changed: run the same command again.`), { exit: 75 });
|
|
81
|
+
return r.out;
|
|
89
82
|
}
|
|
90
83
|
|
|
91
84
|
function load() {
|
|
@@ -213,7 +206,9 @@ function start(j) {
|
|
|
213
206
|
if (!fs.existsSync(j.cwd)) return fail(`its folder ${j.cwd} is gone`);
|
|
214
207
|
let fd;
|
|
215
208
|
try {
|
|
216
|
-
|
|
209
|
+
// Each job's log is new here. On Windows an append handle has no plain write
|
|
210
|
+
// access, and Git Bash's programs (echo, printf) fail to write through it.
|
|
211
|
+
fd = fs.openSync(logOf(j.id), OS === 'windows' ? 'w' : 'a', 0o600);
|
|
217
212
|
fs.writeSync(fd, `dibs later ${j.id}: ${j.cmd.join(' ')} in ${j.cwd}, ${trigger(j)}, started ${new Date(j.fired).toISOString()}`
|
|
218
213
|
+ `${j.late ? `; ran late by ${dur(j.late)} (the machine was asleep or no runner was up)` : ''}\n`);
|
|
219
214
|
} catch (e) { return fail(`couldn't write its log: ${e.message}`); }
|
package/src/lock.mjs
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
// The lock every shared file in ~/.dibs changes under: state.json (src/state.mjs), and
|
|
2
|
+
// messages, questions, later jobs, the subagent ledger, alerts and the web's pairing file.
|
|
3
|
+
//
|
|
4
|
+
// A lock is a directory, <name>, as every dibs before it made, so an older dibs still running
|
|
5
|
+
// during a rollout and this one keep out of each other's way. What holds:
|
|
6
|
+
//
|
|
7
|
+
// 1. One holder. A process holds the lock while <name>/owner.<pid>.<start>.<nonce> is its own
|
|
8
|
+
// file. The directory is made whole beside it (<name>.new.*, with that file and a pid file
|
|
9
|
+
// for older dibs to read) and renamed into place. A rename onto a directory that has
|
|
10
|
+
// anything in it fails (ENOTEMPTY on APFS, ENOTEMPTY or EEXIST on Linux), so of two makers
|
|
11
|
+
// one wins, and no lock is ever seen without its owner.
|
|
12
|
+
// 2. Staleness is the owner's death, never the lock's age. A lock is stale when its owner is
|
|
13
|
+
// gone (kill 0 says so, or ps shows that pid started at another time: a reused pid), a
|
|
14
|
+
// zombie, or stopped (a paused job's own dibs, which nobody can resume while it holds the
|
|
15
|
+
// lock everyone needs). A live owner, however slow, is waited for; one holding past
|
|
16
|
+
// STUCK_AFTER is reported (onStuck), since a hung one stops every dibs command. A lock held 30 s used to be
|
|
17
|
+
// taken from its live owner: at load 238 (2026-11-08) a starved holder lost it
|
|
18
|
+
// mid-change, two writers ran at once, and each crashed on the other's files (exit 70).
|
|
19
|
+
// 3. Takeover is atomic and never moves the lock. The taker renames the stale owner's file to
|
|
20
|
+
// its own owner name, inside <name>: of two takers one wins, and a fresh lock that replaced
|
|
21
|
+
// the stale one has no file of that name, so it can't be taken by mistake. (Moving the whole
|
|
22
|
+
// lock aside to look at it, then back, could hide a live owner's lock from it for a moment:
|
|
23
|
+
// its release then left the lock in place and everyone waited on it for good.)
|
|
24
|
+
// 4. A holder checks its owner file is still there just before it commits (commit() below), so
|
|
25
|
+
// a holder taken over while stopped never writes over its taker's change. Each writer's
|
|
26
|
+
// temporary file has its pid in the name: two writers never share one.
|
|
27
|
+
// 5. Release removes only the holder's own lock, checked by its owner file, and never throws.
|
|
28
|
+
// A lock with this process's pid and another nonce is one it no longer holds: stale.
|
|
29
|
+
//
|
|
30
|
+
// A lock made by an older dibs (a directory with only a pid file in it) is judged by that pid,
|
|
31
|
+
// the same way; with no pid in it after PIDLESS_STALE, its writer died before writing one.
|
|
32
|
+
// That older dibs can still take a lock from a live owner after 30 s (and a new lock renamed
|
|
33
|
+
// in the moment between its mkdir and its pid write replaces it): both end once every running
|
|
34
|
+
// dibs process is this version.
|
|
35
|
+
import fs from 'node:fs';
|
|
36
|
+
import path from 'node:path';
|
|
37
|
+
import { spawnSync } from 'node:child_process';
|
|
38
|
+
import { sleepSync } from './util.mjs';
|
|
39
|
+
|
|
40
|
+
const WIN = process.platform === 'win32';
|
|
41
|
+
// This process's start, to tell it from a later process given the same pid.
|
|
42
|
+
const START = Math.round(Date.now() - process.uptime() * 1000);
|
|
43
|
+
// An older dibs makes its lock empty and writes its pid just after.
|
|
44
|
+
const PIDLESS_STALE = 3000;
|
|
45
|
+
// A live owner holds for milliseconds. Held past this, ps is asked whether it's stopped, a zombie
|
|
46
|
+
// or a newer process under a reused pid: one ps call, then again after twice as long each time, up
|
|
47
|
+
// to ASK_MOST apart, so forty waiters on one slow owner don't each run ps every 2 s.
|
|
48
|
+
const ASK_AFTER = 2000, ASK_MOST = 30e3;
|
|
49
|
+
// START is Node's own start, which comes after the exec ps reports (seconds after, under memory
|
|
50
|
+
// pressure), so the owner's real start is never after it. A pid reused by a later process started
|
|
51
|
+
// after it: only a ps start this much later than START is another process (ps counts whole seconds).
|
|
52
|
+
const SAME_START = 5000;
|
|
53
|
+
// A stale lock that can't be taken (a plain file where the lock goes, a folder of another user's):
|
|
54
|
+
// after this many tries in a row, the waiter gives up (LockBroken), naming the path to remove.
|
|
55
|
+
const CLAIM_TRIES = 200;
|
|
56
|
+
// A live owner holding this long is hung, not slow (a ps that never returns, a frozen disk, a
|
|
57
|
+
// debugger): waiters keep waiting, but say so once each (onStuck), so the person hears of it.
|
|
58
|
+
export const STUCK_AFTER = 60e3;
|
|
59
|
+
|
|
60
|
+
let made = 0;
|
|
61
|
+
const nonce = () => `${process.pid}.${START}.${(++made).toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
|
62
|
+
|
|
63
|
+
export class LostLock extends Error {
|
|
64
|
+
constructor(lock) { super(`${lock} was taken over while this process held it`); this.code = 'ELOSTLOCK'; }
|
|
65
|
+
}
|
|
66
|
+
export class LockBroken extends Error {
|
|
67
|
+
constructor(lock) {
|
|
68
|
+
super(`${lock} is in the way and dibs can't take it over (a file, or a folder it may not change). Nothing ran. If no dibs is running, remove it: rm -rf ${lock}`);
|
|
69
|
+
this.code = 'ELOCKBROKEN';
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Waits for the lock and returns its handle ({ owns, release }), or null once `wait` ms pass.
|
|
74
|
+
// fake: called while the lock is made, so a test can make that step fail as a full disk would.
|
|
75
|
+
// files: data files whose per-process temporary copies (commit) a dead writer may have left.
|
|
76
|
+
export function acquire(lock, { wait = Infinity, fake, files = [], onStuck } = {}) {
|
|
77
|
+
fs.mkdirSync(path.dirname(lock), { recursive: true });
|
|
78
|
+
const owner = `owner.${nonce()}`;
|
|
79
|
+
const t0 = Date.now();
|
|
80
|
+
let seen = null, told = false, failed = 0;
|
|
81
|
+
for (;;) {
|
|
82
|
+
// Made only where there's no lock: a rename onto an older dibs's lock in the moment it's still
|
|
83
|
+
// an empty folder (made, its pid not written yet) would replace it under its writer.
|
|
84
|
+
const o = holder(lock);
|
|
85
|
+
if (!o) {
|
|
86
|
+
if (make(lock, owner, fake)) return handle(lock, owner);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (seen?.key !== o.key) seen = { key: o.key, since: Date.now(), asked: 0, gap: ASK_AFTER };
|
|
90
|
+
if (stale(o, seen)) {
|
|
91
|
+
if (claim(lock, o, owner)) { sweep(lock, files); return handle(lock, owner); }
|
|
92
|
+
if (++failed >= CLAIM_TRIES) throw new LockBroken(lock);
|
|
93
|
+
} else failed = 0;
|
|
94
|
+
if (Date.now() - t0 >= wait) return null;
|
|
95
|
+
if (told !== o.key && onStuck) {
|
|
96
|
+
const held = heldFor(lock, o);
|
|
97
|
+
if (held > STUCK_AFTER) { told = o.key; try { onStuck(o, held); } catch {} }
|
|
98
|
+
}
|
|
99
|
+
sleepSync(10 + Math.random() * 20);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// How long the owner has held it: its owner file dates from when it took the lock (a claim
|
|
104
|
+
// touches the file it renamed in); an older dibs's lock dates from its directory.
|
|
105
|
+
function heldFor(lock, o) {
|
|
106
|
+
try { return Date.now() - (o.old ? fs.statSync(lock) : fs.statSync(path.join(lock, o.name))).mtimeMs; } catch { return 0; }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Who holds the lock and for how long, for a board that mustn't wait for it: { key, pid, held }, or null.
|
|
110
|
+
export function heldBy(lock) {
|
|
111
|
+
const o = holder(lock);
|
|
112
|
+
return o ? { key: o.key, pid: o.pid, held: heldFor(lock, o) } : null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Made whole, then renamed into place: false if someone else's lock is there.
|
|
116
|
+
function make(lock, owner, fake) {
|
|
117
|
+
const tmp = `${lock}.new.${owner.slice(6)}`;
|
|
118
|
+
try {
|
|
119
|
+
fs.mkdirSync(tmp);
|
|
120
|
+
fake?.();
|
|
121
|
+
fs.writeFileSync(path.join(tmp, 'pid'), String(process.pid));
|
|
122
|
+
fs.writeFileSync(path.join(tmp, owner), '');
|
|
123
|
+
if (exists(lock)) throw Object.assign(new Error('taken'), { code: 'EEXIST' });
|
|
124
|
+
fs.renameSync(tmp, lock);
|
|
125
|
+
return true;
|
|
126
|
+
} catch (e) {
|
|
127
|
+
try { fs.rmSync(tmp, { recursive: true, force: true }); } catch {}
|
|
128
|
+
// Windows refuses a rename onto any directory with EPERM.
|
|
129
|
+
if (e.code === 'ENOTEMPTY' || e.code === 'EEXIST' || e.code === 'ENOTDIR' || (WIN && e.code === 'EPERM')) return false;
|
|
130
|
+
throw e;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const exists = p => { try { fs.lstatSync(p); return true; } catch { return false; } };
|
|
135
|
+
|
|
136
|
+
// Who holds it: { key, pid, start, name } for a lock of this version, { key, pid, ino, age, old } for an
|
|
137
|
+
// older dibs's, or null when it's gone or changed while being read (look again).
|
|
138
|
+
function holder(lock) {
|
|
139
|
+
let a, names, b;
|
|
140
|
+
try { a = fs.statSync(lock); names = a.isDirectory() ? fs.readdirSync(lock) : []; b = fs.statSync(lock); }
|
|
141
|
+
catch (e) { if (e.code === 'ENOENT') return null; throw e; }
|
|
142
|
+
if (a.ino !== b.ino) return null;
|
|
143
|
+
if (!a.isDirectory()) return { key: `file.${b.ino}`, pid: 0, ino: b.ino, age: Date.now() - b.mtimeMs, old: true, file: true };
|
|
144
|
+
const name = names.find(n => n.startsWith('owner.'));
|
|
145
|
+
if (name) {
|
|
146
|
+
const [, pid, start] = name.split('.');
|
|
147
|
+
return { key: name, name, pid: Number(pid) || 0, start: Number(start) || 0 };
|
|
148
|
+
}
|
|
149
|
+
let pid = 0;
|
|
150
|
+
try { pid = Number(fs.readFileSync(path.join(lock, 'pid'), 'utf8')) || 0; } catch {}
|
|
151
|
+
return { key: `old.${b.ino}.${pid}`, pid, ino: b.ino, age: Date.now() - b.mtimeMs, old: true };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const answers = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
155
|
+
|
|
156
|
+
function stale(o, seen) {
|
|
157
|
+
if (!o.pid) return o.age > PIDLESS_STALE;
|
|
158
|
+
if (o.pid === process.pid) return true; // single-threaded: not a lock this process is in
|
|
159
|
+
if (!answers(o.pid)) return true;
|
|
160
|
+
const t = Date.now();
|
|
161
|
+
if (WIN || t - seen.since < ASK_AFTER || t - seen.asked < seen.gap) return false;
|
|
162
|
+
if (seen.asked) seen.gap = Math.min(seen.gap * 2, ASK_MOST);
|
|
163
|
+
seen.asked = t;
|
|
164
|
+
const p = psOf(o.pid);
|
|
165
|
+
if (p === undefined) return false; // can't tell: wait, rather than take a live owner's lock
|
|
166
|
+
if (p === null || /^[TZ]/.test(p.stat)) return true;
|
|
167
|
+
return !!o.start && t - p.elapsed - o.start > SAME_START;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// The command line a pid runs, for saying who dibs is stuck behind, or '' when ps can't say.
|
|
171
|
+
export function commandOf(pid) {
|
|
172
|
+
if (WIN) return '';
|
|
173
|
+
const r = spawnSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
|
|
174
|
+
return (r.stdout || '').trim().slice(0, 200);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// { stat, elapsed ms } from ps, null when the process is gone, undefined when ps can't say.
|
|
178
|
+
function psOf(pid) {
|
|
179
|
+
const r = spawnSync('ps', ['-o', 'stat=,etime=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
|
|
180
|
+
if (r.status == null) return undefined;
|
|
181
|
+
const m = r.stdout.trim().match(/^(\S+)\s+(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/);
|
|
182
|
+
if (!m) return r.status === 0 ? undefined : null;
|
|
183
|
+
const [, stat, d = 0, h = 0, mi, s] = m;
|
|
184
|
+
return { stat, elapsed: (((Number(d) * 24 + Number(h)) * 60 + Number(mi)) * 60 + Number(s)) * 1000 };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Takes the stale lock where it stands. An older dibs's lock is claimed through its pid file the
|
|
188
|
+
// same way; with nothing in it to claim (it died before writing its pid), it's emptied, and the
|
|
189
|
+
// next make() renames a whole lock over the empty directory.
|
|
190
|
+
function claim(lock, o, owner) {
|
|
191
|
+
if (o.file) return false; // a plain file where the lock goes: not dibs's to take (LockBroken)
|
|
192
|
+
const mine = path.join(lock, owner), from = path.join(lock, o.old ? 'pid' : o.name);
|
|
193
|
+
try {
|
|
194
|
+
if (o.old && !o.pid) {
|
|
195
|
+
for (const n of fs.readdirSync(lock)) if (!n.startsWith('owner.')) fs.rmSync(path.join(lock, n), { recursive: true, force: true });
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
fs.renameSync(from, mine);
|
|
199
|
+
} catch { return false; }
|
|
200
|
+
try {
|
|
201
|
+
// An older dibs's pid file: the one judged only if it still names the dead pid in the same folder.
|
|
202
|
+
// An older waiter may have taken the lock over meanwhile and written its own live pid, or a lock
|
|
203
|
+
// of this version may have replaced the folder (another owner file): either way, not ours.
|
|
204
|
+
const theirs = o.old
|
|
205
|
+
&& (Number(fs.readFileSync(mine, 'utf8')) !== o.pid || fs.statSync(lock).ino !== o.ino || fs.readdirSync(lock).some(n => n.startsWith('owner.') && n !== owner));
|
|
206
|
+
if (theirs) { fs.renameSync(mine, from); return false; }
|
|
207
|
+
const at = new Date();
|
|
208
|
+
fs.utimesSync(mine, at, at);
|
|
209
|
+
fs.writeFileSync(path.join(lock, 'pid'), String(process.pid));
|
|
210
|
+
return true;
|
|
211
|
+
} catch (e) {
|
|
212
|
+
// Half claimed: put back what was there, so the next waiter judges the lock as it was.
|
|
213
|
+
try { fs.renameSync(mine, from); } catch {}
|
|
214
|
+
if (e.code === 'ENOSPC' || e.code === 'EDQUOT') throw e;
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// What a writer killed mid-change leaves beside the lock: a lock it was making, one it moved
|
|
220
|
+
// aside, its temporary data file. Only names with a pid in them, and only a dead pid's. Run when a
|
|
221
|
+
// dead owner's lock is claimed, and now and then by the broker (sweepLock).
|
|
222
|
+
export const sweepLock = (lock, files = []) => sweep(lock, files);
|
|
223
|
+
function sweep(lock, files) {
|
|
224
|
+
const dir = path.dirname(lock), base = path.basename(lock);
|
|
225
|
+
const dibsMade = [new RegExp(`^${re(base)}\\.(?:new|gone)\\.(\\d+)\\.`), new RegExp(`^${re(base)}\\.stale-(\\d+)-`),
|
|
226
|
+
...files.filter(f => path.dirname(f) === dir).map(f => new RegExp(`^${re(path.basename(f))}\\.(\\d+)\\.tmp$`))];
|
|
227
|
+
let names = [];
|
|
228
|
+
try { names = fs.readdirSync(dir); } catch { return; }
|
|
229
|
+
for (const n of names) {
|
|
230
|
+
const pid = dibsMade.map(r => n.match(r)?.[1]).find(Boolean);
|
|
231
|
+
if (pid && !answers(Number(pid))) try { fs.rmSync(path.join(dir, n), { recursive: true, force: true }); } catch {}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const re = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
235
|
+
|
|
236
|
+
function handle(lock, owner) {
|
|
237
|
+
const mine = path.join(lock, owner);
|
|
238
|
+
return {
|
|
239
|
+
owns: () => fs.existsSync(mine),
|
|
240
|
+
release() {
|
|
241
|
+
// Nobody moves a live owner's lock (3), so the one found here is still this one when it's
|
|
242
|
+
// renamed aside: whole, in one step, so nobody sees it half removed.
|
|
243
|
+
try {
|
|
244
|
+
if (!fs.existsSync(mine)) return false;
|
|
245
|
+
const aside = `${lock}.gone.${nonce()}`;
|
|
246
|
+
fs.renameSync(lock, aside);
|
|
247
|
+
fs.rmSync(aside, { recursive: true, force: true });
|
|
248
|
+
return true;
|
|
249
|
+
} catch { return false; }
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// The holder's write of a whole file: a temporary copy named for this process (no two writers share
|
|
255
|
+
// one, and a write cut short by a full disk leaves the old file whole), then a rename, only while it
|
|
256
|
+
// still holds the lock (LostLock if not, with nothing written). fake as in acquire.
|
|
257
|
+
// Returns whether it still held the lock just after the rename: false means another writer took it in
|
|
258
|
+
// the moment between the check and the rename (only possible from a holder stopped right there), and
|
|
259
|
+
// one of the two changes may be lost; the caller puts that on record.
|
|
260
|
+
export function commit(h, file, text, opts = {}) {
|
|
261
|
+
return commitAll(h, [[file, text, opts]]);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Several files as one change: every copy written, one check that the lock is still held, then the
|
|
265
|
+
// renames. Checking before each instead could lose the lock after the first file landed, and the
|
|
266
|
+
// change made again would land twice in that file (a message sent twice).
|
|
267
|
+
export function commitAll(h, files) {
|
|
268
|
+
const tmps = [];
|
|
269
|
+
try {
|
|
270
|
+
for (const [file, text, { mode, fake } = {}] of files) {
|
|
271
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
272
|
+
tmps.push(tmp);
|
|
273
|
+
fake?.();
|
|
274
|
+
fs.writeFileSync(tmp, text, mode ? { mode } : undefined);
|
|
275
|
+
}
|
|
276
|
+
if (!h.owns()) throw new LostLock(path.dirname(files[0][0]));
|
|
277
|
+
} catch (e) { for (const tmp of tmps) try { fs.rmSync(tmp, { force: true }); } catch {} throw e; }
|
|
278
|
+
files.forEach(([file], i) => fs.renameSync(tmps[i], file));
|
|
279
|
+
return h.owns();
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// fn under the lock, done again from the start if the lock was lost before it wrote.
|
|
283
|
+
// null when wait passes first.
|
|
284
|
+
export function underLock(lock, fn, opts = {}) {
|
|
285
|
+
for (;;) {
|
|
286
|
+
const h = acquire(lock, opts);
|
|
287
|
+
if (!h) return null;
|
|
288
|
+
try { return { out: fn(h) }; }
|
|
289
|
+
catch (e) { if (!(e instanceof LostLock)) throw e; }
|
|
290
|
+
finally { h.release(); }
|
|
291
|
+
}
|
|
292
|
+
}
|
package/src/measure.mjs
CHANGED
|
@@ -111,7 +111,7 @@ function shareDisk(s, got, m, t) {
|
|
|
111
111
|
const last = s.diskSample;
|
|
112
112
|
s.diskSample = { free: m.diskFree ?? null, swap: m.swapUsed ?? null, ...(m.swapFiles != null && { files: m.swapFiles }), at: t };
|
|
113
113
|
const runs = s.leases.filter(l => got.has(l.id) && !l.pausedAt);
|
|
114
|
-
for (const l of runs) l.ate ??= 0;
|
|
114
|
+
for (const l of runs) { l.ate ??= 0; l.ateLast = 0; }
|
|
115
115
|
if (!last || last.free == null || m.diskFree == null || t - last.at > 3 * SAMPLE_EVERY) return;
|
|
116
116
|
const swapGrew = Math.max(0, last.swap != null && m.swapUsed != null ? m.swapUsed - last.swap : 0,
|
|
117
117
|
last.files != null && m.swapFiles != null ? m.swapFiles - last.files : 0);
|
|
@@ -119,7 +119,8 @@ function shareDisk(s, got, m, t) {
|
|
|
119
119
|
if (!fell || !runs.length) return;
|
|
120
120
|
const w = l => Math.max(l.disk || 0, DISK_WEIGHT);
|
|
121
121
|
const all = runs.reduce((a, l) => a + w(l), 0);
|
|
122
|
-
|
|
122
|
+
// ateLast, this reading's share alone: which run is writing now, for the hard stop (src/preempt.mjs).
|
|
123
|
+
for (const l of runs) { l.ateLast = fell * w(l) / all; l.ate += l.ateLast; }
|
|
123
124
|
}
|
|
124
125
|
|
|
125
126
|
// Measure every run lease on the machine, if this process won the slot.
|
|
@@ -148,9 +149,13 @@ export function sample(t = now()) {
|
|
|
148
149
|
l.use = { ...u, at: t };
|
|
149
150
|
// When its memory last rose past what it had reached: a job let in by the
|
|
150
151
|
// stall breaker counts as settled once this is a while ago (schedule.mjs).
|
|
151
|
-
|
|
152
|
+
// How far into the run that was goes into history, so a later run of the same
|
|
153
|
+
// command that has run past it is known to be done growing (schedule.mjs pastPeak).
|
|
154
|
+
const rose = !(u.mem <= (l.peak?.mem ?? -1) * 1.05);
|
|
155
|
+
if (rose) l.peakAt = t;
|
|
156
|
+
const at = rose ? t - l.start : l.peak?.in;
|
|
152
157
|
l.peak = { mem: Math.max(l.peak?.mem || 0, u.mem), cpu: Math.max(l.peak?.cpu || 0, u.cpu), fit: true,
|
|
153
|
-
...(l.ate != null && { ate: l.ate }) };
|
|
158
|
+
...(at != null && { in: at }), ...(l.ate != null && { ate: l.ate }) };
|
|
154
159
|
const x = overAsk(l);
|
|
155
160
|
if (!x) continue;
|
|
156
161
|
if (!l.overAsk) {
|
package/src/news.mjs
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// What changed in dibs, for the agents using it: the CHANGELOG's sections, which version each
|
|
2
|
+
// agent last heard about (seen.json, shared with bin/dibs.mjs's what's-new line), the version on
|
|
3
|
+
// disk now (an update lands while a long dibs listen is running), and whether dibs.cc has a
|
|
4
|
+
// newer release (asked at most every 6 hours per machine, never for a git checkout).
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { HOME, paths, loadConfig } from './config.mjs';
|
|
9
|
+
|
|
10
|
+
export const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
11
|
+
// DIBS_VERSION_FILE stands in for it in tests, which can't bump the real one.
|
|
12
|
+
const VERSION_FILE = process.env.DIBS_VERSION_FILE || path.join(ROOT, 'src', 'version.mjs');
|
|
13
|
+
// The newest release, as the Mac app reads it. DIBS_UPDATE_URL points a test at its own.
|
|
14
|
+
const LATEST = process.env.DIBS_UPDATE_URL || 'https://dibs.cc/mac/latest.json';
|
|
15
|
+
// How often one machine asks dibs.cc, whoever asks: a release a few hours old can wait.
|
|
16
|
+
export const CHECK_EVERY = 6 * 36e5;
|
|
17
|
+
// An answer slower than this is no answer: the check never holds anything up.
|
|
18
|
+
const CHECK_TIMEOUT = 3000;
|
|
19
|
+
const CHECKED = path.join(HOME, 'update-check.json');
|
|
20
|
+
export const UPGRADE = 'curl -fsSL https://dibs.cc/install.sh | sh';
|
|
21
|
+
|
|
22
|
+
// "0.0.178" against "0.0.99": by number, part by part.
|
|
23
|
+
export function newer(a, b) {
|
|
24
|
+
const x = String(a).split('.').map(Number), y = String(b).split('.').map(Number);
|
|
25
|
+
for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0);
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// The changelog's sections, newest first: [{ version, body }].
|
|
30
|
+
export function changelog() {
|
|
31
|
+
try {
|
|
32
|
+
return fs.readFileSync(path.join(ROOT, 'CHANGELOG.md'), 'utf8').split(/^## /m).slice(1)
|
|
33
|
+
.map(sec => ({ version: sec.split(/\s/)[0], body: sec.slice(sec.indexOf('\n') + 1).trim() }));
|
|
34
|
+
} catch { return []; }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// The sections after from, up to and including to, oldest first.
|
|
38
|
+
export const since = (from, to) => changelog().filter(c => /^\d/.test(c.version) && newer(c.version, from) && !newer(c.version, to)).reverse();
|
|
39
|
+
|
|
40
|
+
const readSeen = () => { try { return JSON.parse(fs.readFileSync(paths.seen, 'utf8')); } catch { return {}; } };
|
|
41
|
+
export const seenBy = key => readSeen()[key] || null;
|
|
42
|
+
export function markSeen(key, version) {
|
|
43
|
+
const seen = readSeen();
|
|
44
|
+
seen[key] = version;
|
|
45
|
+
try {
|
|
46
|
+
fs.writeFileSync(`${paths.seen}.${process.pid}`, JSON.stringify(seen));
|
|
47
|
+
fs.renameSync(`${paths.seen}.${process.pid}`, paths.seen);
|
|
48
|
+
} catch {}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// The version on disk, which is what the next dibs command runs: read again only when the file
|
|
52
|
+
// changed, so a listener can look every few seconds for nothing.
|
|
53
|
+
let onDisk = { mtime: 0, version: null };
|
|
54
|
+
export function diskVersion() {
|
|
55
|
+
try {
|
|
56
|
+
const m = fs.statSync(VERSION_FILE).mtimeMs;
|
|
57
|
+
if (m !== onDisk.mtime) onDisk = { mtime: m, version: /VERSION = '([^']+)'/.exec(fs.readFileSync(VERSION_FILE, 'utf8'))?.[1] || null };
|
|
58
|
+
} catch {}
|
|
59
|
+
return onDisk.version;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// A git checkout (this repo, linked from ~/bin) updates by git, not by the install script.
|
|
63
|
+
const checkout = () => !process.env.DIBS_UPDATE_URL && fs.existsSync(path.join(ROOT, '.git'));
|
|
64
|
+
const readChecked = () => { try { return JSON.parse(fs.readFileSync(CHECKED, 'utf8')); } catch { return {}; } };
|
|
65
|
+
function writeChecked(c) {
|
|
66
|
+
try {
|
|
67
|
+
fs.writeFileSync(`${CHECKED}.${process.pid}`, JSON.stringify(c));
|
|
68
|
+
fs.renameSync(`${CHECKED}.${process.pid}`, CHECKED);
|
|
69
|
+
} catch {}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// The newest release dibs.cc knows of, as last asked, asking again (in the background) when
|
|
73
|
+
// the machine's last ask is older than CHECK_EVERY. Off with config updateCheck: false.
|
|
74
|
+
export function latest(t = Date.now()) {
|
|
75
|
+
let off = false;
|
|
76
|
+
try { off = loadConfig().updateCheck === false; } catch {}
|
|
77
|
+
if (off || checkout()) return null;
|
|
78
|
+
const c = readChecked();
|
|
79
|
+
if (!(t - (c.at || 0) < CHECK_EVERY)) {
|
|
80
|
+
// Claimed before asking, so a dozen listeners waking together ask once.
|
|
81
|
+
writeChecked({ ...c, at: t });
|
|
82
|
+
fetch(LATEST, { signal: AbortSignal.timeout(CHECK_TIMEOUT) }).then(r => (r.ok ? r.json() : null))
|
|
83
|
+
.then(j => { if (typeof j?.version === 'string' && /^\d+(\.\d+)*$/.test(j.version)) writeChecked({ ...readChecked(), latest: j.version }); })
|
|
84
|
+
.catch(() => {});
|
|
85
|
+
}
|
|
86
|
+
return c.latest || null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Each thread hears about a release once.
|
|
90
|
+
export const toldOf = key => readChecked().told?.[key] || null;
|
|
91
|
+
// Threads remembered: plenty for a machine's sessions over the weeks between releases.
|
|
92
|
+
const TOLD_KEEP = 500;
|
|
93
|
+
export function tell(key, version) {
|
|
94
|
+
const c = readChecked();
|
|
95
|
+
const told = { ...(c.told || {}) };
|
|
96
|
+
delete told[key];
|
|
97
|
+
told[key] = version;
|
|
98
|
+
const keys = Object.keys(told);
|
|
99
|
+
for (const k of keys.slice(0, Math.max(0, keys.length - TOLD_KEEP))) delete told[k];
|
|
100
|
+
writeChecked({ ...c, told });
|
|
101
|
+
}
|