Skip to content

Commit 3519428

Browse files
committed
test(mcp): cover concurrent settings creation with real lock
1 parent dcd729b commit 3519428

1 file changed

Lines changed: 176 additions & 0 deletions

File tree

Lines changed: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
1+
import * as fs from "fs/promises"
2+
import * as os from "os"
3+
import * as path from "path"
4+
5+
import * as lockfile from "proper-lockfile"
6+
7+
import type { ClineProvider } from "../../../core/webview/ClineProvider"
8+
9+
import { GlobalFileNames } from "../../../shared/globalFileNames"
10+
import { McpHub } from "../McpHub"
11+
12+
// McpHub loads the vscode module at import time. Watcher setup is skipped
13+
// because Vitest runs with NODE_ENV=test; the stub only keeps the module
14+
// graph loadable.
15+
vi.mock("vscode", () => ({
16+
workspace: {
17+
createFileSystemWatcher: vi.fn().mockReturnValue({
18+
onDidChange: vi.fn(),
19+
onDidCreate: vi.fn(),
20+
onDidDelete: vi.fn(),
21+
dispose: vi.fn(),
22+
}),
23+
onDidChangeWorkspaceFolders: vi.fn(),
24+
workspaceFolders: [],
25+
},
26+
window: {
27+
showErrorMessage: vi.fn(),
28+
showInformationMessage: vi.fn(),
29+
showWarningMessage: vi.fn(),
30+
},
31+
ProgressLocation: { Notification: 15 },
32+
Disposable: { from: vi.fn() },
33+
}))
34+
35+
// Pass-through spy on the real proper-lockfile. Production safeWriteJson and
36+
// this test share the same instrumented lock function, so the advisory lock,
37+
// its retry contention, and its release behavior all stay real.
38+
vi.mock("proper-lockfile", async () => {
39+
const actual = await vi.importActual<typeof import("proper-lockfile")>("proper-lockfile")
40+
return { ...actual, lock: vi.fn(actual.lock) }
41+
})
42+
43+
describe("McpHub initial settings creation (real filesystem)", () => {
44+
let tempDir: string
45+
let mcpHub: McpHub
46+
let mockProvider: Partial<ClineProvider>
47+
48+
beforeEach(async () => {
49+
vi.clearAllMocks()
50+
51+
tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "mcp-hub-settings-"))
52+
53+
mockProvider = {
54+
cwd: tempDir,
55+
ensureSettingsDirectoryExists: vi.fn().mockResolvedValue(tempDir),
56+
postMessageToWebview: vi.fn().mockResolvedValue(undefined),
57+
getState: vi.fn().mockResolvedValue({ mcpEnabled: true }),
58+
}
59+
60+
mcpHub = new McpHub(mockProvider as ClineProvider)
61+
// The constructor creates the stub settings file through the real
62+
// safeWriteJson creation path. Remove it so the test starts from a
63+
// machine without any MCP settings file.
64+
await mcpHub.waitUntilReady()
65+
await fs.rm(path.join(tempDir, GlobalFileNames.mcpSettings), { force: true })
66+
})
67+
68+
afterEach(async () => {
69+
await mcpHub.dispose()
70+
await fs.rm(tempDir, { recursive: true, force: true })
71+
vi.restoreAllMocks()
72+
})
73+
74+
it("preserves a config written under the advisory lock by a concurrent creator (#1371)", async () => {
75+
const settingsPath = path.join(tempDir, GlobalFileNames.mcpSettings)
76+
const concurrentConfig = {
77+
mcpServers: {
78+
"concurrent-server": { type: "stdio", command: "node", args: ["server.js"] },
79+
},
80+
}
81+
82+
let releaseB: () => Promise<void> = async () => {}
83+
let bLockReleased = false
84+
let creation: Promise<string> | undefined
85+
try {
86+
// Writer B (a lock-aware competing process) takes the real advisory
87+
// lock before writer A's creation pass starts. proper-lockfile can
88+
// lock a path whose target does not exist yet, so the file is still
89+
// absent at this point.
90+
releaseB = await lockfile.lock(settingsPath, { realpath: false })
91+
92+
// Gate writer A's lock attempt. The wrapper forwards to the real
93+
// proper-lockfile lock, records the in-flight acquisition promise,
94+
// and signals the moment A calls it inside production safeWriteJson.
95+
const actualLock = (await vi.importActual<typeof import("proper-lockfile")>("proper-lockfile")).lock
96+
let aLockAttempt: ReturnType<typeof lockfile.lock> | undefined
97+
let signalALockAttempted: () => void = () => {}
98+
const aLockAttempted = new Promise<void>((resolve) => {
99+
signalALockAttempted = resolve
100+
})
101+
vi.mocked(lockfile.lock).mockImplementationOnce(async (filePath, options) => {
102+
aLockAttempt = actualLock(filePath, options)
103+
signalALockAttempted()
104+
return aLockAttempt
105+
})
106+
107+
// Writer A enters the initial-creation path. The file is still
108+
// absent, so its existence check resolves false while B holds the
109+
// lock; the result is stale the moment B writes.
110+
creation = mcpHub.getMcpSettingsFilePath()
111+
112+
// A must reach the real lock acquisition while B holds the lock.
113+
// If production safeWriteJson ever bypassed lockfile.lock, A would
114+
// finish the clobbering write first and this race rejects.
115+
await Promise.race([
116+
aLockAttempted,
117+
creation.then(() => {
118+
throw new Error("safeWriteJson completed without acquiring the advisory lock")
119+
}),
120+
])
121+
122+
// The lock B holds is genuinely enforced at the filesystem level.
123+
// realpath: false stats only the .lock path; the settings file is
124+
// still absent at this point.
125+
expect(await lockfile.check(settingsPath, { realpath: false })).toBe(true)
126+
127+
// Writer B commits a real configuration under its lock while A
128+
// waits, which is what makes A's earlier false result stale.
129+
await fs.writeFile(settingsPath, JSON.stringify(concurrentConfig), "utf-8")
130+
131+
// A must still be blocked on B's lock. Acquiring the lock needs
132+
// B's release, which only a macrotask can complete, so a settled
133+
// attempt would flip the flag during this microtask drain.
134+
let aLockSettled = false
135+
void aLockAttempt?.then(
136+
() => {
137+
aLockSettled = true
138+
},
139+
() => {
140+
aLockSettled = true
141+
},
142+
)
143+
await Promise.resolve()
144+
expect(aLockSettled).toBe(false)
145+
146+
// Releasing B lets A's retry acquire the lock. The locked merge
147+
// read then sees B's committed config instead of clobbering it.
148+
await releaseB()
149+
bLockReleased = true
150+
151+
const returnedPath = await creation
152+
153+
expect(returnedPath).toBe(settingsPath)
154+
155+
// The creation pass must not clobber the concurrent config with the
156+
// empty default stub.
157+
const content = JSON.parse(await fs.readFile(settingsPath, "utf-8"))
158+
expect(content).toEqual(concurrentConfig)
159+
160+
// The creation pass leaves no temp, backup, or lock artifacts
161+
// behind.
162+
const leftovers = (await fs.readdir(tempDir)).filter((entry) => entry !== GlobalFileNames.mcpSettings)
163+
expect(leftovers).toEqual([])
164+
} finally {
165+
// Failure paths must not leak B's lock or leave writer A pending as
166+
// an unhandled rejection. Awaiting a settled creation is free; on a
167+
// failure path it unblocks A before afterEach removes the temp dir.
168+
if (!bLockReleased) {
169+
await releaseB().catch(() => {})
170+
}
171+
if (creation) {
172+
await creation.catch(() => {})
173+
}
174+
}
175+
})
176+
})

0 commit comments

Comments
 (0)