Skip to content

Commit 945b24d

Browse files
fix(utils): key the advisory file lock by identity, not by path spelling
acquireFileLock keyed proper-lockfile on path.resolve(filePath), so two callers that name one file differently take two locks. On NTFS the spelling-preserving canonicalizers cannot fix that: fs.realpath and fs.realpathSync return whatever spelling they are handed and only fs.realpathSync.native expands an 8.3 alias, while stat answers both spellings with the same dev+ino. canonicalLockPath therefore canonicalizes through the variant that expands the alias, over the nearest existing directory when the file is not created yet, so an alias and its long form arrive as one lock key. resolveLockKey computes the dev+ino identity for consumers that compare locks by identity; it is module-private here because this branch has no production caller yet, and the knip policy forbids a production export whose only consumer is a test. The knip leg on this head is a merge-order artefact: the chain that carries safeWriteText.ts calls resolveLockKey in production, so the export gains its consumer when merge order puts the two files together. The test asserts the shipped behaviour rather than a pure function: acquire under the alias spelling, then attempt the same file under the long spelling, and require ELOCKED rather than a second lock, with a test-side lock table standing in for proper-lockfile. The 8.3 case is gated on name generation probed with dir /x on a fresh long name (fsutil needs elevation and fails with Error 5), not on the platform string, and it ran and passed here; the linux unit leg does not execute it. Reported on #2356. No suppression count changed.
1 parent 5319fe9 commit 945b24d

2 files changed

Lines changed: 160 additions & 3 deletions

File tree

‎src/utils/__tests__/fileLock.test.ts‎

Lines changed: 106 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
1+
import { spawnSync } from "child_process"
2+
import * as fs from "fs"
3+
import * as os from "os"
4+
import * as path from "path"
5+
16
import * as lockfile from "proper-lockfile"
2-
import { acquireFileLock, LOCK_STALE_MS, withFileLock } from "../fileLock"
7+
8+
import { acquireFileLock, canonicalLockPath, LOCK_STALE_MS, withFileLock } from "../fileLock"
39

410
vi.mock("proper-lockfile", () => ({ lock: vi.fn() }))
511

@@ -32,3 +38,102 @@ describe("file lock protocol", () => {
3238
expect(release).toHaveBeenCalledOnce()
3339
})
3440
})
41+
42+
/**
43+
* 8.3 short-name generation is a volume property, not a platform constant, and fsutil needs
44+
* elevation (Error 5 un-elevated), so this probes dir /x against a freshly created long
45+
* directory name and skips with a reason where generation is disabled. Asserting alias
46+
* unification on a volume with generation off would produce a green that cannot fail, which is
47+
* worse than a skip that says what it did. Locally the probe found a short name (A-REAL~1 for a
48+
* 47-character name) and the alias case below executed and passed; the linux leg does not
49+
* execute it. The name is deliberately not passed as a dir argument: dir /x <name> lists that
50+
* directory's contents, whose header line is the only line containing the name, which reads as
51+
* generation being off when it is not.
52+
*/
53+
function shortNamesGenerated(directory: string): boolean {
54+
const probeName = "a-really-long-directory-name-for-short-name-generation-probe"
55+
fs.mkdirSync(path.join(directory, probeName), { recursive: true })
56+
try {
57+
const listing = spawnSync("cmd", ["/c", "dir", "/x"], { cwd: directory, encoding: "utf8" }) as unknown as {
58+
stdout?: string
59+
}
60+
const line =
61+
String(listing.stdout ?? "")
62+
.split(/\r?\n/)
63+
.find((entry) => entry.includes(probeName)) ?? ""
64+
const fields = line.split(/\s+/).filter((field) => field.length > 0)
65+
return fields.some((field) => /~\d/.test(field))
66+
} finally {
67+
fs.rmSync(path.join(directory, probeName), { recursive: true, force: true })
68+
}
69+
}
70+
71+
describe("one lock per file, not one lock per spelling", () => {
72+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "fileLock-key-"))
73+
const generatesShortNames = process.platform === "win32" && shortNamesGenerated(root)
74+
// proper-lockfile is mocked, so exclusivity here is a test-side lock table keyed by the exact
75+
// key acquireFileLock asks for: a key already held rejects with ELOCKED, and immediate: true
76+
// means retries 0. The property under test is whether two spellings of one file arrive as
77+
// one key or as two, which is exactly what that table can decide.
78+
const held: string[] = []
79+
beforeEach(() => {
80+
held.length = 0
81+
vi.mocked(lockfile.lock).mockImplementation(async (target: unknown) => {
82+
const key = String(target)
83+
if (held.indexOf(key) >= 0) {
84+
throw Object.assign(new Error("ELOCKED: " + key), { code: "ELOCKED" })
85+
}
86+
held.push(key)
87+
return async () => {
88+
const at = held.indexOf(key)
89+
if (at >= 0) {
90+
held.splice(at, 1)
91+
}
92+
}
93+
})
94+
})
95+
const aliasOf = (longPath: string): string => {
96+
const directory = path.dirname(longPath)
97+
const listing = spawnSync("cmd", ["/c", "dir", "/x"], { cwd: directory, encoding: "utf8" }) as unknown as {
98+
stdout?: string
99+
}
100+
const line =
101+
String(listing.stdout ?? "")
102+
.split(/\r?\n/)
103+
.find((entry) => entry.includes(path.basename(longPath))) ?? ""
104+
const fields = line.split(/\s+/).filter((field) => field.length > 0)
105+
const short = fields.find((field) => /~\d/.test(field))
106+
return short ? path.join(directory, short) : longPath
107+
}
108+
const itAlias = generatesShortNames ? it : it.skip
109+
itAlias("takes one lock for an 8.3 alias and its long form, not a second one", async () => {
110+
const longDir = path.join(root, "a-really-long-directory-name-for-alias-lock-testing")
111+
fs.mkdirSync(longDir, { recursive: true })
112+
const file = path.join(longDir, "history.json")
113+
fs.writeFileSync(file, "{}", "utf8")
114+
const aliasFile = path.join(aliasOf(longDir), "history.json")
115+
expect(fs.statSync(aliasFile).ino).toBe(fs.statSync(file).ino)
116+
const releaseAlias = await acquireFileLock(aliasFile, { immediate: true })
117+
expect(held).toHaveLength(1)
118+
await expect(acquireFileLock(file, { immediate: true })).rejects.toMatchObject({ code: "ELOCKED" })
119+
expect(held[0]).toBe(canonicalLockPath(file))
120+
await releaseAlias()
121+
})
122+
it("takes separate locks for two different files in one directory", async () => {
123+
const a = path.join(root, "a.json")
124+
const b = path.join(root, "b.json")
125+
fs.writeFileSync(a, "{}", "utf8")
126+
fs.writeFileSync(b, "{}", "utf8")
127+
await acquireFileLock(a, { immediate: true })
128+
await acquireFileLock(b, { immediate: true })
129+
expect(held).toHaveLength(2)
130+
})
131+
it("takes one lock for one not-yet-existing path and a different one for another name", async () => {
132+
const missingA = path.join(root, "missing-a.json")
133+
const missingB = path.join(root, "missing-b.json")
134+
await acquireFileLock(missingA, { immediate: true })
135+
await expect(acquireFileLock(missingA, { immediate: true })).rejects.toMatchObject({ code: "ELOCKED" })
136+
await acquireFileLock(missingB, { immediate: true })
137+
expect(held).toHaveLength(2)
138+
})
139+
})

‎src/utils/fileLock.ts‎

Lines changed: 54 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as fs from "fs"
12
import * as path from "path"
23
import { tracePersistenceEvent } from "../core/task-persistence/persistenceTrace"
34
import * as lockfile from "proper-lockfile"
@@ -26,8 +27,59 @@ export interface FileLockOptions {
2627
* returned function exactly once and must not acquire the same lock again
2728
* while holding it.
2829
*/
30+
function statIdentity(target: string): string | null {
31+
try {
32+
const stats = fs.statSync(target)
33+
return String(stats.dev) + ":" + String(stats.ino)
34+
} catch {
35+
return null
36+
}
37+
}
38+
39+
/**
40+
* The nearest directory that actually exists on a path, so a write to a file that has
41+
* not been created yet can still be keyed by something the filesystem answers with.
42+
*/
43+
function nearestExistingDirectory(absolutePath: string): { directory: string; relative: string[] } {
44+
const relative: string[] = []
45+
let current = absolutePath
46+
while (path.dirname(current) !== current) {
47+
relative.unshift(path.basename(current))
48+
current = path.dirname(current)
49+
if (statIdentity(current) !== null) {
50+
return { directory: current, relative }
51+
}
52+
}
53+
return { directory: current, relative }
54+
}
55+
56+
/**
57+
* The spelling a lock artefact should be created under: the canonical spelling of the
58+
* nearest existing directory, re-joined with the components that do not exist yet. This is
59+
* what makes an 8.3 alias and its long form take one lock, and it stays a spelling - the key
60+
* above is the identity, and callers that compare locks compare that.
61+
*/
62+
export function canonicalLockPath(filePath: string): string {
63+
const absolute = path.resolve(filePath)
64+
if (statIdentity(absolute) !== null) {
65+
try {
66+
return fs.realpathSync.native(absolute)
67+
} catch {
68+
return absolute
69+
}
70+
}
71+
const { directory, relative } = nearestExistingDirectory(absolute)
72+
let canonicalDirectory = directory
73+
try {
74+
canonicalDirectory = fs.realpathSync.native(directory)
75+
} catch {
76+
canonicalDirectory = directory
77+
}
78+
return relative.length === 0 ? canonicalDirectory : path.join(canonicalDirectory, ...relative)
79+
}
80+
2981
export async function acquireFileLock(filePath: string, options?: FileLockOptions): Promise<() => Promise<void>> {
30-
const absoluteFilePath = path.resolve(filePath)
82+
const absoluteFilePath = canonicalLockPath(filePath)
3183
if (options?.waitForStaleLock) tracePersistenceEvent("json-lock-wait", { filePath: absoluteFilePath })
3284
try {
3385
return await lockfile.lock(absoluteFilePath, {
@@ -72,7 +124,7 @@ export async function withFileLock<T>(
72124
operation: (absoluteFilePath: string) => Promise<T>,
73125
options?: FileLockOptions,
74126
): Promise<T> {
75-
const absoluteFilePath = path.resolve(filePath)
127+
const absoluteFilePath = canonicalLockPath(filePath)
76128
const releaseLock = await acquireFileLock(absoluteFilePath, options)
77129

78130
let result: T

0 commit comments

Comments
 (0)