perf: drop per-acquire existsSync stat from file lock fast path
tryAcquire() ran fs.existsSync(dir) on every lock acquisition to lazily create the
lock directory. The dir almost always already exists (team dirs are created up
front), so that stat was wasted on every acquire — and the file-lock path churns
heavily during a launch (inbox writes, journals, task mutations all lock per write,
showing up as unlink/open/stat syscall load in the launch profile).
Attempt the openSync('wx') directly; only on ENOENT create the directory and retry
the acquire in the same call. Same locking semantics, same files, same first-acquire
latency for a missing dir — just one fewer stat per acquire in the common case.
This commit is contained in:
parent
c8d40be460
commit
635321dd9a
1 changed files with 23 additions and 7 deletions
|
|
@ -69,18 +69,34 @@ function removeLockPath(lockPath: string): void {
|
|||
}
|
||||
}
|
||||
|
||||
function writeLockFile(lockPath: string): void {
|
||||
const fd = fs.openSync(lockPath, 'wx');
|
||||
fs.writeSync(fd, `${process.pid}\n${Date.now()}\n`);
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
|
||||
function tryAcquire(lockPath: string, options: Required<FileLockOptions>): boolean {
|
||||
try {
|
||||
const dir = path.dirname(lockPath);
|
||||
if (!fs.existsSync(dir)) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
const fd = fs.openSync(lockPath, 'wx');
|
||||
fs.writeSync(fd, `${process.pid}\n${Date.now()}\n`);
|
||||
fs.closeSync(fd);
|
||||
// Fast path: assume the lock directory already exists (the common case once a
|
||||
// team dir is created). This drops an existsSync(dir) stat from EVERY acquire,
|
||||
// which adds up across the many lock cycles during a team launch.
|
||||
writeLockFile(lockPath);
|
||||
return true;
|
||||
} catch (err) {
|
||||
const code = (err as NodeJS.ErrnoException).code;
|
||||
if (code === 'ENOENT') {
|
||||
// Lock directory missing — create it lazily and acquire in the same call, so
|
||||
// first-acquire latency in a fresh dir is unchanged.
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(lockPath), { recursive: true });
|
||||
writeLockFile(lockPath);
|
||||
return true;
|
||||
} catch {
|
||||
// Lost a race (another process created the dir/lock) or still failing —
|
||||
// fall through to a normal retry on the next loop iteration.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (code === 'EEXIST' || code === 'EISDIR') {
|
||||
if (shouldBreakExistingLock(lockPath, options.staleTimeoutMs)) {
|
||||
removeLockPath(lockPath);
|
||||
|
|
|
|||
Loading…
Reference in a new issue