@open-qa/qa 0.0.0-stage → 0.1.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +204 -0
- package/NOTICE +7 -0
- package/THIRD_PARTY.md +12 -0
- package/THIRD_PARTY_NOTICES.md +11 -0
- package/drizzle/0000_qa_core.sql +158 -0
- package/drizzle/0001_run_health.sql +3 -0
- package/drizzle/0002_bounded_cleanup.sql +5 -0
- package/drizzle/0003_step_replay_cache.sql +9 -0
- package/drizzle/0004_credential_expiry.sql +1 -0
- package/drizzle/0005_server_api.sql +19 -0
- package/drizzle/0006_submission_created.sql +3 -0
- package/drizzle/0007_findings.sql +19 -0
- package/drizzle/0008_classification_labels.sql +14 -0
- package/drizzle/0009_job_queue.sql +20 -0
- package/drizzle/0010_result_notifications.sql +13 -0
- package/drizzle/0011_result_notification_retries.sql +5 -0
- package/drizzle/0012_result_notification_flows.sql +44 -0
- package/drizzle/0013_flow_quarantine.sql +35 -0
- package/drizzle/0014_run_budgets.sql +2 -0
- package/drizzle/0015_flow_lifecycle.sql +9 -0
- package/drizzle/0016_open_qa_classification.sql +28 -0
- package/drizzle/meta/0000_snapshot.json +1002 -0
- package/drizzle/meta/0001_snapshot.json +1021 -0
- package/drizzle/meta/0002_snapshot.json +1027 -0
- package/drizzle/meta/0003_snapshot.json +1081 -0
- package/drizzle/meta/0004_snapshot.json +1087 -0
- package/drizzle/meta/0005_snapshot.json +1210 -0
- package/drizzle/meta/0006_snapshot.json +1244 -0
- package/drizzle/meta/0007_snapshot.json +1353 -0
- package/drizzle/meta/0008_snapshot.json +1435 -0
- package/drizzle/meta/0009_snapshot.json +1587 -0
- package/drizzle/meta/0010_snapshot.json +1675 -0
- package/drizzle/meta/0011_snapshot.json +1692 -0
- package/drizzle/meta/0012_snapshot.json +1818 -0
- package/drizzle/meta/0013_snapshot.json +2016 -0
- package/drizzle/meta/0014_snapshot.json +2028 -0
- package/drizzle/meta/0015_snapshot.json +2064 -0
- package/drizzle/meta/0016_snapshot.json +2076 -0
- package/drizzle/meta/_journal.json +125 -0
- package/package.json +118 -4
- package/problem-matcher.json +32 -0
- package/src/adapters/db-lease-pool.d.ts +25 -0
- package/src/adapters/db-lease-pool.js +293 -0
- package/src/adapters/dir-artifact-store.d.ts +9 -0
- package/src/adapters/dir-artifact-store.js +64 -0
- package/src/adapters/e2b-agent.d.ts +7 -0
- package/src/adapters/e2b-agent.js +94 -0
- package/src/adapters/e2b-artifacts.d.ts +3 -0
- package/src/adapters/e2b-artifacts.js +66 -0
- package/src/adapters/e2b-bounded.d.ts +1 -0
- package/src/adapters/e2b-bounded.js +19 -0
- package/src/adapters/e2b-client.d.ts +33 -0
- package/src/adapters/e2b-client.js +114 -0
- package/src/adapters/e2b-executor.d.ts +26 -0
- package/src/adapters/e2b-executor.js +194 -0
- package/src/adapters/e2b-lifetime.d.ts +20 -0
- package/src/adapters/e2b-lifetime.js +73 -0
- package/src/adapters/e2b-prune.d.ts +13 -0
- package/src/adapters/e2b-prune.js +42 -0
- package/src/adapters/file-replay-cache.d.ts +14 -0
- package/src/adapters/file-replay-cache.js +120 -0
- package/src/adapters/file-run-store.d.ts +175 -0
- package/src/adapters/file-run-store.js +280 -0
- package/src/adapters/fixed-lease-pool.d.ts +10 -0
- package/src/adapters/fixed-lease-pool.js +237 -0
- package/src/adapters/gcs/artifact-store.d.ts +49 -0
- package/src/adapters/gcs/artifact-store.js +247 -0
- package/src/adapters/gcs/client.d.ts +22 -0
- package/src/adapters/gcs/client.js +106 -0
- package/src/adapters/gcs/download.d.ts +9 -0
- package/src/adapters/gcs/download.js +43 -0
- package/src/adapters/gcs/index.d.ts +8 -0
- package/src/adapters/gcs/index.js +23 -0
- package/src/adapters/gcs/periodic-flush.d.ts +5 -0
- package/src/adapters/gcs/periodic-flush.js +16 -0
- package/src/adapters/gcs/pg-catalog.d.ts +16 -0
- package/src/adapters/gcs/pg-catalog.js +149 -0
- package/src/adapters/gcs/replay-completeness.d.ts +1 -0
- package/src/adapters/gcs/replay-completeness.js +65 -0
- package/src/adapters/gcs/scan-upload.d.ts +10 -0
- package/src/adapters/gcs/scan-upload.js +26 -0
- package/src/adapters/index.d.ts +5 -0
- package/src/adapters/index.js +12 -0
- package/src/adapters/lease-transaction.d.ts +2 -0
- package/src/adapters/lease-transaction.js +61 -0
- package/src/adapters/local-credential-resolver.d.ts +5 -0
- package/src/adapters/local-credential-resolver.js +15 -0
- package/src/adapters/local-env.d.ts +1 -0
- package/src/adapters/local-env.js +37 -0
- package/src/adapters/local-files.d.ts +17 -0
- package/src/adapters/local-files.js +150 -0
- package/src/adapters/pg-classification-store.d.ts +58 -0
- package/src/adapters/pg-classification-store.js +112 -0
- package/src/adapters/pg-replay-cache.d.ts +16 -0
- package/src/adapters/pg-replay-cache.js +111 -0
- package/src/adapters/pg-run-store.d.ts +58 -0
- package/src/adapters/pg-run-store.js +399 -0
- package/src/adapters/resource-pools.d.ts +2 -0
- package/src/adapters/resource-pools.js +28 -0
- package/src/adapters/secret-manager-credential-resolver.d.ts +44 -0
- package/src/adapters/secret-manager-credential-resolver.js +102 -0
- package/src/artifact-scan.d.ts +21 -0
- package/src/artifact-scan.js +139 -0
- package/src/budget-confirmation.d.ts +23 -0
- package/src/budget-confirmation.js +43 -0
- package/src/cache-command.d.ts +7 -0
- package/src/cache-command.js +107 -0
- package/src/classification-command.d.ts +14 -0
- package/src/classification-command.js +72 -0
- package/src/classification-diff.d.ts +10 -0
- package/src/classification-diff.js +47 -0
- package/src/classification-model.d.ts +17 -0
- package/src/classification-model.js +51 -0
- package/src/classification-notifier.d.ts +21 -0
- package/src/classification-notifier.js +34 -0
- package/src/classify-runs.d.ts +31 -0
- package/src/classify-runs.js +138 -0
- package/src/cli-program.d.ts +9 -0
- package/src/cli-program.js +172 -0
- package/src/cli.d.ts +2 -0
- package/src/cli.js +12 -0
- package/src/commands.d.ts +7 -0
- package/src/commands.js +17 -0
- package/src/credential-references.d.ts +24 -0
- package/src/credential-references.js +33 -0
- package/src/db/commands.d.ts +1 -0
- package/src/db/commands.js +34 -0
- package/src/db/credentials.d.ts +16 -0
- package/src/db/credentials.js +73 -0
- package/src/db/database.d.ts +12 -0
- package/src/db/database.js +135 -0
- package/src/db/event-chunks.d.ts +405 -0
- package/src/db/event-chunks.js +74 -0
- package/src/db/fencing.d.ts +8 -0
- package/src/db/fencing.js +16 -0
- package/src/db/flow-status.d.ts +41 -0
- package/src/db/flow-status.js +208 -0
- package/src/db/index.d.ts +12 -0
- package/src/db/index.js +24 -0
- package/src/db/queries.d.ts +73 -0
- package/src/db/queries.js +122 -0
- package/src/db/resources.d.ts +14 -0
- package/src/db/resources.js +61 -0
- package/src/db/schema.d.ts +3532 -0
- package/src/db/schema.js +501 -0
- package/src/demo-command.d.ts +1 -0
- package/src/demo-command.js +50 -0
- package/src/doctor-command.d.ts +15 -0
- package/src/doctor-command.js +275 -0
- package/src/doctor-summary.d.ts +2 -0
- package/src/doctor-summary.js +31 -0
- package/src/draft-api.d.ts +460 -0
- package/src/draft-api.js +333 -0
- package/src/draft-command.d.ts +10 -0
- package/src/draft-command.js +73 -0
- package/src/draft-hooks.d.ts +3 -0
- package/src/draft-hooks.js +33 -0
- package/src/draft-pages.d.ts +11 -0
- package/src/draft-pages.js +82 -0
- package/src/engine.d.ts +105 -0
- package/src/engine.js +323 -0
- package/src/execution-snapshot.d.ts +21 -0
- package/src/execution-snapshot.js +141 -0
- package/src/flow-check.d.ts +9 -0
- package/src/flow-check.js +68 -0
- package/src/flow-lifecycle.d.ts +6 -0
- package/src/flow-lifecycle.js +61 -0
- package/src/flow-lint.d.ts +8 -0
- package/src/flow-lint.js +73 -0
- package/src/flow-loader.d.ts +219 -0
- package/src/flow-loader.js +236 -0
- package/src/flow-source.d.ts +2 -0
- package/src/flow-source.js +6 -0
- package/src/flows-api.d.ts +1 -0
- package/src/flows-api.js +12 -0
- package/src/heal-notification.d.ts +16 -0
- package/src/heal-notification.js +62 -0
- package/src/hooks/api.d.ts +29 -0
- package/src/hooks/api.js +15 -0
- package/src/hooks/consumer.d.ts +18 -0
- package/src/hooks/consumer.js +98 -0
- package/src/hooks/loader.d.ts +6 -0
- package/src/hooks/loader.js +28 -0
- package/src/hooks/registry.d.ts +22 -0
- package/src/hooks/registry.js +23 -0
- package/src/hooks/runner.d.ts +19 -0
- package/src/hooks/runner.js +279 -0
- package/src/hooks/session-cache.d.ts +16 -0
- package/src/hooks/session-cache.js +42 -0
- package/src/hooks/session-store.d.ts +20 -0
- package/src/hooks/session-store.js +95 -0
- package/src/hooks/worker.d.ts +1 -0
- package/src/hooks/worker.js +84 -0
- package/src/http-stage-client.d.ts +367 -0
- package/src/http-stage-client.js +190 -0
- package/src/independent-model.d.ts +22 -0
- package/src/independent-model.js +215 -0
- package/src/lifecycle-command.d.ts +15 -0
- package/src/lifecycle-command.js +190 -0
- package/src/local-command.d.ts +3 -0
- package/src/local-command.js +27 -0
- package/src/local-host-executor.d.ts +38 -0
- package/src/local-host-executor.js +196 -0
- package/src/open-command.d.ts +7 -0
- package/src/open-command.js +39 -0
- package/src/operations-api.d.ts +2 -0
- package/src/operations-api.js +6 -0
- package/src/personas.d.ts +2 -0
- package/src/personas.js +61 -0
- package/src/program-runner.d.ts +3 -0
- package/src/program-runner.js +263 -0
- package/src/program-sandbox.py +75 -0
- package/src/program-scratch.d.ts +2 -0
- package/src/program-scratch.js +48 -0
- package/src/program-worker.mjs +101 -0
- package/src/public-id.d.ts +2 -0
- package/src/public-id.js +5 -0
- package/src/public-report-url.d.ts +1 -0
- package/src/public-report-url.js +18 -0
- package/src/publication-check.d.ts +1 -0
- package/src/publication-check.js +31 -0
- package/src/quarantine-command.d.ts +9 -0
- package/src/quarantine-command.js +69 -0
- package/src/remote-command.d.ts +30 -0
- package/src/remote-command.js +156 -0
- package/src/replay-image.d.ts +1 -0
- package/src/replay-image.js +35 -0
- package/src/report/assets.d.ts +1 -0
- package/src/report/assets.js +5 -0
- package/src/report/browser.css +414 -0
- package/src/report/browser.d.ts +1 -0
- package/src/report/browser.js +219 -0
- package/src/report/data.d.ts +1 -0
- package/src/report/data.js +4 -0
- package/src/report/generate.d.ts +1 -0
- package/src/report/generate.js +54 -0
- package/src/report/load.d.ts +870 -0
- package/src/report/load.js +139 -0
- package/src/report/resource-table.d.ts +2 -0
- package/src/report/resource-table.js +4 -0
- package/src/report/status-icon.d.ts +2 -0
- package/src/report/status-icon.js +20 -0
- package/src/report/style.css +413 -0
- package/src/result-notifier.d.ts +121 -0
- package/src/result-notifier.js +230 -0
- package/src/result-transports.d.ts +12 -0
- package/src/result-transports.js +150 -0
- package/src/run-command.d.ts +32 -0
- package/src/run-command.js +493 -0
- package/src/run-setup-error.d.ts +11 -0
- package/src/run-setup-error.js +18 -0
- package/src/sandboxes-command.d.ts +9 -0
- package/src/sandboxes-command.js +29 -0
- package/src/screen-proxy.d.ts +5 -0
- package/src/screen-proxy.js +79 -0
- package/src/screen-url.d.ts +18 -0
- package/src/screen-url.js +54 -0
- package/src/server/app.d.ts +29 -0
- package/src/server/app.js +350 -0
- package/src/server/auth.d.ts +33 -0
- package/src/server/auth.js +113 -0
- package/src/server/credentials.d.ts +30 -0
- package/src/server/credentials.js +77 -0
- package/src/server/errors.d.ts +9 -0
- package/src/server/errors.js +26 -0
- package/src/server/index.d.ts +35 -0
- package/src/server/index.js +96 -0
- package/src/server/maintenance.d.ts +13 -0
- package/src/server/maintenance.js +54 -0
- package/src/server/repository.d.ts +534 -0
- package/src/server/repository.js +219 -0
- package/src/setup-command.d.ts +10 -0
- package/src/setup-command.js +52 -0
- package/src/stage-environment.d.ts +1 -0
- package/src/stage-environment.js +35 -0
- package/src/stage-supervisor.mjs +95 -0
- package/src/studio-command.d.ts +7 -0
- package/src/studio-command.js +47 -0
- package/src/studio-control.d.ts +5 -0
- package/src/studio-control.js +207 -0
- package/src/studio-review.d.ts +24 -0
- package/src/studio-review.js +64 -0
- package/src/studio-worker.d.ts +1 -0
- package/src/studio-worker.js +48 -0
- package/src/system-config.d.ts +7 -0
- package/src/system-config.js +70 -0
- package/src/terminal-reporter.d.ts +13 -0
- package/src/terminal-reporter.js +93 -0
- package/src/vendor/gmail.d.ts +45 -0
- package/src/vendor/gmail.js +193 -0
- package/src/watch-command.d.ts +16 -0
- package/src/watch-command.js +93 -0
- package/src/watch-state.d.ts +4 -0
- package/src/watch-state.js +53 -0
- package/src/worker/execution-error.d.ts +5 -0
- package/src/worker/execution-error.js +10 -0
- package/src/worker/execution.d.ts +24 -0
- package/src/worker/execution.js +190 -0
- package/src/worker/index.d.ts +8 -0
- package/src/worker/index.js +40 -0
- package/src/worker/prune.d.ts +3 -0
- package/src/worker/prune.js +22 -0
- package/src/worker/quarantine-notifications.d.ts +8 -0
- package/src/worker/quarantine-notifications.js +89 -0
- package/src/worker/queue.d.ts +65 -0
- package/src/worker/queue.js +438 -0
- package/src/worker/result-notifications.d.ts +28 -0
- package/src/worker/result-notifications.js +347 -0
- package/src/worker/store.d.ts +4 -0
- package/src/worker/store.js +46 -0
- package/src/worker/worker.d.ts +21 -0
- package/src/worker/worker.js +140 -0
- package/README.md +0 -3
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import { publicRunUsage } from "@open-qa/qa-engine";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { isDeepStrictEqual } from "node:util";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { readExecutionSnapshot } from "@open-qa/qa-engine/protocol";
|
|
6
|
+
import {
|
|
7
|
+
batchDtoSchema,
|
|
8
|
+
publicationSchemas,
|
|
9
|
+
artifactPathSchema
|
|
10
|
+
} from "@open-qa/qa-engine/protocol";
|
|
11
|
+
import { assertPostgresText } from "../db/database.js";
|
|
12
|
+
import { publicId } from "../public-id.js";
|
|
13
|
+
import { PgRunStore } from "../adapters/pg-run-store.js";
|
|
14
|
+
class Conflict extends Error {
|
|
15
|
+
}
|
|
16
|
+
class PgServerRepository {
|
|
17
|
+
constructor(db, project, objects, redactor) {
|
|
18
|
+
this.db = db;
|
|
19
|
+
this.project = project;
|
|
20
|
+
this.objects = objects;
|
|
21
|
+
this.redactor = redactor;
|
|
22
|
+
publicId.parse(project);
|
|
23
|
+
this.runs = new PgRunStore(db, project, objects);
|
|
24
|
+
}
|
|
25
|
+
db;
|
|
26
|
+
project;
|
|
27
|
+
objects;
|
|
28
|
+
redactor;
|
|
29
|
+
runs;
|
|
30
|
+
async submit(userId, trigger, key, request) {
|
|
31
|
+
assertPostgresText(request);
|
|
32
|
+
const fingerprint = createHash("sha256").update(JSON.stringify([trigger, request])).digest("hex");
|
|
33
|
+
return this.db.transaction(async (client) => {
|
|
34
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [
|
|
35
|
+
JSON.stringify([this.project, userId, key])
|
|
36
|
+
]);
|
|
37
|
+
const existing = await client.query(
|
|
38
|
+
"SELECT fingerprint,response FROM qa.server_submissions WHERE project_id=$1 AND principal_id=$2 AND idempotency_key=$3",
|
|
39
|
+
[this.project, userId, key]
|
|
40
|
+
);
|
|
41
|
+
if (existing.rows[0]) {
|
|
42
|
+
if (existing.rows[0].fingerprint !== fingerprint)
|
|
43
|
+
throw new Conflict("Idempotency key already used");
|
|
44
|
+
return publicBatch(existing.rows[0].response);
|
|
45
|
+
}
|
|
46
|
+
const response = {
|
|
47
|
+
schemaVersion: 1,
|
|
48
|
+
projectId: this.project,
|
|
49
|
+
id: randomUUID(),
|
|
50
|
+
trigger,
|
|
51
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
52
|
+
request
|
|
53
|
+
};
|
|
54
|
+
await client.query(
|
|
55
|
+
"INSERT INTO qa.batches(project_id,id,trigger,target,commit,created_by) VALUES($1,$2,$3,$4,$5,$6)",
|
|
56
|
+
[this.project, response.id, trigger, request.target, request.commit, userId]
|
|
57
|
+
);
|
|
58
|
+
await client.query(
|
|
59
|
+
"INSERT INTO qa.server_submissions(project_id,principal_id,idempotency_key,fingerprint,batch_id,response,created_at) VALUES($1,$2,$3,$4,$5,$6,$7)",
|
|
60
|
+
[this.project, userId, key, fingerprint, response.id, response, response.createdAt]
|
|
61
|
+
);
|
|
62
|
+
for (const flow of request.flows) {
|
|
63
|
+
const runId = randomUUID();
|
|
64
|
+
await client.query(
|
|
65
|
+
"INSERT INTO qa.runs(project_id,id,batch_id,flow,started_at) VALUES($1,$2,$3,$4,$5)",
|
|
66
|
+
[this.project, runId, response.id, flow, Date.now()]
|
|
67
|
+
);
|
|
68
|
+
await client.query("INSERT INTO qa.jobs(project_id,id,run_id) VALUES($1,$2,$3)", [
|
|
69
|
+
this.project,
|
|
70
|
+
randomUUID(),
|
|
71
|
+
runId
|
|
72
|
+
]);
|
|
73
|
+
}
|
|
74
|
+
return response;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
async batches(limit, offset) {
|
|
78
|
+
const { rows } = await this.db.pool.query(
|
|
79
|
+
"SELECT response FROM qa.server_submissions WHERE project_id=$1 ORDER BY created_at DESC NULLS LAST,batch_id LIMIT $2 OFFSET $3",
|
|
80
|
+
[this.project, limit, offset]
|
|
81
|
+
);
|
|
82
|
+
return rows.map((r) => publicBatch(r.response));
|
|
83
|
+
}
|
|
84
|
+
recentUsage(flow) {
|
|
85
|
+
return this.runs.recentUsage(flow);
|
|
86
|
+
}
|
|
87
|
+
async batch(id) {
|
|
88
|
+
const { rows } = await this.db.pool.query(
|
|
89
|
+
"SELECT response FROM qa.server_submissions WHERE project_id=$1 AND batch_id=$2",
|
|
90
|
+
[this.project, id]
|
|
91
|
+
);
|
|
92
|
+
return rows[0] ? { ...publicBatch(rows[0].response), usage: await this.runs.queries.batchUsage(id) } : void 0;
|
|
93
|
+
}
|
|
94
|
+
async run(id) {
|
|
95
|
+
const run = await this.runs.getRun(id);
|
|
96
|
+
if (!run) return void 0;
|
|
97
|
+
return {
|
|
98
|
+
schemaVersion: 1,
|
|
99
|
+
projectId: this.project,
|
|
100
|
+
id,
|
|
101
|
+
flow: run.run.flow,
|
|
102
|
+
startedAt: run.run.startedAt,
|
|
103
|
+
lastSeq: run.eventIndex.lastSeq,
|
|
104
|
+
result: run.result ? {
|
|
105
|
+
verdict: run.result.verdict,
|
|
106
|
+
finishedAt: run.result.finishedAt,
|
|
107
|
+
...run.result.usage && { usage: publicRunUsage(run.result.usage) },
|
|
108
|
+
costStatus: run.result.costStatus,
|
|
109
|
+
...run.result.errorReason && { errorReason: run.result.errorReason }
|
|
110
|
+
} : null
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
async events(id, after, limit) {
|
|
114
|
+
return (await this.runs.readEvents(id, after, limit)).map(
|
|
115
|
+
(event) => event.kind === "usage" && event.costUsd !== void 0 ? { ...event, costUsd: Number(event.costUsd.toFixed(6)) } : event
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
async cancel(id, userId) {
|
|
119
|
+
const result = await this.db.pool.query(
|
|
120
|
+
`UPDATE qa.jobs SET state='cancel-requested' WHERE project_id=$1 AND run_id=$2 AND state IN ('queued','claimed','running','cancel-requested') AND EXISTS (
|
|
121
|
+
SELECT 1 FROM qa.runs r JOIN qa.batches b ON b.project_id=r.project_id AND b.id=r.batch_id WHERE r.project_id=$1 AND r.id=$2 AND b.created_by=$3) RETURNING id`,
|
|
122
|
+
[this.project, id, userId]
|
|
123
|
+
);
|
|
124
|
+
return !!result.rowCount;
|
|
125
|
+
}
|
|
126
|
+
async rerun(id, userId, key) {
|
|
127
|
+
const { rows } = await this.db.pool.query(
|
|
128
|
+
`SELECT s.response,r.flow FROM qa.runs r JOIN qa.server_submissions s ON s.project_id=r.project_id AND s.batch_id=r.batch_id WHERE r.project_id=$1 AND r.id=$2 AND s.principal_id=$3`,
|
|
129
|
+
[this.project, id, userId]
|
|
130
|
+
);
|
|
131
|
+
if (!rows[0]) return void 0;
|
|
132
|
+
return this.submit(userId, "developer", `rerun-${id}-${key}`, {
|
|
133
|
+
...publicBatch(rows[0].response).request,
|
|
134
|
+
flows: [rows[0].flow]
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
async leases() {
|
|
138
|
+
const { rows } = await this.db.pool.query(
|
|
139
|
+
"SELECT id,run_id,state,expires_at FROM qa.leases WHERE project_id=$1 ORDER BY id LIMIT 1000",
|
|
140
|
+
[this.project]
|
|
141
|
+
);
|
|
142
|
+
return rows.map((r) => ({
|
|
143
|
+
id: r.id,
|
|
144
|
+
runId: r.run_id,
|
|
145
|
+
state: r.state,
|
|
146
|
+
expiresAt: r.expires_at.toISOString()
|
|
147
|
+
}));
|
|
148
|
+
}
|
|
149
|
+
async publish(kind, input) {
|
|
150
|
+
const document = publicationSchemas[kind].parse(input);
|
|
151
|
+
if (document.projectId !== this.project) throw new Error("Publication scope mismatch");
|
|
152
|
+
assertPostgresText(document);
|
|
153
|
+
if (this.redactor.contains(JSON.stringify(document))) throw new Error("Unsafe publication");
|
|
154
|
+
await this.db.transaction(async (client) => {
|
|
155
|
+
await client.query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))", [
|
|
156
|
+
JSON.stringify([this.project, kind])
|
|
157
|
+
]);
|
|
158
|
+
const { rows } = await client.query(
|
|
159
|
+
"SELECT document FROM qa.read_publications WHERE project_id=$1 AND kind=$2",
|
|
160
|
+
[this.project, kind]
|
|
161
|
+
);
|
|
162
|
+
const previous = rows[0]?.document;
|
|
163
|
+
if (previous && (Date.parse(previous.capturedAt) > Date.parse(document.capturedAt) || Date.parse(previous.capturedAt) === Date.parse(document.capturedAt) && !isDeepStrictEqual(previous, document)))
|
|
164
|
+
throw new Conflict("Publication is older than the stored revision");
|
|
165
|
+
await client.query(
|
|
166
|
+
"INSERT INTO qa.read_publications(project_id,kind,document) VALUES($1,$2,$3) ON CONFLICT(project_id,kind) DO UPDATE SET document=EXCLUDED.document",
|
|
167
|
+
[this.project, kind, document]
|
|
168
|
+
);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
async published(kind) {
|
|
172
|
+
const { rows } = await this.db.pool.query(
|
|
173
|
+
"SELECT document FROM qa.read_publications WHERE project_id=$1 AND kind=$2",
|
|
174
|
+
[this.project, kind]
|
|
175
|
+
);
|
|
176
|
+
const base = { schemaVersion: 1, projectId: this.project };
|
|
177
|
+
if (!rows[0]) return { ...base, state: "not-recorded" };
|
|
178
|
+
const parsed = publicationSchemas[kind].safeParse(rows[0].document);
|
|
179
|
+
return parsed.success && parsed.data.projectId === this.project ? { ...base, state: "recorded", publication: parsed.data } : { ...base, state: "unknown" };
|
|
180
|
+
}
|
|
181
|
+
async snapshot(id) {
|
|
182
|
+
const run = await this.runs.getRun(id);
|
|
183
|
+
if (!run) return void 0;
|
|
184
|
+
const read = readExecutionSnapshot(run.run.metadata?.executionSnapshot);
|
|
185
|
+
const base = { schemaVersion: 1, projectId: this.project, runId: id };
|
|
186
|
+
if (read.status === "recorded" && read.snapshot.projectId === this.project)
|
|
187
|
+
return { ...base, state: "recorded", snapshot: read.snapshot };
|
|
188
|
+
return { ...base, state: read.status === "not-recorded" ? "not-recorded" : "unknown" };
|
|
189
|
+
}
|
|
190
|
+
async artifact(id, path) {
|
|
191
|
+
artifactPathSchema.parse(path);
|
|
192
|
+
const { rows } = await this.db.pool.query(
|
|
193
|
+
"SELECT object_key,bytes,sha256 FROM qa.artifacts WHERE project_id=$1 AND run_id=$2 AND path=$3",
|
|
194
|
+
[this.project, id, path]
|
|
195
|
+
);
|
|
196
|
+
const artifact = rows[0];
|
|
197
|
+
if (!artifact) return void 0;
|
|
198
|
+
const run = await this.runs.getRun(id);
|
|
199
|
+
const receipt = z.object({ status: z.literal("passed"), files: z.record(z.string(), z.string()) }).safeParse(run?.run.metadata?.artifactScan);
|
|
200
|
+
if (!receipt.success || receipt.data.files[path] !== artifact.sha256 || Number(artifact.bytes) > 64 * 1024 * 1024)
|
|
201
|
+
throw new Error("Artifact is unavailable");
|
|
202
|
+
const data = await this.objects.read(artifact.object_key);
|
|
203
|
+
if (data.byteLength !== Number(artifact.bytes) || createHash("sha256").update(data).digest("hex") !== artifact.sha256 || this.redactor.contains(Buffer.from(data).toString("utf8")))
|
|
204
|
+
throw new Error("Artifact is unavailable");
|
|
205
|
+
return data;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
function publicBatch(input) {
|
|
209
|
+
if (input && typeof input === "object" && !Array.isArray(input)) {
|
|
210
|
+
const fields = { ...input };
|
|
211
|
+
if ("createdBy" in fields) delete fields.createdBy;
|
|
212
|
+
return batchDtoSchema.parse(fields);
|
|
213
|
+
}
|
|
214
|
+
return batchDtoSchema.parse(input);
|
|
215
|
+
}
|
|
216
|
+
export {
|
|
217
|
+
Conflict,
|
|
218
|
+
PgServerRepository
|
|
219
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { HookRegistry } from "./hooks/registry.js";
|
|
2
|
+
import { type LocalCommand } from "./local-command.js";
|
|
3
|
+
export declare function setupCommand(options: {
|
|
4
|
+
root?: string;
|
|
5
|
+
envFile?: string;
|
|
6
|
+
registry?: HookRegistry;
|
|
7
|
+
}, command?: LocalCommand, output?: {
|
|
8
|
+
(...data: any[]): void;
|
|
9
|
+
(message?: any, ...optionalParams: any[]): void;
|
|
10
|
+
}): Promise<number>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { parseEnv } from "node:util";
|
|
4
|
+
import { loadConsumerRegistry } from "./hooks/consumer.js";
|
|
5
|
+
import { hasCode } from "./adapters/local-files.js";
|
|
6
|
+
import { parseResourcePools } from "./adapters/resource-pools.js";
|
|
7
|
+
import { localCommand, playwrightCli } from "./local-command.js";
|
|
8
|
+
async function setupCommand(options, command = localCommand, output = console.log) {
|
|
9
|
+
const root = resolve(options.root ?? ".qa");
|
|
10
|
+
await mkdir(root, { recursive: true });
|
|
11
|
+
const file = join(root, ".env.local");
|
|
12
|
+
let content = "# Local QA credentials. Never commit this file.\nQA_RESOURCES='{}'\nQA_RESOURCE_POOLS='{}'\n# QA_CF_ACCESS_CLIENT_ID=\n# QA_CF_ACCESS_CLIENT_SECRET=\n# QA_GMAIL_CLIENT_ID=\n# QA_GMAIL_CLIENT_SECRET=\n# QA_GMAIL_REFRESH_TOKEN=\n";
|
|
13
|
+
if (options.envFile) {
|
|
14
|
+
const source = await readFile(resolve(options.envFile), "utf8");
|
|
15
|
+
const env = parseEnv(source);
|
|
16
|
+
const registry = options.registry ?? await loadConsumerRegistry(root, { env });
|
|
17
|
+
const values = {
|
|
18
|
+
...Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("QA_"))),
|
|
19
|
+
QA_RESOURCES: env.QA_RESOURCES ?? "{}",
|
|
20
|
+
QA_RESOURCE_POOLS: env.QA_RESOURCE_POOLS ?? "{}",
|
|
21
|
+
...registry.services.setup?.(env)
|
|
22
|
+
};
|
|
23
|
+
parseResourcePools(values.QA_RESOURCE_POOLS);
|
|
24
|
+
content = Object.entries(values).map(([key, value]) => {
|
|
25
|
+
if (value.includes("'") || /[\r\n]/.test(value))
|
|
26
|
+
throw new Error(
|
|
27
|
+
`Unsupported multiline or quoted value in ${key}; configure .env.local manually`
|
|
28
|
+
);
|
|
29
|
+
return `${key}='${value}'`;
|
|
30
|
+
}).join("\n") + "\n";
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
await writeFile(file, content, { flag: "wx", mode: 384 });
|
|
34
|
+
output(`Created ${file} (0600)`);
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (!hasCode(error, "EEXIST")) throw error;
|
|
37
|
+
output(`Kept existing ${file}`);
|
|
38
|
+
}
|
|
39
|
+
output("Installing Playwright Chromium...");
|
|
40
|
+
try {
|
|
41
|
+
await command(process.execPath, [playwrightCli(), "install", "chromium"], 6e5);
|
|
42
|
+
} catch {
|
|
43
|
+
throw new Error(
|
|
44
|
+
"Chromium installation failed. Run the installed Playwright CLI with install chromium; install OS dependencies if requested."
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
output("Setup complete. Configure config.yaml targets and run open-qa doctor.");
|
|
48
|
+
return 0;
|
|
49
|
+
}
|
|
50
|
+
export {
|
|
51
|
+
setupCommand
|
|
52
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function stageEnvironment(source?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
const stageEnvironmentKeys = [
|
|
2
|
+
"PATH",
|
|
3
|
+
"HOME",
|
|
4
|
+
"USER",
|
|
5
|
+
"LOGNAME",
|
|
6
|
+
"SHELL",
|
|
7
|
+
"TMPDIR",
|
|
8
|
+
"TMP",
|
|
9
|
+
"TEMP",
|
|
10
|
+
"LANG",
|
|
11
|
+
"LANGUAGE",
|
|
12
|
+
"LC_ALL",
|
|
13
|
+
"LC_CTYPE",
|
|
14
|
+
"TZ",
|
|
15
|
+
"DISPLAY",
|
|
16
|
+
"WAYLAND_DISPLAY",
|
|
17
|
+
"XAUTHORITY",
|
|
18
|
+
"DBUS_SESSION_BUS_ADDRESS",
|
|
19
|
+
"XDG_RUNTIME_DIR",
|
|
20
|
+
"XDG_CONFIG_HOME",
|
|
21
|
+
"XDG_DATA_HOME",
|
|
22
|
+
"XDG_CACHE_HOME",
|
|
23
|
+
"XDG_SESSION_TYPE",
|
|
24
|
+
"XDG_CURRENT_DESKTOP",
|
|
25
|
+
// Playwright resolves the preinstalled browser path in the Node process.
|
|
26
|
+
"PLAYWRIGHT_BROWSERS_PATH"
|
|
27
|
+
];
|
|
28
|
+
function stageEnvironment(source = process.env) {
|
|
29
|
+
return Object.fromEntries(
|
|
30
|
+
stageEnvironmentKeys.flatMap((key) => source[key] === void 0 ? [] : [[key, source[key]]])
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
export {
|
|
34
|
+
stageEnvironment
|
|
35
|
+
};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import process from "node:process";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { rm } from "node:fs/promises";
|
|
4
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
5
|
+
|
|
6
|
+
// The IPC pipe closes even if the conductor dies before it can run cleanup.
|
|
7
|
+
const command = JSON.parse(process.argv[2]);
|
|
8
|
+
const graceMs = Number(process.argv[3]);
|
|
9
|
+
const shutdownTimeoutMs = Number(process.argv[4]);
|
|
10
|
+
const directory = process.cwd();
|
|
11
|
+
const stage = spawn(command[0], command.slice(1), {
|
|
12
|
+
cwd: directory,
|
|
13
|
+
env: { ...process.env },
|
|
14
|
+
detached: true,
|
|
15
|
+
stdio: ["ignore", "pipe", "inherit"],
|
|
16
|
+
});
|
|
17
|
+
delete process.env.QA_STAGE_CONFIG;
|
|
18
|
+
stage.once("spawn", () => {
|
|
19
|
+
if (process.connected) process.send({ type: "spawned", pid: stage.pid }, () => {});
|
|
20
|
+
});
|
|
21
|
+
let closed = false;
|
|
22
|
+
let resolveClosed;
|
|
23
|
+
const stageClosed = new Promise((resolve) => {
|
|
24
|
+
resolveClosed = resolve;
|
|
25
|
+
});
|
|
26
|
+
let cleanup;
|
|
27
|
+
function kill(signal) {
|
|
28
|
+
if (!stage.pid) return;
|
|
29
|
+
try {
|
|
30
|
+
process.kill(-stage.pid, signal);
|
|
31
|
+
} catch (error) {
|
|
32
|
+
if (error.code !== "ESRCH") throw error;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
function stop() {
|
|
36
|
+
return (cleanup ??= (async () => {
|
|
37
|
+
kill("SIGTERM");
|
|
38
|
+
if (!closed) await Promise.race([stageClosed, delay(graceMs)]);
|
|
39
|
+
// The leader can exit while a browser or another descendant is still alive.
|
|
40
|
+
kill("SIGKILL");
|
|
41
|
+
try {
|
|
42
|
+
await Promise.race([
|
|
43
|
+
stageClosed,
|
|
44
|
+
delay(shutdownTimeoutMs).then(() => {
|
|
45
|
+
throw new Error("Stage process pipes did not close");
|
|
46
|
+
}),
|
|
47
|
+
]);
|
|
48
|
+
} finally {
|
|
49
|
+
stage.stdout.destroy();
|
|
50
|
+
await rm(directory, { recursive: true, force: true });
|
|
51
|
+
}
|
|
52
|
+
})().then(
|
|
53
|
+
() => process.exit(0),
|
|
54
|
+
() => process.exit(1)
|
|
55
|
+
));
|
|
56
|
+
}
|
|
57
|
+
for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"])
|
|
58
|
+
process.on(signal, () => {
|
|
59
|
+
void stop();
|
|
60
|
+
});
|
|
61
|
+
process.once("disconnect", () => {
|
|
62
|
+
void stop();
|
|
63
|
+
});
|
|
64
|
+
process.on("message", (message) => {
|
|
65
|
+
if (message?.type === "stop") void stop();
|
|
66
|
+
});
|
|
67
|
+
stage.once("error", () => {
|
|
68
|
+
void stop();
|
|
69
|
+
});
|
|
70
|
+
stage.once("exit", () => {
|
|
71
|
+
void stop();
|
|
72
|
+
});
|
|
73
|
+
stage.once("close", () => {
|
|
74
|
+
closed = true;
|
|
75
|
+
resolveClosed();
|
|
76
|
+
void stop();
|
|
77
|
+
});
|
|
78
|
+
let output = "";
|
|
79
|
+
let announced = false;
|
|
80
|
+
stage.stdout.on("data", (chunk) => {
|
|
81
|
+
if (announced) return;
|
|
82
|
+
output += chunk.toString();
|
|
83
|
+
let end;
|
|
84
|
+
while ((end = output.indexOf("\n")) >= 0) {
|
|
85
|
+
const line = output.slice(0, end).trim();
|
|
86
|
+
output = output.slice(end + 1);
|
|
87
|
+
const match = /^QA stage listening on (http:\/\/127\.0\.0\.1:\d+)$/.exec(line);
|
|
88
|
+
if (match && process.connected) {
|
|
89
|
+
announced = true;
|
|
90
|
+
process.send({ endpoint: match[1], pid: stage.pid }, () => {});
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (output.length > 65536) output = "";
|
|
95
|
+
});
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
async function studioCommand(options) {
|
|
4
|
+
const args = [];
|
|
5
|
+
for (const [key, value] of [
|
|
6
|
+
["--root", options.root],
|
|
7
|
+
["--port", options.port],
|
|
8
|
+
["--ready-timeout", options.readyTimeout]
|
|
9
|
+
])
|
|
10
|
+
if (value) args.push(key, value);
|
|
11
|
+
if (options.open === false) args.push("--no-open");
|
|
12
|
+
let control;
|
|
13
|
+
if (options.allowRun) {
|
|
14
|
+
const { tsImport } = await import("tsx/esm/api");
|
|
15
|
+
const { listenStudio } = await tsImport(
|
|
16
|
+
"./studio-control.js",
|
|
17
|
+
import.meta.url
|
|
18
|
+
);
|
|
19
|
+
control = await listenStudio(options.root ?? ".qa");
|
|
20
|
+
args.push("--control-socket", control.path);
|
|
21
|
+
}
|
|
22
|
+
const child = spawn(
|
|
23
|
+
process.execPath,
|
|
24
|
+
[fileURLToPath(import.meta.resolve("@open-qa/qa-studio/cli")), ...args],
|
|
25
|
+
{ stdio: ["inherit", "inherit", "inherit", "ipc"] }
|
|
26
|
+
);
|
|
27
|
+
const stop = () => {
|
|
28
|
+
child.kill("SIGTERM");
|
|
29
|
+
};
|
|
30
|
+
process.on("SIGINT", stop);
|
|
31
|
+
process.on("SIGTERM", stop);
|
|
32
|
+
process.on("SIGHUP", stop);
|
|
33
|
+
try {
|
|
34
|
+
return await new Promise((resolve, reject) => {
|
|
35
|
+
child.once("error", reject);
|
|
36
|
+
child.once("exit", (code) => resolve(code ?? 1));
|
|
37
|
+
});
|
|
38
|
+
} finally {
|
|
39
|
+
await control?.close();
|
|
40
|
+
process.off("SIGINT", stop);
|
|
41
|
+
process.off("SIGTERM", stop);
|
|
42
|
+
process.off("SIGHUP", stop);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
export {
|
|
46
|
+
studioCommand
|
|
47
|
+
};
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { fork } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { constants } from "node:fs";
|
|
4
|
+
import { mkdtemp, link, open, realpath, rm, unlink, writeFile } from "node:fs/promises";
|
|
5
|
+
import { createServer } from "node:http";
|
|
6
|
+
import { tmpdir } from "node:os";
|
|
7
|
+
import { join, resolve } from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
import { setupReasons } from "./run-setup-error.js";
|
|
11
|
+
import { reviewFlow, StudioError } from "./studio-review.js";
|
|
12
|
+
const runId = z.string().regex(/^run_[\da-f-]{36}$/);
|
|
13
|
+
const command = z.discriminatedUnion("action", [
|
|
14
|
+
z.strictObject({
|
|
15
|
+
action: z.literal("review"),
|
|
16
|
+
project: z.string(),
|
|
17
|
+
flowId: z.string().regex(/^[a-f0-9]{64}$/),
|
|
18
|
+
source: z.string().max(1024),
|
|
19
|
+
target: z.string().min(1).max(128)
|
|
20
|
+
}),
|
|
21
|
+
z.strictObject({
|
|
22
|
+
action: z.literal("start"),
|
|
23
|
+
ticket: z.uuid(),
|
|
24
|
+
key: z.uuid(),
|
|
25
|
+
accepted: z.boolean()
|
|
26
|
+
}),
|
|
27
|
+
z.strictObject({ action: z.enum(["stop", "status"]), runId })
|
|
28
|
+
]);
|
|
29
|
+
async function lockOwner(lock) {
|
|
30
|
+
const handle = await open(lock, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW);
|
|
31
|
+
try {
|
|
32
|
+
const bytes = Buffer.alloc(64);
|
|
33
|
+
if (!(await handle.stat()).isFile()) return;
|
|
34
|
+
const { bytesRead } = await handle.read(bytes, 0, bytes.length, 0);
|
|
35
|
+
const active = runId.safeParse(bytes.toString("utf8", 0, bytesRead));
|
|
36
|
+
return active.success ? active.data : void 0;
|
|
37
|
+
} finally {
|
|
38
|
+
await handle.close();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
async function acquireStudioLock(root, id) {
|
|
42
|
+
const lock = join(root, ".studio-run.lock"), staging = lock + "." + randomUUID();
|
|
43
|
+
await writeFile(staging, id, { mode: 384, flag: "wx" });
|
|
44
|
+
try {
|
|
45
|
+
try {
|
|
46
|
+
await link(staging, lock);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (error.code !== "EEXIST") throw error;
|
|
49
|
+
throw new StudioError(
|
|
50
|
+
`Another run holds the project lock at ${lock}. Check its worker and resource leases before manually clearing a stale lock.`,
|
|
51
|
+
409,
|
|
52
|
+
await lockOwner(lock)
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
} finally {
|
|
56
|
+
await unlink(staging);
|
|
57
|
+
}
|
|
58
|
+
return async () => {
|
|
59
|
+
try {
|
|
60
|
+
if (await lockOwner(lock) === id) await unlink(lock);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
if (error.code !== "ENOENT") throw error;
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
async function listenStudio(directory) {
|
|
67
|
+
const root = await realpath(directory), temp = await mkdtemp(join(tmpdir(), "open-qa-"));
|
|
68
|
+
const path = join(temp, "control.sock"), tickets = /* @__PURE__ */ new Map();
|
|
69
|
+
const runs = /* @__PURE__ */ new Map();
|
|
70
|
+
let active;
|
|
71
|
+
let closing = false;
|
|
72
|
+
async function start(t, accepted) {
|
|
73
|
+
const r = t.request;
|
|
74
|
+
const current = await reviewFlow(root, r.project, r.source, r.flowId, r.target);
|
|
75
|
+
if (JSON.stringify(current) !== JSON.stringify(t.review))
|
|
76
|
+
throw new StudioError("Configuration changed; review again.");
|
|
77
|
+
if (current.prompt && !accepted)
|
|
78
|
+
throw new StudioError("Confirm this cost estimate to continue.", 400);
|
|
79
|
+
const id = "run_" + randomUUID();
|
|
80
|
+
const release = await acquireStudioLock(root, id);
|
|
81
|
+
try {
|
|
82
|
+
if (closing) throw new StudioError("Launcher is closing.");
|
|
83
|
+
const worker = fork(fileURLToPath(new URL("./studio-worker.js", import.meta.url)), [], {
|
|
84
|
+
execArgv: ["--import", import.meta.resolve("tsx")],
|
|
85
|
+
stdio: ["ignore", "ignore", "ignore", "ipc"]
|
|
86
|
+
});
|
|
87
|
+
const result = { runId: id, state: "starting" };
|
|
88
|
+
if (runs.size >= 128) runs.delete(runs.keys().next().value);
|
|
89
|
+
runs.set(id, result);
|
|
90
|
+
let timer;
|
|
91
|
+
const stop = () => {
|
|
92
|
+
if (result.state === "stopping") return;
|
|
93
|
+
result.state = "stopping";
|
|
94
|
+
if (worker.connected) worker.send("stop", () => {
|
|
95
|
+
});
|
|
96
|
+
timer = setTimeout(() => worker.kill("SIGKILL"), 15e3);
|
|
97
|
+
};
|
|
98
|
+
let saved = false;
|
|
99
|
+
worker.on("message", (m) => {
|
|
100
|
+
if (typeof m === "string" && Object.hasOwn(setupReasons, m))
|
|
101
|
+
result.reason = setupReasons[m];
|
|
102
|
+
if (m === "saved") saved = true;
|
|
103
|
+
if (m === "running" && result.state === "starting") result.state = "running";
|
|
104
|
+
});
|
|
105
|
+
const done = new Promise((resolveDone) => {
|
|
106
|
+
worker.once("error", () => {
|
|
107
|
+
result.state = "failed";
|
|
108
|
+
result.reason = "Studio could not launch the local worker. Restart Studio and try again.";
|
|
109
|
+
});
|
|
110
|
+
worker.once("close", async (_code, signal) => {
|
|
111
|
+
clearTimeout(timer);
|
|
112
|
+
result.state = signal ? "interrupted" : saved ? "finished" : "failed";
|
|
113
|
+
if (!signal)
|
|
114
|
+
await release().catch(() => {
|
|
115
|
+
result.state = "interrupted";
|
|
116
|
+
});
|
|
117
|
+
if (active?.runId === id) active = void 0;
|
|
118
|
+
resolveDone();
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
active = { runId: id, stop, done };
|
|
122
|
+
worker.send(
|
|
123
|
+
{ root, path: resolve(root, r.source), runId: id, review: current, accepted },
|
|
124
|
+
(error) => {
|
|
125
|
+
if (error) stop();
|
|
126
|
+
}
|
|
127
|
+
);
|
|
128
|
+
return result;
|
|
129
|
+
} catch (error) {
|
|
130
|
+
await release();
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
const server = createServer(async (req, res) => {
|
|
135
|
+
const reply = (status, value) => {
|
|
136
|
+
res.writeHead(status, { "Content-Type": "application/json" });
|
|
137
|
+
res.end(JSON.stringify(value));
|
|
138
|
+
};
|
|
139
|
+
try {
|
|
140
|
+
if (closing || req.method !== "POST" || req.url !== "/")
|
|
141
|
+
throw new StudioError("Unavailable.", 403);
|
|
142
|
+
const chunks = [];
|
|
143
|
+
let size = 0;
|
|
144
|
+
for await (const chunk of req) {
|
|
145
|
+
size += chunk.length;
|
|
146
|
+
if (size > 4096) throw new StudioError("Request too large.", 413);
|
|
147
|
+
chunks.push(chunk);
|
|
148
|
+
}
|
|
149
|
+
const parsed = command.safeParse(JSON.parse(Buffer.concat(chunks).toString()));
|
|
150
|
+
if (!parsed.success) throw new StudioError("Invalid request.", 400);
|
|
151
|
+
const input = parsed.data;
|
|
152
|
+
if (input.action === "review") {
|
|
153
|
+
const review = await reviewFlow(
|
|
154
|
+
root,
|
|
155
|
+
input.project,
|
|
156
|
+
input.source,
|
|
157
|
+
input.flowId,
|
|
158
|
+
input.target
|
|
159
|
+
);
|
|
160
|
+
for (const [k, t] of tickets) if (t.expires <= Date.now()) tickets.delete(k);
|
|
161
|
+
if (tickets.size >= 128)
|
|
162
|
+
throw new StudioError("Too many recent reviews. Try again later.", 429);
|
|
163
|
+
const ticket = randomUUID();
|
|
164
|
+
tickets.set(ticket, { request: input, review, expires: Date.now() + 10 * 6e4 });
|
|
165
|
+
return reply(200, { ticket, ...review });
|
|
166
|
+
}
|
|
167
|
+
if (input.action === "start") {
|
|
168
|
+
const t = tickets.get(input.ticket);
|
|
169
|
+
if (!t || t.expires <= Date.now()) throw new StudioError("Review expired; review again.");
|
|
170
|
+
if (t.start && t.start.key !== input.key)
|
|
171
|
+
throw new StudioError("This review has already been used.");
|
|
172
|
+
t.start ??= { key: input.key, result: start(t, input.accepted) };
|
|
173
|
+
return reply(200, await t.start.result);
|
|
174
|
+
}
|
|
175
|
+
const result = runs.get(input.runId);
|
|
176
|
+
if (!result) throw new StudioError("This launcher does not own the run.", 404);
|
|
177
|
+
if (input.action === "stop" && active?.runId === input.runId) active.stop();
|
|
178
|
+
reply(200, result);
|
|
179
|
+
} catch (error) {
|
|
180
|
+
if (error instanceof StudioError)
|
|
181
|
+
reply(error.status, { error: error.message, runId: error.runId });
|
|
182
|
+
else
|
|
183
|
+
reply(400, {
|
|
184
|
+
error: "Unable to read or start this flow. Review the project configuration."
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
server.requestTimeout = 1e4;
|
|
189
|
+
await new Promise((res, rej) => {
|
|
190
|
+
server.once("error", rej);
|
|
191
|
+
server.listen(path, res);
|
|
192
|
+
});
|
|
193
|
+
return {
|
|
194
|
+
path,
|
|
195
|
+
async close() {
|
|
196
|
+
closing = true;
|
|
197
|
+
const closed = new Promise((res) => server.close(() => res()));
|
|
198
|
+
active?.stop();
|
|
199
|
+
await Promise.all([closed, active?.done]);
|
|
200
|
+
await rm(temp, { force: true, recursive: true });
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
export {
|
|
205
|
+
acquireStudioLock,
|
|
206
|
+
listenStudio
|
|
207
|
+
};
|