Skip to content

Commit ba51ec2

Browse files
committed
test: move process lock test helpers to fixtures and share the guard intercept
process-lock.test.ts crossed the 1,000-line test tripwire. Its helpers move to process-lock.fixtures.ts and the three guard interleaving tests share one first-open intercept.
1 parent 0637af1 commit ba51ec2

2 files changed

Lines changed: 61 additions & 68 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import fs from 'node:fs';
2+
import { vi } from 'vitest';
3+
import { readProcessStartTime } from './host-process.ts';
4+
import type { ProcessLockOwner } from './process-lock.ts';
5+
6+
export function currentProcessOwner(): ProcessLockOwner {
7+
return {
8+
pid: process.pid,
9+
startTime: readProcessStartTime(process.pid),
10+
acquiredAtMs: Date.now(),
11+
};
12+
}
13+
14+
export function stampDirectoryAbandoned(directory: string): void {
15+
const abandoned = new Date(Date.now() - 60_000);
16+
fs.utimesSync(directory, abandoned, abandoned);
17+
}
18+
19+
/** A reclaim that finishes leaves neither a parked directory nor a mutex behind. */
20+
export function listReclaimSiblings(directory: string): string[] {
21+
return fs
22+
.readdirSync(directory)
23+
.filter((entry) => entry.includes('.reclaim'))
24+
.sort();
25+
}
26+
27+
/** Runs `action` the first time a contender opens the guard file, before the open itself. */
28+
export function onFirstGuardOpen(mutexPath: string, action: () => void) {
29+
let fired = false;
30+
const realOpen = fs.openSync;
31+
const spy = vi.spyOn(fs, 'openSync').mockImplementation(((
32+
target: fs.PathLike,
33+
flags: fs.OpenMode,
34+
mode?: fs.Mode,
35+
) => {
36+
if (String(target) === mutexPath && !fired) {
37+
fired = true;
38+
action();
39+
}
40+
return realOpen(target, flags, mode);
41+
}) as typeof fs.openSync);
42+
return { fired: () => fired, restore: () => spy.mockRestore() };
43+
}

‎packages/host-kit/src/internal/process-lock.test.ts‎

Lines changed: 18 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -30,12 +30,16 @@ import {
3030
tryAcquireProcessLock,
3131
inspectProcessLock,
3232
withProcessLock,
33-
type ProcessLockOwner,
3433
type ProcessLockRelease,
3534
} from './process-lock.ts';
36-
import { readProcessStartTime } from './host-process.ts';
3735
import { mkdtempForTestSync } from './tmp-dir.fixtures.ts';
3836
import { holdLegacyReclaimMutex } from './legacy-process-lock.fixtures.ts';
37+
import {
38+
currentProcessOwner,
39+
listReclaimSiblings,
40+
onFirstGuardOpen,
41+
stampDirectoryAbandoned,
42+
} from './process-lock.fixtures.ts';
3943

4044
let tmpDir: string;
4145

@@ -301,14 +305,6 @@ test('one abandoned lock offered to two contenders is held by exactly one of the
301305
assert.deepEqual(listReclaimSiblings(tmpDir), []);
302306
});
303307

304-
/** A reclaim that finishes leaves neither a parked directory nor a mutex behind. */
305-
function listReclaimSiblings(directory: string): string[] {
306-
return fs
307-
.readdirSync(directory)
308-
.filter((entry) => entry.includes('.reclaim'))
309-
.sort();
310-
}
311-
312308
const UNINFORMATIVE_OWNER_RECORDS = [
313309
'{ pid: ',
314310
'null',
@@ -468,17 +464,7 @@ test('a contender that claims the path during a reclaim keeps its lock', async (
468464
// The moment a contender is admitted to judging this lock, another process clears the dead
469465
// claim and publishes its own. Nothing is removed: the record re-read under the mutex names a
470466
// claim token the dead one cannot answer to, and the judge walks away from the path.
471-
let claimed = false;
472-
const realOpen = fs.openSync;
473-
const guardSpy = vi.spyOn(fs, 'openSync').mockImplementation(((
474-
target: fs.PathLike,
475-
flags: fs.OpenMode,
476-
mode?: fs.Mode,
477-
) => {
478-
if (String(target) !== mutexPath || claimed) {
479-
return realOpen(target, flags, mode);
480-
}
481-
claimed = true;
467+
const guard = onFirstGuardOpen(mutexPath, () => {
482468
fs.rmSync(lockDirPath, { recursive: true, force: true });
483469
fs.mkdirSync(lockDirPath);
484470
fs.writeFileSync(
@@ -492,8 +478,7 @@ test('a contender that claims the path during a reclaim keeps its lock', async (
492478
claimToken: 'contender-claim',
493479
}),
494480
);
495-
return realOpen(target, flags, mode);
496-
}) as typeof fs.openSync);
481+
});
497482

498483
try {
499484
await assert.rejects(
@@ -511,15 +496,15 @@ test('a contender that claims the path during a reclaim keeps its lock', async (
511496
return true;
512497
},
513498
);
514-
assert.equal(claimed, true);
499+
assert.equal(guard.fired(), true);
515500
const record = JSON.parse(fs.readFileSync(ownerFilePath, 'utf8')) as {
516501
pid: number;
517502
claimToken: string;
518503
};
519504
assert.equal(record.pid, process.ppid);
520505
assert.equal(record.claimToken, 'contender-claim');
521506
} finally {
522-
guardSpy.mockRestore();
507+
guard.restore();
523508
}
524509
});
525510

@@ -535,17 +520,7 @@ test('a claim published while a reclaim holds the mutex outlives the empty direc
535520

536521
// Writing the record is also what re-dates the directory, which is the fact the reclaim re-asks
537522
// for under its mutex before it removes anything.
538-
let published = false;
539-
const realOpen = fs.openSync;
540-
const guardSpy = vi.spyOn(fs, 'openSync').mockImplementation(((
541-
target: fs.PathLike,
542-
flags: fs.OpenMode,
543-
mode?: fs.Mode,
544-
) => {
545-
if (String(target) !== mutexPath || published) {
546-
return realOpen(target, flags, mode);
547-
}
548-
published = true;
523+
const guard = onFirstGuardOpen(mutexPath, () => {
549524
fs.writeFileSync(
550525
ownerFilePath,
551526
// See the contender above: another process's claim names another pid.
@@ -556,8 +531,7 @@ test('a claim published while a reclaim holds the mutex outlives the empty direc
556531
claimToken: 'late-claim',
557532
}),
558533
);
559-
return realOpen(target, flags, mode);
560-
}) as typeof fs.openSync);
534+
});
561535

562536
try {
563537
await assert.rejects(
@@ -574,12 +548,12 @@ test('a claim published while a reclaim holds the mutex outlives the empty direc
574548
return true;
575549
},
576550
);
577-
assert.equal(published, true);
551+
assert.equal(guard.fired(), true);
578552
assert.equal(fs.existsSync(lockDirPath), true);
579553
const record = JSON.parse(fs.readFileSync(ownerFilePath, 'utf8')) as { claimToken: string };
580554
assert.equal(record.claimToken, 'late-claim');
581555
} finally {
582-
guardSpy.mockRestore();
556+
guard.restore();
583557
}
584558
});
585559

@@ -591,23 +565,12 @@ test('a lock directory made anew while a reclaim holds the mutex is not the one
591565

592566
// Replacing the directory rather than filling it is what a contender that won the path looks
593567
// like from the inside: same name, same emptiness, and an age that says it was never abandoned.
594-
let replaced = false;
595568
let refilledAtMs = 0;
596-
const realOpen = fs.openSync;
597-
const guardSpy = vi.spyOn(fs, 'openSync').mockImplementation(((
598-
target: fs.PathLike,
599-
flags: fs.OpenMode,
600-
mode?: fs.Mode,
601-
) => {
602-
if (String(target) !== mutexPath || replaced) {
603-
return realOpen(target, flags, mode);
604-
}
605-
replaced = true;
569+
const guard = onFirstGuardOpen(mutexPath, () => {
606570
fs.rmSync(lockDirPath, { recursive: true, force: true });
607571
fs.mkdirSync(lockDirPath);
608572
refilledAtMs = fs.statSync(lockDirPath).mtimeMs;
609-
return realOpen(target, flags, mode);
610-
}) as typeof fs.openSync);
573+
});
611574

612575
try {
613576
await assert.rejects(
@@ -623,14 +586,14 @@ test('a lock directory made anew while a reclaim holds the mutex is not the one
623586
return true;
624587
},
625588
);
626-
assert.equal(replaced, true);
589+
assert.equal(guard.fired(), true);
627590
assert.equal(
628591
fs.statSync(lockDirPath).mtimeMs,
629592
refilledAtMs,
630593
'the reclaim removed a directory it had not judged abandoned',
631594
);
632595
} finally {
633-
guardSpy.mockRestore();
596+
guard.restore();
634597
}
635598
});
636599

@@ -826,19 +789,6 @@ test('a completed task still reports a lock it could not give back', async () =>
826789
);
827790
});
828791

829-
function stampDirectoryAbandoned(directory: string): void {
830-
const abandoned = new Date(Date.now() - 60_000);
831-
fs.utimesSync(directory, abandoned, abandoned);
832-
}
833-
834-
function currentProcessOwner(): ProcessLockOwner {
835-
return {
836-
pid: process.pid,
837-
startTime: readProcessStartTime(process.pid),
838-
acquiredAtMs: Date.now(),
839-
};
840-
}
841-
842792
test('one nonblocking attempt acquires, refuses a live claim, and invalidates its released handle', async () => {
843793
const lockDirPath = path.join(tmpDir, 'one-attempt.lock');
844794
const first = tryAcquireProcessLock({ lockDirPath, owner: currentProcessOwner() });

0 commit comments

Comments
 (0)