@loucompanion/forge-bridge 0.1.4-dev.bfa11ebe98c6 → 0.1.4-dev.d2d83bc81b6a
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/README.md +1 -1
- package/dist/bridge/bridge.service.d.ts +9 -0
- package/dist/bridge/bridge.service.js +42 -4
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- package/dist/cli/cli.help.js +2 -2
- package/dist/runtime/attempt-database-broker.d.ts +89 -0
- package/dist/runtime/attempt-database-broker.js +390 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +24 -0
- package/dist/runtime/attempt-process-supervisor.js +77 -3
- package/dist/runtime/host-diagnostics.js +4 -3
- package/dist/runtime/host-runtime-contract.js +69 -10
- package/dist/runtime/host-runtime-lease.d.ts +4 -2
- package/dist/runtime/host-runtime-lease.js +108 -24
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/node-host-runtime-adapter.js +5 -4
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
- package/dist/sandbox/repository-lock.js +3 -2
- package/dist/sandbox/runtime.js +5 -4
- package/dist/session/managed-attempt-tools.d.ts +25 -0
- package/dist/session/managed-attempt-tools.js +222 -20
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +8 -4
- package/dist/session/phase-completion.runtime.js +30 -18
- package/dist/session/pre-publication-process.d.ts +20 -0
- package/dist/session/pre-publication-process.js +96 -0
- package/dist/session/pre-publication-validation.js +9 -54
- package/dist/session/provider-cli/provider-cli.process.d.ts +6 -1
- package/dist/session/provider-cli/provider-cli.process.js +198 -16
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +14 -0
- package/dist/session/provider-cli/provider-cli.service.js +10 -5
- package/dist/session/provider-cli/provider-usage.d.ts +2 -1
- package/dist/shared/process/host-process-recovery.js +3 -2
- package/dist/shared/process/host-process-supervisor.js +5 -4
- package/dist/shared/time/monotonic.d.ts +1 -0
- package/dist/shared/time/monotonic.js +8 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.js +74 -0
- package/package.json +1 -1
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
/**
|
|
6
|
+
* The managed host attempt's database capability. The Bridge keeps the test cluster's
|
|
7
|
+
* administrator credential; an attempt (its agent, its application runtime and its tests)
|
|
8
|
+
* receives only a login for one database created for it. Forge.Api checks that login before it
|
|
9
|
+
* migrates (AttemptScopedDatabasePolicy.AssertBrokeredCapabilityAsync), but that check runs in
|
|
10
|
+
* attempt code: the boundary is what this broker issues and the cluster's pg_hba rules, which
|
|
11
|
+
* let an attempt role log in only to its own database.
|
|
12
|
+
*/
|
|
13
|
+
export const attemptDatabaseCapabilityEnvironment = "FORGE_ATTEMPT_DATABASE_CAPABILITY";
|
|
14
|
+
export class AttemptDatabaseBrokerError extends Error {
|
|
15
|
+
code;
|
|
16
|
+
constructor(code, detail) {
|
|
17
|
+
super(`${code}: ${detail}`);
|
|
18
|
+
this.code = code;
|
|
19
|
+
this.name = "AttemptDatabaseBrokerError";
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const markerVersion = "broker-v1";
|
|
23
|
+
const attemptNamePattern = /^forge_attempt_[0-9a-f]{32}$/u;
|
|
24
|
+
const template1BusyPattern = /source database "template1" is being accessed by other users/u;
|
|
25
|
+
const hbaRejectPattern = /pg_hba\.conf rejects connection|no pg_hba\.conf entry/u;
|
|
26
|
+
// Three attempts at this limit stay well under the cluster's 200 connections, leaving room for
|
|
27
|
+
// the administrator; the issued pool stays below it.
|
|
28
|
+
const attemptConnectionLimit = 40;
|
|
29
|
+
const attemptPoolSize = 20;
|
|
30
|
+
/**
|
|
31
|
+
* The ownership marker on the attempt's role. Only a role with CREATEROLE can change a role's
|
|
32
|
+
* comment, so the attempt cannot forge or erase it (it can rewrite its database's comment, which
|
|
33
|
+
* is therefore informational). Must match AttemptScopedDatabasePolicy.BrokeredRoleMarkerPrefix.
|
|
34
|
+
*/
|
|
35
|
+
export function brokeredDatabaseMarker(dispatchAttemptId, fencingToken, owner) {
|
|
36
|
+
return `${brokeredMarkerPrefix(dispatchAttemptId, fencingToken)}owner=${owner}`;
|
|
37
|
+
}
|
|
38
|
+
function brokeredMarkerPrefix(dispatchAttemptId, fencingToken) {
|
|
39
|
+
const name = attemptDatabaseName(dispatchAttemptId);
|
|
40
|
+
return `forge_attempt_database:${markerVersion};id=${hex(dispatchAttemptId)};fence=${hex(fencingToken)};database=${name};`;
|
|
41
|
+
}
|
|
42
|
+
export function attemptDatabaseName(dispatchAttemptId) {
|
|
43
|
+
return `forge_attempt_${hex(dispatchAttemptId)}`;
|
|
44
|
+
}
|
|
45
|
+
/** Identifies one Bridge's broker on a shared cluster, so it reaps only databases it issued. */
|
|
46
|
+
export function attemptDatabaseBrokerOwner(stateRoot) {
|
|
47
|
+
return createHash("sha256").update(path.resolve(stateRoot).toLowerCase()).digest("hex").slice(0, 16);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Brokers attempt databases on the dedicated native test cluster that
|
|
51
|
+
* scripts/setup-native-test-postgres.ps1 provisions. That cluster holds only disposable test
|
|
52
|
+
* databases, so even a leaked attempt capability cannot reach developer data. Each attempt
|
|
53
|
+
* gets a login role and a database it owns, cloned from template1 (which carries pgvector,
|
|
54
|
+
* an extension an unprivileged owner cannot create).
|
|
55
|
+
*/
|
|
56
|
+
export class NativeTestClusterDatabaseBroker {
|
|
57
|
+
admin;
|
|
58
|
+
runSql;
|
|
59
|
+
owner;
|
|
60
|
+
delay;
|
|
61
|
+
/** Names being provisioned right now; the reaper leaves them alone. */
|
|
62
|
+
provisioning = new Set();
|
|
63
|
+
constructor(admin, runSql, owner, delay = milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds))) {
|
|
64
|
+
this.admin = admin;
|
|
65
|
+
this.runSql = runSql;
|
|
66
|
+
this.owner = owner;
|
|
67
|
+
this.delay = delay;
|
|
68
|
+
if (!/^[0-9a-f]{16}$/u.test(owner)) {
|
|
69
|
+
throw new AttemptDatabaseBrokerError("attempt_database_broker_invalid", "the broker owner must be 16 hex characters.");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async provision(dispatchAttemptId, fencingToken, signal) {
|
|
73
|
+
const name = attemptDatabaseName(dispatchAttemptId);
|
|
74
|
+
const marker = brokeredDatabaseMarker(dispatchAttemptId, fencingToken, this.owner);
|
|
75
|
+
this.provisioning.add(name);
|
|
76
|
+
const password = randomBytes(24).toString("hex");
|
|
77
|
+
try {
|
|
78
|
+
const state = await this.state(name, signal);
|
|
79
|
+
if (state.roleMarker !== null && state.roleMarker !== marker) {
|
|
80
|
+
throw new AttemptDatabaseBrokerError("attempt_database_not_owned", `role ${name} exists without this attempt's broker marker and was left untouched.`);
|
|
81
|
+
}
|
|
82
|
+
if (state.databaseOwner !== null && (state.roleMarker === null || state.databaseOwner !== name)) {
|
|
83
|
+
throw new AttemptDatabaseBrokerError("attempt_database_not_owned", `database ${name} is not owned by this attempt's broker role and was left untouched.`);
|
|
84
|
+
}
|
|
85
|
+
// One transaction: an interrupted run leaves either no role or a marked one.
|
|
86
|
+
await this.runSql([
|
|
87
|
+
"BEGIN;",
|
|
88
|
+
...(state.roleMarker === null
|
|
89
|
+
? [
|
|
90
|
+
`CREATE ROLE ${ident(name)} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS NOINHERIT CONNECTION LIMIT ${attemptConnectionLimit} PASSWORD ${literal(password)};`,
|
|
91
|
+
`COMMENT ON ROLE ${ident(name)} IS ${literal(marker)};`,
|
|
92
|
+
// Lets the administrator create, and later drop, a database the attempt role owns.
|
|
93
|
+
`GRANT ${ident(name)} TO CURRENT_USER;`,
|
|
94
|
+
]
|
|
95
|
+
: [`ALTER ROLE ${ident(name)} LOGIN PASSWORD ${literal(password)};`]),
|
|
96
|
+
"COMMIT;",
|
|
97
|
+
].join("\n"), signal);
|
|
98
|
+
if (state.databaseOwner === null)
|
|
99
|
+
await this.createDatabase(name, signal);
|
|
100
|
+
// Idempotent, so a retry after an interrupted provision converges.
|
|
101
|
+
await this.runSql([
|
|
102
|
+
`COMMENT ON DATABASE ${ident(name)} IS ${literal(marker)};`,
|
|
103
|
+
`REVOKE ALL ON DATABASE ${ident(name)} FROM PUBLIC;`,
|
|
104
|
+
`GRANT CONNECT, TEMPORARY ON DATABASE ${ident(name)} TO ${ident(name)};`,
|
|
105
|
+
].join("\n"), signal);
|
|
106
|
+
await this.assertConfinedToOwnDatabase(name, password, signal);
|
|
107
|
+
return {
|
|
108
|
+
databaseName: name,
|
|
109
|
+
connectionString: [
|
|
110
|
+
`Host=${this.admin.host}`,
|
|
111
|
+
`Port=${this.admin.port}`,
|
|
112
|
+
`Database=${name}`,
|
|
113
|
+
`Username=${name}`,
|
|
114
|
+
`Password=${password}`,
|
|
115
|
+
"Timeout=15",
|
|
116
|
+
"Command Timeout=60",
|
|
117
|
+
`Maximum Pool Size=${attemptPoolSize}`,
|
|
118
|
+
].join(";"),
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (error instanceof Error) {
|
|
123
|
+
error.message = error.message.replaceAll(password, "[redacted]");
|
|
124
|
+
if (error.stack)
|
|
125
|
+
error.stack = error.stack.replaceAll(password, "[redacted]");
|
|
126
|
+
}
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
this.provisioning.delete(name);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
async release(dispatchAttemptId, fencingToken) {
|
|
134
|
+
const name = attemptDatabaseName(dispatchAttemptId);
|
|
135
|
+
const state = await this.state(name);
|
|
136
|
+
if (state.roleMarker === null && state.databaseOwner === null)
|
|
137
|
+
return "missing";
|
|
138
|
+
if (state.roleMarker !== brokeredDatabaseMarker(dispatchAttemptId, fencingToken, this.owner)
|
|
139
|
+
|| (state.databaseOwner !== null && state.databaseOwner !== name)) {
|
|
140
|
+
throw new AttemptDatabaseBrokerError("attempt_database_not_owned", `${name} is not this attempt's broker database and was left untouched.`);
|
|
141
|
+
}
|
|
142
|
+
return await this.drop(name);
|
|
143
|
+
}
|
|
144
|
+
async reapOrphans(isLive) {
|
|
145
|
+
const rows = await this.runSql([
|
|
146
|
+
"SELECT r.rolname, COALESCE(shobj_description(r.oid, 'pg_authid'), '') FROM pg_roles r",
|
|
147
|
+
"WHERE r.rolname ~ '^forge_attempt_[0-9a-f]{32}$';",
|
|
148
|
+
].join("\n"));
|
|
149
|
+
const dropped = [];
|
|
150
|
+
for (const line of rows.split(/\r?\n/u)) {
|
|
151
|
+
const separator = line.indexOf("|");
|
|
152
|
+
if (separator < 0)
|
|
153
|
+
continue;
|
|
154
|
+
const name = line.slice(0, separator);
|
|
155
|
+
const marker = line.slice(separator + 1);
|
|
156
|
+
if (!attemptNamePattern.test(name))
|
|
157
|
+
continue;
|
|
158
|
+
// Only this broker's exact-name role marker is ownership evidence; prefix matches are not.
|
|
159
|
+
const id = name.slice("forge_attempt_".length);
|
|
160
|
+
if (!new RegExp(`^forge_attempt_database:${markerVersion};id=${id};fence=[0-9a-f]{32};database=${name};owner=${this.owner}$`, "u")
|
|
161
|
+
.test(marker))
|
|
162
|
+
continue;
|
|
163
|
+
try {
|
|
164
|
+
const state = await this.state(name);
|
|
165
|
+
if (state.databaseOwner !== null && state.databaseOwner !== name)
|
|
166
|
+
continue;
|
|
167
|
+
// Asked last, so an attempt admitted while the role list was read is still spared.
|
|
168
|
+
if (this.provisioning.has(name) || isLive(uuidFromHex(id)))
|
|
169
|
+
continue;
|
|
170
|
+
if (await this.drop(name) === "dropped")
|
|
171
|
+
dropped.push(name);
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
// One stuck name must not stop the rest of the reap; it is retried next time.
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return dropped;
|
|
178
|
+
}
|
|
179
|
+
async state(name, signal) {
|
|
180
|
+
const output = await this.runSql([
|
|
181
|
+
`SELECT 'role', COALESCE(shobj_description(oid, 'pg_authid'), '') FROM pg_roles WHERE rolname = ${literal(name)}`,
|
|
182
|
+
"UNION ALL",
|
|
183
|
+
`SELECT 'database', pg_get_userbyid(datdba) FROM pg_database WHERE datname = ${literal(name)};`,
|
|
184
|
+
].join("\n"), signal);
|
|
185
|
+
let roleMarker = null;
|
|
186
|
+
let databaseOwner = null;
|
|
187
|
+
for (const line of output.split(/\r?\n/u)) {
|
|
188
|
+
const separator = line.indexOf("|");
|
|
189
|
+
if (separator < 0)
|
|
190
|
+
continue;
|
|
191
|
+
const kind = line.slice(0, separator);
|
|
192
|
+
const value = line.slice(separator + 1);
|
|
193
|
+
if (kind === "role")
|
|
194
|
+
roleMarker = value;
|
|
195
|
+
if (kind === "database")
|
|
196
|
+
databaseOwner = value;
|
|
197
|
+
}
|
|
198
|
+
return { roleMarker, databaseOwner };
|
|
199
|
+
}
|
|
200
|
+
async createDatabase(name, signal) {
|
|
201
|
+
// CREATE DATABASE needs template1 to itself for a moment; .NET test fixtures on the same
|
|
202
|
+
// cluster can hold it briefly.
|
|
203
|
+
for (let attempt = 1;; attempt += 1) {
|
|
204
|
+
try {
|
|
205
|
+
await this.runSql(`CREATE DATABASE ${ident(name)} OWNER ${ident(name)} TEMPLATE template1;`, signal);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
if (attempt >= 10 || !template1BusyPattern.test(String(error.message)))
|
|
210
|
+
throw error;
|
|
211
|
+
signal?.throwIfAborted();
|
|
212
|
+
await this.delay(500 * attempt);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
/** Fails closed unless the cluster lets this login reach its own database and nothing else. */
|
|
217
|
+
async assertConfinedToOwnDatabase(name, password, signal) {
|
|
218
|
+
const own = await this.runSql("SELECT current_user;", signal, { database: name, username: name, password });
|
|
219
|
+
if (own.trim() !== name) {
|
|
220
|
+
throw new AttemptDatabaseBrokerError("attempt_database_broker_failed", `${name} could not log in to its own database.`);
|
|
221
|
+
}
|
|
222
|
+
let confined = true;
|
|
223
|
+
// A database that cannot exist stands for every other name: pg_hba is checked before the
|
|
224
|
+
// database is looked up, so only a rule that rejects this role everywhere else rejects it.
|
|
225
|
+
const unmatched = `forge_confinement_probe_${randomBytes(8).toString("hex")}`;
|
|
226
|
+
for (const other of ["postgres", "template1", unmatched]) {
|
|
227
|
+
try {
|
|
228
|
+
await this.runSql("SELECT 1;", signal, { database: other, username: name, password });
|
|
229
|
+
confined = false;
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
if (!hbaRejectPattern.test(String(error.message)))
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
if (confined)
|
|
237
|
+
return;
|
|
238
|
+
await this.drop(name).catch(() => "retained");
|
|
239
|
+
throw new AttemptDatabaseBrokerError("attempt_database_cluster_unrestricted", "the native test cluster lets attempt roles log in to other databases; run scripts/setup-native-test-postgres.ps1 -Action RestrictAttemptRoles.");
|
|
240
|
+
}
|
|
241
|
+
async drop(name) {
|
|
242
|
+
try {
|
|
243
|
+
await this.runSql([
|
|
244
|
+
// Refuse new logins first, so nothing reconnects between the terminate and the drop.
|
|
245
|
+
`ALTER ROLE ${ident(name)} NOLOGIN;`,
|
|
246
|
+
`SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = ${literal(name)} OR usename = ${literal(name)};`,
|
|
247
|
+
`DROP DATABASE IF EXISTS ${ident(name)} WITH (FORCE);`,
|
|
248
|
+
`DROP OWNED BY ${ident(name)};`,
|
|
249
|
+
`DROP ROLE IF EXISTS ${ident(name)};`,
|
|
250
|
+
].join("\n"));
|
|
251
|
+
return "dropped";
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return "retained";
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
export function nativeTestClusterAdmin(fallback) {
|
|
259
|
+
const fields = new Map();
|
|
260
|
+
for (const segment of fallback.connectionString.split(";")) {
|
|
261
|
+
const separator = segment.indexOf("=");
|
|
262
|
+
if (separator <= 0)
|
|
263
|
+
continue;
|
|
264
|
+
fields.set(segment.slice(0, separator).trim().toLowerCase().replaceAll(" ", ""), segment.slice(separator + 1).trim());
|
|
265
|
+
}
|
|
266
|
+
const separator = fallback.endpoint.lastIndexOf(":");
|
|
267
|
+
const host = fallback.endpoint.slice(0, separator).replace(/^\[(.*)\]$/u, "$1");
|
|
268
|
+
const port = Number.parseInt(fallback.endpoint.slice(separator + 1), 10);
|
|
269
|
+
const username = fields.get("username") ?? fields.get("userid") ?? fields.get("user") ?? "";
|
|
270
|
+
return { host, port, username, password: fields.get("password") ?? "" };
|
|
271
|
+
}
|
|
272
|
+
/** Runs SQL through the psql that ships with the PostgreSQL install hosting the native test cluster. */
|
|
273
|
+
export function psqlSqlRunner(admin, psqlPath, timeoutMs = 120_000) {
|
|
274
|
+
return (sql, signal, login) => new Promise((resolve, reject) => {
|
|
275
|
+
const username = login?.username ?? admin.username;
|
|
276
|
+
const password = login?.password ?? admin.password;
|
|
277
|
+
const child = spawn(psqlPath, [
|
|
278
|
+
"-X", "-q", "-A", "-t", "-w",
|
|
279
|
+
"-v", "ON_ERROR_STOP=1",
|
|
280
|
+
"-h", admin.host,
|
|
281
|
+
"-p", String(admin.port),
|
|
282
|
+
"-U", username,
|
|
283
|
+
"-d", login?.database ?? "postgres",
|
|
284
|
+
], {
|
|
285
|
+
// Only what psql needs: never the Bridge's own environment.
|
|
286
|
+
env: {
|
|
287
|
+
PGPASSWORD: password,
|
|
288
|
+
PGCONNECT_TIMEOUT: "10",
|
|
289
|
+
PGAPPNAME: "Forge.Bridge.AttemptDatabaseBroker",
|
|
290
|
+
...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
|
|
291
|
+
...(process.env.PATH ? { PATH: process.env.PATH } : {}),
|
|
292
|
+
},
|
|
293
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
294
|
+
windowsHide: true,
|
|
295
|
+
signal,
|
|
296
|
+
});
|
|
297
|
+
let stdout = "";
|
|
298
|
+
let stderr = "";
|
|
299
|
+
const timer = setTimeout(() => child.kill(), timeoutMs);
|
|
300
|
+
child.stdout.setEncoding("utf8").on("data", chunk => { stdout += chunk; });
|
|
301
|
+
child.stderr.setEncoding("utf8").on("data", chunk => { stderr += chunk; });
|
|
302
|
+
child.once("error", error => {
|
|
303
|
+
clearTimeout(timer);
|
|
304
|
+
reject(error);
|
|
305
|
+
});
|
|
306
|
+
child.once("close", code => {
|
|
307
|
+
clearTimeout(timer);
|
|
308
|
+
if (code === 0)
|
|
309
|
+
resolve(stdout);
|
|
310
|
+
else
|
|
311
|
+
reject(new AttemptDatabaseBrokerError("attempt_database_broker_failed", stderr.trim().slice(-2_000).replaceAll(password, "[redacted]").replaceAll(admin.password, "[redacted]")
|
|
312
|
+
|| `psql exited with ${code}`));
|
|
313
|
+
});
|
|
314
|
+
child.stdin.end(sql);
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
/** psql beside the cluster's pg_ctl: FORGE_NATIVE_TEST_POSTGRES_PSQL, a Windows install, or PATH. */
|
|
318
|
+
export function resolvePsqlPath() {
|
|
319
|
+
const configured = process.env.FORGE_NATIVE_TEST_POSTGRES_PSQL?.trim();
|
|
320
|
+
if (configured)
|
|
321
|
+
return fs.existsSync(configured) ? configured : null;
|
|
322
|
+
if (process.platform === "win32") {
|
|
323
|
+
const root = path.join(process.env.ProgramFiles ?? "C:\\Program Files", "PostgreSQL");
|
|
324
|
+
let versions;
|
|
325
|
+
try {
|
|
326
|
+
versions = fs.readdirSync(root).filter(entry => /^\d+$/u.test(entry));
|
|
327
|
+
}
|
|
328
|
+
catch {
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
for (const version of versions.sort((left, right) => Number(right) - Number(left))) {
|
|
332
|
+
const candidate = path.join(root, version, "bin", "psql.exe");
|
|
333
|
+
if (fs.existsSync(candidate))
|
|
334
|
+
return candidate;
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
338
|
+
for (const directory of (process.env.PATH ?? "").split(path.delimiter)) {
|
|
339
|
+
const candidate = path.join(directory, "psql");
|
|
340
|
+
if (directory && fs.existsSync(candidate))
|
|
341
|
+
return candidate;
|
|
342
|
+
}
|
|
343
|
+
return null;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* The broker for this host, or null when no native test cluster is provisioned. Without a
|
|
347
|
+
* broker, Forge.Api still refuses to start in a managed host attempt; other applications run.
|
|
348
|
+
*/
|
|
349
|
+
export function createNativeTestClusterDatabaseBroker(readFallback, stateRoot) {
|
|
350
|
+
let fallback;
|
|
351
|
+
try {
|
|
352
|
+
fallback = readFallback();
|
|
353
|
+
}
|
|
354
|
+
catch {
|
|
355
|
+
// An unsafe cluster file is reported by pre-publication validation; it is never brokered.
|
|
356
|
+
return null;
|
|
357
|
+
}
|
|
358
|
+
const psqlPath = fallback ? resolvePsqlPath() : null;
|
|
359
|
+
if (!fallback || !psqlPath)
|
|
360
|
+
return null;
|
|
361
|
+
const admin = nativeTestClusterAdmin(fallback);
|
|
362
|
+
return new NativeTestClusterDatabaseBroker(admin, psqlSqlRunner(admin, psqlPath), attemptDatabaseBrokerOwner(stateRoot));
|
|
363
|
+
}
|
|
364
|
+
/** The exact strings to redact wherever a capability may be printed: the whole value and its password. */
|
|
365
|
+
export function attemptDatabaseCapabilitySecrets(capability) {
|
|
366
|
+
const value = capability?.trim();
|
|
367
|
+
if (!value)
|
|
368
|
+
return [];
|
|
369
|
+
const password = /(?:^|;)\s*Password\s*=\s*([^;]+)/iu.exec(value)?.[1]?.trim();
|
|
370
|
+
return password ? [value, password] : [value];
|
|
371
|
+
}
|
|
372
|
+
function uuidFromHex(value) {
|
|
373
|
+
return `${value.slice(0, 8)}-${value.slice(8, 12)}-${value.slice(12, 16)}-${value.slice(16, 20)}-${value.slice(20)}`;
|
|
374
|
+
}
|
|
375
|
+
function hex(uuid) {
|
|
376
|
+
const value = uuid.trim().toLowerCase().replaceAll("-", "");
|
|
377
|
+
if (!/^[0-9a-f]{32}$/u.test(value)) {
|
|
378
|
+
throw new AttemptDatabaseBrokerError("attempt_database_broker_invalid", "attempt identifiers must be UUIDs.");
|
|
379
|
+
}
|
|
380
|
+
return value;
|
|
381
|
+
}
|
|
382
|
+
function ident(name) {
|
|
383
|
+
if (!attemptNamePattern.test(name)) {
|
|
384
|
+
throw new AttemptDatabaseBrokerError("attempt_database_broker_invalid", `${name} is not an attempt database name.`);
|
|
385
|
+
}
|
|
386
|
+
return `"${name}"`;
|
|
387
|
+
}
|
|
388
|
+
function literal(value) {
|
|
389
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
390
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ProviderProcessHandlers, ProviderProcessRunRequest, ProviderProcessRunner, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
|
|
2
|
+
import { type ManagedCommandTeardownOptions, type ManagedCommandTeardownOutcome } from "./managed-command-teardown.js";
|
|
2
3
|
export type AttemptProcessChildStatus = "starting" | "running" | "stopping" | "exited" | "failed";
|
|
3
4
|
export type AttemptProcessSupervisorStatus = "active" | "stopping" | "stopped" | "degraded";
|
|
4
5
|
export interface AttemptProcessSupervisorIdentity {
|
|
@@ -32,6 +33,8 @@ export interface AttemptProcessSupervisorLedger {
|
|
|
32
33
|
readonly status: AttemptProcessSupervisorStatus;
|
|
33
34
|
readonly updatedAt: string;
|
|
34
35
|
readonly children: readonly AttemptProcessChildLedgerEntry[];
|
|
36
|
+
/** A provider-exit managed-command cleanup that failed and was left to attempt teardown. */
|
|
37
|
+
readonly deferredManagedCommandTeardownFailure?: string;
|
|
35
38
|
}
|
|
36
39
|
export interface AttemptProcessChildHandle {
|
|
37
40
|
readonly name: string;
|
|
@@ -46,6 +49,9 @@ export interface AttemptProcessChildHandle {
|
|
|
46
49
|
export interface AttemptProcessSupervisorOptions {
|
|
47
50
|
readonly metadataReadyTimeoutMs?: number;
|
|
48
51
|
readonly signal?: AbortSignal;
|
|
52
|
+
readonly replaceLedgerFile?: (temporaryPath: string, ledgerPath: string) => Promise<void>;
|
|
53
|
+
readonly ledgerReplaceRetryMs?: number;
|
|
54
|
+
readonly managedCommandTeardownGraceMs?: number;
|
|
49
55
|
}
|
|
50
56
|
export interface AttemptProcessChildReadyOptions {
|
|
51
57
|
readonly maxStartAttempts?: number;
|
|
@@ -62,6 +68,9 @@ export declare class AttemptProcessSupervisor {
|
|
|
62
68
|
readonly ledgerPath: string;
|
|
63
69
|
private readonly identity;
|
|
64
70
|
private readonly metadataReadyTimeoutMs;
|
|
71
|
+
private readonly replaceLedgerFile;
|
|
72
|
+
private readonly ledgerReplaceRetryMs;
|
|
73
|
+
private readonly managedCommandTeardownGraceMs;
|
|
65
74
|
private readonly records;
|
|
66
75
|
private readonly currentByName;
|
|
67
76
|
private readonly attemptController;
|
|
@@ -69,6 +78,8 @@ export declare class AttemptProcessSupervisor {
|
|
|
69
78
|
private persistTail;
|
|
70
79
|
private persistenceFailure;
|
|
71
80
|
private stopOperation;
|
|
81
|
+
private managedCommandTeardownTail;
|
|
82
|
+
private deferredManagedCommandTeardownFailure;
|
|
72
83
|
constructor(identity: AttemptProcessSupervisorIdentity, runner: ProviderProcessRunner, options?: AttemptProcessSupervisorOptions);
|
|
73
84
|
startChild(name: string, request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<AttemptProcessChildHandle>;
|
|
74
85
|
/**
|
|
@@ -82,10 +93,23 @@ export declare class AttemptProcessSupervisor {
|
|
|
82
93
|
stopChild(name: string, generation: number, fencingToken: string, reason?: unknown): Promise<ProviderProcessRunResult>;
|
|
83
94
|
stopAll(fencingToken: string, reason?: unknown): Promise<void>;
|
|
84
95
|
private performStopAll;
|
|
96
|
+
/**
|
|
97
|
+
* Stops the managed commands this attempt's MCP servers started and finalizes their
|
|
98
|
+
* receipts. With `onlyOrphaned`, a command whose owning MCP server is still alive is
|
|
99
|
+
* left running: it survives wait slices and MCP call boundaries within a live provider.
|
|
100
|
+
*/
|
|
101
|
+
terminateManagedCommands(options: Omit<ManagedCommandTeardownOptions, "graceMs">): Promise<readonly ManagedCommandTeardownOutcome[]>;
|
|
102
|
+
/**
|
|
103
|
+
* After a provider exits, stops the managed commands its MCP server left behind. It never
|
|
104
|
+
* fails the provider's result: a command it cannot prove stopped is recorded in the ledger
|
|
105
|
+
* and left to attempt teardown, which fails closed.
|
|
106
|
+
*/
|
|
107
|
+
stopOrphanedManagedCommands(): Promise<void>;
|
|
85
108
|
snapshot(): AttemptProcessSupervisorLedger;
|
|
86
109
|
providerMemoryTelemetry(): AttemptProcessTreeMemoryTelemetry | null;
|
|
87
110
|
private observeChildReady;
|
|
88
111
|
private settleChild;
|
|
112
|
+
private replaceLedger;
|
|
89
113
|
private assertFence;
|
|
90
114
|
private persist;
|
|
91
115
|
}
|
|
@@ -2,8 +2,15 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { ForgeFailureError, sanitizeFailureError } from "../session/session.types.js";
|
|
5
|
+
import { terminateAttemptManagedCommands, } from "./managed-command-teardown.js";
|
|
6
|
+
import { monotonicNowMs } from "../shared/time/monotonic.js";
|
|
5
7
|
const terminalChildStatuses = new Set(["exited", "failed"]);
|
|
6
8
|
const defaultMetadataReadyTimeoutMs = process.platform === "win32" ? 60_000 : 10_000;
|
|
9
|
+
// Windows refuses to replace a file another process (a scanner or indexer) briefly holds
|
|
10
|
+
// open. One such refusal must not degrade the attempt, so the ledger replace is retried.
|
|
11
|
+
const ledgerReplaceAttempts = 40;
|
|
12
|
+
const defaultLedgerReplaceRetryMs = 25;
|
|
13
|
+
const transientLedgerReplaceCodes = new Set(["EPERM", "EACCES", "EBUSY"]);
|
|
7
14
|
/**
|
|
8
15
|
* Owns the independently supervised process trees that belong to one host
|
|
9
16
|
* dispatch attempt. Each named child gets a distinct Windows Job Object or
|
|
@@ -15,6 +22,9 @@ export class AttemptProcessSupervisor {
|
|
|
15
22
|
ledgerPath;
|
|
16
23
|
identity;
|
|
17
24
|
metadataReadyTimeoutMs;
|
|
25
|
+
replaceLedgerFile;
|
|
26
|
+
ledgerReplaceRetryMs;
|
|
27
|
+
managedCommandTeardownGraceMs;
|
|
18
28
|
records = [];
|
|
19
29
|
currentByName = new Map();
|
|
20
30
|
attemptController = new AbortController();
|
|
@@ -22,10 +32,15 @@ export class AttemptProcessSupervisor {
|
|
|
22
32
|
persistTail = Promise.resolve();
|
|
23
33
|
persistenceFailure;
|
|
24
34
|
stopOperation = null;
|
|
35
|
+
managedCommandTeardownTail = Promise.resolve();
|
|
36
|
+
deferredManagedCommandTeardownFailure;
|
|
25
37
|
constructor(identity, runner, options = {}) {
|
|
26
38
|
this.runner = runner;
|
|
27
39
|
this.identity = validateIdentity(identity);
|
|
28
40
|
this.metadataReadyTimeoutMs = boundedInteger(options.metadataReadyTimeoutMs ?? defaultMetadataReadyTimeoutMs, 100, 120_000, "metadataReadyTimeoutMs");
|
|
41
|
+
this.replaceLedgerFile = options.replaceLedgerFile ?? ((temporaryPath, ledgerPath) => fs.rename(temporaryPath, ledgerPath));
|
|
42
|
+
this.ledgerReplaceRetryMs = options.ledgerReplaceRetryMs ?? defaultLedgerReplaceRetryMs;
|
|
43
|
+
this.managedCommandTeardownGraceMs = options.managedCommandTeardownGraceMs;
|
|
29
44
|
this.ledgerPath = path.join(this.identity.logDirectory, "attempt-process-supervisor.json");
|
|
30
45
|
if (options.signal?.aborted) {
|
|
31
46
|
this.status = "stopping";
|
|
@@ -189,6 +204,14 @@ export class AttemptProcessSupervisor {
|
|
|
189
204
|
const rejected = results.flatMap((result, index) => result.status === "rejected"
|
|
190
205
|
? [sanitizeFailureError(result.reason, active[index].failureRedactionValues)]
|
|
191
206
|
: []);
|
|
207
|
+
// Managed commands run in their own process groups, outside every child tree stopped
|
|
208
|
+
// above. The attempt is not stopped until each of them is proven stopped too.
|
|
209
|
+
try {
|
|
210
|
+
await this.terminateManagedCommands({ reason: "attempt_teardown" });
|
|
211
|
+
}
|
|
212
|
+
catch (error) {
|
|
213
|
+
rejected.push(error instanceof Error ? error : new Error(String(error)));
|
|
214
|
+
}
|
|
192
215
|
const terminalStatus = rejected.length > 0 || this.persistenceFailure !== undefined ? "degraded" : "stopped";
|
|
193
216
|
await this.persist({
|
|
194
217
|
...this.snapshot(),
|
|
@@ -202,6 +225,40 @@ export class AttemptProcessSupervisor {
|
|
|
202
225
|
if (this.persistenceFailure !== undefined)
|
|
203
226
|
throw this.persistenceFailure;
|
|
204
227
|
}
|
|
228
|
+
/**
|
|
229
|
+
* Stops the managed commands this attempt's MCP servers started and finalizes their
|
|
230
|
+
* receipts. With `onlyOrphaned`, a command whose owning MCP server is still alive is
|
|
231
|
+
* left running: it survives wait slices and MCP call boundaries within a live provider.
|
|
232
|
+
*/
|
|
233
|
+
async terminateManagedCommands(options) {
|
|
234
|
+
// One sweep at a time: a provider-exit sweep and attempt teardown would otherwise
|
|
235
|
+
// signal the same groups and write the same receipts concurrently, and stopAll must
|
|
236
|
+
// not report the attempt stopped while an earlier sweep is still writing.
|
|
237
|
+
const sweep = this.managedCommandTeardownTail.then(async () => await terminateAttemptManagedCommands({
|
|
238
|
+
logDirectory: this.identity.logDirectory,
|
|
239
|
+
dispatchAttemptId: this.identity.dispatchAttemptId,
|
|
240
|
+
runtimeLeaseId: this.identity.executionLeaseId,
|
|
241
|
+
}, {
|
|
242
|
+
...options,
|
|
243
|
+
...(this.managedCommandTeardownGraceMs === undefined ? {} : { graceMs: this.managedCommandTeardownGraceMs }),
|
|
244
|
+
}));
|
|
245
|
+
this.managedCommandTeardownTail = sweep.catch(() => undefined);
|
|
246
|
+
return await sweep;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* After a provider exits, stops the managed commands its MCP server left behind. It never
|
|
250
|
+
* fails the provider's result: a command it cannot prove stopped is recorded in the ledger
|
|
251
|
+
* and left to attempt teardown, which fails closed.
|
|
252
|
+
*/
|
|
253
|
+
async stopOrphanedManagedCommands() {
|
|
254
|
+
try {
|
|
255
|
+
await this.terminateManagedCommands({ reason: "owner_exited", onlyOrphaned: true });
|
|
256
|
+
}
|
|
257
|
+
catch (error) {
|
|
258
|
+
this.deferredManagedCommandTeardownFailure = boundedFailure(error, []);
|
|
259
|
+
await this.persist().catch(() => undefined);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
205
262
|
snapshot() {
|
|
206
263
|
return {
|
|
207
264
|
schemaVersion: 1,
|
|
@@ -210,6 +267,9 @@ export class AttemptProcessSupervisor {
|
|
|
210
267
|
executionLeaseId: this.identity.executionLeaseId,
|
|
211
268
|
status: this.status,
|
|
212
269
|
updatedAt: new Date().toISOString(),
|
|
270
|
+
...(this.deferredManagedCommandTeardownFailure
|
|
271
|
+
? { deferredManagedCommandTeardownFailure: this.deferredManagedCommandTeardownFailure }
|
|
272
|
+
: {}),
|
|
213
273
|
children: this.records.map(record => ({
|
|
214
274
|
name: record.name,
|
|
215
275
|
generation: record.generation,
|
|
@@ -248,8 +308,8 @@ export class AttemptProcessSupervisor {
|
|
|
248
308
|
};
|
|
249
309
|
}
|
|
250
310
|
async observeChildReady(record) {
|
|
251
|
-
const deadline =
|
|
252
|
-
while (
|
|
311
|
+
const deadline = monotonicNowMs() + this.metadataReadyTimeoutMs;
|
|
312
|
+
while (monotonicNowMs() <= deadline) {
|
|
253
313
|
if (await fileExists(record.metadataPath)) {
|
|
254
314
|
if (record.status === "starting") {
|
|
255
315
|
record.status = "running";
|
|
@@ -290,6 +350,20 @@ export class AttemptProcessSupervisor {
|
|
|
290
350
|
this.status = "degraded";
|
|
291
351
|
});
|
|
292
352
|
}
|
|
353
|
+
async replaceLedger(temporary) {
|
|
354
|
+
for (let attempt = 1;; attempt += 1) {
|
|
355
|
+
try {
|
|
356
|
+
await this.replaceLedgerFile(temporary, this.ledgerPath);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
catch (error) {
|
|
360
|
+
const code = error.code;
|
|
361
|
+
if (attempt >= ledgerReplaceAttempts || !code || !transientLedgerReplaceCodes.has(code))
|
|
362
|
+
throw error;
|
|
363
|
+
await wait(this.ledgerReplaceRetryMs);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
293
367
|
assertFence(fencingToken) {
|
|
294
368
|
if (fencingToken !== this.identity.fencingToken) {
|
|
295
369
|
throw new Error("attempt_process_supervisor_fenced: fencing token does not own this attempt.");
|
|
@@ -308,7 +382,7 @@ export class AttemptProcessSupervisor {
|
|
|
308
382
|
finally {
|
|
309
383
|
await handle.close();
|
|
310
384
|
}
|
|
311
|
-
await
|
|
385
|
+
await this.replaceLedger(temporary);
|
|
312
386
|
}
|
|
313
387
|
catch (error) {
|
|
314
388
|
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
|
@@ -6,6 +6,7 @@ import { assertCanonicalDirectory } from "./attempt-private-directory.js";
|
|
|
6
6
|
import { runAttemptArchiveOperation, runAttemptPathOperation } from "./attempt-path-operation.js";
|
|
7
7
|
import { readPinnedSourceDirectory } from "./pinned-source-directory.js";
|
|
8
8
|
import { compactHostAttemptId } from "./host-execution-root.js";
|
|
9
|
+
import { monotonicNowMs } from "../shared/time/monotonic.js";
|
|
9
10
|
const maximumEvidenceBytes = 200 * 1024 * 1024;
|
|
10
11
|
const diagnosticsRetentionDeadlineMs = 30_000;
|
|
11
12
|
const diagnosticsHelperTerminationConfirmationMs = 2_000;
|
|
@@ -21,7 +22,7 @@ export async function retainHostDiagnostics(stateRoot, attemptRoot, attemptId, e
|
|
|
21
22
|
const configuredDeadlineMs = Math.max(1, Math.min(diagnosticsRetentionDeadlineMs, Number.isFinite(requestedDeadlineMs) && (requestedDeadlineMs ?? 0) > 0
|
|
22
23
|
? Math.floor(requestedDeadlineMs)
|
|
23
24
|
: diagnosticsRetentionDeadlineMs));
|
|
24
|
-
const retentionDeadline =
|
|
25
|
+
const retentionDeadline = monotonicNowMs() + configuredDeadlineMs;
|
|
25
26
|
const identity = attemptId.replaceAll("-", "").toLowerCase();
|
|
26
27
|
const compactAttemptRoot = path.resolve(attemptOwnerRoot, "a", compactHostAttemptId(attemptId));
|
|
27
28
|
const legacyAttemptRoot = path.resolve(stateRoot, "host-attempts", identity);
|
|
@@ -155,7 +156,7 @@ function remainingHelperTiming(retentionDeadline, configuredDeadlineMs) {
|
|
|
155
156
|
return { operationTimeoutMs, terminationConfirmationMs };
|
|
156
157
|
}
|
|
157
158
|
function remainingRetentionMs(retentionDeadline, configuredDeadlineMs) {
|
|
158
|
-
const remainingMs = retentionDeadline -
|
|
159
|
+
const remainingMs = retentionDeadline - monotonicNowMs();
|
|
159
160
|
if (remainingMs <= 0)
|
|
160
161
|
throw diagnosticsDeadlineError(configuredDeadlineMs);
|
|
161
162
|
return remainingMs;
|
|
@@ -181,7 +182,7 @@ async function runWithinRetentionHelperDeadline(operation, retentionDeadline, co
|
|
|
181
182
|
return await operation();
|
|
182
183
|
}
|
|
183
184
|
catch (error) {
|
|
184
|
-
if (
|
|
185
|
+
if (monotonicNowMs() >= retentionDeadline)
|
|
185
186
|
throw diagnosticsDeadlineError(configuredDeadlineMs);
|
|
186
187
|
throw error;
|
|
187
188
|
}
|