Skip to content

Commit f3ba3bf

Browse files
Merge pull request #189 from devarshishimpi/fix/e2e-playwright-hardening
fix(e2e): harden server lifecycle and environment isolation
2 parents b0c1b6e + d81de69 commit f3ba3bf

6 files changed

Lines changed: 324 additions & 54 deletions

File tree

‎CONTRIBUTING.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -100,17 +100,19 @@ npm run test:watch
100100
npm run typecheck
101101
```
102102

103-
104103
### Browser E2E tests
105104

106105
Browser tests live in `playwright/`, separate from the existing Vitest/JSDOM tests under `test/`. The Playwright setup runs one Chromium smoke test against the real local Node server and uses a synthetic signed-out session response; it does not sign in to GitHub or call a real LLM provider.
107106

108107
Requirements: Node.js 24+, Docker, and disposable local PostgreSQL and Redis services.
109108

110109
```bash
110+
# Clean up any leftover test containers from a previous run
111+
docker rm -f codra-e2e-postgres codra-e2e-redis 2>/dev/null || true
112+
111113
# Start isolated local services (keep these separate from any real Codra data).
112-
docker run -d --name codra-e2e-postgres -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=codra_e2e -p 5432:5432 postgres:16
113-
docker run -d --name codra-e2e-redis -p 6379:6379 redis:7-alpine
114+
docker run -d --name codra-e2e-postgres -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=codra_e2e -p 127.0.0.1:5432:5432 postgres:16
115+
docker run -d --name codra-e2e-redis -p 127.0.0.1:6379:6379 redis:7-alpine
114116

115117
# Use only the synthetic values in this file.
116118
cp .env.e2e.example .env.e2e
@@ -120,15 +122,14 @@ npm ci
120122
npx playwright install chromium
121123
npm run test:e2e
122124

123-
# Stop the disposable services when finished.
124-
docker stop codra-e2e-postgres codra-e2e-redis
125+
# Stop and remove the disposable services when finished.
126+
docker rm -f codra-e2e-postgres codra-e2e-redis 2>/dev/null || true
125127
```
126128

127129
`npm run test:e2e` builds the Node server and dashboard, then Playwright starts the Node server on `http://localhost:3000` automatically. The launcher reads `.env.e2e`, generates a throwaway GitHub App private key for server initialization, disables the background review worker and telemetry, and never needs real GitHub, OAuth, or LLM credentials. The smoke test stubs only `GET /api/auth/session` as signed out. No database migration or seeded application data is needed for this first smoke test; keep `DATABASE_URL` pointed at the disposable database above.
128130

129131
The browser output is written to `test-results/` and `playwright-report/`; both are gitignored. To inspect the HTML report after a run, use `npx playwright show-report`.
130132

131-
132133
---
133134

134135
## Contributing to Documentation

‎apps/node/src/index.ts‎

Lines changed: 126 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,9 @@ if (process.env.START_WORKER !== "false") {
100100
logger.info("BullMQ Background Worker started.");
101101
}
102102

103+
let server: ReturnType<typeof serve> | undefined;
103104
if (process.env.START_API !== "false") {
104-
const server = serve(
105+
server = serve(
105106
{
106107
fetch: async (request) => {
107108
const apiEnv = {
@@ -147,32 +148,140 @@ import("@codraoss/models").then(({ ModelRegistryService }) => {
147148
(timer as unknown as { unref?: () => void }).unref?.();
148149
}).catch(() => {});
149150

150-
const shutdown = async () => {
151+
const withTimeout = async <T>(promise: Promise<T>, timeoutMs: number, label: string): Promise<T> => {
152+
let timer: NodeJS.Timeout | undefined;
153+
const timeoutPromise = new Promise<never>((_, reject) => {
154+
timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
155+
timer.unref?.();
156+
});
157+
try {
158+
return await Promise.race([promise, timeoutPromise]);
159+
} finally {
160+
if (timer) clearTimeout(timer);
161+
}
162+
};
163+
164+
let isShuttingDown = false;
165+
let shutdownStartTime = 0;
166+
const shutdown = async (signal?: string) => {
167+
const now = Date.now();
168+
if (isShuttingDown) {
169+
if (now - shutdownStartTime > 100) {
170+
logger.warn("Repeated shutdown signal received, forcing immediate exit.");
171+
process.exit(signal === "SIGINT" ? 130 : 143);
172+
}
173+
return;
174+
}
175+
isShuttingDown = true;
176+
shutdownStartTime = now;
177+
178+
const globalShutdownTimeout = setTimeout(() => {
179+
logger.error("Global shutdown timed out after 10000ms. Forcing immediate exit.");
180+
process.exit(1);
181+
}, 10000);
182+
globalShutdownTimeout.unref?.();
183+
151184
logger.info("Shutting down Codra Node server...");
152185

153-
// Close BullMQ worker
186+
let exitCode = 0;
187+
188+
// 1. Close HTTP server listener
189+
if (server) {
190+
try {
191+
logger.info("Closing HTTP server listener...");
192+
await new Promise<void>((resolve, reject) => {
193+
let isDone = false;
194+
const finish = (err?: unknown) => {
195+
if (isDone) return;
196+
isDone = true;
197+
clearTimeout(drainTimer);
198+
clearTimeout(hardTimer);
199+
if (err) reject(err);
200+
else resolve();
201+
};
202+
203+
const drainTimer = setTimeout(() => {
204+
(server as unknown as { closeAllConnections?: () => void })?.closeAllConnections?.();
205+
}, 3000);
206+
drainTimer.unref?.();
207+
208+
const hardTimer = setTimeout(() => {
209+
finish(new Error("HTTP server listener close timed out after 5000ms"));
210+
}, 5000);
211+
hardTimer.unref?.();
212+
213+
server?.close((err) => {
214+
if (err) finish(err);
215+
else finish();
216+
});
217+
});
218+
logger.info("HTTP server listener closed.");
219+
} catch (err) {
220+
logger.error("Error closing HTTP server listener:", err);
221+
exitCode = 1;
222+
}
223+
}
224+
225+
// 2. Close BullMQ worker
154226
if (worker) {
155-
logger.info("Waiting for active BullMQ jobs to finish...");
156-
await worker.close();
157-
logger.info("BullMQ Worker closed gracefully.");
227+
try {
228+
logger.info("Waiting for active BullMQ jobs to finish...");
229+
await withTimeout(worker.close(), 4000, "BullMQ worker close");
230+
logger.info("BullMQ Worker closed gracefully.");
231+
} catch (err) {
232+
logger.error("Error closing BullMQ worker:", err);
233+
exitCode = 1;
234+
}
158235
}
159236

160-
// Close Redis connection
237+
// 3. Close BullMQ queue
238+
if (reviewQueue) {
239+
try {
240+
await withTimeout(reviewQueue.close(), 2000, "BullMQ reviewQueue close");
241+
} catch (err) {
242+
logger.error("Error closing reviewQueue:", err);
243+
exitCode = 1;
244+
}
245+
}
246+
247+
// 4. Close Redis connection
161248
if (redisClient) {
162-
logger.info("Closing Redis client...");
163-
await redisClient.quit();
164-
logger.info("Redis client closed.");
249+
try {
250+
logger.info("Closing Redis client...");
251+
await withTimeout(redisClient.quit(), 2000, "Redis client quit");
252+
logger.info("Redis client closed.");
253+
} catch (err) {
254+
logger.error("Error closing Redis client:", err);
255+
try {
256+
redisClient.disconnect();
257+
} catch {
258+
// Disconnect fallback
259+
}
260+
exitCode = 1;
261+
}
165262
}
166263

167-
// Close Postgres client pool
264+
// 5. Close Postgres client pool
168265
if (dbClient?.close) {
169-
logger.info("Closing Postgres client...");
170-
await dbClient.close();
171-
logger.info("Postgres client closed.");
266+
try {
267+
logger.info("Closing Postgres client...");
268+
await withTimeout(dbClient.close(), 2000, "Postgres client close");
269+
logger.info("Postgres client closed.");
270+
} catch (err) {
271+
logger.error("Error closing Postgres client:", err);
272+
exitCode = 1;
273+
}
172274
}
173275

174-
logger.info("All services stopped. Exiting.");
276+
clearTimeout(globalShutdownTimeout);
277+
278+
if (exitCode === 0) {
279+
logger.info("All services stopped. Exiting.");
280+
} else {
281+
logger.error("Services stopped with errors. Exiting.");
282+
}
283+
process.exit(exitCode);
175284
};
176285

177-
process.on("SIGTERM", shutdown);
178-
process.on("SIGINT", shutdown);
286+
process.on("SIGTERM", () => shutdown("SIGTERM"));
287+
process.on("SIGINT", () => shutdown("SIGINT"));

‎package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
"devDependencies": {
5151
"@arethetypeswrong/cli": "^0.18.5",
5252
"@eslint/js": "^10.0.1",
53+
"@playwright/test": "1.65.1",
5354
"@tailwindcss/vite": "^4.2.4",
5455
"@testing-library/dom": "^10.4.2",
5556
"@testing-library/react": "^16.3.3",
@@ -73,8 +74,7 @@
7374
"typescript-eslint": "^8.66.0",
7475
"vite": "^8.0.16",
7576
"vitest": "^4.1.11",
76-
"wrangler": "^4.114.0",
77-
"@playwright/test": "1.65.1"
77+
"wrangler": "^4.114.0"
7878
},
7979
"dependencies": {
8080
"@base-ui/react": "^1.6.0",

‎playwright.config.ts‎

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,72 @@
1+
import { readFileSync } from "node:fs";
2+
import path from "node:path";
3+
import { fileURLToPath } from "node:url";
14
import { defineConfig, devices } from "@playwright/test";
25

3-
const baseURL = "http://localhost:3000";
6+
function loadE2eEnv(): Record<string, string> {
7+
const rootDir = path.dirname(fileURLToPath(import.meta.url));
8+
const envPath = path.join(rootDir, ".env.e2e");
9+
try {
10+
const content = readFileSync(envPath, "utf8");
11+
const parsed: Record<string, string> = {};
12+
for (const line of content.split(/\r?\n/)) {
13+
const trimmed = line.trim();
14+
if (!trimmed || trimmed.startsWith("#")) continue;
15+
const idx = trimmed.indexOf("=");
16+
if (idx > 0) {
17+
let val = trimmed.slice(idx + 1).trim();
18+
if (
19+
(val.startsWith('"') && val.endsWith('"')) ||
20+
(val.startsWith("'") && val.endsWith("'"))
21+
) {
22+
val = val.slice(1, -1);
23+
}
24+
parsed[trimmed.slice(0, idx).trim()] = val;
25+
}
26+
}
27+
return parsed;
28+
} catch (error) {
29+
if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
30+
return {};
31+
}
32+
throw error;
33+
}
34+
}
35+
36+
const e2eEnv = loadE2eEnv();
37+
const port = e2eEnv.PORT || process.env.PORT || "3000";
38+
let baseURL = `http://localhost:${port}`;
39+
// Prioritize .env.e2e APP_URL over ambient environment to preserve isolation
40+
const configuredUrl = e2eEnv.APP_URL || process.env.APP_URL;
41+
if (configuredUrl) {
42+
try {
43+
const parsedUrl = new URL(configuredUrl);
44+
if (parsedUrl.protocol !== "http:") {
45+
throw new Error(`E2E APP_URL must use http: protocol, got "${parsedUrl.protocol}".`);
46+
}
47+
if (parsedUrl.username || parsedUrl.password) {
48+
throw new Error("E2E APP_URL must not contain authentication credentials.");
49+
}
50+
if (parsedUrl.pathname !== "/" && parsedUrl.pathname !== "") {
51+
throw new Error(`E2E APP_URL must not include a path, got "${parsedUrl.pathname}".`);
52+
}
53+
if (parsedUrl.search || parsedUrl.hash) {
54+
throw new Error("E2E APP_URL must not include query parameters or hash fragments.");
55+
}
56+
if (parsedUrl.hostname !== "localhost" && parsedUrl.hostname !== "127.0.0.1") {
57+
throw new Error(
58+
`E2E APP_URL must point to a loopback address (localhost or 127.0.0.1), got "${configuredUrl}".`,
59+
);
60+
}
61+
parsedUrl.port = port;
62+
baseURL = parsedUrl.origin;
63+
} catch (err) {
64+
if (err instanceof Error && err.message.startsWith("E2E APP_URL")) {
65+
throw err;
66+
}
67+
throw new Error(`Invalid APP_URL in e2e configuration: "${configuredUrl}"`, { cause: err });
68+
}
69+
}
470

571
export default defineConfig({
672
testDir: "./playwright",
@@ -28,5 +94,7 @@ export default defineConfig({
2894
url: baseURL,
2995
reuseExistingServer: false,
3096
timeout: 120_000,
97+
stdout: "pipe",
98+
stderr: "pipe",
3199
},
32100
});

‎playwright/smoke.spec.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@ import { expect, test } from "@playwright/test";
33
test("signed-out visitors see the GitHub sign-in page", async ({ page }) => {
44
// Keep this smoke test independent of OAuth, Redis session state, and any
55
// real GitHub account. The browser still loads the built dashboard from the
6-
// local Node server; only the session lookup is given a deterministic result.
6+
// local Node server; only the session lookup is given a deterministic result
7+
// matching the server's signed-out 401 response.
78
await page.route("**/api/auth/session", async (route) => {
89
await route.fulfill({
9-
status: 200,
10+
status: 401,
1011
contentType: "application/json",
11-
body: JSON.stringify({ user: null }),
12+
body: JSON.stringify({ error: "Unauthorized" }),
1213
});
1314
});
1415

0 commit comments

Comments
 (0)