@loucompanion/forge-bridge 0.1.4-dev.86fc5d1208e6 → 0.1.4-dev.8f4846c6e7a9
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 +2 -2
- package/dist/bridge/bridge.service.d.ts +14 -1
- package/dist/bridge/bridge.service.js +73 -8
- package/dist/bridge/bridge.types.d.ts +11 -0
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- 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/cli/cli.service.js +3 -1
- package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
- package/dist/runtime/attempt-process-supervisor.js +50 -0
- 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-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-load-admission.d.ts +52 -0
- package/dist/runtime/host-load-admission.js +84 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +8 -0
- package/dist/runtime/host-load-forge-cgroups.js +51 -0
- package/dist/runtime/host-load-governor-config.d.ts +34 -0
- package/dist/runtime/host-load-governor-config.js +46 -0
- package/dist/runtime/host-load-governor.d.ts +123 -0
- package/dist/runtime/host-load-governor.js +415 -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-sampler.d.ts +121 -0
- package/dist/runtime/host-load-sampler.js +224 -0
- package/dist/runtime/host-load-step-class.d.ts +33 -0
- package/dist/runtime/host-load-step-class.js +46 -0
- package/dist/runtime/host-load-token-ledger.d.ts +135 -0
- package/dist/runtime/host-load-token-ledger.js +345 -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 +6 -1
- package/dist/runtime/host-runtime-lease.d.ts +13 -2
- package/dist/runtime/host-runtime-lease.js +82 -11
- package/dist/runtime/host-runtime-promotion.js +12 -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/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/session/managed-attempt-tools.d.ts +25 -0
- package/dist/session/managed-attempt-tools.js +212 -15
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +4 -1
- package/dist/session/phase-completion.artifacts.js +4 -0
- package/dist/session/phase-completion.runtime.js +22 -17
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +96 -0
- package/dist/session/pre-publication-process.d.ts +20 -0
- package/dist/session/pre-publication-process.js +97 -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 +9 -9
- package/dist/session/pre-publication-validation.js +44 -112
- 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 +297 -23
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
- package/dist/session/provider-cli/provider-cli.service.js +126 -26
- 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/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/session.base.d.ts +3 -0
- package/dist/session/session.service.d.ts +2 -0
- package/dist/session/session.service.js +5 -0
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +14 -2
- 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
package/README.md
CHANGED
|
@@ -190,9 +190,9 @@ Production shared runners require a Linux rootless Docker daemon. Docker Desktop
|
|
|
190
190
|
|
|
191
191
|
Before selecting `sandbox_required`, save the full approved 40- or 64-character Git commit SHA in the project's Sandbox policy dialog. The server persists that SHA on the immutable attempt and the bridge reads `.forge/forge.sandbox.yml`, `.forge/Dockerfile`, and the tracked build context only from that commit. API-key dispatches carry an opaque one-time grant handle; the authenticated current runner instance redeems it after reservation, and plaintext stays out of offers, database payloads, Docker metadata, and host-persisted control files.
|
|
192
192
|
|
|
193
|
-
Temporary host fallback for `sandbox_preferred` requires both sides to opt in: a project owner must save a reason and future expiry (maximum 30 days), and an operator must enable **Host fallback** for the runner in
|
|
193
|
+
Temporary host fallback for `sandbox_preferred` requires both sides to opt in: a project owner must save a reason and future expiry (maximum 30 days), and an operator must enable **Host fallback** for the runner in Settings › Runners. Either missing or expired authorization fails closed. `sandbox_required` never falls back.
|
|
194
194
|
|
|
195
|
-
The bridge reaps exact-labeled orphan resources before connecting and every minute afterward. Connected passes reconcile current-instance ledgers against an authoritative, instance-scoped server attempt snapshot; startup does not adopt old-instance resources and terminates them before advertising capacity. Per-resource removal outcomes are written mode-0600 under `FORGE_SANDBOX_STATE_ROOT/cleanup-reports` before transmission, replayed after reconnect, acknowledged by report ID, and persisted by the API only when attempt, fence, resource runner instance, and current reporting runner match. Fenced dispatch events also persist image/cache status, build/agent-start/import/teardown timestamps, and a validated inventory of created agent/sidecar containers, networks, volumes, and published ports. Selected-session diagnostics expose that lifecycle data and recent cleanup actions while retaining cleanup-pending state after the agent outcome is terminal. Install `forge-bridge sandbox reap` as an independently supervised OS timer with the same `FORGE_RUNNER_ID`, Docker context, and state root so resources are reconciled while the bridge is down; the Docker-context ownership lock makes an overlapping pass fail safely. A non-zero `degradedReservationCount` means teardown has not completed; the affected capacity remains unavailable until a successful reaper pass. Drain a runner from
|
|
195
|
+
The bridge reaps exact-labeled orphan resources before connecting and every minute afterward. Connected passes reconcile current-instance ledgers against an authoritative, instance-scoped server attempt snapshot; startup does not adopt old-instance resources and terminates them before advertising capacity. Per-resource removal outcomes are written mode-0600 under `FORGE_SANDBOX_STATE_ROOT/cleanup-reports` before transmission, replayed after reconnect, acknowledged by report ID, and persisted by the API only when attempt, fence, resource runner instance, and current reporting runner match. Fenced dispatch events also persist image/cache status, build/agent-start/import/teardown timestamps, and a validated inventory of created agent/sidecar containers, networks, volumes, and published ports. Selected-session diagnostics expose that lifecycle data and recent cleanup actions while retaining cleanup-pending state after the agent outcome is terminal. Install `forge-bridge sandbox reap` as an independently supervised OS timer with the same `FORGE_RUNNER_ID`, Docker context, and state root so resources are reconciled while the bridge is down; the Docker-context ownership lock makes an overlapping pass fail safely. A non-zero `degradedReservationCount` means teardown has not completed; the affected capacity remains unavailable until a successful reaper pass. Drain a runner from Settings › Runners before upgrades or Docker maintenance, wait for active/starting counts to reach zero, then restart the bridge. Settings › Runners also exposes a scoped **Reap** action; the API delivers it only to the currently established protocol-v2 runner instance. Image GC runs only while disk pressure is latched, shares the build lock, preserves active image digests, and prunes only expired images beyond the per-project retention count. Lease renewals are HMAC-bound to the attempt and fence and advance an in-container monotonic deadline; lease, hard-wall, and idle expiry produce distinct failure codes.
|
|
196
196
|
|
|
197
197
|
Every attempt-owned container (including short-lived initialization helpers), network, and volume carries `dev.forge.resource-lease-id` equal to the dispatch execution lease. Ledger schema v2 persists the same `resourceLeaseId`; teardown compares the complete expected label set, and orphan reaping fails closed unless the managed, resource-lease, execution-lease, attempt, runner, runner-instance, and fencing identities are all present and consistent.
|
|
198
198
|
|
|
@@ -7,6 +7,7 @@ import type { SandboxPreflightResult } from "../sandbox/sandbox.types.js";
|
|
|
7
7
|
import { type SandboxRuntime } from "../sandbox/runtime.js";
|
|
8
8
|
import type { BridgeConnection, BridgeConnectionFactory, BridgeService } from "./bridge.base.js";
|
|
9
9
|
import { type RunnerHostCapabilityProbe } from "./runner-host-capabilities.js";
|
|
10
|
+
import { type HostLoadSource } from "../runtime/host-load-sampler.js";
|
|
10
11
|
import type { BridgeCancelHandler, BridgeChatTurnHandler, BridgeDispatchHandler, BridgeLeaseUpdateRequest, BridgeReapRequest, BridgeServiceConfig } from "./bridge.types.js";
|
|
11
12
|
import { type ReadinessResultOutbox } from "./readiness-result-outbox.js";
|
|
12
13
|
import { type DispatchResultOutbox } from "./dispatch-result-outbox.js";
|
|
@@ -29,6 +30,7 @@ export declare class ForgeBridgeService implements BridgeService {
|
|
|
29
30
|
private readonly connections;
|
|
30
31
|
private readonly hostCapabilityProbe;
|
|
31
32
|
private readonly chatProcessRunner;
|
|
33
|
+
private readonly hostLoad;
|
|
32
34
|
private connection;
|
|
33
35
|
private heartbeatTimer;
|
|
34
36
|
private heartbeatInFlight;
|
|
@@ -58,9 +60,11 @@ export declare class ForgeBridgeService implements BridgeService {
|
|
|
58
60
|
private readonly sessions;
|
|
59
61
|
private readonly enforceHostDatabaseCapabilityBoundary;
|
|
60
62
|
private hostCapabilities;
|
|
63
|
+
private dockerAvailable;
|
|
64
|
+
private hostRequirementFacts;
|
|
61
65
|
private readonly recoveredHostAttempts;
|
|
62
66
|
private hostCapabilitiesDetected;
|
|
63
|
-
constructor(config: BridgeServiceConfig, sessions?: SessionService | undefined, connections?: BridgeConnectionFactory, preflight?: DockerPreflight, sandboxRuntime?: SandboxRuntime, sandboxResourceResolver?: SandboxResourceResolver, dockerEngineProbe?: DockerEngineProbe, hostCapabilityProbe?: RunnerHostCapabilityProbe, readinessResultOutbox?: ReadinessResultOutbox, chatProcessRunner?: ProviderProcessRunner, dispatchResultOutbox?: DispatchResultOutbox);
|
|
67
|
+
constructor(config: BridgeServiceConfig, sessions?: SessionService | undefined, connections?: BridgeConnectionFactory, preflight?: DockerPreflight, sandboxRuntime?: SandboxRuntime, sandboxResourceResolver?: SandboxResourceResolver, dockerEngineProbe?: DockerEngineProbe, hostCapabilityProbe?: RunnerHostCapabilityProbe, readinessResultOutbox?: ReadinessResultOutbox, chatProcessRunner?: ProviderProcessRunner, dispatchResultOutbox?: DispatchResultOutbox, hostLoad?: HostLoadSource);
|
|
64
68
|
connectOnce(): Promise<void>;
|
|
65
69
|
private rememberRecoveredHostAttempts;
|
|
66
70
|
private recoveredHostAttemptsForHello;
|
|
@@ -107,6 +111,15 @@ export declare class ForgeBridgeService implements BridgeService {
|
|
|
107
111
|
private sendResultPayloadDirect;
|
|
108
112
|
private flushDispatchResults;
|
|
109
113
|
private flushDispatchResultsCore;
|
|
114
|
+
/**
|
|
115
|
+
* Forge binds each result to the runner instance that ran the attempt. On an
|
|
116
|
+
* authoritative connection it rejects another instance's result with
|
|
117
|
+
* bridge.stale_result_instance; Forge's own recovery handles that attempt,
|
|
118
|
+
* so the record can never be delivered and must not block the replay queue.
|
|
119
|
+
* bridge.stale_runner_instance means this connection is not authoritative
|
|
120
|
+
* and says nothing about the record, so it never quarantines.
|
|
121
|
+
*/
|
|
122
|
+
private isReplacedRunnerInstanceResult;
|
|
110
123
|
private startHeartbeat;
|
|
111
124
|
private heartbeatTick;
|
|
112
125
|
private startLeaseWatchdog;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
|
|
1
2
|
import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
|
|
2
3
|
import fs from "node:fs";
|
|
3
4
|
import path from "node:path";
|
|
@@ -33,8 +34,9 @@ import { codexSandboxProviderAuthAdapter, sandboxProviderAuthAdapterFor, sandbox
|
|
|
33
34
|
import { assertBridgeChatCallbackPayload, bridgeChatMaxProviderThreadIdChars, bridgeChatProtocolVersion, isTerminalChatTurnCallbackKind, parseChatTurnDispatchPacket, } from "./bridge-chat.types.js";
|
|
34
35
|
import { formatBytes } from "../shared/format/format-bytes.js";
|
|
35
36
|
import { emptyRunnerHostCapabilitySnapshot, ProcessRunnerHostCapabilityProbe, } from "./runner-host-capabilities.js";
|
|
37
|
+
import { HostLoadSampler } from "../runtime/host-load-sampler.js";
|
|
36
38
|
import { FileReadinessResultOutbox } from "./readiness-result-outbox.js";
|
|
37
|
-
import { FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
|
|
39
|
+
import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
|
|
38
40
|
/**
|
|
39
41
|
* Protocol-v2 events are acknowledged one at a time before runOnce returns.
|
|
40
42
|
* Sending the complete transcript again in DispatchResult made long QA and CI
|
|
@@ -53,6 +55,7 @@ export class ForgeBridgeService {
|
|
|
53
55
|
connections;
|
|
54
56
|
hostCapabilityProbe;
|
|
55
57
|
chatProcessRunner;
|
|
58
|
+
hostLoad;
|
|
56
59
|
connection = null;
|
|
57
60
|
heartbeatTimer = null;
|
|
58
61
|
heartbeatInFlight = false;
|
|
@@ -82,16 +85,31 @@ export class ForgeBridgeService {
|
|
|
82
85
|
sessions;
|
|
83
86
|
enforceHostDatabaseCapabilityBoundary;
|
|
84
87
|
hostCapabilities = emptyRunnerHostCapabilitySnapshot();
|
|
88
|
+
dockerAvailable = false;
|
|
89
|
+
hostRequirementFacts() {
|
|
90
|
+
const facts = this.hostLoad.facts();
|
|
91
|
+
return {
|
|
92
|
+
logicalThreads: facts?.logicalThreads ?? os.cpus().length,
|
|
93
|
+
totalMemoryBytes: facts?.totalMemoryBytes ?? os.totalmem(),
|
|
94
|
+
availableToolchains: Object.entries(this.hostCapabilities.toolchains)
|
|
95
|
+
.filter(([, tool]) => tool?.available === true)
|
|
96
|
+
.map(([name]) => name),
|
|
97
|
+
dockerAvailable: this.dockerAvailable,
|
|
98
|
+
browserLaunch: this.hostCapabilities.browserLaunch,
|
|
99
|
+
testPostgresSuperuser: this.hostCapabilities.testPostgres.superuser,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
85
102
|
// Reaping deletes the stale ledger, so its stopped-process proof is held here
|
|
86
103
|
// until a Hello carrying it is accepted. A bridge restart forgets it, which
|
|
87
104
|
// leaves those attempts on Forge's conservative unknown-outcome path.
|
|
88
105
|
recoveredHostAttempts = new Map();
|
|
89
106
|
hostCapabilitiesDetected = false;
|
|
90
|
-
constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox) {
|
|
107
|
+
constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox, hostLoad = new HostLoadSampler()) {
|
|
91
108
|
this.config = config;
|
|
92
109
|
this.connections = connections;
|
|
93
110
|
this.hostCapabilityProbe = hostCapabilityProbe;
|
|
94
111
|
this.chatProcessRunner = chatProcessRunner;
|
|
112
|
+
this.hostLoad = hostLoad;
|
|
95
113
|
this.enforceHostDatabaseCapabilityBoundary = sessions === undefined;
|
|
96
114
|
if (this.enforceHostDatabaseCapabilityBoundary) {
|
|
97
115
|
establishHostDatabaseCapabilityBoundary();
|
|
@@ -123,7 +141,7 @@ export class ForgeBridgeService {
|
|
|
123
141
|
},
|
|
124
142
|
onStatus: logBridgeStatus,
|
|
125
143
|
});
|
|
126
|
-
this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe);
|
|
144
|
+
this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
|
|
127
145
|
this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
|
|
128
146
|
this.sandboxResourceResolver = sandboxResourceResolver
|
|
129
147
|
?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
|
|
@@ -156,6 +174,10 @@ export class ForgeBridgeService {
|
|
|
156
174
|
this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
|
|
157
175
|
this.hostCapabilitiesDetected = true;
|
|
158
176
|
}
|
|
177
|
+
// Static host facts and the first load sample ride on Hello; the sampler
|
|
178
|
+
// keeps refreshing its cached snapshot for later heartbeats.
|
|
179
|
+
await this.hostLoad.start().catch(() => undefined);
|
|
180
|
+
this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
|
|
159
181
|
const connection = this.connections.create(this.config);
|
|
160
182
|
this.connection = connection;
|
|
161
183
|
this.transportRecovery = null;
|
|
@@ -306,6 +328,7 @@ export class ForgeBridgeService {
|
|
|
306
328
|
this.abortActiveSessions("bridge stopping");
|
|
307
329
|
this.abortActiveReadinessProbes("bridge stopping");
|
|
308
330
|
await this.stopConnection();
|
|
331
|
+
this.hostLoad.stop();
|
|
309
332
|
await this.preflight.release();
|
|
310
333
|
}
|
|
311
334
|
async handleChatTurn(rawDispatch) {
|
|
@@ -1468,6 +1491,19 @@ export class ForgeBridgeService {
|
|
|
1468
1491
|
await this.dispatchResultOutbox.acknowledge(pending.payload.leaseId);
|
|
1469
1492
|
continue;
|
|
1470
1493
|
}
|
|
1494
|
+
if (this.isReplacedRunnerInstanceResult(pending.payload, error)) {
|
|
1495
|
+
try {
|
|
1496
|
+
await this.dispatchResultOutbox.quarantine(pending);
|
|
1497
|
+
}
|
|
1498
|
+
catch (quarantineError) {
|
|
1499
|
+
// Keep the record and surface Forge's rejection: replay stays
|
|
1500
|
+
// deferred and a heartbeat tick does not count it as a failure.
|
|
1501
|
+
logBridgeStatus(`Dispatch result ${pending.payload.leaseId} from replaced runner instance ${pending.payload.runnerInstanceId} could not be quarantined: ${errorMessage(quarantineError)}`);
|
|
1502
|
+
throw error;
|
|
1503
|
+
}
|
|
1504
|
+
logBridgeStatus(`Quarantined dispatch result ${pending.payload.leaseId}: Forge rejected it because it belongs to replaced runner instance ${pending.payload.runnerInstanceId}. Forge's own recovery handles that instance's attempt; the redacted result is kept in ${dispatchResultQuarantineDirectory} for reconciliation.`);
|
|
1505
|
+
continue;
|
|
1506
|
+
}
|
|
1471
1507
|
throw error;
|
|
1472
1508
|
}
|
|
1473
1509
|
}
|
|
@@ -1478,6 +1514,20 @@ export class ForgeBridgeService {
|
|
|
1478
1514
|
this.dispatchResultFlushedGeneration = startedGeneration;
|
|
1479
1515
|
}
|
|
1480
1516
|
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Forge binds each result to the runner instance that ran the attempt. On an
|
|
1519
|
+
* authoritative connection it rejects another instance's result with
|
|
1520
|
+
* bridge.stale_result_instance; Forge's own recovery handles that attempt,
|
|
1521
|
+
* so the record can never be delivered and must not block the replay queue.
|
|
1522
|
+
* bridge.stale_runner_instance means this connection is not authoritative
|
|
1523
|
+
* and says nothing about the record, so it never quarantines.
|
|
1524
|
+
*/
|
|
1525
|
+
isReplacedRunnerInstanceResult(payload, error) {
|
|
1526
|
+
return error instanceof BridgeCallbackRejectedError
|
|
1527
|
+
&& error.code === "bridge.stale_result_instance"
|
|
1528
|
+
&& typeof payload.runnerInstanceId === "string"
|
|
1529
|
+
&& payload.runnerInstanceId.toLowerCase() !== this.config.runnerInstanceId.toLowerCase();
|
|
1530
|
+
}
|
|
1481
1531
|
startHeartbeat() {
|
|
1482
1532
|
this.stopHeartbeat();
|
|
1483
1533
|
this.consecutiveHeartbeatFailures = 0;
|
|
@@ -1496,8 +1546,11 @@ export class ForgeBridgeService {
|
|
|
1496
1546
|
return;
|
|
1497
1547
|
this.heartbeatInFlight = true;
|
|
1498
1548
|
try {
|
|
1499
|
-
|
|
1500
|
-
|
|
1549
|
+
// A rejected replay is an answer from Forge, so the connection is alive:
|
|
1550
|
+
// an undeliverable record must not count as a heartbeat failure and
|
|
1551
|
+
// force reconnects. Transport failures still do.
|
|
1552
|
+
await this.flushDispatchResults().catch(deferRejectedReplay("Dispatch"));
|
|
1553
|
+
await this.flushReadinessResults().catch(deferRejectedReplay("Readiness"));
|
|
1501
1554
|
await this.sendHeartbeat();
|
|
1502
1555
|
this.consecutiveHeartbeatFailures = 0;
|
|
1503
1556
|
}
|
|
@@ -1640,6 +1693,7 @@ export class ForgeBridgeService {
|
|
|
1640
1693
|
capabilities() {
|
|
1641
1694
|
const preflight = this.preflight.current();
|
|
1642
1695
|
const dockerEngine = this.dockerEngineProbe.current();
|
|
1696
|
+
this.dockerAvailable = dockerEngine?.available === true;
|
|
1643
1697
|
const runtimeState = this.sandboxRuntime.snapshot();
|
|
1644
1698
|
const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
|
|
1645
1699
|
const used = this.usedSandboxResources(runtimeState.degraded);
|
|
@@ -1656,7 +1710,7 @@ export class ForgeBridgeService {
|
|
|
1656
1710
|
pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
|
|
1657
1711
|
}) : null;
|
|
1658
1712
|
return {
|
|
1659
|
-
schemaVersion:
|
|
1713
|
+
schemaVersion: 7,
|
|
1660
1714
|
activeSessionCount: this.activeSessions.size,
|
|
1661
1715
|
cliProviders: this.config.cliProviders,
|
|
1662
1716
|
providerStatuses: this.config.providerStatuses,
|
|
@@ -1679,6 +1733,9 @@ export class ForgeBridgeService {
|
|
|
1679
1733
|
playwrightProjects: this.hostCapabilities.playwrightProjects,
|
|
1680
1734
|
browserLaunch: this.hostCapabilities.browserLaunch,
|
|
1681
1735
|
providerConnectivity: this.hostCapabilities.providerConnectivity,
|
|
1736
|
+
testPostgres: this.hostCapabilities.testPostgres,
|
|
1737
|
+
host: this.hostLoad.facts(),
|
|
1738
|
+
load: this.hostLoad.current(),
|
|
1682
1739
|
maxConcurrentSandboxes: capacity.sandboxSlots,
|
|
1683
1740
|
reservedSandboxCount: reserved,
|
|
1684
1741
|
activeSandboxCount: runtimeState.active,
|
|
@@ -1880,6 +1937,13 @@ class BridgeCallbackRejectedError extends Error {
|
|
|
1880
1937
|
this.name = "BridgeCallbackRejectedError";
|
|
1881
1938
|
}
|
|
1882
1939
|
}
|
|
1940
|
+
function deferRejectedReplay(kind) {
|
|
1941
|
+
return error => {
|
|
1942
|
+
if (!(error instanceof BridgeCallbackRejectedError))
|
|
1943
|
+
throw error;
|
|
1944
|
+
logBridgeStatus(`${kind} result replay deferred: ${errorMessage(error)}`);
|
|
1945
|
+
};
|
|
1946
|
+
}
|
|
1883
1947
|
function isDispatchNoLongerPending(error) {
|
|
1884
1948
|
if (error instanceof BridgeCallbackRejectedError) {
|
|
1885
1949
|
return error.code === "bridge.dispatch_not_pending" || error.code === "bridge.stale_dispatch";
|
|
@@ -1898,11 +1962,12 @@ function isProviderStorageUnavailable(error) {
|
|
|
1898
1962
|
function isBridgeCallbackTimeout(error) {
|
|
1899
1963
|
return errorMessage(error).startsWith("bridge_callback_timeout:");
|
|
1900
1964
|
}
|
|
1901
|
-
function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe) {
|
|
1965
|
+
function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
|
|
1902
1966
|
const rawProcessRunner = new StreamingProviderProcessRunner();
|
|
1903
1967
|
const processSupervisors = new AttemptProcessSupervisorRegistry();
|
|
1904
1968
|
const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
|
|
1905
|
-
|
|
1969
|
+
const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
|
|
1970
|
+
return new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot)), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
|
|
1906
1971
|
}
|
|
1907
1972
|
export class SignalRBridgeConnectionFactory {
|
|
1908
1973
|
create(config) {
|
|
@@ -1,8 +1,12 @@
|
|
|
1
|
+
import type { HostRuntimeRequirements } from "../runtime/host-runtime-requirements.js";
|
|
2
|
+
import type { BridgeTestPostgresCapability } from "./test-postgres-capability.js";
|
|
1
3
|
import type { ApiKeySecretGrant, DispatchSandboxResourceRequest, RunOnceResultPacket, RunnerDispatchEvent } from "../session/session.types.js";
|
|
2
4
|
import type { SandboxFeatureMatrix } from "../sandbox/sandbox.types.js";
|
|
3
5
|
import type { HostRuntimeCapacitySnapshot } from "../runtime/host-runtime-lease.js";
|
|
4
6
|
import type { MemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
|
|
5
7
|
import type { DockerEngineCapabilitySnapshot } from "../runtime/docker-engine-probe.js";
|
|
8
|
+
import type { HostFacts } from "../runtime/host-facts.js";
|
|
9
|
+
import type { HostLoadSnapshot } from "../runtime/host-load-sampler.js";
|
|
6
10
|
import type { BridgeChatCapability, ChatTurnCancelPacket } from "./bridge-chat.types.js";
|
|
7
11
|
export interface BridgeServiceConfig {
|
|
8
12
|
readonly serverUrl: string;
|
|
@@ -142,6 +146,12 @@ export interface BridgeCapabilities {
|
|
|
142
146
|
readonly playwrightProjects?: readonly string[] | null;
|
|
143
147
|
readonly browserLaunch?: boolean | null;
|
|
144
148
|
readonly providerConnectivity?: Readonly<Record<string, boolean>> | null;
|
|
149
|
+
/** Native test PostgreSQL and whether its role is a superuser (decision 0013 placement). */
|
|
150
|
+
readonly testPostgres?: BridgeTestPostgresCapability | null;
|
|
151
|
+
/** Static host hardware facts (schema 7). Material: changes are persisted immediately. */
|
|
152
|
+
readonly host?: HostFacts | null;
|
|
153
|
+
/** Live host load sample (schema 7). Never material: heartbeats with only load changes are not persisted. */
|
|
154
|
+
readonly load?: HostLoadSnapshot | null;
|
|
145
155
|
}
|
|
146
156
|
export interface SandboxMemoryCapacityDiagnostics {
|
|
147
157
|
readonly defaultWorkerMemoryLimitBytes: number;
|
|
@@ -292,6 +302,7 @@ export interface BridgeRuntimeReadinessResult {
|
|
|
292
302
|
readonly status: "parallel_ready" | "serialized" | "failed";
|
|
293
303
|
readonly runtimeContractFingerprint?: string | null;
|
|
294
304
|
readonly runtimeContractSource?: string | null;
|
|
305
|
+
readonly runtimeRequirements?: HostRuntimeRequirements | null;
|
|
295
306
|
readonly reasonCode?: string | null;
|
|
296
307
|
readonly reasonMessage?: string | null;
|
|
297
308
|
readonly qaAppLaunchTarget?: BridgeRuntimeReadinessQaLaunchTarget | null;
|
|
@@ -8,7 +8,14 @@ export interface DispatchResultOutbox {
|
|
|
8
8
|
persist(payload: BridgeDispatchResultCallback): Promise<void>;
|
|
9
9
|
pending(): Promise<readonly DurableDispatchResult[]>;
|
|
10
10
|
acknowledge(leaseId: string): Promise<void>;
|
|
11
|
+
/**
|
|
12
|
+
* Moves an undeliverable record out of the replay set. The redacted result
|
|
13
|
+
* is kept, with its original persistedAt, so preserved work can be reconciled.
|
|
14
|
+
*/
|
|
15
|
+
quarantine(record: DurableDispatchResult): Promise<void>;
|
|
11
16
|
}
|
|
17
|
+
export declare const dispatchResultOutboxDirectory = "dispatch-results";
|
|
18
|
+
export declare const dispatchResultQuarantineDirectory = "dispatch-results-quarantine";
|
|
12
19
|
/**
|
|
13
20
|
* Persists the already-redacted terminal result before the Bridge attempts its
|
|
14
21
|
* SignalR callback. A transport or API restart can therefore delay delivery,
|
|
@@ -16,10 +23,13 @@ export interface DispatchResultOutbox {
|
|
|
16
23
|
*/
|
|
17
24
|
export declare class FileDispatchResultOutbox implements DispatchResultOutbox {
|
|
18
25
|
private readonly stateRoot;
|
|
26
|
+
private readonly directory;
|
|
19
27
|
private readonly writes;
|
|
20
|
-
constructor(stateRoot: string);
|
|
28
|
+
constructor(stateRoot: string, directory?: string);
|
|
21
29
|
persist(payload: BridgeDispatchResultCallback): Promise<void>;
|
|
30
|
+
private persistRecord;
|
|
22
31
|
pending(): Promise<readonly DurableDispatchResult[]>;
|
|
23
32
|
acknowledge(leaseId: string): Promise<void>;
|
|
33
|
+
quarantine(record: DurableDispatchResult): Promise<void>;
|
|
24
34
|
private operate;
|
|
25
35
|
}
|
|
@@ -3,6 +3,8 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
3
3
|
import { assertCanonicalDirectory, createCanonicalDirectory } from "../runtime/attempt-private-directory.js";
|
|
4
4
|
import { runPinnedDirectoryProcess } from "../runtime/pinned-directory-process.js";
|
|
5
5
|
import { dispatchResultReceiptWorker } from "./dispatch-result-worker.js";
|
|
6
|
+
export const dispatchResultOutboxDirectory = "dispatch-results";
|
|
7
|
+
export const dispatchResultQuarantineDirectory = "dispatch-results-quarantine";
|
|
6
8
|
/**
|
|
7
9
|
* Persists the already-redacted terminal result before the Bridge attempts its
|
|
8
10
|
* SignalR callback. A transport or API restart can therefore delay delivery,
|
|
@@ -10,11 +12,16 @@ import { dispatchResultReceiptWorker } from "./dispatch-result-worker.js";
|
|
|
10
12
|
*/
|
|
11
13
|
export class FileDispatchResultOutbox {
|
|
12
14
|
stateRoot;
|
|
15
|
+
directory;
|
|
13
16
|
writes = new Map();
|
|
14
|
-
constructor(stateRoot) {
|
|
17
|
+
constructor(stateRoot, directory = dispatchResultOutboxDirectory) {
|
|
15
18
|
this.stateRoot = stateRoot;
|
|
19
|
+
this.directory = directory;
|
|
16
20
|
}
|
|
17
21
|
async persist(payload) {
|
|
22
|
+
await this.persistRecord(payload, new Date().toISOString());
|
|
23
|
+
}
|
|
24
|
+
async persistRecord(payload, persistedAt) {
|
|
18
25
|
const name = recordName(payload.leaseId);
|
|
19
26
|
const value = JSON.parse(JSON.stringify({ payload }));
|
|
20
27
|
const pending = this.writes.get(name);
|
|
@@ -27,7 +34,7 @@ export class FileDispatchResultOutbox {
|
|
|
27
34
|
const write = this.operate({
|
|
28
35
|
kind: "persist",
|
|
29
36
|
name,
|
|
30
|
-
record: { schemaVersion: 1, persistedAt
|
|
37
|
+
record: { schemaVersion: 1, persistedAt, ...value },
|
|
31
38
|
}).then(() => undefined);
|
|
32
39
|
this.writes.set(name, { value, write });
|
|
33
40
|
try {
|
|
@@ -44,8 +51,23 @@ export class FileDispatchResultOutbox {
|
|
|
44
51
|
async acknowledge(leaseId) {
|
|
45
52
|
await this.operate({ kind: "acknowledge", name: recordName(leaseId) });
|
|
46
53
|
}
|
|
54
|
+
async quarantine(record) {
|
|
55
|
+
// One execution lease can carry several dispatch attempts, so quarantine
|
|
56
|
+
// files are grouped per attempt: <quarantine>/<attempt>/<lease>.json.
|
|
57
|
+
// Copy before removal: a crash in between leaves an identical record in
|
|
58
|
+
// both places, and the next replay quarantines it again idempotently.
|
|
59
|
+
// A record without an attempt id has no per-attempt bucket; the caller
|
|
60
|
+
// keeps it deferred rather than grouping unrelated attempts together.
|
|
61
|
+
const { payload } = record;
|
|
62
|
+
if (!payload.dispatchAttemptId) {
|
|
63
|
+
throw new Error("dispatch_result_invalid: only attempt-bound results can be quarantined.");
|
|
64
|
+
}
|
|
65
|
+
const bucket = path.join(dispatchResultQuarantineDirectory, compactUuid(payload.dispatchAttemptId));
|
|
66
|
+
await new FileDispatchResultOutbox(this.stateRoot, bucket).persistRecord(payload, record.persistedAt);
|
|
67
|
+
await this.acknowledge(payload.leaseId);
|
|
68
|
+
}
|
|
47
69
|
async operate(operation) {
|
|
48
|
-
const root = path.resolve(this.stateRoot,
|
|
70
|
+
const root = path.resolve(this.stateRoot, this.directory);
|
|
49
71
|
await createCanonicalDirectory(root);
|
|
50
72
|
const identity = await assertCanonicalDirectory(root);
|
|
51
73
|
if (!identity)
|
|
@@ -54,9 +76,12 @@ export class FileDispatchResultOutbox {
|
|
|
54
76
|
}
|
|
55
77
|
}
|
|
56
78
|
function recordName(leaseId) {
|
|
57
|
-
|
|
79
|
+
return `${compactUuid(leaseId)}.json`;
|
|
80
|
+
}
|
|
81
|
+
function compactUuid(id) {
|
|
82
|
+
const value = id.replaceAll("-", "").toLowerCase();
|
|
58
83
|
if (!/^[0-9a-f]{32}$/u.test(value)) {
|
|
59
|
-
throw new Error("dispatch_result_invalid:
|
|
84
|
+
throw new Error("dispatch_result_invalid: identifiers must be UUIDs.");
|
|
60
85
|
}
|
|
61
|
-
return
|
|
86
|
+
return value;
|
|
62
87
|
}
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { BridgeServiceConfig, BridgeToolchainCapabilities } from "./bridge.types.js";
|
|
2
|
+
import { type BridgeTestPostgresCapability } from "./test-postgres-capability.js";
|
|
2
3
|
export interface RunnerHostCapabilitySnapshot {
|
|
3
4
|
readonly toolchains: BridgeToolchainCapabilities;
|
|
4
5
|
readonly playwrightProjects: readonly string[];
|
|
5
6
|
readonly browserLaunch: boolean;
|
|
6
7
|
readonly providerConnectivity: Readonly<Record<string, boolean>>;
|
|
8
|
+
readonly testPostgres: BridgeTestPostgresCapability;
|
|
7
9
|
}
|
|
8
10
|
export interface RunnerHostCapabilityProbe {
|
|
9
11
|
detect(config: BridgeServiceConfig): Promise<RunnerHostCapabilitySnapshot>;
|
|
@@ -2,6 +2,7 @@ import { execFile } from "node:child_process";
|
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { promisify } from "node:util";
|
|
5
|
+
import { probeTestPostgresCapability } from "./test-postgres-capability.js";
|
|
5
6
|
const execFileAsync = promisify(execFile);
|
|
6
7
|
export class ProcessRunnerHostCapabilityProbe {
|
|
7
8
|
async detect(config) {
|
|
@@ -16,6 +17,7 @@ export class ProcessRunnerHostCapabilityProbe {
|
|
|
16
17
|
: Promise.resolve(unavailable("powershell.exe")),
|
|
17
18
|
]);
|
|
18
19
|
const playwrightProjects = await detectPlaywrightProjects(config.repoMappings);
|
|
20
|
+
const testPostgres = await probeTestPostgresCapability();
|
|
19
21
|
const browserLaunch = playwrightProjects.length > 0
|
|
20
22
|
|| config.repoMappings.some(mapping => Boolean(mapping.qaAppLaunchTarget?.url
|
|
21
23
|
|| mapping.qaAppLaunchTarget?.command
|
|
@@ -33,6 +35,7 @@ export class ProcessRunnerHostCapabilityProbe {
|
|
|
33
35
|
browserLaunch,
|
|
34
36
|
providerConnectivity: Object.fromEntries(Object.entries(config.providerStatuses)
|
|
35
37
|
.map(([provider, status]) => [provider, status.signedIn === true])),
|
|
38
|
+
testPostgres,
|
|
36
39
|
};
|
|
37
40
|
}
|
|
38
41
|
}
|
|
@@ -89,5 +92,6 @@ export function emptyRunnerHostCapabilitySnapshot() {
|
|
|
89
92
|
playwrightProjects: [],
|
|
90
93
|
browserLaunch: false,
|
|
91
94
|
providerConnectivity: {},
|
|
95
|
+
testPostgres: { available: false, superuser: null },
|
|
92
96
|
};
|
|
93
97
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether this host offers a native test PostgreSQL and whether its role is a superuser
|
|
3
|
+
* (decision 0013 placement). Suites that need `session_replication_role`, `CREATE ROLE` or
|
|
4
|
+
* similar can only run on a superuser test database or on Docker-backed Testcontainers.
|
|
5
|
+
*/
|
|
6
|
+
export interface BridgeTestPostgresCapability {
|
|
7
|
+
readonly available: boolean;
|
|
8
|
+
/** Null when the cluster is configured but the role could not be checked. */
|
|
9
|
+
readonly superuser: boolean | null;
|
|
10
|
+
}
|
|
11
|
+
export type PsqlRunner = (args: readonly string[], env: NodeJS.ProcessEnv) => Promise<string>;
|
|
12
|
+
export declare function probeTestPostgresCapability(environment?: NodeJS.ProcessEnv, runPsql?: PsqlRunner, readFallback?: () => string | null): Promise<BridgeTestPostgresCapability>;
|
|
13
|
+
/** Maps an Npgsql-style connection string or a postgres:// URI to libpq environment. */
|
|
14
|
+
export declare function psqlTarget(connection: string): Record<string, string> | null;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { hostRuntimeTestPostgresAdminEnvironment } from "../runtime/host-runtime-contract.js";
|
|
4
|
+
import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
|
|
5
|
+
const execFileAsync = promisify(execFile);
|
|
6
|
+
const superuserQuery = "select rolsuper from pg_roles where rolname = current_user";
|
|
7
|
+
export async function probeTestPostgresCapability(environment = process.env, runPsql = defaultPsql, readFallback = configuredFallbackConnection) {
|
|
8
|
+
// Same sources pre-publication validation uses: the environment, else the operator's
|
|
9
|
+
// native test cluster file.
|
|
10
|
+
const connection = environment[hostRuntimeTestPostgresAdminEnvironment]?.trim() || readFallback()?.trim();
|
|
11
|
+
if (!connection)
|
|
12
|
+
return { available: false, superuser: null };
|
|
13
|
+
const target = psqlTarget(connection);
|
|
14
|
+
if (!target)
|
|
15
|
+
return { available: true, superuser: null };
|
|
16
|
+
try {
|
|
17
|
+
// The secret travels only in the child's environment, never in argv or logs.
|
|
18
|
+
const output = await runPsql(["-X", "-A", "-t", "-w", "-c", superuserQuery], { ...process.env, ...target, PGCONNECT_TIMEOUT: "5" });
|
|
19
|
+
const value = output.trim().toLowerCase();
|
|
20
|
+
return { available: true, superuser: value === "t" ? true : value === "f" ? false : null };
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return { available: true, superuser: null };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Maps an Npgsql-style connection string or a postgres:// URI to libpq environment. */
|
|
27
|
+
export function psqlTarget(connection) {
|
|
28
|
+
// libpq reads PGDATABASE as a database name only, so a URI is split into PG* variables
|
|
29
|
+
// rather than passed whole (and not as psql's argument, which would put the secret in argv).
|
|
30
|
+
if (/^postgres(?:ql)?:\/\//iu.test(connection))
|
|
31
|
+
return uriTarget(connection);
|
|
32
|
+
const keys = {
|
|
33
|
+
host: "PGHOST", server: "PGHOST", port: "PGPORT", database: "PGDATABASE",
|
|
34
|
+
username: "PGUSER", "user id": "PGUSER", userid: "PGUSER", user: "PGUSER", password: "PGPASSWORD",
|
|
35
|
+
};
|
|
36
|
+
const target = {};
|
|
37
|
+
for (const part of connection.split(";")) {
|
|
38
|
+
const separator = part.indexOf("=");
|
|
39
|
+
if (separator <= 0)
|
|
40
|
+
continue;
|
|
41
|
+
const name = keys[part.slice(0, separator).trim().toLowerCase()];
|
|
42
|
+
const value = part.slice(separator + 1).trim();
|
|
43
|
+
if (name && value)
|
|
44
|
+
target[name] = value;
|
|
45
|
+
}
|
|
46
|
+
return target.PGHOST || target.PGUSER ? target : null;
|
|
47
|
+
}
|
|
48
|
+
/** libpq URI query parameters that have a PG* environment equivalent. */
|
|
49
|
+
const uriParameterEnvironment = {
|
|
50
|
+
host: "PGHOST", hostaddr: "PGHOSTADDR", port: "PGPORT", dbname: "PGDATABASE", user: "PGUSER",
|
|
51
|
+
password: "PGPASSWORD", passfile: "PGPASSFILE", options: "PGOPTIONS", application_name: "PGAPPNAME",
|
|
52
|
+
sslmode: "PGSSLMODE", sslrootcert: "PGSSLROOTCERT", sslcert: "PGSSLCERT", sslkey: "PGSSLKEY",
|
|
53
|
+
sslcrl: "PGSSLCRL", gssencmode: "PGGSSENCMODE", target_session_attrs: "PGTARGETSESSIONATTRS",
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Parses `postgres[ql]://[user[:password]@][host[:port][,...]][/dbname][?param=value&...]`
|
|
57
|
+
* (libpq's URI form, including comma-separated hosts, bracketed IPv6 and percent-encoding).
|
|
58
|
+
*/
|
|
59
|
+
function uriTarget(connection) {
|
|
60
|
+
const match = /^postgres(?:ql)?:\/\/([^/?#]*)(?:\/([^?#]*))?(?:\?([^#]*))?/iu.exec(connection);
|
|
61
|
+
if (!match)
|
|
62
|
+
return null;
|
|
63
|
+
try {
|
|
64
|
+
const [, authority = "", path, query] = match;
|
|
65
|
+
const target = {};
|
|
66
|
+
const at = authority.lastIndexOf("@");
|
|
67
|
+
if (at >= 0) {
|
|
68
|
+
const userInfo = authority.slice(0, at);
|
|
69
|
+
const colon = userInfo.indexOf(":");
|
|
70
|
+
const user = decodeURIComponent(colon >= 0 ? userInfo.slice(0, colon) : userInfo);
|
|
71
|
+
if (user)
|
|
72
|
+
target.PGUSER = user;
|
|
73
|
+
if (colon >= 0)
|
|
74
|
+
target.PGPASSWORD = decodeURIComponent(userInfo.slice(colon + 1));
|
|
75
|
+
}
|
|
76
|
+
const hosts = [];
|
|
77
|
+
const ports = [];
|
|
78
|
+
for (const entry of authority.slice(at + 1).split(",")) {
|
|
79
|
+
const ipv6 = /^\[([^\]]*)\](?::(.*))?$/u.exec(entry);
|
|
80
|
+
const colon = entry.lastIndexOf(":");
|
|
81
|
+
const host = ipv6 ? ipv6[1] ?? "" : colon >= 0 ? entry.slice(0, colon) : entry;
|
|
82
|
+
const port = ipv6 ? ipv6[2] ?? "" : colon >= 0 ? entry.slice(colon + 1) : "";
|
|
83
|
+
hosts.push(decodeURIComponent(host));
|
|
84
|
+
ports.push(port);
|
|
85
|
+
}
|
|
86
|
+
if (hosts.some(Boolean))
|
|
87
|
+
target.PGHOST = hosts.join(",");
|
|
88
|
+
if (ports.some(Boolean))
|
|
89
|
+
target.PGPORT = ports.join(",");
|
|
90
|
+
const database = path ? decodeURIComponent(path) : "";
|
|
91
|
+
if (database)
|
|
92
|
+
target.PGDATABASE = database;
|
|
93
|
+
for (const parameter of (query ?? "").split("&")) {
|
|
94
|
+
const separator = parameter.indexOf("=");
|
|
95
|
+
if (separator <= 0)
|
|
96
|
+
continue;
|
|
97
|
+
const name = uriParameterEnvironment[decodeURIComponent(parameter.slice(0, separator))];
|
|
98
|
+
const value = decodeURIComponent(parameter.slice(separator + 1));
|
|
99
|
+
if (name && value)
|
|
100
|
+
target[name] = value;
|
|
101
|
+
}
|
|
102
|
+
return target;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// Malformed percent-encoding: the role cannot be checked.
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function configuredFallbackConnection() {
|
|
110
|
+
try {
|
|
111
|
+
return readNativeTestPostgresFallback()?.connectionString ?? null;
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
async function defaultPsql(args, env) {
|
|
118
|
+
const result = await execFileAsync("psql", [...args], { encoding: "utf8", timeout: 10_000, env });
|
|
119
|
+
return result.stdout;
|
|
120
|
+
}
|
package/dist/cli/cli.service.js
CHANGED
|
@@ -30,7 +30,9 @@ export class ForgeBridgeCliService {
|
|
|
30
30
|
pairRunner;
|
|
31
31
|
cleanupFactory;
|
|
32
32
|
dotNetToolchainConfigurator;
|
|
33
|
-
constructor(
|
|
33
|
+
constructor(
|
|
34
|
+
// The default session chain validates without the host load governor (Docker-mode gap, decision 0013).
|
|
35
|
+
sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
|
|
34
36
|
this.sessions = sessions;
|
|
35
37
|
this.bridgeFactory = bridgeFactory;
|
|
36
38
|
this.pairRunner = pairRunner;
|