@loucompanion/forge-bridge 0.1.4-dev.bfa11ebe98c6 → 0.1.4-dev.c03d3c89ec4a
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 +45 -3
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +84 -2
- package/dist/bridge/bridge.service.js +358 -12
- package/dist/bridge/bridge.types.d.ts +22 -0
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/runner-host-capabilities.d.ts +2 -0
- package/dist/bridge/runner-host-capabilities.js +4 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup.service.d.ts +9 -0
- package/dist/cleanup/cleanup.service.js +72 -109
- package/dist/cleanup/cleanup.types.d.ts +4 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
- package/dist/cleanup/host-runtime-ledger.js +109 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.js +20 -2
- package/dist/cli/cli.service.d.ts +16 -0
- package/dist/cli/cli.service.js +142 -16
- package/dist/cli/local-config.d.ts +4 -0
- package/dist/cli/local-config.js +26 -4
- package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
- 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-database-capability-boundary.d.ts +1 -1
- package/dist/runtime/host-database-capability-boundary.js +1 -0
- package/dist/runtime/host-diagnostics.js +4 -3
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-load-admission.d.ts +60 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +22 -0
- package/dist/runtime/host-load-child-environment.js +67 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +43 -0
- package/dist/runtime/host-load-governor-config.js +76 -0
- package/dist/runtime/host-load-governor.d.ts +174 -0
- package/dist/runtime/host-load-governor.js +541 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +185 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +78 -0
- package/dist/runtime/host-load-sampler.d.ts +126 -0
- package/dist/runtime/host-load-sampler.js +232 -0
- package/dist/runtime/host-load-step-class.d.ts +68 -0
- package/dist/runtime/host-load-step-class.js +106 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-token-ledger.d.ts +174 -0
- package/dist/runtime/host-load-token-ledger.js +421 -0
- package/dist/runtime/host-pressure-stall.d.ts +61 -0
- package/dist/runtime/host-pressure-stall.js +168 -0
- package/dist/runtime/host-runtime-contract.d.ts +4 -0
- package/dist/runtime/host-runtime-contract.js +75 -11
- package/dist/runtime/host-runtime-lease.d.ts +76 -4
- package/dist/runtime/host-runtime-lease.js +386 -32
- package/dist/runtime/host-runtime-promotion.d.ts +23 -0
- package/dist/runtime/host-runtime-promotion.js +48 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- 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 +18 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +61 -55
- package/dist/runtime/runner-settings.d.ts +100 -0
- package/dist/runtime/runner-settings.js +214 -0
- package/dist/sandbox/host-capacity-broker.d.ts +107 -0
- package/dist/sandbox/host-capacity-broker.js +315 -0
- package/dist/sandbox/repository-lock.js +3 -2
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +50 -6
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/managed-attempt-tools.d.ts +27 -0
- package/dist/session/managed-attempt-tools.js +366 -45
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +8 -4
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +7 -0
- package/dist/session/phase-completion.artifacts.js +98 -25
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +4 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +4 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -3
- package/dist/session/phase-completion.runtime.js +78 -36
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +206 -221
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +46 -92
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +60 -0
- package/dist/session/pre-publication-pass.js +145 -0
- package/dist/session/pre-publication-process.d.ts +23 -0
- package/dist/session/pre-publication-process.js +109 -0
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- package/dist/session/pre-publication-step-execution.d.ts +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +30 -20
- package/dist/session/pre-publication-validation.js +178 -193
- package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
- package/dist/session/provider-cli/pre-publication-repair.js +243 -0
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +37 -1
- package/dist/session/provider-cli/provider-cli.process.js +299 -25
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +62 -9
- 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.d.ts +4 -1
- package/dist/session/provider-cli/provider-cli.service.js +200 -162
- package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
- package/dist/session/provider-cli/provider-output-state.js +9 -0
- package/dist/session/provider-cli/provider-usage.d.ts +2 -1
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +229 -0
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +9 -2
- package/dist/session/session.service.js +120 -5
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +15 -3
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/process/host-process-recovery.js +3 -2
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +6 -5
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/shared/provider-capabilities.js +5 -6
- 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.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +120 -10
- package/dist/worktree/worktree.service.d.ts +10 -1
- package/dist/worktree/worktree.service.js +42 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +2 -2
|
@@ -30,8 +30,12 @@ export interface LocalRepoMapping extends BridgeRepoMapping {
|
|
|
30
30
|
export declare function resolveLocalConfigPath(): string;
|
|
31
31
|
export declare function readLocalConfig(): Promise<BridgeLocalConfig>;
|
|
32
32
|
export declare function readLocalConfigSync(): BridgeLocalConfig;
|
|
33
|
+
/** Decision 0014 §5: `bridge.json` holds the device token, so only its owner may read it. */
|
|
34
|
+
export declare const localConfigFileMode = 384;
|
|
33
35
|
export declare function writeLocalConfig(config: BridgeLocalConfig): Promise<void>;
|
|
34
36
|
export declare function applyLocalConfigDefaults(config: BridgeServiceConfig, local: BridgeLocalConfig): BridgeServiceConfig;
|
|
37
|
+
/** Decision 0014: the `forge-bridge yield` flag, beside the bridge config and never inside it. */
|
|
38
|
+
export declare function resolveLocalYieldFlagPath(): string;
|
|
35
39
|
export declare function addRepoMapping(label: string, repoPath: string): Promise<BridgeLocalConfig>;
|
|
36
40
|
export declare function removeRepoMapping(label: string): Promise<{
|
|
37
41
|
readonly config: BridgeLocalConfig;
|
package/dist/cli/local-config.js
CHANGED
|
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
|
|
|
2
2
|
import fsSync from "node:fs";
|
|
3
3
|
import os from "node:os";
|
|
4
4
|
import path from "node:path";
|
|
5
|
+
import { localYieldFlagPathFor } from "../bridge/local-yield-flag.js";
|
|
5
6
|
export function resolveLocalConfigPath() {
|
|
6
7
|
if (process.env.FORGE_BRIDGE_CONFIG?.trim()) {
|
|
7
8
|
return path.resolve(process.env.FORGE_BRIDGE_CONFIG);
|
|
@@ -28,12 +29,28 @@ export function readLocalConfigSync() {
|
|
|
28
29
|
}
|
|
29
30
|
return parseLocalConfig(fsSync.readFileSync(configPath, "utf8"));
|
|
30
31
|
}
|
|
32
|
+
/** Decision 0014 §5: `bridge.json` holds the device token, so only its owner may read it. */
|
|
33
|
+
export const localConfigFileMode = 0o600;
|
|
34
|
+
const localConfigDirectoryMode = 0o700;
|
|
31
35
|
export async function writeLocalConfig(config) {
|
|
32
36
|
const configPath = resolveLocalConfigPath();
|
|
33
|
-
await fs.mkdir(path.dirname(configPath), { recursive: true });
|
|
37
|
+
await fs.mkdir(path.dirname(configPath), { recursive: true, mode: localConfigDirectoryMode });
|
|
34
38
|
const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
|
|
35
|
-
|
|
36
|
-
|
|
39
|
+
try {
|
|
40
|
+
await fs.writeFile(tempPath, `${JSON.stringify(normalizeLocalConfig(config), null, 2)}\n`, {
|
|
41
|
+
encoding: "utf8",
|
|
42
|
+
mode: localConfigFileMode
|
|
43
|
+
});
|
|
44
|
+
if (process.platform !== "win32") {
|
|
45
|
+
// The create mode is masked by the umask; set it exactly before the file becomes visible.
|
|
46
|
+
await fs.chmod(tempPath, localConfigFileMode);
|
|
47
|
+
}
|
|
48
|
+
await fs.rename(tempPath, configPath);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
await fs.rm(tempPath, { force: true }).catch(() => undefined);
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
37
54
|
}
|
|
38
55
|
export function applyLocalConfigDefaults(config, local) {
|
|
39
56
|
const cliProviders = local.cliProviders && local.cliProviders.length > 0 ? [...local.cliProviders] : config.cliProviders;
|
|
@@ -65,9 +82,14 @@ export function applyLocalConfigDefaults(config, local) {
|
|
|
65
82
|
supportsRunnerAuthoredPhaseArtifacts: local.supportsRunnerAuthoredPhaseArtifacts ?? config.supportsRunnerAuthoredPhaseArtifacts,
|
|
66
83
|
supportsDraftRunOnce: local.supportsDraftRunOnce ?? config.supportsDraftRunOnce,
|
|
67
84
|
supportsDraftAttachments: local.supportsDraftAttachments ?? config.supportsDraftAttachments,
|
|
68
|
-
supportsDraftImageAttachments: local.supportsDraftImageAttachments ?? config.supportsDraftImageAttachments
|
|
85
|
+
supportsDraftImageAttachments: local.supportsDraftImageAttachments ?? config.supportsDraftImageAttachments,
|
|
86
|
+
localYieldFlagPath: resolveLocalYieldFlagPath()
|
|
69
87
|
};
|
|
70
88
|
}
|
|
89
|
+
/** Decision 0014: the `forge-bridge yield` flag, beside the bridge config and never inside it. */
|
|
90
|
+
export function resolveLocalYieldFlagPath() {
|
|
91
|
+
return localYieldFlagPathFor(resolveLocalConfigPath());
|
|
92
|
+
}
|
|
71
93
|
export async function addRepoMapping(label, repoPath) {
|
|
72
94
|
const normalizedLabel = normalizeLabel(label);
|
|
73
95
|
const localPath = path.resolve(repoPath);
|
|
@@ -211,7 +211,7 @@ async function aspNetBuildInputs(plan) {
|
|
|
211
211
|
const projectDirectory = path.extname(plan.projectPath).toLowerCase() === ".csproj"
|
|
212
212
|
? path.dirname(plan.projectPath)
|
|
213
213
|
: plan.projectPath;
|
|
214
|
-
const sourceDigest = await
|
|
214
|
+
const sourceDigest = await projectSourceDigest(plan, projectDirectory);
|
|
215
215
|
const dependencyReceipt = path.join(projectDirectory, "obj", ".forge-dependency-preparation.json");
|
|
216
216
|
const dependencyContent = await fs.readFile(dependencyReceipt).catch(() => null);
|
|
217
217
|
const globalJson = await findAncestorFile(projectDirectory, plan.worktreePath, "global.json");
|
|
@@ -225,18 +225,106 @@ async function aspNetBuildInputs(plan) {
|
|
|
225
225
|
sdkVersion: await dotnetSdkVersion(plan.cwd),
|
|
226
226
|
};
|
|
227
227
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
228
|
+
/**
|
|
229
|
+
* Digest of everything the project build compiles from inside the worktree: the
|
|
230
|
+
* project directory, every project it references (transitively, through
|
|
231
|
+
* ProjectReference), and the Directory.Build/Directory.Packages files above them.
|
|
232
|
+
* A change in a referenced project must invalidate the receipt, or the launch
|
|
233
|
+
* reuses a binary built from the previous source.
|
|
234
|
+
*/
|
|
235
|
+
async function projectSourceDigest(plan, projectDirectory) {
|
|
236
|
+
const worktree = path.resolve(plan.worktreePath);
|
|
237
|
+
const directories = await projectSourceDirectories(plan, projectDirectory);
|
|
238
|
+
const files = new Set();
|
|
239
|
+
for (const directory of directories) {
|
|
240
|
+
const collected = [];
|
|
241
|
+
await collectInputFiles(directory, directory, collected);
|
|
242
|
+
for (const file of collected)
|
|
243
|
+
files.add(file);
|
|
244
|
+
for (const buildFile of await ancestorBuildFiles(directory, worktree))
|
|
245
|
+
files.add(buildFile);
|
|
246
|
+
}
|
|
231
247
|
const hash = createHash("sha256");
|
|
232
|
-
for (const file of files.sort((left, right) => left.localeCompare(right))) {
|
|
233
|
-
hash.update(path.relative(
|
|
248
|
+
for (const file of [...files].sort((left, right) => left.localeCompare(right))) {
|
|
249
|
+
hash.update(path.relative(worktree, file).replaceAll("\\", "/"));
|
|
234
250
|
hash.update("\0");
|
|
235
251
|
hash.update(await fs.readFile(file));
|
|
236
252
|
hash.update("\0");
|
|
237
253
|
}
|
|
238
254
|
return `sha256:${hash.digest("hex")}`;
|
|
239
255
|
}
|
|
256
|
+
const msbuildProjectExtensions = new Set([".csproj", ".fsproj", ".vbproj"]);
|
|
257
|
+
const msbuildDirectoryFiles = ["Directory.Build.props", "Directory.Build.targets", "Directory.Packages.props"];
|
|
258
|
+
/** The project directory and the directories of the projects it references inside the worktree. */
|
|
259
|
+
async function projectSourceDirectories(plan, projectDirectory) {
|
|
260
|
+
const worktree = path.resolve(plan.worktreePath);
|
|
261
|
+
const directories = new Set([path.resolve(projectDirectory)]);
|
|
262
|
+
const queue = msbuildProjectExtensions.has(path.extname(plan.projectPath).toLowerCase())
|
|
263
|
+
? [path.resolve(plan.projectPath)]
|
|
264
|
+
: await projectFilesIn(projectDirectory);
|
|
265
|
+
const visited = new Set();
|
|
266
|
+
while (queue.length > 0) {
|
|
267
|
+
const projectFile = queue.shift();
|
|
268
|
+
if (visited.has(projectFile))
|
|
269
|
+
continue;
|
|
270
|
+
visited.add(projectFile);
|
|
271
|
+
const content = await fs.readFile(projectFile, "utf8").catch(() => null);
|
|
272
|
+
if (content === null)
|
|
273
|
+
continue;
|
|
274
|
+
for (const include of projectReferenceIncludes(content)) {
|
|
275
|
+
// An MSBuild property cannot be resolved here; the referenced source stays outside the digest.
|
|
276
|
+
if (include.includes("$("))
|
|
277
|
+
continue;
|
|
278
|
+
const referenced = path.resolve(path.dirname(projectFile), include.replaceAll("\\", "/"));
|
|
279
|
+
if (!containedIn(worktree, referenced))
|
|
280
|
+
continue;
|
|
281
|
+
directories.add(path.dirname(referenced));
|
|
282
|
+
queue.push(referenced);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return [...directories];
|
|
286
|
+
}
|
|
287
|
+
async function projectFilesIn(directory) {
|
|
288
|
+
const entries = await fs.readdir(directory, { withFileTypes: true }).catch(() => []);
|
|
289
|
+
return entries
|
|
290
|
+
.filter(entry => entry.isFile() && msbuildProjectExtensions.has(path.extname(entry.name).toLowerCase()))
|
|
291
|
+
.map(entry => path.join(directory, entry.name));
|
|
292
|
+
}
|
|
293
|
+
function projectReferenceIncludes(projectXml) {
|
|
294
|
+
const withoutComments = projectXml.replaceAll(/<!--[\s\S]*?-->/gu, "");
|
|
295
|
+
const includes = [];
|
|
296
|
+
for (const match of withoutComments.matchAll(/<ProjectReference\b[^>]*?\bInclude\s*=\s*(?:"([^"]*)"|'([^']*)')/giu)) {
|
|
297
|
+
const value = match[1] ?? match[2] ?? "";
|
|
298
|
+
for (const part of value.split(";")) {
|
|
299
|
+
const trimmed = part.trim();
|
|
300
|
+
if (trimmed)
|
|
301
|
+
includes.push(trimmed);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return includes;
|
|
305
|
+
}
|
|
306
|
+
async function ancestorBuildFiles(directory, worktree) {
|
|
307
|
+
const found = [];
|
|
308
|
+
let current = path.resolve(directory);
|
|
309
|
+
while (containedIn(worktree, current)) {
|
|
310
|
+
for (const name of msbuildDirectoryFiles) {
|
|
311
|
+
const candidate = path.join(current, name);
|
|
312
|
+
if (await fs.stat(candidate).then(stat => stat.isFile()).catch(() => false))
|
|
313
|
+
found.push(candidate);
|
|
314
|
+
}
|
|
315
|
+
if (current === worktree)
|
|
316
|
+
break;
|
|
317
|
+
const parent = path.dirname(current);
|
|
318
|
+
if (parent === current)
|
|
319
|
+
break;
|
|
320
|
+
current = parent;
|
|
321
|
+
}
|
|
322
|
+
return found;
|
|
323
|
+
}
|
|
324
|
+
function containedIn(root, candidate) {
|
|
325
|
+
const relative = path.relative(root, candidate);
|
|
326
|
+
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
|
|
327
|
+
}
|
|
240
328
|
async function collectInputFiles(root, directory, files) {
|
|
241
329
|
const entries = await fs.readdir(directory, { withFileTypes: true }).catch(() => []);
|
|
242
330
|
for (const entry of entries) {
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import type { NativeTestPostgresFallback } from "./native-test-postgres-fallback.js";
|
|
2
|
+
/**
|
|
3
|
+
* The managed host attempt's database capability. The Bridge keeps the test cluster's
|
|
4
|
+
* administrator credential; an attempt (its agent, its application runtime and its tests)
|
|
5
|
+
* receives only a login for one database created for it. Forge.Api checks that login before it
|
|
6
|
+
* migrates (AttemptScopedDatabasePolicy.AssertBrokeredCapabilityAsync), but that check runs in
|
|
7
|
+
* attempt code: the boundary is what this broker issues and the cluster's pg_hba rules, which
|
|
8
|
+
* let an attempt role log in only to its own database.
|
|
9
|
+
*/
|
|
10
|
+
export declare const attemptDatabaseCapabilityEnvironment = "FORGE_ATTEMPT_DATABASE_CAPABILITY";
|
|
11
|
+
export interface AttemptDatabaseCapability {
|
|
12
|
+
readonly databaseName: string;
|
|
13
|
+
readonly connectionString: string;
|
|
14
|
+
}
|
|
15
|
+
export type AttemptDatabaseReleaseOutcome = "dropped" | "missing" | "retained";
|
|
16
|
+
export interface AttemptDatabaseBroker {
|
|
17
|
+
provision(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal): Promise<AttemptDatabaseCapability>;
|
|
18
|
+
release(dispatchAttemptId: string, fencingToken: string): Promise<AttemptDatabaseReleaseOutcome>;
|
|
19
|
+
/**
|
|
20
|
+
* Drops this broker's databases whose attempt is no longer live, asking `isLive` about each one
|
|
21
|
+
* just before acting on it. Returns the dropped names.
|
|
22
|
+
*/
|
|
23
|
+
reapOrphans(isLive: (dispatchAttemptId: string) => boolean): Promise<readonly string[]>;
|
|
24
|
+
}
|
|
25
|
+
export declare class AttemptDatabaseBrokerError extends Error {
|
|
26
|
+
readonly code: string;
|
|
27
|
+
constructor(code: string, detail: string);
|
|
28
|
+
}
|
|
29
|
+
export interface AttemptDatabaseLogin {
|
|
30
|
+
readonly database: string;
|
|
31
|
+
readonly username: string;
|
|
32
|
+
readonly password: string;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Runs one psql script and returns its unaligned output: as the cluster administrator against
|
|
36
|
+
* `postgres`, or, given a login, as that login against its database.
|
|
37
|
+
*/
|
|
38
|
+
export type AttemptDatabaseSqlRunner = (sql: string, signal?: AbortSignal, login?: AttemptDatabaseLogin) => Promise<string>;
|
|
39
|
+
/**
|
|
40
|
+
* The ownership marker on the attempt's role. Only a role with CREATEROLE can change a role's
|
|
41
|
+
* comment, so the attempt cannot forge or erase it (it can rewrite its database's comment, which
|
|
42
|
+
* is therefore informational). Must match AttemptScopedDatabasePolicy.BrokeredRoleMarkerPrefix.
|
|
43
|
+
*/
|
|
44
|
+
export declare function brokeredDatabaseMarker(dispatchAttemptId: string, fencingToken: string, owner: string): string;
|
|
45
|
+
export declare function attemptDatabaseName(dispatchAttemptId: string): string;
|
|
46
|
+
/** Identifies one Bridge's broker on a shared cluster, so it reaps only databases it issued. */
|
|
47
|
+
export declare function attemptDatabaseBrokerOwner(stateRoot: string): string;
|
|
48
|
+
/**
|
|
49
|
+
* Brokers attempt databases on the dedicated native test cluster that
|
|
50
|
+
* scripts/setup-native-test-postgres.ps1 provisions. That cluster holds only disposable test
|
|
51
|
+
* databases, so even a leaked attempt capability cannot reach developer data. Each attempt
|
|
52
|
+
* gets a login role and a database it owns, cloned from template1 (which carries pgvector,
|
|
53
|
+
* an extension an unprivileged owner cannot create).
|
|
54
|
+
*/
|
|
55
|
+
export declare class NativeTestClusterDatabaseBroker implements AttemptDatabaseBroker {
|
|
56
|
+
private readonly admin;
|
|
57
|
+
private readonly runSql;
|
|
58
|
+
private readonly owner;
|
|
59
|
+
private readonly delay;
|
|
60
|
+
/** Names being provisioned right now; the reaper leaves them alone. */
|
|
61
|
+
private readonly provisioning;
|
|
62
|
+
constructor(admin: NativeTestClusterAdmin, runSql: AttemptDatabaseSqlRunner, owner: string, delay?: (milliseconds: number) => Promise<void>);
|
|
63
|
+
provision(dispatchAttemptId: string, fencingToken: string, signal?: AbortSignal): Promise<AttemptDatabaseCapability>;
|
|
64
|
+
release(dispatchAttemptId: string, fencingToken: string): Promise<AttemptDatabaseReleaseOutcome>;
|
|
65
|
+
reapOrphans(isLive: (dispatchAttemptId: string) => boolean): Promise<readonly string[]>;
|
|
66
|
+
private state;
|
|
67
|
+
private createDatabase;
|
|
68
|
+
/** Fails closed unless the cluster lets this login reach its own database and nothing else. */
|
|
69
|
+
private assertConfinedToOwnDatabase;
|
|
70
|
+
private drop;
|
|
71
|
+
}
|
|
72
|
+
export interface NativeTestClusterAdmin {
|
|
73
|
+
readonly host: string;
|
|
74
|
+
readonly port: number;
|
|
75
|
+
readonly username: string;
|
|
76
|
+
readonly password: string;
|
|
77
|
+
}
|
|
78
|
+
export declare function nativeTestClusterAdmin(fallback: NativeTestPostgresFallback): NativeTestClusterAdmin;
|
|
79
|
+
/** Runs SQL through the psql that ships with the PostgreSQL install hosting the native test cluster. */
|
|
80
|
+
export declare function psqlSqlRunner(admin: NativeTestClusterAdmin, psqlPath: string, timeoutMs?: number): AttemptDatabaseSqlRunner;
|
|
81
|
+
/** psql beside the cluster's pg_ctl: FORGE_NATIVE_TEST_POSTGRES_PSQL, a Windows install, or PATH. */
|
|
82
|
+
export declare function resolvePsqlPath(): string | null;
|
|
83
|
+
/**
|
|
84
|
+
* The broker for this host, or null when no native test cluster is provisioned. Without a
|
|
85
|
+
* broker, Forge.Api still refuses to start in a managed host attempt; other applications run.
|
|
86
|
+
*/
|
|
87
|
+
export declare function createNativeTestClusterDatabaseBroker(readFallback: () => NativeTestPostgresFallback | null, stateRoot: string): AttemptDatabaseBroker | null;
|
|
88
|
+
/** The exact strings to redact wherever a capability may be printed: the whole value and its password. */
|
|
89
|
+
export declare function attemptDatabaseCapabilitySecrets(capability: string | undefined): readonly string[];
|
|
@@ -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
|
+
}
|