Skip to content

Commit 8572655

Browse files
authored
test(qa): join fixture owners before removing resources (#133821)
1 parent 1f8ea99 commit 8572655

7 files changed

Lines changed: 431 additions & 69 deletions

‎test/e2e/qa-lab/plugins/discord-show-widget-contextual-presenter.e2e.test.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,8 @@ function writeJson(res: ServerResponse, statusCode: number, value: unknown): voi
9595

9696
async function startDiscordRestLoopback() {
9797
const requests: DiscordRestRequest[] = [];
98-
const server = createServer(async (req, res) => {
99-
try {
98+
const server = createServer((req, res) => {
99+
void (async () => {
100100
const pathname = new URL(req.url ?? "/", "http://127.0.0.1").pathname;
101101
const method = req.method ?? "GET";
102102
const payload = await readRequestBody(req);
@@ -110,9 +110,9 @@ async function startDiscordRestLoopback() {
110110
return;
111111
}
112112
writeJson(res, 404, { message: `unexpected Discord REST request: ${method} ${pathname}` });
113-
} catch (error) {
113+
})().catch((error: unknown) => {
114114
writeJson(res, 500, { message: error instanceof Error ? error.message : String(error) });
115-
}
115+
});
116116
});
117117
await new Promise<void>((resolve, reject) => {
118118
server.once("error", reject);
@@ -126,9 +126,9 @@ async function startDiscordRestLoopback() {
126126
baseUrl: `http://127.0.0.1:${address.port}`,
127127
requests,
128128
stop: async () =>
129-
await new Promise<void>((resolve, reject) =>
130-
server.close((error) => (error ? reject(error) : resolve())),
131-
),
129+
await new Promise<void>((resolve, reject) => {
130+
server.close((error) => (error ? reject(error) : resolve()));
131+
}),
132132
};
133133
}
134134

‎test/e2e/qa-lab/runtime/gateway-compaction-abort.ts‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,8 @@ async function runCases(runtime: Runtime, repoRoot: string, artifactBase: string
491491
path.join(artifactBase, "channel-transcript.json"),
492492
`${JSON.stringify(state.getSnapshot().messages, null, 2)}\n`,
493493
);
494+
} catch (error) {
495+
failures.push(error instanceof Error ? error.message : String(error));
494496
} finally {
495497
active?.releaseSummary.resolve();
496498
active?.releaseAfterHook.resolve();
@@ -538,6 +540,11 @@ async function runCases(runtime: Runtime, repoRoot: string, artifactBase: string
538540
await provider?.stop();
539541
},
540542
() => bus.stop(),
543+
async () => {
544+
if (cleanupErrors.length === 0) {
545+
await fs.writeFile(path.join(tmpRoot, "gateway-stopped"), "confirmed\n");
546+
}
547+
},
541548
];
542549
for (const stop of cleanup) {
543550
try {
@@ -547,9 +554,10 @@ async function runCases(runtime: Runtime, repoRoot: string, artifactBase: string
547554
}
548555
}
549556
if (cleanupErrors.length) {
550-
throw new AggregateError(cleanupErrors, "Gateway proof cleanup failed");
557+
failures.push(
558+
`Gateway proof cleanup failed: ${cleanupErrors.map((error) => (error instanceof Error ? error.message : String(error))).join("; ")}`,
559+
);
551560
}
552-
await fs.writeFile(path.join(tmpRoot, "gateway-stopped"), "confirmed\n");
553561
}
554562
return failures;
555563
}

‎test/e2e/qa-lab/runtime/gateway-mcp-app-grant-revalidation.e2e.test.ts‎

Lines changed: 2 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { randomUUID } from "node:crypto";
2-
import { watch } from "node:fs";
32
import fs from "node:fs/promises";
43
import path from "node:path";
54
import { isRecord } from "@openclaw/normalization-core/record-coerce";
@@ -20,55 +19,15 @@ import {
2019
createChildEnv,
2120
startHttpFixture,
2221
stopChild,
22+
waitForMcpFixtureGate,
2323
type GatewayHandle,
2424
type HttpFixture,
2525
} from "./gateway-node-mcp.test-support.js";
2626

2727
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
28-
const GATE_WAIT_TIMEOUT_MS = 30_000;
2928
const APP_TOOL_NAME = "streamableHttp__parity_app";
3029
const POST_REVOCATION_MARKER = "post-revocation";
3130

32-
async function waitForFile(filePath: string): Promise<void> {
33-
try {
34-
await fs.access(filePath);
35-
return;
36-
} catch (error) {
37-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
38-
throw error;
39-
}
40-
}
41-
await new Promise<void>((resolve, reject) => {
42-
const timeout = setTimeout(() => {
43-
watcher.close();
44-
reject(new Error(`timed out waiting for fixture gate: ${path.basename(filePath)}`));
45-
}, GATE_WAIT_TIMEOUT_MS);
46-
timeout.unref();
47-
const finish = (error?: unknown) => {
48-
clearTimeout(timeout);
49-
watcher.close();
50-
error ? reject(error) : resolve();
51-
};
52-
const inspect = () => {
53-
void fs.access(filePath).then(
54-
() => finish(),
55-
(error: NodeJS.ErrnoException) => {
56-
if (error.code !== "ENOENT") {
57-
finish(error);
58-
}
59-
},
60-
);
61-
};
62-
const watcher = watch(path.dirname(filePath), (_event, filename) => {
63-
if (!filename || filename.toString() === path.basename(filePath)) {
64-
inspect();
65-
}
66-
});
67-
watcher.once("error", finish);
68-
inspect();
69-
});
70-
}
71-
7231
function requireMcpAppViewId(messages: unknown[]): string {
7332
for (const message of messages) {
7433
if (!isRecord(message) || message.toolName !== APP_TOOL_NAME || !isRecord(message.details)) {
@@ -298,7 +257,7 @@ describe("Gateway MCP App board grant revalidation", () => {
298257
expect(notificationCall.status).toBe(200);
299258

300259
pendingCall = postStandalone({ gateway, ticket, marker: POST_REVOCATION_MARKER });
301-
await waitForFile(startedPath);
260+
await waitForMcpFixtureGate(startedPath);
302261
await gateway.call("board.update", {
303262
sessionKey,
304263
ops: [{ kind: "widget_remove", name: widget.name }],

‎test/e2e/qa-lab/runtime/gateway-node-mcp.test-support.test.ts‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,93 @@
1+
import { once } from "node:events";
2+
import nodeFs from "node:fs";
13
import fs from "node:fs/promises";
24
import os from "node:os";
35
import path from "node:path";
46
import { afterEach, describe, expect, it, vi } from "vitest";
7+
import { createDeferred } from "../../../helpers/promise.js";
58
import { useAutoCleanupTempDirTracker } from "../../../helpers/temp-dir.js";
69
import {
710
createChildEnv,
811
parseNodeMcpTextRecord,
912
processIsAlive,
1013
startHttpFixture,
1114
stopChild,
15+
waitForMcpFixtureGate,
1216
} from "./gateway-node-mcp.test-support.js";
1317

1418
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
1519

1620
describe("gateway node MCP fixture ownership", () => {
21+
it.each(["existing", "published"] as const)(
22+
"joins its watcher when the gate is %s",
23+
async (mode) => {
24+
const root = tempDirs.make("mcp-gate-publication-");
25+
const gate = path.join(root, "gate");
26+
if (mode === "existing") {
27+
await fs.writeFile(gate, "ready");
28+
}
29+
const watching = createDeferred<nodeFs.FSWatcher>();
30+
const watch = nodeFs.watch;
31+
const observeWatch = vi.fn((...args: Parameters<typeof watch>) => {
32+
const watcher = watch(...args);
33+
watching.resolve(watcher);
34+
return watcher;
35+
});
36+
vi.resetModules();
37+
vi.doMock("node:fs", () => ({ ...nodeFs, watch: observeWatch }));
38+
const { waitForMcpFixtureGate: waitForGate } =
39+
await import("./gateway-node-mcp.test-support.js");
40+
let watcher: nodeFs.FSWatcher | undefined;
41+
const waiting = waitForGate(gate);
42+
try {
43+
if (mode === "published") {
44+
watcher = await watching.promise;
45+
const closed = once(watcher, "close");
46+
await fs.writeFile(gate, "ready");
47+
await waiting;
48+
await closed;
49+
} else {
50+
await waiting;
51+
expect(observeWatch).not.toHaveBeenCalled();
52+
}
53+
expect(await fs.readFile(gate, "utf8")).toBe("ready");
54+
} finally {
55+
watcher?.close();
56+
await waiting;
57+
vi.doUnmock("node:fs");
58+
vi.resetModules();
59+
}
60+
},
61+
);
62+
63+
it("releases its deadline when the real gate watcher cannot be constructed", async () => {
64+
const root = tempDirs.make("mcp-gate-watch-failure-");
65+
const timers = vi.spyOn(globalThis, "setTimeout");
66+
const cleared = vi.spyOn(globalThis, "clearTimeout");
67+
try {
68+
await expect(waitForMcpFixtureGate(path.join(root, "missing", "gate"))).rejects.toMatchObject(
69+
{
70+
code: "ENOENT",
71+
syscall: "watch",
72+
},
73+
);
74+
const allocated = timers.mock.results.flatMap((result, index) =>
75+
result.type === "return" && timers.mock.calls[index]?.[1] === 30_000 ? [result.value] : [],
76+
);
77+
expect(
78+
allocated.filter((timer) => !cleared.mock.calls.some(([value]) => value === timer)).length,
79+
).toBe(0);
80+
} finally {
81+
for (const result of timers.mock.results) {
82+
if (result.type === "return") {
83+
clearTimeout(result.value);
84+
}
85+
}
86+
timers.mockRestore();
87+
cleared.mockRestore();
88+
}
89+
});
90+
1791
it.each([
1892
["direct", (payload: object) => payload],
1993
["node.invoke", (payload: object) => ({ ok: true, payload })],

‎test/e2e/qa-lab/runtime/gateway-node-mcp.test-support.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
11
import { spawn, type ChildProcess } from "node:child_process";
22
import { randomUUID } from "node:crypto";
33
import { once } from "node:events";
4+
import { watch } from "node:fs";
5+
import fs from "node:fs/promises";
46
import path from "node:path";
57
import { createInterface } from "node:readline";
68
import { setTimeout as delay } from "node:timers/promises";
9+
import { toErrorObject } from "@openclaw/normalization-core/error-coercion";
710
import { isRecord } from "@openclaw/normalization-core/record-coerce";
811
import { expect, vi } from "vitest";
912
import type { QaGatewayChild } from "../../../../extensions/qa-lab/api.js";
1013
import type { NodePluginToolDescriptor } from "../../../../packages/gateway-protocol/src/schema/nodes.js";
1114
import type { McpServerConfig } from "../../../../src/config/types.mcp.js";
15+
import { hasErrnoCode } from "../../../../src/infra/errno.js";
1216
import { signalProcessTree } from "../../../../src/process/kill-tree.js";
1317

1418
export const TEST_TIMEOUT_MS = 180_000;
@@ -59,6 +63,51 @@ export type ToolsEffectiveResult = {
5963

6064
const CHILD_ENV_KEYS = ["PATH", "PATHEXT", "SystemRoot", "WINDIR", "ComSpec"] as const;
6165

66+
export async function waitForMcpFixtureGate(filePath: string): Promise<void> {
67+
try {
68+
await fs.access(filePath);
69+
return;
70+
} catch (error) {
71+
if (!hasErrnoCode(error, "ENOENT")) {
72+
throw error;
73+
}
74+
}
75+
await new Promise<void>((resolve, reject) => {
76+
const finish = (error?: Error) => {
77+
clearTimeout(timeout);
78+
watcher.close();
79+
if (error) {
80+
reject(error);
81+
} else {
82+
resolve();
83+
}
84+
};
85+
const inspect = () => {
86+
void fs.access(filePath).then(
87+
() => finish(),
88+
(error: unknown) => {
89+
if (!hasErrnoCode(error, "ENOENT")) {
90+
finish(toErrorObject(error, "Fixture gate inspection failed"));
91+
}
92+
},
93+
);
94+
};
95+
const watcher = watch(path.dirname(filePath), (_event, filename) => {
96+
if (!filename || filename === path.basename(filePath)) {
97+
inspect();
98+
}
99+
});
100+
// watch() can throw synchronously; only a constructed watcher owns a deadline.
101+
const timeout = setTimeout(() => {
102+
watcher.close();
103+
reject(new Error(`timed out waiting for fixture gate: ${path.basename(filePath)}`));
104+
}, WAIT_TIMEOUT_MS);
105+
timeout.unref();
106+
watcher.once("error", finish);
107+
inspect();
108+
});
109+
}
110+
62111
function captureChild(child: ChildProcess): CapturedChild {
63112
let stdout = "";
64113
let stderr = "";

0 commit comments

Comments
 (0)