pi-odd-worktree 2.1.0 → 3.0.0
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/README.md +54 -319
- package/extensions/odd-worktree-tools.ts +4145 -2529
- package/lib/bash-activity.js +1164 -0
- package/lib/bash-design.js +684 -0
- package/lib/bash-destructive.js +559 -0
- package/lib/bash-frame.js +205 -0
- package/lib/card-content.js +23 -0
- package/lib/card-style.js +175 -0
- package/lib/checkout-facts.js +30 -70
- package/lib/codegraph-card-preview.js +628 -0
- package/lib/codegraph-card.js +515 -0
- package/lib/codegraph-compaction.js +76 -0
- package/lib/codegraph-daemon.js +246 -0
- package/lib/codegraph-edit-sync.js +182 -0
- package/lib/codegraph-guard-target.js +337 -0
- package/lib/codegraph-guard.js +211 -0
- package/lib/codegraph-index.js +1020 -0
- package/lib/codegraph-lock.js +607 -0
- package/lib/codegraph-mcp-config.js +134 -0
- package/lib/codegraph-mcp.js +123 -0
- package/lib/codegraph-paths.js +69 -0
- package/lib/codegraph-prompt/explore.md +11 -0
- package/lib/codegraph-prompt/fix.md +6 -0
- package/lib/codegraph-prompt/generic.md +8 -0
- package/lib/codegraph-prompt/judge.md +9 -0
- package/lib/codegraph-prompt/orchestrator.md +17 -0
- package/lib/codegraph-prompt/verify.md +10 -0
- package/lib/codegraph-prompt/worker.md +7 -0
- package/lib/codegraph-role.js +55 -0
- package/lib/codegraph-rules.js +146 -0
- package/lib/codegraph-session.js +303 -383
- package/lib/codegraph-warmup.js +139 -0
- package/lib/file-card-markdown.js +141 -0
- package/lib/file-card-resolver.js +245 -0
- package/lib/file-card.js +659 -0
- package/lib/files-index.js +387 -0
- package/lib/files-insert.js +81 -0
- package/lib/files-orders.js +326 -0
- package/lib/files-picker-view.js +1416 -0
- package/lib/files-preview.js +338 -0
- package/lib/files-scope-detail.js +171 -0
- package/lib/files-scope-view.js +507 -0
- package/lib/gh-issues.js +308 -14
- package/lib/issue-preview.js +26 -7
- package/lib/issues-bash-mutation.js +206 -0
- package/lib/issues-cache-store.js +261 -0
- package/lib/issues-section.js +710 -0
- package/lib/issues-view.js +649 -52
- package/lib/odd-prompt/odd-worktrees.md +21 -0
- package/lib/odd-worktrees-prompt.js +10 -28
- package/lib/related-issues-cache.js +210 -0
- package/lib/shell-card.js +825 -0
- package/lib/skill-odd-card.js +183 -0
- package/lib/tui-paint.js +4 -5
- package/lib/warp-create-panel.js +538 -250
- package/lib/warp-create-picker.js +56 -9
- package/lib/warp-delete-confirm.js +19 -28
- package/lib/warp-selector-view.js +160 -82
- package/lib/which-command.js +90 -0
- package/lib/worktree-card.js +267 -897
- package/lib/worktree-cards.js +383 -0
- package/lib/worktree-create.js +287 -0
- package/lib/worktree-git.js +3 -3
- package/lib/worktree-guard.js +548 -0
- package/lib/worktree-hooks.js +421 -712
- package/lib/worktree-list.js +120 -0
- package/lib/worktree-registry.js +162 -879
- package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
- package/lib/worktree-setup-runner.js +376 -0
- package/lib/worktree-setup.js +140 -0
- package/lib/worktree-warp-busy.js +462 -85
- package/lib/worktree-warp-sessions.js +1 -2
- package/package.json +2 -2
- package/tools/bash-activity.test.js +1419 -0
- package/tools/bash-design.test.js +1091 -0
- package/tools/bash-destructive.test.js +139 -0
- package/tools/card-content.test.js +44 -0
- package/tools/card-style.test.js +298 -0
- package/tools/codegraph-card-preview.test.js +254 -0
- package/tools/codegraph-card.test.js +1080 -0
- package/tools/codegraph-compaction.test.js +378 -0
- package/tools/codegraph-daemon.test.js +248 -0
- package/tools/codegraph-edit-sync.test.js +295 -0
- package/tools/codegraph-guard-target.test.js +174 -0
- package/tools/codegraph-guard.test.js +238 -0
- package/tools/codegraph-index.test.js +1948 -0
- package/tools/codegraph-lock.test.js +932 -0
- package/tools/codegraph-mcp-config.test.js +181 -0
- package/tools/codegraph-mcp.test.js +194 -0
- package/tools/codegraph-paths.test.js +44 -0
- package/tools/codegraph-role.test.js +30 -0
- package/tools/codegraph-rules.test.js +250 -0
- package/tools/codegraph-session.test.js +660 -391
- package/tools/codegraph-warmup.test.js +316 -0
- package/tools/commands.test.js +510 -31
- package/tools/file-card-markdown.test.js +188 -0
- package/tools/file-card.test.js +1289 -0
- package/tools/files-bridge.test.js +575 -0
- package/tools/files-command.test.js +610 -0
- package/tools/files-index.test.js +473 -0
- package/tools/files-insert.test.js +139 -0
- package/tools/files-orders.test.js +597 -0
- package/tools/files-picker-view.test.js +1871 -0
- package/tools/files-preview.test.js +452 -0
- package/tools/files-scope-detail.test.js +264 -0
- package/tools/files-scope-view.test.js +614 -0
- package/tools/fixtures/card-codegraph-outputs.js +110 -0
- package/tools/fixtures/codegraph-cli-stub.js +16 -0
- package/tools/fixtures/codegraph-init-process.js +28 -0
- package/tools/fixtures/codegraph-lock-worker.js +117 -0
- package/tools/fixtures/daemon-fake.js +98 -0
- package/tools/fixtures/daemon-mcp-server.js +39 -0
- package/tools/fixtures/daemon-warmup-worker.js +12 -0
- package/tools/fixtures/load-extension.js +136 -3
- package/tools/gh-issues-feedback.test.js +31 -7
- package/tools/gh-issues.test.js +391 -1
- package/tools/issue-preview.test.js +44 -7
- package/tools/issues-bash-mutation.test.js +101 -0
- package/tools/issues-cache-store.test.js +222 -0
- package/tools/issues-command.test.js +1512 -66
- package/tools/issues-open-guard.test.js +1096 -0
- package/tools/issues-section.test.js +4195 -0
- package/tools/issues-seed-query-regression.test.js +67 -0
- package/tools/issues-view.test.js +1489 -60
- package/tools/odd-worktrees-prompt.test.js +98 -65
- package/tools/package-surface.test.js +431 -36
- package/tools/related-issues-cache.test.js +324 -0
- package/tools/shell-card.test.js +834 -0
- package/tools/skill-odd-card.test.js +200 -0
- package/tools/t5-session-identity.test.js +44 -22
- package/tools/warp-busy-guard.test.js +2565 -309
- package/tools/warp-create-panel.test.js +499 -74
- package/tools/warp-create-picker.test.js +101 -5
- package/tools/warp-delete-confirm.test.js +49 -15
- package/tools/warp-empty-session.test.js +0 -1
- package/tools/warp-fallback-regression.test.js +533 -0
- package/tools/warp-selector-view.test.js +460 -196
- package/tools/which-command.test.js +126 -0
- package/tools/worktree-card.test.js +551 -0
- package/tools/worktree-cards.test.js +845 -0
- package/tools/worktree-changes.test.js +4 -5
- package/tools/worktree-create.test.js +489 -0
- package/tools/worktree-guard.test.js +823 -0
- package/tools/worktree-hooks.test.js +905 -0
- package/tools/worktree-list.test.js +170 -0
- package/tools/worktree-registry.test.js +89 -230
- package/tools/worktree-remove-async.test.js +318 -0
- package/tools/worktree-setup-runner.test.js +276 -0
- package/tools/worktree-setup.test.js +140 -0
- package/tools/worktree-tools.test.js +419 -199
- package/lib/codegraph-commands.js +0 -165
- package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
- package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
- package/lib/worktree-model-result.js +0 -291
- package/tools/codegraph-commands.test.js +0 -371
- package/tools/herdr-free-create.test.js +0 -161
- package/tools/worktree-close-herdr-async.test.js +0 -204
- package/tools/worktree-odd-migration.test.js +0 -224
- package/tools/worktree-registry-cache.test.js +0 -163
- package/tools/worktree-registry-odd.test.js +0 -231
|
@@ -0,0 +1,932 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The two pieces of index coordination (S3), through their public surface: one init lock per project, and one
|
|
3
|
+
// per-project sync lease shared by the sessions of this user. No real codegraph ever runs here: the attempts are
|
|
4
|
+
// injected, and the multi-process cases use a fixture session that speaks the same public API.
|
|
5
|
+
|
|
6
|
+
const { test, after } = require('node:test');
|
|
7
|
+
const assert = require('node:assert/strict');
|
|
8
|
+
const fs = require('node:fs');
|
|
9
|
+
const os = require('node:os');
|
|
10
|
+
const path = require('node:path');
|
|
11
|
+
const { spawn } = require('node:child_process');
|
|
12
|
+
|
|
13
|
+
const {
|
|
14
|
+
LOCK_MAX_AGE_MS,
|
|
15
|
+
PROXY_TRUST_MS,
|
|
16
|
+
SYNC_LEASE_MAX_AGE_MS,
|
|
17
|
+
UNWRITTEN_GRACE_MS,
|
|
18
|
+
codegraphWritingIndex,
|
|
19
|
+
isInitLocked,
|
|
20
|
+
isInitRunning,
|
|
21
|
+
realInitLock,
|
|
22
|
+
realSyncLease,
|
|
23
|
+
syncLease,
|
|
24
|
+
tryAcquireInitLock,
|
|
25
|
+
} = require('../lib/codegraph-lock.js');
|
|
26
|
+
|
|
27
|
+
const WORKER = path.join(__dirname, 'fixtures', 'codegraph-lock-worker.js');
|
|
28
|
+
const scratchDirs = [];
|
|
29
|
+
|
|
30
|
+
after(() => {
|
|
31
|
+
for (const dir of scratchDirs) {
|
|
32
|
+
try {
|
|
33
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
34
|
+
} catch {
|
|
35
|
+
// Best effort: the system temp directory is the owner.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
function temp(prefix) {
|
|
41
|
+
const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix)));
|
|
42
|
+
scratchDirs.push(dir);
|
|
43
|
+
return dir;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** A state folder and a project of their own, so these cases never meet the user's locks. */
|
|
47
|
+
function scratch() {
|
|
48
|
+
return { dir: temp('cg-lock-state-'), project: temp('cg-lock-project-') };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const lockEntries = (dir) => fs.readdirSync(dir).filter((entry) => entry.startsWith('pcs-init-'));
|
|
52
|
+
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
53
|
+
|
|
54
|
+
const waitUntilGone = async (pid, deadlineMs) => {
|
|
55
|
+
const until = Date.now() + deadlineMs;
|
|
56
|
+
while (Date.now() < until) {
|
|
57
|
+
try {
|
|
58
|
+
process.kill(pid, 0);
|
|
59
|
+
} catch {
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
await pause(100);
|
|
63
|
+
}
|
|
64
|
+
return false;
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// ---- The init lock ----
|
|
68
|
+
|
|
69
|
+
test('S3: the first session gets the lock, a second one finds it busy, and releasing frees it', () => {
|
|
70
|
+
const { dir, project } = scratch();
|
|
71
|
+
const first = tryAcquireInitLock(project, { dir });
|
|
72
|
+
assert.equal(first.status, 'acquired');
|
|
73
|
+
assert.equal(isInitLocked(project, { dir }), true);
|
|
74
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir }), { status: 'busy' });
|
|
75
|
+
first.release();
|
|
76
|
+
assert.equal(isInitLocked(project, { dir }), false);
|
|
77
|
+
assert.deepEqual(lockEntries(dir), []);
|
|
78
|
+
const again = tryAcquireInitLock(project, { dir });
|
|
79
|
+
assert.equal(again.status, 'acquired');
|
|
80
|
+
again.release();
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
test('S3: without a lock nothing reads as locked', () => {
|
|
84
|
+
const { dir, project } = scratch();
|
|
85
|
+
assert.equal(isInitLocked(project, { dir }), false);
|
|
86
|
+
assert.equal(isInitRunning(project, { dir }), false);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test('S3: different projects have independent locks', () => {
|
|
90
|
+
const { dir, project } = scratch();
|
|
91
|
+
const other = scratch().project;
|
|
92
|
+
const a = tryAcquireInitLock(project, { dir });
|
|
93
|
+
const b = tryAcquireInitLock(other, { dir });
|
|
94
|
+
assert.equal(a.status, 'acquired');
|
|
95
|
+
assert.equal(b.status, 'acquired');
|
|
96
|
+
assert.equal(isInitLocked(other, { dir }), true);
|
|
97
|
+
a.release();
|
|
98
|
+
assert.equal(isInitLocked(other, { dir }), true);
|
|
99
|
+
b.release();
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test('S3: the same project spelled with a trailing separator shares one lock', () => {
|
|
103
|
+
const { dir, project } = scratch();
|
|
104
|
+
const held = tryAcquireInitLock(project, { dir });
|
|
105
|
+
assert.equal(held.status, 'acquired');
|
|
106
|
+
const spellings = [project + (process.platform === 'win32' ? '\\' : '/')];
|
|
107
|
+
if (process.platform === 'win32') spellings.push(project.toUpperCase(), project.toLowerCase());
|
|
108
|
+
for (const spelling of spellings) {
|
|
109
|
+
assert.deepEqual(tryAcquireInitLock(spelling, { dir }), { status: 'busy' }, spelling);
|
|
110
|
+
assert.equal(isInitLocked(spelling, { dir }), true, spelling);
|
|
111
|
+
}
|
|
112
|
+
held.release();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test('S3: a lock whose process is gone is stale: the next session takes it over', () => {
|
|
116
|
+
const { dir, project } = scratch();
|
|
117
|
+
const dead = tryAcquireInitLock(project, { dir });
|
|
118
|
+
assert.equal(dead.status, 'acquired');
|
|
119
|
+
assert.equal(isInitLocked(project, { dir, isAlive: () => false }), false);
|
|
120
|
+
const taken = tryAcquireInitLock(project, { dir, isAlive: () => false });
|
|
121
|
+
assert.equal(taken.status, 'acquired');
|
|
122
|
+
taken.release();
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test('S3: a lock older than the longest an init can run is stale even if its pid looks alive', () => {
|
|
126
|
+
const { dir, project } = scratch();
|
|
127
|
+
const held = tryAcquireInitLock(project, { dir, now: () => Date.now() - LOCK_MAX_AGE_MS - 1_000 });
|
|
128
|
+
assert.equal(held.status, 'acquired');
|
|
129
|
+
assert.equal(isInitLocked(project, { dir, isAlive: () => true }), false);
|
|
130
|
+
const taken = tryAcquireInitLock(project, { dir, isAlive: () => true });
|
|
131
|
+
assert.equal(taken.status, 'acquired');
|
|
132
|
+
taken.release();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test('S3: a lock directory that is still being written counts as held; an abandoned one does not', () => {
|
|
136
|
+
const { dir, project } = scratch();
|
|
137
|
+
const held = tryAcquireInitLock(project, { dir });
|
|
138
|
+
const lockDir = path.join(dir, lockEntries(dir)[0]);
|
|
139
|
+
held.release();
|
|
140
|
+
fs.mkdirSync(lockDir);
|
|
141
|
+
assert.equal(isInitLocked(project, { dir }), true, 'fresh and empty: the owner has not written its record yet');
|
|
142
|
+
const longAgo = new Date(Date.now() - 120_000);
|
|
143
|
+
fs.utimesSync(lockDir, longAgo, longAgo);
|
|
144
|
+
assert.equal(isInitLocked(project, { dir }), false, 'empty for two minutes: abandoned');
|
|
145
|
+
const taken = tryAcquireInitLock(project, { dir });
|
|
146
|
+
assert.equal(taken.status, 'acquired');
|
|
147
|
+
taken.release();
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('S3: a damaged owner record is treated like an abandoned lock once it is old enough', () => {
|
|
151
|
+
const { dir, project } = scratch();
|
|
152
|
+
const held = tryAcquireInitLock(project, { dir });
|
|
153
|
+
const lockDir = path.join(dir, lockEntries(dir)[0]);
|
|
154
|
+
fs.writeFileSync(path.join(lockDir, 'owner.json'), 'not json');
|
|
155
|
+
const longAgo = new Date(Date.now() - 120_000);
|
|
156
|
+
fs.utimesSync(lockDir, longAgo, longAgo);
|
|
157
|
+
assert.equal(isInitLocked(project, { dir }), false);
|
|
158
|
+
held.release();
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test('S3: releasing never removes a lock that now belongs to someone else', () => {
|
|
162
|
+
const { dir, project } = scratch();
|
|
163
|
+
const mine = tryAcquireInitLock(project, { dir });
|
|
164
|
+
assert.equal(mine.status, 'acquired');
|
|
165
|
+
const taken = tryAcquireInitLock(project, { dir, isAlive: () => false });
|
|
166
|
+
assert.equal(taken.status, 'acquired');
|
|
167
|
+
mine.release();
|
|
168
|
+
assert.equal(isInitLocked(project, { dir }), true, "the new owner's lock must survive the old owner's release");
|
|
169
|
+
taken.release();
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
test('S3: a holder whose lock was taken over cannot undo the takeover, and the new owner keeps holding it', () => {
|
|
173
|
+
const { dir, project } = scratch();
|
|
174
|
+
const start = Date.now();
|
|
175
|
+
// A's record is older than the longest an init can run: B judges it stale although the pid it names is this one.
|
|
176
|
+
const a = tryAcquireInitLock(project, { dir, now: () => start - LOCK_MAX_AGE_MS - 1_000 });
|
|
177
|
+
assert.equal(a.status, 'acquired');
|
|
178
|
+
const lock = path.join(dir, lockEntries(dir)[0]);
|
|
179
|
+
const record = () => JSON.parse(fs.readFileSync(path.join(lock, 'owner.json'), 'utf8'));
|
|
180
|
+
const aToken = record().token;
|
|
181
|
+
const b = tryAcquireInitLock(project, { dir });
|
|
182
|
+
assert.equal(b.status, 'acquired', 'B took the stale lock over');
|
|
183
|
+
const bToken = record().token;
|
|
184
|
+
assert.notEqual(bToken, aToken, 'the takeover wrote a record of its own');
|
|
185
|
+
// Everything A can still do points at a record that is no longer its own.
|
|
186
|
+
a.adopt(424242);
|
|
187
|
+
a.release();
|
|
188
|
+
assert.equal(record().token, bToken, "A's late release left the record B wrote");
|
|
189
|
+
assert.equal(isInitLocked(project, { dir }), true, 'B still holds the lock');
|
|
190
|
+
assert.equal(isInitRunning(project, { dir }), true);
|
|
191
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir }), { status: 'busy' }, 'a third session answers to B, not to A');
|
|
192
|
+
// The true holder's release does remove it.
|
|
193
|
+
b.release();
|
|
194
|
+
assert.deepEqual(lockEntries(dir), []);
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
test('S3: an unusable lock directory never throws: the session simply goes on as if it had the lock', () => {
|
|
198
|
+
const project = scratch().project;
|
|
199
|
+
const dir = path.join(temp('cg-lock-missing-'), 'gone', 'deeper');
|
|
200
|
+
const attempt = tryAcquireInitLock(project, { dir });
|
|
201
|
+
assert.equal(attempt.status, 'acquired');
|
|
202
|
+
attempt.adopt(4242);
|
|
203
|
+
attempt.release();
|
|
204
|
+
assert.equal(isInitLocked(project, { dir }), false);
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* `count` sessions that all try at the same instant. The winner keeps the lock until every session has tried: on a
|
|
209
|
+
* busy machine a worker can reach the start line after a fixed hold has ended, and then it rightly takes the lock.
|
|
210
|
+
*/
|
|
211
|
+
async function sessionsAtOnce(dir, project, count) {
|
|
212
|
+
const startAt = Date.now() + 800;
|
|
213
|
+
const sessions = Array.from({ length: count }, () => {
|
|
214
|
+
const child = spawn(process.execPath, [WORKER, dir, project, String(startAt), 'stdin', 'lock'], { stdio: ['pipe', 'pipe', 'ignore'] });
|
|
215
|
+
const closed = new Promise((resolve) => child.once('close', () => resolve()));
|
|
216
|
+
const result = new Promise((resolve) => {
|
|
217
|
+
let out = '';
|
|
218
|
+
const done = () => {
|
|
219
|
+
try {
|
|
220
|
+
resolve(JSON.parse(out.trim().split('\n')[0]));
|
|
221
|
+
} catch {
|
|
222
|
+
resolve({ status: `worker produced no result: ${out.slice(0, 80)}`, pid: 0 });
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
child.stdout.on('data', (chunk) => {
|
|
226
|
+
out += chunk;
|
|
227
|
+
if (out.includes('\n')) done();
|
|
228
|
+
});
|
|
229
|
+
void closed.then(done);
|
|
230
|
+
});
|
|
231
|
+
return { child, closed, result };
|
|
232
|
+
});
|
|
233
|
+
const results = await Promise.all(sessions.map((session) => session.result));
|
|
234
|
+
// Every session has tried: now the winner may let go.
|
|
235
|
+
for (const session of sessions) session.child.stdin.end();
|
|
236
|
+
await Promise.all(sessions.map((session) => session.closed));
|
|
237
|
+
return results;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
test('S3: sessions that try at the very same instant: exactly one gets the lock, every time', async () => {
|
|
241
|
+
for (const sessions of [2, 4]) {
|
|
242
|
+
for (let round = 0; round < 2; round++) {
|
|
243
|
+
const { dir, project } = scratch();
|
|
244
|
+
const results = await sessionsAtOnce(dir, project, sessions);
|
|
245
|
+
const winners = results.filter((result) => result.status === 'acquired').length;
|
|
246
|
+
const busy = results.filter((result) => result.status === 'busy').length;
|
|
247
|
+
assert.deepEqual({ winners, busy }, { winners: 1, busy: sessions - 1 }, `${sessions} sessions, round ${round}: ${JSON.stringify(results)}`);
|
|
248
|
+
assert.deepEqual(lockEntries(dir), [], `${sessions} sessions, round ${round}: the winner released the lock`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
test('S3: a holder that is killed leaves a lock the next session recognises as stale', async () => {
|
|
254
|
+
const { dir, project } = scratch();
|
|
255
|
+
const child = spawn(process.execPath, [WORKER, dir, project, '0', '60000', 'lock'], { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
256
|
+
await new Promise((resolve) => child.stdout.once('data', () => resolve()));
|
|
257
|
+
assert.equal(isInitLocked(project, { dir }), true);
|
|
258
|
+
child.kill('SIGKILL');
|
|
259
|
+
await new Promise((resolve) => child.once('close', resolve));
|
|
260
|
+
assert.equal(fs.existsSync(path.join(dir, lockEntries(dir)[0])), true, 'a killed process cannot clean up after itself');
|
|
261
|
+
assert.equal(isInitLocked(project, { dir }), false);
|
|
262
|
+
const taken = tryAcquireInitLock(project, { dir });
|
|
263
|
+
assert.equal(taken.status, 'acquired');
|
|
264
|
+
taken.release();
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
test('S3: two sessions that both find the same stale lock: only one of them takes it over', () => {
|
|
268
|
+
const { dir, project } = scratch();
|
|
269
|
+
const old = tryAcquireInitLock(project, { dir, now: () => Date.now() - LOCK_MAX_AGE_MS - 1_000 });
|
|
270
|
+
assert.equal(old.status, 'acquired');
|
|
271
|
+
let rival;
|
|
272
|
+
// The rival runs its whole attempt right after this session judged the lock stale and before it cleared it.
|
|
273
|
+
const mine = tryAcquireInitLock(project, {
|
|
274
|
+
dir,
|
|
275
|
+
onStale: () => {
|
|
276
|
+
if (rival === undefined) rival = tryAcquireInitLock(project, { dir });
|
|
277
|
+
},
|
|
278
|
+
});
|
|
279
|
+
assert.ok(rival, 'the race window was reached');
|
|
280
|
+
assert.deepEqual([mine.status, rival.status].sort(), ['acquired', 'busy']);
|
|
281
|
+
assert.equal(isInitLocked(project, { dir }), true);
|
|
282
|
+
for (const attempt of [mine, rival]) if (attempt.status === 'acquired') attempt.release();
|
|
283
|
+
assert.deepEqual(lockEntries(dir), [], 'the winner release leaves nothing behind, takeover guard included');
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
test('S3: a takeover guard left by a session that died mid-takeover does not block the lock for good', () => {
|
|
287
|
+
const { dir, project } = scratch();
|
|
288
|
+
const old = tryAcquireInitLock(project, { dir, now: () => Date.now() - LOCK_MAX_AGE_MS - 1_000 });
|
|
289
|
+
assert.equal(old.status, 'acquired');
|
|
290
|
+
const guard = path.join(dir, `${lockEntries(dir)[0]}.takeover`);
|
|
291
|
+
fs.mkdirSync(guard);
|
|
292
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir }), { status: 'busy' }, 'a fresh guard: someone is taking over right now');
|
|
293
|
+
const longAgo = new Date(Date.now() - 60_000);
|
|
294
|
+
fs.utimesSync(guard, longAgo, longAgo);
|
|
295
|
+
let taken = tryAcquireInitLock(project, { dir });
|
|
296
|
+
if (taken.status === 'busy') taken = tryAcquireInitLock(project, { dir });
|
|
297
|
+
assert.equal(taken.status, 'acquired');
|
|
298
|
+
taken.release();
|
|
299
|
+
assert.deepEqual(lockEntries(dir), []);
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
test('S3: the lock stays held while the init process lives, even when the session that took it is gone', () => {
|
|
303
|
+
const { dir, project } = scratch();
|
|
304
|
+
const held = tryAcquireInitLock(project, { dir });
|
|
305
|
+
assert.equal(held.status, 'acquired');
|
|
306
|
+
held.adopt(424242);
|
|
307
|
+
assert.equal(isInitLocked(project, { dir, isAlive: (pid) => pid === 424242 }), true, 'session gone, init alive');
|
|
308
|
+
assert.equal(isInitLocked(project, { dir, isAlive: (pid) => pid === process.pid }), true, 'session alive');
|
|
309
|
+
assert.equal(isInitLocked(project, { dir, isAlive: () => false }), false, 'both gone');
|
|
310
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir, isAlive: (pid) => pid === 424242 }), { status: 'busy' });
|
|
311
|
+
held.release();
|
|
312
|
+
assert.deepEqual(lockEntries(dir), []);
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
test('S3 real: a session that exits while its init process goes on leaves the lock held until that process ends', async () => {
|
|
316
|
+
const { dir, project } = scratch();
|
|
317
|
+
const out = await new Promise((resolve) => {
|
|
318
|
+
const child = spawn(process.execPath, [WORKER, dir, project, '0', '30000', 'orphan'], { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
319
|
+
let text = '';
|
|
320
|
+
child.stdout.on('data', (chunk) => (text += chunk));
|
|
321
|
+
child.on('close', () => resolve(text));
|
|
322
|
+
});
|
|
323
|
+
const { status, initPid } = JSON.parse(out.trim());
|
|
324
|
+
assert.equal(status, 'acquired');
|
|
325
|
+
try {
|
|
326
|
+
assert.equal(isInitLocked(project, { dir }), true, 'the session is gone but its init is not');
|
|
327
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir }), { status: 'busy' });
|
|
328
|
+
} finally {
|
|
329
|
+
process.kill(initPid);
|
|
330
|
+
}
|
|
331
|
+
await pause(500);
|
|
332
|
+
assert.equal(isInitLocked(project, { dir }), false, 'once the init is gone too, the lock is stale');
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
test('S3: the adopted pid is written atomically: a reader never sees the record vanish', () => {
|
|
336
|
+
const { dir, project } = scratch();
|
|
337
|
+
const held = tryAcquireInitLock(project, { dir });
|
|
338
|
+
assert.equal(held.status, 'acquired');
|
|
339
|
+
for (let i = 0; i < 200; i++) {
|
|
340
|
+
held.adopt(1000 + i);
|
|
341
|
+
assert.equal(isInitLocked(project, { dir, isAlive: (pid) => pid === 1000 + i }), true, `round ${i}`);
|
|
342
|
+
}
|
|
343
|
+
assert.deepEqual(fs.readdirSync(path.join(dir, lockEntries(dir)[0])), ['owner.json'], 'no temporary files left behind');
|
|
344
|
+
held.release();
|
|
345
|
+
});
|
|
346
|
+
|
|
347
|
+
test('S3: a record that adopted the init process itself is stale as soon as that process is gone', () => {
|
|
348
|
+
const { dir, project } = scratch();
|
|
349
|
+
const start = Date.now();
|
|
350
|
+
const held = tryAcquireInitLock(project, { dir, now: () => start });
|
|
351
|
+
assert.equal(held.status, 'acquired');
|
|
352
|
+
held.adopt(424242);
|
|
353
|
+
// Nothing to wait for: the pid that was adopted is the process that does the work.
|
|
354
|
+
assert.equal(isInitLocked(project, { dir, isAlive: () => false, now: () => start + 1 }), false);
|
|
355
|
+
const taken = tryAcquireInitLock(project, { dir, isAlive: () => false, now: () => start + 1 });
|
|
356
|
+
assert.equal(taken.status, 'acquired');
|
|
357
|
+
taken.release();
|
|
358
|
+
held.release();
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
test("S3: while a CodeGraph process writes the index, the lock stays held whatever pid the session adopted", () => {
|
|
362
|
+
const { dir, project } = scratch();
|
|
363
|
+
const held = tryAcquireInitLock(project, { dir });
|
|
364
|
+
assert.equal(held.status, 'acquired');
|
|
365
|
+
// The pid this session adopted was the shell, and it is gone; the init itself goes on and says so in
|
|
366
|
+
// CodeGraph's own lock, which is the pid that decides.
|
|
367
|
+
held.adopt(424242, { proxy: true });
|
|
368
|
+
fs.mkdirSync(path.join(project, '.codegraph'), { recursive: true });
|
|
369
|
+
fs.writeFileSync(path.join(project, '.codegraph', 'codegraph.lock'), String(process.pid));
|
|
370
|
+
assert.equal(isInitLocked(project, { dir, isAlive: () => false }), true, 'the init is alive, the session and its shell are not');
|
|
371
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir, isAlive: () => false }), { status: 'busy' });
|
|
372
|
+
held.release();
|
|
373
|
+
assert.equal(isInitLocked(project, { dir }), false, "the record is gone: CodeGraph's lock alone never holds it");
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
test('S3: right after a shell spawned the init, before CodeGraph writes its own lock, the record is still trusted', () => {
|
|
377
|
+
const { dir, project } = scratch();
|
|
378
|
+
const start = Date.now();
|
|
379
|
+
const held = tryAcquireInitLock(project, { dir, now: () => start });
|
|
380
|
+
assert.equal(held.status, 'acquired');
|
|
381
|
+
held.adopt(424242, { proxy: true });
|
|
382
|
+
const dead = { isAlive: () => false };
|
|
383
|
+
assert.equal(isInitLocked(project, { dir, ...dead, now: () => start + 1_000 }), true, 'the shell died and the init has not shown up yet');
|
|
384
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir, ...dead, now: () => start + 1_000 }), { status: 'busy' });
|
|
385
|
+
const later = start + PROXY_TRUST_MS + 1;
|
|
386
|
+
assert.equal(isInitLocked(project, { dir, ...dead, now: () => later }), false, 'after that window no init ever showed up: stale');
|
|
387
|
+
const taken = tryAcquireInitLock(project, { dir, ...dead, now: () => later });
|
|
388
|
+
assert.equal(taken.status, 'acquired');
|
|
389
|
+
taken.release();
|
|
390
|
+
held.release();
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
test('S3: a sync holder locks the index for an init but is not an init running', () => {
|
|
394
|
+
const { dir, project } = scratch();
|
|
395
|
+
const sync = tryAcquireInitLock(project, { dir }, 'sync');
|
|
396
|
+
assert.equal(sync.status, 'acquired');
|
|
397
|
+
assert.equal(isInitLocked(project, { dir }), true, 'the index is being written by this package');
|
|
398
|
+
assert.equal(isInitRunning(project, { dir }), false, 'a sync is not an init');
|
|
399
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir }, 'init'), { status: 'busy' }, 'an init cannot start while the sync runs');
|
|
400
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir }, 'sync'), { status: 'busy' }, 'nor a second sync');
|
|
401
|
+
sync.release();
|
|
402
|
+
assert.equal(isInitLocked(project, { dir }), false);
|
|
403
|
+
assert.equal(isInitRunning(project, { dir }), false);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
test('S3: an init holder is both locked and an init running', () => {
|
|
407
|
+
const { dir, project } = scratch();
|
|
408
|
+
const init = tryAcquireInitLock(project, { dir });
|
|
409
|
+
assert.equal(init.status, 'acquired');
|
|
410
|
+
assert.equal(isInitLocked(project, { dir }), true);
|
|
411
|
+
assert.equal(isInitRunning(project, { dir }), true);
|
|
412
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir }, 'sync'), { status: 'busy' }, 'a sync cannot start while the init runs');
|
|
413
|
+
init.release();
|
|
414
|
+
});
|
|
415
|
+
|
|
416
|
+
test('S3: the kind of a holder survives adopting the process it started', () => {
|
|
417
|
+
const { dir, project } = scratch();
|
|
418
|
+
const sync = tryAcquireInitLock(project, { dir }, 'sync');
|
|
419
|
+
assert.equal(sync.status, 'acquired');
|
|
420
|
+
sync.adopt(424242);
|
|
421
|
+
assert.equal(isInitLocked(project, { dir }), true);
|
|
422
|
+
assert.equal(isInitRunning(project, { dir }), false);
|
|
423
|
+
sync.release();
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
test('S3 real: the shell of a spawned init dies while the init goes on: the lock stays held and no session takes it over', async () => {
|
|
427
|
+
const { dir, project } = scratch();
|
|
428
|
+
const out = await new Promise((resolve) => {
|
|
429
|
+
const child = spawn(process.execPath, [WORKER, dir, project, '0', '30000', 'shell'], { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
430
|
+
let text = '';
|
|
431
|
+
child.stdout.on('data', (chunk) => (text += chunk));
|
|
432
|
+
child.on('close', () => resolve(text));
|
|
433
|
+
});
|
|
434
|
+
const { status, initPid: shellPid } = JSON.parse(out.trim());
|
|
435
|
+
assert.equal(status, 'acquired');
|
|
436
|
+
let initPid = 0;
|
|
437
|
+
try {
|
|
438
|
+
initPid = Number(fs.readFileSync(path.join(project, '.codegraph', 'codegraph.lock'), 'utf8'));
|
|
439
|
+
} catch {
|
|
440
|
+
// Reported below.
|
|
441
|
+
}
|
|
442
|
+
assert.ok(initPid > 0, `the init announced itself in CodeGraph's own lock: ${out.trim()}`);
|
|
443
|
+
try {
|
|
444
|
+
// The session is gone. On Windows its shell went with it; elsewhere the Pi that owned it would kill it.
|
|
445
|
+
if (!(await waitUntilGone(shellPid, 3_000))) process.kill(shellPid);
|
|
446
|
+
assert.ok(await waitUntilGone(shellPid, 5_000), 'the shell really is gone');
|
|
447
|
+
process.kill(initPid, 0);
|
|
448
|
+
assert.equal(isInitLocked(project, { dir }), true, 'nobody is left to speak for the lock but the init itself');
|
|
449
|
+
assert.deepEqual(tryAcquireInitLock(project, { dir }), { status: 'busy' }, 'a new session must not start a second init');
|
|
450
|
+
} finally {
|
|
451
|
+
try {
|
|
452
|
+
process.kill(initPid);
|
|
453
|
+
} catch {
|
|
454
|
+
// It is gone already.
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
assert.ok(await waitUntilGone(initPid, 10_000), 'the init is gone too');
|
|
458
|
+
assert.equal(isInitLocked(project, { dir }), true, 'its pid is no longer alive, but the shell was never proof of death');
|
|
459
|
+
assert.equal(isInitLocked(project, { dir, now: () => Date.now() + PROXY_TRUST_MS + 1_000 }), false, 'past that window the lock is stale again');
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
test("S3: CodeGraph's own lock names the process writing the index, and counts only a live one", async () => {
|
|
463
|
+
const dir = temp('cg-writing-');
|
|
464
|
+
fs.mkdirSync(path.join(dir, '.codegraph'));
|
|
465
|
+
const lock = path.join(dir, '.codegraph', 'codegraph.lock');
|
|
466
|
+
fs.writeFileSync(lock, String(process.pid));
|
|
467
|
+
assert.equal(codegraphWritingIndex(dir), true);
|
|
468
|
+
const gone = spawn(process.execPath, ['-e', 'process.exit(0)'], { stdio: 'ignore' });
|
|
469
|
+
await new Promise((resolve) => gone.on('close', resolve));
|
|
470
|
+
fs.writeFileSync(lock, String(gone.pid));
|
|
471
|
+
assert.equal(codegraphWritingIndex(dir), false, `dead pid ${gone.pid}`);
|
|
472
|
+
fs.writeFileSync(lock, 'not a pid');
|
|
473
|
+
assert.equal(codegraphWritingIndex(dir), false);
|
|
474
|
+
fs.writeFileSync(lock, '');
|
|
475
|
+
assert.equal(codegraphWritingIndex(dir), false);
|
|
476
|
+
fs.rmSync(lock);
|
|
477
|
+
assert.equal(codegraphWritingIndex(dir), false);
|
|
478
|
+
assert.equal(codegraphWritingIndex(path.join(dir, 'nowhere')), false);
|
|
479
|
+
});
|
|
480
|
+
|
|
481
|
+
test('S3: the module exports the real init lock a caller can wire without a folder of its own', () => {
|
|
482
|
+
assert.equal(typeof realInitLock.acquire, 'function');
|
|
483
|
+
assert.equal(typeof realInitLock.isHeld, 'function');
|
|
484
|
+
assert.equal(typeof realInitLock.isInitRunning, 'function');
|
|
485
|
+
assert.equal(typeof realSyncLease.request, 'function');
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
// ---- The per-project sync lease ----
|
|
489
|
+
|
|
490
|
+
function lease(prefix) {
|
|
491
|
+
return syncLease({ dir: temp(prefix), pollMs: 5, requestWaitMs: 20_000 });
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* The lease a reader outside the module sees in `dir`: its state folder and the record of its `run/`. Nobody else
|
|
496
|
+
* writes into the folder of a case, so one state folder per `dir` is what the coordination leaves there.
|
|
497
|
+
*/
|
|
498
|
+
function leaseOnDisk(dir) {
|
|
499
|
+
const entry = fs.readdirSync(dir).find((name) => name.startsWith('pcs-sync-'));
|
|
500
|
+
if (entry === undefined) return { state: undefined, record: undefined };
|
|
501
|
+
const state = path.join(dir, entry);
|
|
502
|
+
try {
|
|
503
|
+
return { state, record: JSON.parse(fs.readFileSync(path.join(state, 'run', 'owner.json'), 'utf8')) };
|
|
504
|
+
} catch {
|
|
505
|
+
return { state, record: undefined };
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
/**
|
|
510
|
+
* A clock pinned to the takeover folder's own recorded `mtime`, `offset` milliseconds into the grace the module gives a
|
|
511
|
+
* record that is still being written. "Fresh" becomes a property of the folder itself instead of an assumption about
|
|
512
|
+
* the real clock: a machine paused past the grace can no longer invert what these cases expect.
|
|
513
|
+
*/
|
|
514
|
+
function clockAt(runDir, offset) {
|
|
515
|
+
return fs.statSync(runDir).mtimeMs + offset;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* The instant a takeover passes through: `run/` created again while its record is not written yet (`record`
|
|
520
|
+
* undefined) or is being replaced (an unreadable one). No case can pause another session inside that window, so it
|
|
521
|
+
* recreates exactly what a reader sees there and lets the holder's own release be the next thing to touch it.
|
|
522
|
+
*/
|
|
523
|
+
function takeoverWindow(state, record) {
|
|
524
|
+
const runDir = path.join(state, 'run');
|
|
525
|
+
fs.rmSync(runDir, { recursive: true, force: true });
|
|
526
|
+
fs.mkdirSync(runDir);
|
|
527
|
+
if (record !== undefined) fs.writeFileSync(path.join(runDir, 'owner.json'), record);
|
|
528
|
+
return runDir;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/**
|
|
532
|
+
* A session that holds the lease of `project` and blocks inside its attempt until the case lets it come back. Its own
|
|
533
|
+
* demand is removed first, as the takeover's run serves it, so it settles at once instead of asking again.
|
|
534
|
+
*/
|
|
535
|
+
async function holderBlockedInAttempt(dir, project, options = {}) {
|
|
536
|
+
const coordinator = syncLease({ dir, pollMs: 5, requestWaitMs: 20_000, ...options });
|
|
537
|
+
let release = () => {};
|
|
538
|
+
const blocked = new Promise((resolve) => {
|
|
539
|
+
release = resolve;
|
|
540
|
+
});
|
|
541
|
+
let started = false;
|
|
542
|
+
const settled = coordinator.request(project, async () => {
|
|
543
|
+
started = true;
|
|
544
|
+
await blocked;
|
|
545
|
+
return { ran: false };
|
|
546
|
+
});
|
|
547
|
+
await waitFor(() => started, "the holder's attempt to start");
|
|
548
|
+
const { state, record } = leaseOnDisk(dir);
|
|
549
|
+
assert.equal(typeof record.token, 'string', 'the holder wrote its lease record');
|
|
550
|
+
fs.rmSync(path.join(state, 'req', record.token), { force: true });
|
|
551
|
+
return {
|
|
552
|
+
state,
|
|
553
|
+
record,
|
|
554
|
+
go: () => {
|
|
555
|
+
release();
|
|
556
|
+
return settled;
|
|
557
|
+
},
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** A run that fails the test if two of them overlap, and records when each one started. */
|
|
562
|
+
function guardedRun(runs, state, holdMs) {
|
|
563
|
+
return async () => {
|
|
564
|
+
assert.equal(state.running, false, 'two syncs of one project ran at the same time');
|
|
565
|
+
state.running = true;
|
|
566
|
+
runs.push({ start: Date.now() });
|
|
567
|
+
try {
|
|
568
|
+
await pause(holdMs);
|
|
569
|
+
} finally {
|
|
570
|
+
state.running = false;
|
|
571
|
+
}
|
|
572
|
+
return { ran: true, ok: true };
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
test('S3: a request during a running sync becomes exactly one follow-up, never a simultaneous run', async () => {
|
|
577
|
+
const { project } = scratch();
|
|
578
|
+
const coordinator = lease('cg-lease-');
|
|
579
|
+
const runs = [];
|
|
580
|
+
const state = { running: false };
|
|
581
|
+
const run = guardedRun(runs, state, 300);
|
|
582
|
+
const first = coordinator.request(project, run);
|
|
583
|
+
await pause(50);
|
|
584
|
+
const requestedAt = [Date.now()];
|
|
585
|
+
const second = coordinator.request(project, run);
|
|
586
|
+
await pause(10);
|
|
587
|
+
requestedAt.push(Date.now());
|
|
588
|
+
const third = coordinator.request(project, run);
|
|
589
|
+
const [a, b, c] = await Promise.all([first, second, third]);
|
|
590
|
+
assert.deepEqual(a, { status: 'ran', ok: true });
|
|
591
|
+
assert.deepEqual(b, { status: 'coalesced' });
|
|
592
|
+
assert.deepEqual(c, { status: 'coalesced' });
|
|
593
|
+
assert.equal(runs.length, 2, 'one run plus one follow-up for both requests together');
|
|
594
|
+
// Neither request was dropped: each is covered by a run that started after it was made.
|
|
595
|
+
for (const at of requestedAt) assert.ok(runs.some((entry) => entry.start >= at), `request at ${at} is covered: ${JSON.stringify(runs)}`);
|
|
596
|
+
});
|
|
597
|
+
|
|
598
|
+
test('S3: a request that arrives during the follow-up is served by a further one, so no demand is lost', async () => {
|
|
599
|
+
const { project } = scratch();
|
|
600
|
+
const coordinator = lease('cg-lease-');
|
|
601
|
+
const runs = [];
|
|
602
|
+
const state = { running: false };
|
|
603
|
+
const run = guardedRun(runs, state, 250);
|
|
604
|
+
const first = coordinator.request(project, run);
|
|
605
|
+
await pause(50);
|
|
606
|
+
const second = coordinator.request(project, run);
|
|
607
|
+
// The follow-up starts when the first run ends; ask again inside it.
|
|
608
|
+
await pause(250);
|
|
609
|
+
const thirdAt = Date.now();
|
|
610
|
+
const third = coordinator.request(project, run);
|
|
611
|
+
const [a, b, c] = await Promise.all([first, second, third]);
|
|
612
|
+
assert.deepEqual(a, { status: 'ran', ok: true });
|
|
613
|
+
assert.deepEqual(b, { status: 'coalesced' });
|
|
614
|
+
assert.deepEqual(c, { status: 'coalesced' });
|
|
615
|
+
assert.equal(runs.length, 3, `each request gets a run after it: ${JSON.stringify(runs)}`);
|
|
616
|
+
assert.ok(runs.some((entry) => entry.start >= thirdAt));
|
|
617
|
+
});
|
|
618
|
+
|
|
619
|
+
test('S3: a run that fails still lets the next request through', async () => {
|
|
620
|
+
const { project } = scratch();
|
|
621
|
+
const coordinator = lease('cg-lease-');
|
|
622
|
+
const failed = await coordinator.request(project, async () => ({ ran: true, ok: false }));
|
|
623
|
+
assert.deepEqual(failed, { status: 'ran', ok: false });
|
|
624
|
+
const again = await coordinator.request(project, async () => ({ ran: true, ok: true }));
|
|
625
|
+
assert.deepEqual(again, { status: 'ran', ok: true }, 'the lease of a failed run is released');
|
|
626
|
+
});
|
|
627
|
+
|
|
628
|
+
test('S3: a run that cannot get the index leaves the demand pending and says queued, never coalesced', async () => {
|
|
629
|
+
const { project } = scratch();
|
|
630
|
+
const coordinator = syncLease({ dir: temp('cg-lease-'), pollMs: 5, requestWaitMs: 200 });
|
|
631
|
+
const outcome = await coordinator.request(project, async () => ({ ran: false }));
|
|
632
|
+
assert.deepEqual(outcome, { status: 'queued' }, 'no run happened: coalesced would be a lie');
|
|
633
|
+
});
|
|
634
|
+
|
|
635
|
+
test('S3: different projects sync independently, and one folder spelled two ways is one lease', async () => {
|
|
636
|
+
const { project } = scratch();
|
|
637
|
+
const other = scratch().project;
|
|
638
|
+
const coordinator = lease('cg-lease-');
|
|
639
|
+
const [a, b] = await Promise.all([
|
|
640
|
+
coordinator.request(project, guardedRun([], { running: false }, 200)),
|
|
641
|
+
coordinator.request(other, guardedRun([], { running: false }, 200)),
|
|
642
|
+
]);
|
|
643
|
+
assert.deepEqual([a.status, b.status], ['ran', 'ran']);
|
|
644
|
+
|
|
645
|
+
const runs = [];
|
|
646
|
+
const state = { running: false };
|
|
647
|
+
const respelled = process.platform === 'win32' ? project.toUpperCase() : `${project}/`;
|
|
648
|
+
const first = coordinator.request(project, guardedRun(runs, state, 300));
|
|
649
|
+
await pause(50);
|
|
650
|
+
const second = coordinator.request(respelled, guardedRun(runs, state, 50));
|
|
651
|
+
const [c, d] = await Promise.all([first, second]);
|
|
652
|
+
assert.deepEqual(c, { status: 'ran', ok: true });
|
|
653
|
+
assert.deepEqual(d, { status: 'coalesced' }, 'another spelling of one folder is the same project');
|
|
654
|
+
});
|
|
655
|
+
|
|
656
|
+
test('S3: a stale lease token never releases the lease the session that took it over is running under', async () => {
|
|
657
|
+
const dir = temp('cg-lease-');
|
|
658
|
+
const { project } = scratch();
|
|
659
|
+
const runs = [];
|
|
660
|
+
// A's record speaks of a sync that started longer ago than any sync can last, so B rightly takes the lease over.
|
|
661
|
+
const stale = syncLease({ dir, pollMs: 5, requestWaitMs: 20_000, now: () => Date.now() - SYNC_LEASE_MAX_AGE_MS - 60_000 });
|
|
662
|
+
let finishA = () => {};
|
|
663
|
+
const aMayEnd = new Promise((resolve) => {
|
|
664
|
+
finishA = resolve;
|
|
665
|
+
});
|
|
666
|
+
let aStarted = false;
|
|
667
|
+
const a = stale.request(project, async () => {
|
|
668
|
+
aStarted = true;
|
|
669
|
+
await aMayEnd;
|
|
670
|
+
return { ran: false };
|
|
671
|
+
});
|
|
672
|
+
await waitFor(() => aStarted, "A's attempt to start");
|
|
673
|
+
const current = syncLease({ dir, pollMs: 5, requestWaitMs: 20_000 });
|
|
674
|
+
let bStarted = false;
|
|
675
|
+
const b = current.request(project, async () => {
|
|
676
|
+
runs.push('B');
|
|
677
|
+
bStarted = true;
|
|
678
|
+
await pause(800);
|
|
679
|
+
return { ran: true, ok: true };
|
|
680
|
+
});
|
|
681
|
+
await waitFor(() => bStarted, 'B to take the lease over');
|
|
682
|
+
const bToken = leaseOnDisk(dir).record.token;
|
|
683
|
+
assert.equal(typeof bToken, 'string', 'B wrote its lease record');
|
|
684
|
+
// A comes back from its attempt and releases, while B is still running under its own record.
|
|
685
|
+
finishA();
|
|
686
|
+
await pause(100);
|
|
687
|
+
const afterA = leaseOnDisk(dir);
|
|
688
|
+
assert.equal(afterA.record && afterA.record.token, bToken, "A's release left B's record in place");
|
|
689
|
+
// A session that arrives now finds B's lease: it waits for B instead of running beside it.
|
|
690
|
+
let cRan = false;
|
|
691
|
+
const c = current.request(project, async () => {
|
|
692
|
+
cRan = true;
|
|
693
|
+
runs.push('C');
|
|
694
|
+
return { ran: true, ok: true };
|
|
695
|
+
});
|
|
696
|
+
const [aOutcome, bOutcome, cOutcome] = await Promise.all([a, b, c]);
|
|
697
|
+
assert.equal(cRan, false, 'no second sync started while B held the lease');
|
|
698
|
+
assert.deepEqual(runs.filter((who) => who !== 'B'), [], `only B ran: ${JSON.stringify(runs)}`);
|
|
699
|
+
assert.deepEqual(aOutcome, { status: 'coalesced' }, 'A was served by B, never by a run of its own');
|
|
700
|
+
assert.deepEqual(bOutcome, { status: 'ran', ok: true });
|
|
701
|
+
assert.deepEqual(cOutcome, { status: 'coalesced' });
|
|
702
|
+
assert.equal(leaseOnDisk(dir).record, undefined, "the true holder's release removed its lease");
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
test('S3: a holder whose record another session is still writing never removes the lease of that session', async () => {
|
|
706
|
+
const dir = temp('cg-lease-');
|
|
707
|
+
const { project } = scratch();
|
|
708
|
+
// The holder reads the clock this case gives it, so the takeover window below can pin it to that folder's mtime.
|
|
709
|
+
let clock = Date.now();
|
|
710
|
+
const holder = await holderBlockedInAttempt(dir, project, { now: () => clock });
|
|
711
|
+
// The takeover window: `run/` is there again and its record is not written yet.
|
|
712
|
+
const runDir = takeoverWindow(holder.state);
|
|
713
|
+
// One millisecond short of the grace: the folder is still being written into, whatever the real clock did meanwhile.
|
|
714
|
+
clock = clockAt(runDir, UNWRITTEN_GRACE_MS - 1);
|
|
715
|
+
assert.deepEqual(await holder.go(), { status: 'coalesced' }, "the takeover's run served the holder's demand");
|
|
716
|
+
assert.equal(fs.existsSync(runDir), true, "the holder's release left the lease the takeover is creating");
|
|
717
|
+
// The takeover finishes: its record lands in the folder the holder must not have touched, and every later session
|
|
718
|
+
// answers to it instead of starting a sync of its own.
|
|
719
|
+
const bRecord = { pid: process.pid, startedAt: Date.now(), token: 'b-token' };
|
|
720
|
+
fs.writeFileSync(path.join(runDir, 'owner.json'), JSON.stringify(bRecord));
|
|
721
|
+
let lateRan = false;
|
|
722
|
+
const late = await syncLease({ dir, pollMs: 5, requestWaitMs: 300 }).request(project, async () => {
|
|
723
|
+
lateRan = true;
|
|
724
|
+
return { ran: true, ok: true };
|
|
725
|
+
});
|
|
726
|
+
assert.equal(lateRan, false, 'the session holding the new lease is not run beside');
|
|
727
|
+
assert.deepEqual(late, { status: 'queued' }, 'the late session waits for the lease it cannot take');
|
|
728
|
+
assert.deepEqual(leaseOnDisk(dir).record, bRecord, "the takeover's record is still the lease");
|
|
729
|
+
});
|
|
730
|
+
|
|
731
|
+
test("S3: a record that cannot be read is never proof that the lease is still the releasing session's", async () => {
|
|
732
|
+
const dir = temp('cg-lease-');
|
|
733
|
+
const { project } = scratch();
|
|
734
|
+
let clock = Date.now();
|
|
735
|
+
const holder = await holderBlockedInAttempt(dir, project, { now: () => clock });
|
|
736
|
+
// The same window read from the other side: a record is in place, and it proves nothing.
|
|
737
|
+
const runDir = takeoverWindow(holder.state, 'not a record');
|
|
738
|
+
clock = clockAt(runDir, UNWRITTEN_GRACE_MS - 1);
|
|
739
|
+
assert.deepEqual(await holder.go(), { status: 'coalesced' });
|
|
740
|
+
assert.equal(fs.existsSync(runDir), true, 'an unreadable record is not proof of ownership: the folder stays');
|
|
741
|
+
assert.equal(fs.readFileSync(path.join(runDir, 'owner.json'), 'utf8'), 'not a record', 'the holder removed nothing');
|
|
742
|
+
});
|
|
743
|
+
|
|
744
|
+
test('S3: a lease abandoned without a record is still removed, so an interrupted session never wedges the project', async () => {
|
|
745
|
+
const dir = temp('cg-lease-');
|
|
746
|
+
const { project } = scratch();
|
|
747
|
+
let clock = Date.now();
|
|
748
|
+
const holder = await holderBlockedInAttempt(dir, project, { now: () => clock });
|
|
749
|
+
const runDir = path.join(holder.state, 'run');
|
|
750
|
+
fs.rmSync(path.join(runDir, 'owner.json'), { force: true });
|
|
751
|
+
// Exactly the grace after the folder was last written to, read from the folder itself: the boundary the module
|
|
752
|
+
// documents, and one millisecond more than the cases above.
|
|
753
|
+
clock = clockAt(runDir, UNWRITTEN_GRACE_MS);
|
|
754
|
+
assert.deepEqual(await holder.go(), { status: 'coalesced' });
|
|
755
|
+
assert.equal(fs.existsSync(runDir), false, 'a record-less lease older than the grace is removed');
|
|
756
|
+
});
|
|
757
|
+
|
|
758
|
+
test("S3: the true holder's release still removes its own lease", async () => {
|
|
759
|
+
const dir = temp('cg-lease-');
|
|
760
|
+
const { project } = scratch();
|
|
761
|
+
const outcome = await syncLease({ dir, pollMs: 5, requestWaitMs: 20_000 }).request(project, async () => ({ ran: true, ok: true }));
|
|
762
|
+
assert.deepEqual(outcome, { status: 'ran', ok: true });
|
|
763
|
+
const { state } = leaseOnDisk(dir);
|
|
764
|
+
assert.equal(fs.existsSync(path.join(state, 'run')), false, "the holder's own release removed its lease");
|
|
765
|
+
});
|
|
766
|
+
|
|
767
|
+
test('S3: unusable coordination state starts no sync at all (fail closed)', async () => {
|
|
768
|
+
const file = path.join(temp('cg-lease-file-'), 'not-a-directory');
|
|
769
|
+
fs.writeFileSync(file, '');
|
|
770
|
+
let ran = false;
|
|
771
|
+
const outcome = await syncLease({ dir: file, pollMs: 5, requestWaitMs: 500 }).request(scratch().project, async () => {
|
|
772
|
+
ran = true;
|
|
773
|
+
return { ran: true, ok: true };
|
|
774
|
+
});
|
|
775
|
+
assert.equal(ran, false, 'without its coordination state the package does not risk a second sync');
|
|
776
|
+
assert.deepEqual(outcome, { status: 'unavailable' });
|
|
777
|
+
});
|
|
778
|
+
|
|
779
|
+
// ---- Across processes: cooperative sessions of this user sharing the same temp folder ----
|
|
780
|
+
|
|
781
|
+
const ledgerPath = (project) => path.join(project, 'runs.log');
|
|
782
|
+
const ledgerText = (project) => {
|
|
783
|
+
try {
|
|
784
|
+
return fs.readFileSync(ledgerPath(project), 'utf8');
|
|
785
|
+
} catch {
|
|
786
|
+
return '';
|
|
787
|
+
}
|
|
788
|
+
};
|
|
789
|
+
const starts = (text) => text.split('\n').filter((line) => line.startsWith('start ')).length;
|
|
790
|
+
const lineTime = (text, prefix) => {
|
|
791
|
+
const line = text.split('\n').find((entry) => entry.startsWith(`${prefix} `));
|
|
792
|
+
return line === undefined ? undefined : Number(line.split(' ')[1]);
|
|
793
|
+
};
|
|
794
|
+
|
|
795
|
+
/** One worker session; `firstLine` resolves with the first JSON line it prints, `result` when it ends. */
|
|
796
|
+
function runWorker(dir, project, holdMs, mode = 'sync', startAt = 0) {
|
|
797
|
+
const child = spawn(process.execPath, [WORKER, dir, project, String(startAt), String(holdMs), mode], { stdio: ['ignore', 'pipe', 'ignore'] });
|
|
798
|
+
let out = '';
|
|
799
|
+
let announced = false;
|
|
800
|
+
let announce = () => {};
|
|
801
|
+
const firstLine = new Promise((resolve) => {
|
|
802
|
+
announce = resolve;
|
|
803
|
+
});
|
|
804
|
+
const read = () => {
|
|
805
|
+
if (announced || !out.includes('\n')) return;
|
|
806
|
+
announced = true;
|
|
807
|
+
try {
|
|
808
|
+
announce(JSON.parse(out.trim().split('\n')[0]));
|
|
809
|
+
} catch {
|
|
810
|
+
announce({ pid: 0, requestedAt: 0, returnedAt: 0, outcome: { status: 'unavailable' } });
|
|
811
|
+
}
|
|
812
|
+
};
|
|
813
|
+
child.stdout.on('data', (chunk) => {
|
|
814
|
+
out += chunk;
|
|
815
|
+
read();
|
|
816
|
+
});
|
|
817
|
+
const result = new Promise((resolve) => {
|
|
818
|
+
child.on('close', () => {
|
|
819
|
+
read();
|
|
820
|
+
try {
|
|
821
|
+
resolve(JSON.parse(out.trim().split('\n')[0]));
|
|
822
|
+
} catch {
|
|
823
|
+
resolve({ pid: 0, requestedAt: 0, returnedAt: 0, outcome: { status: 'unavailable' } });
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
});
|
|
827
|
+
return { child, firstLine, result };
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
async function waitFor(check, what, deadlineMs = 60_000) {
|
|
831
|
+
const until = Date.now() + deadlineMs;
|
|
832
|
+
while (Date.now() < until) {
|
|
833
|
+
if (check()) return;
|
|
834
|
+
await pause(25);
|
|
835
|
+
}
|
|
836
|
+
assert.fail(`timed out waiting for ${what}`);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
/** The runs the workers recorded: their start and end. A run whose end was never written was killed. */
|
|
840
|
+
function recordedRuns(project) {
|
|
841
|
+
const intervals = [];
|
|
842
|
+
for (const line of ledgerText(project).split('\n').filter(Boolean)) {
|
|
843
|
+
const [kind, at] = line.split(' ');
|
|
844
|
+
if (kind === 'start') intervals.push({ start: Number(at), end: Number.POSITIVE_INFINITY });
|
|
845
|
+
else if (kind === 'end' && intervals.length > 0) intervals[intervals.length - 1].end = Number(at);
|
|
846
|
+
}
|
|
847
|
+
return intervals.filter((interval) => Number.isFinite(interval.end));
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
test('S3 real: sessions asking at the same instant: one runs, the others leave their demand to it, never two at once', { timeout: 120_000 }, async () => {
|
|
851
|
+
for (const sessions of [2, 3]) {
|
|
852
|
+
const { dir, project } = scratch();
|
|
853
|
+
const startAt = Date.now() + 2_000;
|
|
854
|
+
const results = await Promise.all(Array.from({ length: sessions }, () => runWorker(dir, project, 600, 'sync', startAt).result));
|
|
855
|
+
const runners = results.filter((result) => result.outcome.status === 'ran');
|
|
856
|
+
const waiters = results.filter((result) => result.outcome.status !== 'ran');
|
|
857
|
+
// A session whose marker lands after the runner's pending-requests snapshot legitimately becomes one
|
|
858
|
+
// follow-up of that run, so "exactly one runner" is stricter than the real guarantee. What must always hold:
|
|
859
|
+
// every demand served, nothing overlapped, at most one follow-up.
|
|
860
|
+
assert.ok(runners.length >= 1 && runners.length <= 2, `${sessions} sessions, at most one follow-up: ${JSON.stringify(results)}`);
|
|
861
|
+
assert.ok(waiters.every((result) => result.outcome.status === 'coalesced'), JSON.stringify(results));
|
|
862
|
+
const runs = recordedRuns(project);
|
|
863
|
+
assert.ok(runs.length >= 1 && runs.length <= 2, `${sessions} sessions, at most one follow-up: ${JSON.stringify(runs)}`);
|
|
864
|
+
for (let index = 1; index < runs.length; index++) {
|
|
865
|
+
assert.ok(runs[index].start >= runs[index - 1].end, `no two syncs overlapped: ${JSON.stringify(runs)}`);
|
|
866
|
+
}
|
|
867
|
+
for (const waiter of waiters) {
|
|
868
|
+
assert.ok(runs.some((entry) => entry.start >= waiter.requestedAt), `the demand of ${waiter.pid} was not lost: ${JSON.stringify(waiter)} ${JSON.stringify(runs)}`);
|
|
869
|
+
}
|
|
870
|
+
const leftovers = fs.readdirSync(dir).filter((entry) => entry.startsWith('pcs-sync-')).filter((entry) => fs.existsSync(path.join(dir, entry, 'run')));
|
|
871
|
+
assert.deepEqual(leftovers, [], `leftover leases in ${dir}`);
|
|
872
|
+
}
|
|
873
|
+
});
|
|
874
|
+
|
|
875
|
+
test('S3 real: a session that asks while another one is syncing is coalesced into exactly one follow-up', { timeout: 120_000 }, async () => {
|
|
876
|
+
const { dir, project } = scratch();
|
|
877
|
+
const running = runWorker(dir, project, 1500);
|
|
878
|
+
await waitFor(() => starts(ledgerText(project)) >= 1, 'the first run to start');
|
|
879
|
+
const requestedAt = Date.now();
|
|
880
|
+
const late = runWorker(dir, project, 100);
|
|
881
|
+
const [first, second] = await Promise.all([running.result, late.result]);
|
|
882
|
+
assert.deepEqual(first.outcome, { status: 'ran', ok: true });
|
|
883
|
+
assert.deepEqual(second.outcome, { status: 'coalesced' });
|
|
884
|
+
const runs = recordedRuns(project);
|
|
885
|
+
assert.equal(runs.length, 2, `one run plus exactly one follow-up: ${JSON.stringify(runs)}`);
|
|
886
|
+
assert.ok(runs[1].start >= runs[0].end, `the follow-up started after the run it was coalesced into: ${JSON.stringify(runs)}`);
|
|
887
|
+
assert.ok(runs[1].start >= requestedAt, 'the follow-up serves the request that arrived during the first run');
|
|
888
|
+
assert.ok(second.requestedAt <= runs[1].start);
|
|
889
|
+
});
|
|
890
|
+
|
|
891
|
+
test('S3 real: a request is not lost when the runner dies inside its follow-up, and is answered only by a completed run', { timeout: 120_000 }, async () => {
|
|
892
|
+
const { dir, project } = scratch();
|
|
893
|
+
const a = runWorker(dir, project, 1200);
|
|
894
|
+
await waitFor(() => starts(ledgerText(project)) >= 1, "A's run to start");
|
|
895
|
+
const b = runWorker(dir, project, 200);
|
|
896
|
+
await waitFor(() => starts(ledgerText(project)) >= 2, "A's follow-up to start");
|
|
897
|
+
a.child.kill('SIGKILL');
|
|
898
|
+
await a.result;
|
|
899
|
+
const bResult = await b.result;
|
|
900
|
+
// The follow-up never completed, so B was not told its demand was served: it takes the lease over and runs.
|
|
901
|
+
assert.deepEqual(bResult.outcome, { status: 'ran', ok: true }, `B served its own demand: ${JSON.stringify(bResult)}`);
|
|
902
|
+
const runs = recordedRuns(project);
|
|
903
|
+
assert.equal(runs.length, 2, `A's completed run and B's: ${JSON.stringify(runs)}`);
|
|
904
|
+
assert.ok(runs[1].start >= runs[0].end, "B's run started only after A's completed run");
|
|
905
|
+
const answered = runs.filter((run) => run.start >= bResult.requestedAt && run.end <= bResult.returnedAt);
|
|
906
|
+
assert.ok(answered.length >= 1, `B was answered by a run that started after it asked and had finished: ${JSON.stringify(runs)} ${JSON.stringify(bResult)}`);
|
|
907
|
+
});
|
|
908
|
+
|
|
909
|
+
test('S3 real: the CLI a killed session started is still an extension sync: the next session waits for it, then syncs', { timeout: 120_000 }, async () => {
|
|
910
|
+
const { dir, project } = scratch();
|
|
911
|
+
const a = runWorker(dir, project, 2500, 'sync-cli');
|
|
912
|
+
const started = await a.firstLine;
|
|
913
|
+
assert.equal(started.status, 'running');
|
|
914
|
+
assert.ok((started.cliPid || 0) > 0, JSON.stringify(started));
|
|
915
|
+
await waitFor(() => ledgerText(project).includes('cli-start'), 'the CLI to start writing the index');
|
|
916
|
+
a.child.kill('SIGKILL');
|
|
917
|
+
await a.result;
|
|
918
|
+
// A second session asks for a sync while the abandoned CLI is still writing.
|
|
919
|
+
const b = runWorker(dir, project, 100);
|
|
920
|
+
const bResult = await b.result;
|
|
921
|
+
assert.deepEqual(bResult.outcome, { status: 'ran', ok: true });
|
|
922
|
+
assert.ok(bResult.requestedAt < Date.now());
|
|
923
|
+
await waitFor(() => ledgerText(project).includes('cli-end'), 'the CLI to finish');
|
|
924
|
+
const runs = recordedRuns(project);
|
|
925
|
+
assert.equal(runs.length, 1, `the abandoned CLI's run never completed; only the second session's did: ${JSON.stringify(runs)}`);
|
|
926
|
+
const cliEnd = lineTime(ledgerText(project), 'cli-end');
|
|
927
|
+
const cliStart = lineTime(ledgerText(project), 'cli-start');
|
|
928
|
+
assert.ok(cliEnd !== undefined && cliStart !== undefined);
|
|
929
|
+
assert.ok(bResult.requestedAt < cliEnd, 'the second session asked while the abandoned CLI was still running');
|
|
930
|
+
assert.ok(runs[0].start >= cliEnd, `the next sync started only after the abandoned CLI ended: ${JSON.stringify(runs)}`);
|
|
931
|
+
assert.throws(() => process.kill(started.cliPid, 0), 'nothing was killed to get there');
|
|
932
|
+
});
|