-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlive-compose-review-path.mjs
More file actions
483 lines (424 loc) · 13.5 KB
/
Copy pathlive-compose-review-path.mjs
File metadata and controls
483 lines (424 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
/* global clearTimeout, setTimeout */
import { randomBytes } from "node:crypto";
import { spawn, spawnSync } from "node:child_process";
import { createServer } from "node:net";
import path from "node:path";
import process from "node:process";
import { fileURLToPath } from "node:url";
const SCRIPT_DIRECTORY = path.dirname(fileURLToPath(import.meta.url));
const REPOSITORY_ROOT = path.resolve(SCRIPT_DIRECTORY, "..");
const COMPOSE_FILE = path.join(REPOSITORY_ROOT, "docker-compose.yml");
const COMPOSE_REVIEW_OVERRIDE_FILE = path.join(REPOSITORY_ROOT, "docker-compose.live-review.yml");
const API_TEST_FILE = path.join(
REPOSITORY_ROOT,
"apps",
"api",
"dist",
".test-dist",
"test",
"live-compose-review-path.js",
);
const PROJECT_NAME = `repomentor-live-review-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;
const RUN_BROWSER = process.argv.includes("--browser");
const BROWSER_RUN_FLAG = "REPOMENTOR_LIVE_COMPOSE_REVIEW_BROWSER";
const API_PORT_ENV = "REPOMENTOR_LIVE_COMPOSE_API_PORT";
const WEB_ORIGIN_ENV = "REPOMENTOR_LIVE_COMPOSE_WEB_ORIGIN";
const E2E_API_ORIGIN_ENV = "REPOMENTOR_E2E_API_ORIGIN";
const E2E_WEB_PORT_ENV = "REPOMENTOR_E2E_WEB_PORT";
const PROJECT_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/u;
const INHERITED_ENV_NAMES = new Set([
"APPDATA",
"COMSPEC",
"DOCKER_CERT_PATH",
"DOCKER_CONTEXT",
"DOCKER_HOST",
"DOCKER_TLS_VERIFY",
"HOME",
"HOMEDRIVE",
"HOMEPATH",
"LOCALAPPDATA",
"OS",
"PATH",
"PATHEXT",
"PROCESSOR_ARCHITECTURE",
"PROGRAMDATA",
"PROGRAMFILES",
"PROGRAMFILES(X86)",
"SYSTEMDRIVE",
"SYSTEMROOT",
"TEMP",
"TMP",
"USERPROFILE",
"WINDIR",
"XDG_CONFIG_HOME",
]);
const BLOCKED_ENV_NAMES = new Set([
"DEEPSEEK_API_BASE_URL",
"DEEPSEEK_API_KEY",
"LUNA_API_BASE_URL",
"LUNA_API_KEY",
"OPENAI_API_BASE_URL",
"OPENAI_API_KEY",
]);
if (!PROJECT_NAME_PATTERN.test(PROJECT_NAME)) {
throw new Error("Generated Compose project name failed its safety check.");
}
function sanitizedEnvironment(overrides) {
const environment = {};
for (const [name, value] of Object.entries(process.env)) {
const normalizedName = name.toUpperCase();
if (INHERITED_ENV_NAMES.has(normalizedName) && !BLOCKED_ENV_NAMES.has(normalizedName)) {
environment[name] = value;
}
}
return { ...environment, ...overrides };
}
function redactOutput(value) {
return String(value)
.replace(/(postgres(?:ql)?:\/\/[^\s/]+:)[^@\s]+@/giu, "$1[REDACTED]@")
.replace(/(redis:\/\/:[^@\s]+@)/giu, "redis://:[REDACTED]@");
}
function run(command, args, environment, label, useShell = false) {
const result = spawnSync(command, args, {
cwd: REPOSITORY_ROOT,
encoding: "utf8",
env: environment,
shell: useShell,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
});
if (result.error || result.status !== 0) {
const details = redactOutput(`${result.stdout ?? ""}\n${result.stderr ?? ""}`).trim();
throw new Error(
`${label} failed (${result.error?.message ?? `exit ${result.status ?? "unknown"}`}).${
details ? `\n${details.slice(-4000)}` : ""
}`,
);
}
return `${result.stdout ?? ""}${result.stderr ?? ""}`;
}
function docker(composeEnvironment, args, label) {
return run(
"docker",
[
"compose",
"--file",
COMPOSE_FILE,
"--file",
COMPOSE_REVIEW_OVERRIDE_FILE,
"--project-name",
PROJECT_NAME,
...args,
],
composeEnvironment,
label,
);
}
function pnpm(testEnvironment, args, label) {
const command = process.platform === "win32" ? "pnpm.cmd" : "pnpm";
return run(command, args, testEnvironment, label, process.platform === "win32");
}
function startApiServer(environment, apiPort, webOrigin) {
const child = spawn(process.execPath, [API_TEST_FILE], {
cwd: REPOSITORY_ROOT,
env: {
...environment,
[BROWSER_RUN_FLAG]: "1",
[API_PORT_ENV]: String(apiPort),
[WEB_ORIGIN_ENV]: webOrigin,
},
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
});
let output = "";
let ready = false;
let exited = false;
let exitCode = null;
let exitSignal = null;
const appendOutput = (chunk) => {
output = `${output}${chunk}`.slice(-12_000);
};
child.stdout.on("data", (chunk) => {
appendOutput(chunk.toString());
});
child.stderr.on("data", (chunk) => {
appendOutput(chunk.toString());
});
const readyMarker = `Live Compose browser API ready on http://127.0.0.1:${apiPort}.`;
const waitForReady = new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject(new Error(`Timed out waiting for the live API server.\n${redactOutput(output)}`));
}, 120_000);
const settleReady = () => {
if (ready || !output.includes(readyMarker)) {
return;
}
ready = true;
clearTimeout(timeout);
resolve();
};
child.stdout.on("data", settleReady);
child.stderr.on("data", settleReady);
child.once("error", (error) => {
if (!ready) {
clearTimeout(timeout);
reject(error);
}
});
child.once("exit", (code, signal) => {
exited = true;
exitCode = code;
exitSignal = signal;
if (!ready) {
clearTimeout(timeout);
reject(
new Error(
`Live API server exited before readiness (code ${code ?? "none"}, signal ${signal ?? "none"}).\n${redactOutput(output)}`,
),
);
}
});
});
const waitForExit = () =>
exited
? Promise.resolve()
: new Promise((resolve) => {
child.once("exit", resolve);
});
const stop = async () => {
if (!exited) {
child.stdin.write("shutdown\n");
const forceKillTimeout = setTimeout(() => {
if (!exited) {
child.kill("SIGKILL");
}
}, 30_000);
await waitForExit();
clearTimeout(forceKillTimeout);
}
if (exitCode !== 0) {
throw new Error(
`Live API server exited with code ${exitCode ?? "none"}, signal ${exitSignal ?? "none"}.\n${redactOutput(output)}`,
);
}
const expectedFakeAiRequests = RUN_BROWSER ? 2 : 1;
if (!output.includes(`FakeAiRequests=${expectedFakeAiRequests} ExternalFetchCalls=0.`)) {
throw new Error(`Live API provider/fetch evidence was incomplete.\n${redactOutput(output)}`);
}
};
return { child, output: () => output, stop, waitForReady };
}
function findAvailablePort() {
return new Promise((resolve, reject) => {
const server = createServer();
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (address === null || typeof address === "string") {
server.close();
reject(new Error("Could not resolve a free loopback port."));
return;
}
server.close((error) => {
if (error) {
reject(error);
return;
}
resolve(address.port);
});
});
});
}
function resourceIds(environment, resourceType) {
const listArguments = [resourceType, "ls"];
if (resourceType === "container") {
listArguments.push("--all");
}
listArguments.push("--quiet", "--filter", `label=com.docker.compose.project=${PROJECT_NAME}`);
const output = run("docker", listArguments, environment, `list Compose ${resourceType}`);
return output
.split(/\r?\n/u)
.map((line) => line.trim())
.filter((line) => line !== "");
}
function assertProjectResourcesAreOwned(environment, ids, resourceType) {
for (const id of ids) {
const raw = run(
"docker",
[resourceType, "inspect", id],
environment,
`inspect ${resourceType}`,
);
const records = JSON.parse(raw);
const labels = records[0]?.Config?.Labels ?? records[0]?.Labels ?? {};
if (labels["com.docker.compose.project"] !== PROJECT_NAME) {
throw new Error(`Refusing cleanup: ${resourceType} ${id} is not owned by ${PROJECT_NAME}.`);
}
}
}
function assertProjectIsUnused(environment) {
for (const resourceType of ["container", "volume", "network"]) {
const ids = resourceIds(environment, resourceType);
if (ids.length > 0) {
throw new Error(`Generated Compose project name is already in use: ${PROJECT_NAME}.`);
}
}
}
function cleanup(environment) {
for (const resourceType of ["container", "volume", "network"]) {
const ids = resourceIds(environment, resourceType);
assertProjectResourcesAreOwned(environment, ids, resourceType);
}
docker(environment, ["down", "--volumes", "--remove-orphans"], "Compose cleanup");
for (const resourceType of ["container", "volume", "network"]) {
const ids = resourceIds(environment, resourceType);
if (ids.length > 0) {
throw new Error(`Compose cleanup left ${resourceType} resources for ${PROJECT_NAME}.`);
}
}
}
const suffix = randomBytes(8).toString("hex");
const postgresDatabase = `repomentor_live_${suffix}`;
const postgresUser = `repomentor_live_${suffix.slice(0, 12)}`;
const postgresPassword = `compose_dummy_${suffix}`;
const redisPassword = `compose_dummy_${suffix}`;
const allocatedPorts = [];
for (let index = 0; index < 4; index += 1) {
const port = await findAvailablePort();
if (allocatedPorts.includes(port)) {
index -= 1;
continue;
}
allocatedPorts.push(port);
}
const [apiHostPort, webHostPort, postgresHostPort, redisHostPort] = allocatedPorts.map(String);
const composeEnvironment = sanitizedEnvironment({
API_HOST_PORT: apiHostPort,
CORS_ORIGINS: `http://127.0.0.1:${webHostPort}`,
COOKIE_SAME_SITE: "lax",
COOKIE_SECURE: "false",
DATABASE_URL: `postgresql://${postgresUser}:${postgresPassword}@postgres:5432/${postgresDatabase}`,
GUEST_QUICK_REVIEWS_PER_DAY: "0",
JWT_ACCESS_SECRET: `compose_dummy_access_${suffix}_0123456789abcdef`,
JWT_REFRESH_SECRET: `compose_dummy_refresh_${suffix}_fedcba9876543210`,
NEXT_PUBLIC_API_ORIGIN: `http://127.0.0.1:${apiHostPort}`,
NODE_ENV: "test",
POSTGRES_DB: postgresDatabase,
POSTGRES_HOST_PORT: postgresHostPort,
POSTGRES_PASSWORD: postgresPassword,
POSTGRES_USER: postgresUser,
QUOTA_ADMISSION_FINGERPRINT_SECRET: `compose_dummy_quota_${suffix}_0123456789abcdef`,
REDIS_HOST_PORT: redisHostPort,
REDIS_PASSWORD: redisPassword,
REDIS_URL: `redis://:${redisPassword}@redis:6379/0`,
USER_DEEP_REVIEWS_PER_DAY: "3",
USER_QUICK_REVIEWS_PER_DAY: "1",
USER_STANDARD_REVIEWS_PER_DAY: "10",
WEB_HOST_PORT: webHostPort,
});
let projectClaimed = false;
let failure;
process.stdout.write(`Starting opt-in live Compose review path for project ${PROJECT_NAME}.\n`);
try {
docker(composeEnvironment, ["config", "--quiet"], "Compose configuration");
assertProjectIsUnused(composeEnvironment);
projectClaimed = true;
docker(
composeEnvironment,
["up", "--detach", "--wait", "postgres", "redis"],
"Compose PostgreSQL and Redis startup",
);
const testEnvironment = sanitizedEnvironment({
...composeEnvironment,
DATABASE_URL: `postgresql://${postgresUser}:${postgresPassword}@127.0.0.1:${postgresHostPort}/${postgresDatabase}`,
REDIS_URL: `redis://:${redisPassword}@127.0.0.1:${redisHostPort}/0`,
["REPOMENTOR_LIVE_COMPOSE_REVIEW_PATH"]: "1",
});
pnpm(testEnvironment, ["db:migrate"], "Prisma migration deploy");
pnpm(testEnvironment, ["--filter", "@repomentor/api", "run", "build:test"], "API test build");
let testOutput;
if (!RUN_BROWSER) {
testOutput = pnpm(
testEnvironment,
[
"--filter",
"@repomentor/api",
"exec",
"node",
"dist/.test-dist/test/live-compose-review-path.js",
],
"live Compose review test",
);
} else {
const webOrigin = `http://127.0.0.1:${webHostPort}`;
const apiServer = startApiServer(testEnvironment, apiHostPort, webOrigin);
let browserFailure;
let shutdownFailure;
try {
await apiServer.waitForReady;
testOutput = pnpm(
sanitizedEnvironment({
...testEnvironment,
[BROWSER_RUN_FLAG]: "1",
[E2E_API_ORIGIN_ENV]: `http://127.0.0.1:${apiHostPort}`,
[E2E_WEB_PORT_ENV]: webHostPort,
}),
[
"--filter",
"@repomentor/web",
"exec",
"playwright",
"test",
"e2e/live-compose-review-journey.spec.ts",
"--config=playwright.config.ts",
],
"live browser review journey",
);
} catch (error) {
browserFailure = error;
} finally {
try {
await apiServer.stop();
} catch (error) {
shutdownFailure = error;
}
}
if (browserFailure && shutdownFailure) {
const browserMessage =
browserFailure instanceof Error ? browserFailure.message : String(browserFailure);
const shutdownMessage =
shutdownFailure instanceof Error ? shutdownFailure.message : String(shutdownFailure);
throw new Error(
`Live browser run and shutdown failed.\n${browserMessage}\n${shutdownMessage}`,
);
}
if (browserFailure) {
throw browserFailure;
}
if (shutdownFailure) {
throw shutdownFailure;
}
}
process.stdout.write(testOutput);
} catch (error) {
failure = error;
} finally {
if (projectClaimed) {
try {
cleanup(composeEnvironment);
} catch (error) {
failure ??= error;
process.stderr.write(
`${error instanceof Error ? error.message : "Compose cleanup failed."}\n`,
);
}
}
}
if (failure) {
process.stderr.write(
`${failure instanceof Error ? failure.message : "Live Compose review path failed."}\n`,
);
process.exitCode = 1;
} else {
process.stdout.write(`Cleaned exact Compose project ${PROJECT_NAME}.\n`);
}