@loucompanion/forge-bridge 0.1.4-dev.fb770705136a → 0.2.1-dev.17ad6c965e41
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 +144 -3
- package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
- package/dist/bridge/bridge-chat-provider-command.js +132 -0
- package/dist/bridge/bridge-chat.types.d.ts +10 -0
- package/dist/bridge/bridge-chat.types.js +16 -1
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.base.d.ts +9 -0
- package/dist/bridge/bridge.service.d.ts +90 -14
- package/dist/bridge/bridge.service.js +436 -350
- package/dist/bridge/bridge.types.d.ts +21 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/readiness-result-outbox.d.ts +5 -1
- package/dist/bridge/readiness-result-outbox.js +20 -0
- package/dist/bridge/runner-host-capabilities.d.ts +5 -0
- package/dist/bridge/runner-host-capabilities.js +17 -0
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +20 -1
- package/dist/cleanup/cleanup.service.js +150 -169
- package/dist/cleanup/cleanup.types.d.ts +6 -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 +7 -0
- package/dist/cleanup/host-runtime-ledger.js +130 -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 +74 -12
- package/dist/cli/cli.service.d.ts +19 -10
- package/dist/cli/cli.service.js +152 -187
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +6 -0
- package/dist/cli/local-config.js +32 -4
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
- package/dist/runtime/attempt-database-broker.d.ts +1 -1
- package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
- package/dist/runtime/attempt-process-supervisor.js +12 -6
- package/dist/runtime/docker-engine-probe.d.ts +5 -0
- package/dist/runtime/docker-engine-probe.js +7 -0
- package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
- package/dist/runtime/dotnet-build-outputs.js +402 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/host-facts.d.ts +2 -1
- package/dist/runtime/host-load-admission.d.ts +67 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +27 -0
- package/dist/runtime/host-load-child-environment.js +76 -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 +52 -0
- package/dist/runtime/host-load-governor-config.js +83 -0
- package/dist/runtime/host-load-governor.d.ts +186 -0
- package/dist/runtime/host-load-governor.js +632 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +187 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +80 -0
- package/dist/runtime/host-load-sampler.d.ts +75 -2
- package/dist/runtime/host-load-sampler.js +142 -8
- package/dist/runtime/host-load-step-class.d.ts +70 -0
- package/dist/runtime/host-load-step-class.js +161 -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-test-slot.d.ts +43 -0
- package/dist/runtime/host-load-test-slot.js +81 -0
- package/dist/runtime/host-load-token-ledger.d.ts +200 -0
- package/dist/runtime/host-load-token-ledger.js +453 -0
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-pressure-stall.d.ts +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-contract.d.ts +15 -0
- package/dist/runtime/host-runtime-contract.js +33 -2
- package/dist/runtime/host-runtime-lease.d.ts +77 -5
- package/dist/runtime/host-runtime-lease.js +311 -165
- package/dist/runtime/host-runtime-ledger-recovery.d.ts +20 -0
- package/dist/runtime/host-runtime-ledger-recovery.js +134 -0
- 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.js +5 -16
- package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
- package/dist/runtime/native-test-postgres-fallback.js +60 -8
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- package/dist/runtime/runner-settings.d.ts +104 -0
- package/dist/runtime/runner-settings.js +236 -0
- package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
- package/dist/runtime/supervised-runtime-build-guard.js +112 -0
- package/dist/sandbox/host-capacity-broker.d.ts +115 -0
- package/dist/sandbox/host-capacity-broker.js +336 -0
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +90 -0
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +47 -8
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -7
- package/dist/session/managed-attempt-tools.js +207 -121
- package/dist/session/managed-build-coordinator.d.ts +16 -0
- package/dist/session/managed-build-coordinator.js +10 -0
- package/dist/session/managed-build-receipt.d.ts +5 -0
- package/dist/session/managed-build-receipt.js +8 -3
- package/dist/session/managed-command-host-load.d.ts +47 -0
- package/dist/session/managed-command-host-load.js +83 -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 +96 -26
- 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 +12 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +5 -0
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -11
- package/dist/session/phase-completion.runtime.js +91 -215
- 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 +208 -231
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +49 -93
- 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-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +31 -19
- package/dist/session/pre-publication-step-execution.d.ts +12 -0
- package/dist/session/pre-publication-step-execution.js +50 -0
- package/dist/session/pre-publication-validation.d.ts +37 -21
- package/dist/session/pre-publication-validation.js +221 -182
- package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
- package/dist/session/provider-cli/claude-background-work.js +181 -0
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +276 -0
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
- package/dist/session/provider-cli/provider-cli.process.js +41 -432
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
- package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
- package/dist/session/provider-cli/provider-cli.service.js +98 -173
- package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
- package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
- package/dist/session/provider-cli/provider-output-pipes.js +67 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
- package/dist/session/provider-cli/provider-output-state.js +6 -0
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
- package/dist/session/sandbox-host-capacity-gate.js +257 -0
- package/dist/session/session-redaction.js +31 -181
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +11 -2
- package/dist/session/session.service.js +189 -69
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +5 -5
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/process/host-process-recovery.d.ts +14 -3
- package/dist/shared/process/host-process-recovery.js +23 -3
- package/dist/shared/process/host-process-supervisor.d.ts +14 -1
- package/dist/shared/process/host-process-supervisor.js +67 -15
- 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/process/windows-app-execution-alias.d.ts +19 -0
- package/dist/shared/process/windows-app-execution-alias.js +45 -0
- package/dist/shared/process/windows-launch.d.ts +18 -0
- package/dist/shared/process/windows-launch.js +68 -0
- package/dist/shared/provider-capabilities.js +14 -7
- 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 +46 -10
- package/dist/worktree/orphan-relink.d.ts +19 -0
- package/dist/worktree/orphan-relink.js +106 -0
- package/dist/worktree/wip-git.d.ts +33 -0
- package/dist/worktree/wip-git.js +122 -0
- package/dist/worktree/wip-refs.d.ts +62 -0
- package/dist/worktree/wip-refs.js +119 -0
- package/dist/worktree/wip-restore.d.ts +38 -0
- package/dist/worktree/wip-restore.js +190 -0
- package/dist/worktree/wip-snapshot.d.ts +50 -0
- package/dist/worktree/wip-snapshot.js +268 -0
- package/dist/worktree/worktree-inputs.d.ts +8 -0
- package/dist/worktree/worktree-inputs.js +134 -0
- package/dist/worktree/worktree-origin-sync.d.ts +34 -0
- package/dist/worktree/worktree-origin-sync.js +127 -0
- package/dist/worktree/worktree-wip-events.d.ts +18 -0
- package/dist/worktree/worktree-wip-events.js +98 -0
- package/dist/worktree/worktree-wip.d.ts +50 -0
- package/dist/worktree/worktree-wip.js +185 -0
- package/dist/worktree/worktree.base.d.ts +7 -1
- package/dist/worktree/worktree.service.d.ts +36 -5
- package/dist/worktree/worktree.service.js +124 -155
- package/dist/worktree/worktree.types.d.ts +38 -0
- package/package.json +2 -2
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { isInFlightEntry } from "./in-flight-registry.js";
|
|
5
|
+
import { withBridgeStateLock } from "./bridge-state-lock.js";
|
|
6
|
+
import { isProcessAlive, withFsRetry, writeJsonFileAtomically } from "./bridge-state-io.js";
|
|
7
|
+
import { readUnpublishedMarkers, removeExitedUnpublishedMarkers, removeUnpublishedMarker, writeUnpublishedMarker, } from "./bridge-state-unpublished.js";
|
|
8
|
+
export { isProcessAlive } from "./bridge-state-io.js";
|
|
9
|
+
// The running `forge-bridge connect` publishes whether it is idle to a small state
|
|
10
|
+
// file beside bridge.json (`bridge.state.json`), so a host can gate a bridge restart
|
|
11
|
+
// on it with `forge-bridge status --idle` (owner, 2026-11-19). The file carries the
|
|
12
|
+
// process id, the runner instance, a heartbeat refreshed every few seconds and the
|
|
13
|
+
// in-flight list. It is rewritten atomically (temp file and rename), so a reader sees
|
|
14
|
+
// either the previous or the next version, never a torn one. Every publisher reads the
|
|
15
|
+
// record and writes its own while holding the state lock (bridge-state-lock.ts), so two
|
|
16
|
+
// publishers never act on a record the other is replacing. A publisher that cannot publish
|
|
17
|
+
// leaves its own marker (bridge-state-unpublished.ts) instead of touching the shared record
|
|
18
|
+
// without the lock. Anything the bridge cannot publish or that a reader cannot fully parse
|
|
19
|
+
// reads as unknown, never as idle.
|
|
20
|
+
export const bridgeStateSchemaVersion = 1;
|
|
21
|
+
export const defaultStatePublishIntervalMs = 5_000;
|
|
22
|
+
const minimumStaleAfterMs = 30_000;
|
|
23
|
+
// Allows for a reader clock slightly ahead of or behind the writer's.
|
|
24
|
+
const futureHeartbeatToleranceMs = 60_000;
|
|
25
|
+
export const bridgeIdleExitCodes = {
|
|
26
|
+
idle: 0,
|
|
27
|
+
busy: 1,
|
|
28
|
+
stale: 3,
|
|
29
|
+
unknown: 3,
|
|
30
|
+
not_running: 4,
|
|
31
|
+
not_yielding: 5,
|
|
32
|
+
};
|
|
33
|
+
/** `<config dir>/<config name>.state.json`, e.g. `~/.config/forge/bridge.state.json` beside `bridge.json`. */
|
|
34
|
+
export function bridgeStatePathFor(configPath) {
|
|
35
|
+
const parsed = path.parse(path.resolve(configPath));
|
|
36
|
+
return path.join(parsed.dir, `${parsed.name}.state.json`);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Writes the state atomically: a temp file in the same folder, then a rename over the
|
|
40
|
+
* old one. On Windows the rename fails with EPERM/EBUSY/EACCES while a reader or an
|
|
41
|
+
* antivirus scanner has the target open, so it retries briefly.
|
|
42
|
+
*/
|
|
43
|
+
export async function writeBridgeStateFile(statePath, state) {
|
|
44
|
+
await writeJsonFileAtomically(statePath, state);
|
|
45
|
+
}
|
|
46
|
+
/** The record and any live publisher's unpublished marker: what `status --idle` evaluates. */
|
|
47
|
+
export async function readBridgeStateFile(statePath) {
|
|
48
|
+
const read = await readBridgeStateRecord(statePath);
|
|
49
|
+
if (read.kind !== "ok")
|
|
50
|
+
return read;
|
|
51
|
+
try {
|
|
52
|
+
const unpublished = await readUnpublishedMarkers(statePath);
|
|
53
|
+
return unpublished.length > 0 ? { ...read, unpublished } : read;
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
return { kind: "invalid", error: error instanceof Error ? error.message : String(error) };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** The record alone, as a publisher reads it before writing the next one. */
|
|
60
|
+
export async function readBridgeStateRecord(statePath) {
|
|
61
|
+
let text;
|
|
62
|
+
try {
|
|
63
|
+
text = await withFsRetry(() => fs.readFile(statePath, "utf8"));
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
if (error.code === "ENOENT")
|
|
67
|
+
return { kind: "missing" };
|
|
68
|
+
return { kind: "invalid", error: error instanceof Error ? error.message : String(error) };
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
const state = parseBridgeState(JSON.parse(text));
|
|
72
|
+
return state ? { kind: "ok", state } : { kind: "invalid", error: "The state file does not match schema version 1." };
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
return { kind: "invalid", error: error instanceof Error ? error.message : String(error) };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Removes the record so readers report unknown. Only a publisher holding the lock, over its own record. */
|
|
79
|
+
export async function removeBridgeStateFile(statePath) {
|
|
80
|
+
await withFsRetry(() => fs.rm(statePath, { force: true }));
|
|
81
|
+
}
|
|
82
|
+
export function staleAfterMsFor(state) {
|
|
83
|
+
const interval = state && Number.isFinite(state.publishIntervalMs) ? state.publishIntervalMs : defaultStatePublishIntervalMs;
|
|
84
|
+
return Math.max(minimumStaleAfterMs, interval * 6);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Idle only when a live bridge process published a fresh heartbeat with nothing in
|
|
88
|
+
* flight. A dead pid, a stale heartbeat, a clean stop or an unreadable file is never
|
|
89
|
+
* reported as idle: each has its own verdict and a non-zero exit code.
|
|
90
|
+
*/
|
|
91
|
+
export function evaluateBridgeIdle(read, options) {
|
|
92
|
+
if (read.kind !== "ok") {
|
|
93
|
+
const reason = read.kind === "missing"
|
|
94
|
+
? "No bridge state file. Either `forge-bridge connect` has not run with this config, the running bridge predates idle reporting, or it could not publish its state; idle cannot be determined."
|
|
95
|
+
: `The bridge state file is unreadable (${read.error}); idle cannot be determined.`;
|
|
96
|
+
return { verdict: "unknown", exitCode: bridgeIdleExitCodes.unknown, reason, heartbeatAgeMs: null, staleAfterMs: staleAfterMsFor(null), pidAlive: null, state: null };
|
|
97
|
+
}
|
|
98
|
+
const state = read.state;
|
|
99
|
+
const staleAfterMs = staleAfterMsFor(state);
|
|
100
|
+
const heartbeatAgeMs = options.now - Date.parse(state.updatedAt);
|
|
101
|
+
const pidAlive = options.pidAlive(state.pid);
|
|
102
|
+
const result = (verdict, reason) => ({ verdict, exitCode: bridgeIdleExitCodes[verdict], reason, heartbeatAgeMs, staleAfterMs, pidAlive, state });
|
|
103
|
+
// Ahead of every other check: the record on disk may be another bridge's, or this one's last idle.
|
|
104
|
+
// Held back unless the marker is provably stale: an unreadable age never lets it lapse.
|
|
105
|
+
const unpublished = (read.unpublished ?? []).find(marker => options.pidAlive(marker.pid)
|
|
106
|
+
&& !(options.now - Date.parse(marker.updatedAt) > staleAfterMsFor(marker)));
|
|
107
|
+
if (unpublished) {
|
|
108
|
+
return result("unknown", `Bridge process ${unpublished.pid} could not publish its state since ${unpublished.since} (${unpublished.error}); the state file may be out of date, so idle cannot be determined.`);
|
|
109
|
+
}
|
|
110
|
+
if (!pidAlive) {
|
|
111
|
+
return result("not_running", `Bridge process ${state.pid} is not running (last heartbeat ${state.updatedAt}${state.state === "stopped" ? ", stopped cleanly" : ", it did not stop cleanly"}). There is no bridge to interrupt, but this is not an idle report.`);
|
|
112
|
+
}
|
|
113
|
+
if (state.conflict && options.pidAlive(state.conflict.pid)) {
|
|
114
|
+
return result("unknown", `Two bridge processes publish to this state file (pid ${state.pid} and pid ${state.conflict.pid}, both using this bridge config); idle cannot be determined. Stop the extra \`forge-bridge connect\`.`);
|
|
115
|
+
}
|
|
116
|
+
if (state.state === "stopped") {
|
|
117
|
+
return result("unknown", `Bridge process ${state.pid} reported a clean stop but is still running; it is shutting down. Check again shortly.`);
|
|
118
|
+
}
|
|
119
|
+
if (!Number.isFinite(heartbeatAgeMs) || heartbeatAgeMs > staleAfterMs || heartbeatAgeMs < -futureHeartbeatToleranceMs) {
|
|
120
|
+
return result("stale", `The heartbeat is stale (${formatAge(heartbeatAgeMs)} old, limit ${formatAge(staleAfterMs)}) although process ${state.pid} exists. The bridge may be hung, or the pid was reused; do not treat it as idle.`);
|
|
121
|
+
}
|
|
122
|
+
if (state.inFlight.length > 0) {
|
|
123
|
+
return result("busy", `${state.inFlight.length} in-flight item(s); restarting the bridge now would kill them.`);
|
|
124
|
+
}
|
|
125
|
+
if (options.requireYield && !state.yielding) {
|
|
126
|
+
return result("not_yielding", "No in-flight work, but the bridge does not report yield, so Forge can start new work before the restart.");
|
|
127
|
+
}
|
|
128
|
+
return result("idle", "No in-flight work.");
|
|
129
|
+
}
|
|
130
|
+
// Published when the bridge cannot read its own ledgers: the file must not claim idle.
|
|
131
|
+
const unreadableInFlight = { kind: "unknown", ids: {}, phase: "in_flight_unreadable", since: null, phaseSince: null };
|
|
132
|
+
/**
|
|
133
|
+
* Keeps the state file current while connect runs: on every in-flight change
|
|
134
|
+
* (coalesced) and on a heartbeat timer. Each publish reads the current record and
|
|
135
|
+
* writes the next one under the state file's lock. A failed publish removes the
|
|
136
|
+
* record, so readers report unknown instead of trusting the last one; failures are
|
|
137
|
+
* logged once per streak and never reach the bridge.
|
|
138
|
+
*/
|
|
139
|
+
export class BridgeStatePublisher {
|
|
140
|
+
statePath;
|
|
141
|
+
identity;
|
|
142
|
+
source;
|
|
143
|
+
options;
|
|
144
|
+
intervalMs;
|
|
145
|
+
now;
|
|
146
|
+
startedAt;
|
|
147
|
+
publisherId = randomUUID();
|
|
148
|
+
timer = null;
|
|
149
|
+
writing = null;
|
|
150
|
+
dirty = false;
|
|
151
|
+
stopped = false;
|
|
152
|
+
failing = false;
|
|
153
|
+
conflict = null;
|
|
154
|
+
unpublishedSince = null;
|
|
155
|
+
sweptExitedMarkers = false;
|
|
156
|
+
constructor(statePath, identity, source, options = {}) {
|
|
157
|
+
this.statePath = statePath;
|
|
158
|
+
this.identity = identity;
|
|
159
|
+
this.source = source;
|
|
160
|
+
this.options = options;
|
|
161
|
+
this.intervalMs = Math.max(250, options.intervalMs ?? defaultStatePublishIntervalMs);
|
|
162
|
+
this.now = options.now ?? (() => new Date());
|
|
163
|
+
this.startedAt = this.now().toISOString();
|
|
164
|
+
}
|
|
165
|
+
start() {
|
|
166
|
+
this.timer = setInterval(() => void this.publish(), this.intervalMs);
|
|
167
|
+
this.timer.unref?.();
|
|
168
|
+
return this.publish();
|
|
169
|
+
}
|
|
170
|
+
/** Publishes now, or right after the write in progress. */
|
|
171
|
+
publish() {
|
|
172
|
+
if (this.stopped)
|
|
173
|
+
return Promise.resolve();
|
|
174
|
+
if (this.writing) {
|
|
175
|
+
this.dirty = true;
|
|
176
|
+
return this.writing;
|
|
177
|
+
}
|
|
178
|
+
this.writing = this.writeLoop().finally(() => {
|
|
179
|
+
this.writing = null;
|
|
180
|
+
});
|
|
181
|
+
return this.writing;
|
|
182
|
+
}
|
|
183
|
+
/** Stops the heartbeat and records a clean stop, only over this publisher's own record. */
|
|
184
|
+
async stop() {
|
|
185
|
+
if (this.timer)
|
|
186
|
+
clearInterval(this.timer);
|
|
187
|
+
this.timer = null;
|
|
188
|
+
// No running write may land after the stop record.
|
|
189
|
+
this.stopped = true;
|
|
190
|
+
await this.writing?.catch(() => undefined);
|
|
191
|
+
await this.publishRecord("stopped");
|
|
192
|
+
// Stopped: nothing of this publisher's is left to hold readers back.
|
|
193
|
+
await removeUnpublishedMarker(this.statePath, this.publisherId).catch(() => undefined);
|
|
194
|
+
}
|
|
195
|
+
snapshot(state = "running") {
|
|
196
|
+
return {
|
|
197
|
+
schemaVersion: bridgeStateSchemaVersion,
|
|
198
|
+
pid: this.pid,
|
|
199
|
+
runnerId: this.identity.runnerId,
|
|
200
|
+
runnerInstanceId: this.identity.runnerInstanceId,
|
|
201
|
+
version: this.identity.version,
|
|
202
|
+
state,
|
|
203
|
+
startedAt: this.startedAt,
|
|
204
|
+
updatedAt: this.now().toISOString(),
|
|
205
|
+
publishIntervalMs: this.intervalMs,
|
|
206
|
+
connected: safely(() => this.source.connected(), false),
|
|
207
|
+
yielding: safely(() => this.source.yielding(), false),
|
|
208
|
+
yieldApplied: safely(() => this.source.yieldApplied?.() ?? this.source.yielding(), false),
|
|
209
|
+
conflict: this.conflict,
|
|
210
|
+
publisherId: this.publisherId,
|
|
211
|
+
inFlight: safely(() => [...this.source.inFlight()], [unreadableInFlight]),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
get pid() {
|
|
215
|
+
return this.options.pid ?? process.pid;
|
|
216
|
+
}
|
|
217
|
+
async read() {
|
|
218
|
+
return await (this.options.read ?? readBridgeStateRecord)(this.statePath).catch(() => null);
|
|
219
|
+
}
|
|
220
|
+
async writeLoop() {
|
|
221
|
+
do {
|
|
222
|
+
this.dirty = false;
|
|
223
|
+
await this.publishRecord("running");
|
|
224
|
+
} while (this.dirty && !this.stopped);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Reads the record and writes the next one while holding the lock, so no other publisher
|
|
228
|
+
* writes in between: a second bridge always sees the first one's record (and publishes the
|
|
229
|
+
* conflict), and a stopping bridge's "stopped" record never lands over a newer bridge's.
|
|
230
|
+
*/
|
|
231
|
+
async publishRecord(state) {
|
|
232
|
+
let failure = null;
|
|
233
|
+
try {
|
|
234
|
+
await withBridgeStateLock(this.statePath, async () => {
|
|
235
|
+
const current = await this.read();
|
|
236
|
+
if (state === "stopped" && !this.ownsRecord(current))
|
|
237
|
+
return;
|
|
238
|
+
if (state === "running")
|
|
239
|
+
this.noteConflict(current);
|
|
240
|
+
try {
|
|
241
|
+
await (this.options.write ?? writeBridgeStateFile)(this.statePath, this.snapshot(state));
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
failure = await this.failClosed(state, error, this.ownsRecord(current));
|
|
245
|
+
}
|
|
246
|
+
}, this.options.lock);
|
|
247
|
+
}
|
|
248
|
+
catch (error) {
|
|
249
|
+
// No lock, so the record may be a newer bridge's: leave it, and mark this publisher instead.
|
|
250
|
+
failure ??= await this.failClosed(state, error, false);
|
|
251
|
+
}
|
|
252
|
+
if (failure) {
|
|
253
|
+
this.noteFailure(failure);
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
await this.clearUnpublished();
|
|
257
|
+
if (this.failing)
|
|
258
|
+
this.options.log?.(`Bridge state file ${this.statePath} is being written again.`);
|
|
259
|
+
this.failing = false;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* The last record may say idle while new work starts. This publisher's marker makes readers
|
|
263
|
+
* report unknown; while it holds the lock it also removes its own record, never another's.
|
|
264
|
+
*/
|
|
265
|
+
async failClosed(state, error, ownRecordUnderLock) {
|
|
266
|
+
// A stop that can't be recorded leaves the running record: its pid exits with this process.
|
|
267
|
+
if (state !== "running")
|
|
268
|
+
return { error, invalidated: false };
|
|
269
|
+
const now = this.now().toISOString();
|
|
270
|
+
this.unpublishedSince ??= now;
|
|
271
|
+
const marker = {
|
|
272
|
+
schemaVersion: 1, pid: this.pid, publisherId: this.publisherId, runnerInstanceId: this.identity.runnerInstanceId,
|
|
273
|
+
since: this.unpublishedSince, updatedAt: now, publishIntervalMs: this.intervalMs,
|
|
274
|
+
error: error instanceof Error ? error.message : String(error),
|
|
275
|
+
};
|
|
276
|
+
const marked = await (this.options.markUnpublished ?? writeUnpublishedMarker)(this.statePath, marker).then(() => true, () => false);
|
|
277
|
+
const removed = ownRecordUnderLock
|
|
278
|
+
&& await (this.options.invalidate ?? removeBridgeStateFile)(this.statePath).then(() => true, () => false);
|
|
279
|
+
return { error, invalidated: marked || removed };
|
|
280
|
+
}
|
|
281
|
+
async clearUnpublished() {
|
|
282
|
+
if (this.unpublishedSince === null && this.sweptExitedMarkers)
|
|
283
|
+
return;
|
|
284
|
+
if (this.unpublishedSince !== null) {
|
|
285
|
+
await removeUnpublishedMarker(this.statePath, this.publisherId).catch(() => undefined);
|
|
286
|
+
this.unpublishedSince = null;
|
|
287
|
+
}
|
|
288
|
+
if (!this.sweptExitedMarkers) {
|
|
289
|
+
// Left by bridges that exited while they could not publish.
|
|
290
|
+
await removeExitedUnpublishedMarkers(this.statePath, this.options.pidAlive);
|
|
291
|
+
this.sweptExitedMarkers = true;
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
noteFailure({ error, invalidated }) {
|
|
295
|
+
if (!this.failing) {
|
|
296
|
+
const outcome = invalidated
|
|
297
|
+
? "forge-bridge status --idle reports unknown until a publish succeeds"
|
|
298
|
+
: "nor could it mark itself unpublished, so forge-bridge status --idle may read the last record until it goes stale";
|
|
299
|
+
this.options.log?.(`Bridge state file ${this.statePath} could not be written; ${outcome}: ${error instanceof Error ? error.message : String(error)}`);
|
|
300
|
+
}
|
|
301
|
+
this.failing = true;
|
|
302
|
+
}
|
|
303
|
+
ownsRecord(current) {
|
|
304
|
+
return current?.kind === "ok" && current.state.publisherId === this.publisherId;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Two `connect` processes on one config would overwrite each other's record, and the
|
|
308
|
+
* last writer could be the idle one. Each remembers the other live, fresh writer it saw
|
|
309
|
+
* until that writer is gone or would read as stale, and publishes it as a conflict.
|
|
310
|
+
*/
|
|
311
|
+
noteConflict(current) {
|
|
312
|
+
const pidAlive = this.options.pidAlive ?? isProcessAlive;
|
|
313
|
+
const now = this.now().getTime();
|
|
314
|
+
const other = current?.kind === "ok" ? current.state : null;
|
|
315
|
+
if (other && other.pid !== this.pid && other.state === "running" && pidAlive(other.pid)
|
|
316
|
+
&& now - Date.parse(other.updatedAt) <= staleAfterMsFor(other)) {
|
|
317
|
+
if (this.conflict?.pid !== other.pid) {
|
|
318
|
+
this.options.log?.(`Another bridge process (pid ${other.pid}, instance ${other.runnerInstanceId}) publishes to ${this.statePath}; forge-bridge status --idle reports unknown until one of them stops.`);
|
|
319
|
+
}
|
|
320
|
+
this.conflict = { pid: other.pid, runnerInstanceId: other.runnerInstanceId, seenAt: new Date(now).toISOString() };
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
if (this.conflict && (!pidAlive(this.conflict.pid) || now - Date.parse(this.conflict.seenAt) > staleAfterMsFor(null))) {
|
|
324
|
+
this.conflict = null;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
export function formatAge(ms) {
|
|
329
|
+
if (!Number.isFinite(ms))
|
|
330
|
+
return "unknown";
|
|
331
|
+
const seconds = Math.round(Math.abs(ms) / 1000);
|
|
332
|
+
const text = seconds < 120 ? `${seconds}s` : `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
|
|
333
|
+
return ms < 0 ? `-${text}` : text;
|
|
334
|
+
}
|
|
335
|
+
// Every field a reader relies on, with its type: an incomplete or partly written record is
|
|
336
|
+
// invalid (unknown), never a record that happens to lack the fields that would make it busy.
|
|
337
|
+
const requiredStateChecks = [
|
|
338
|
+
state => state.schemaVersion === bridgeStateSchemaVersion,
|
|
339
|
+
state => Number.isInteger(state.pid) && state.pid > 0,
|
|
340
|
+
state => typeof state.runnerId === "string",
|
|
341
|
+
state => typeof state.runnerInstanceId === "string" && state.runnerInstanceId.length > 0,
|
|
342
|
+
state => typeof state.version === "string",
|
|
343
|
+
state => state.state === "running" || state.state === "stopped",
|
|
344
|
+
state => isTimestamp(state.startedAt),
|
|
345
|
+
state => isTimestamp(state.updatedAt),
|
|
346
|
+
state => typeof state.publishIntervalMs === "number" && Number.isFinite(state.publishIntervalMs) && state.publishIntervalMs > 0,
|
|
347
|
+
state => typeof state.connected === "boolean",
|
|
348
|
+
state => typeof state.yielding === "boolean",
|
|
349
|
+
state => state.yieldApplied === undefined || typeof state.yieldApplied === "boolean",
|
|
350
|
+
state => state.publisherId === undefined || (typeof state.publisherId === "string" && state.publisherId.length > 0),
|
|
351
|
+
state => state.conflict === undefined || state.conflict === null || isConflict(state.conflict),
|
|
352
|
+
state => Array.isArray(state.inFlight) && state.inFlight.every(isInFlightEntry),
|
|
353
|
+
];
|
|
354
|
+
function parseBridgeState(value) {
|
|
355
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
356
|
+
return null;
|
|
357
|
+
const state = value;
|
|
358
|
+
return requiredStateChecks.every(check => check(state)) ? state : null;
|
|
359
|
+
}
|
|
360
|
+
function isConflict(value) {
|
|
361
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
362
|
+
return false;
|
|
363
|
+
const conflict = value;
|
|
364
|
+
return Number.isInteger(conflict.pid) && typeof conflict.runnerInstanceId === "string" && isTimestamp(conflict.seenAt);
|
|
365
|
+
}
|
|
366
|
+
function isTimestamp(value) {
|
|
367
|
+
return typeof value === "string" && Number.isFinite(Date.parse(value));
|
|
368
|
+
}
|
|
369
|
+
function safely(read, fallback) {
|
|
370
|
+
try {
|
|
371
|
+
return read();
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return fallback;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Writes JSON atomically: a temp file in the same folder, then a rename over the old one.
|
|
3
|
+
* On Windows the rename fails with EPERM/EBUSY/EACCES while a reader or an antivirus
|
|
4
|
+
* scanner has the target open, so it retries briefly.
|
|
5
|
+
*/
|
|
6
|
+
export declare function writeJsonFileAtomically(target: string, value: unknown): Promise<void>;
|
|
7
|
+
/** True when a process with this id exists. EPERM means it exists but belongs to someone else. */
|
|
8
|
+
export declare function isProcessAlive(pid: number): boolean;
|
|
9
|
+
/** Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is open. */
|
|
10
|
+
export declare function withFsRetry<T>(operation: () => Promise<T>, attempts?: number): Promise<T>;
|
|
11
|
+
export declare function errorCode(error: unknown): string;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
// File helpers shared by the bridge state file and its unpublished markers.
|
|
5
|
+
const retryableFsCodes = new Set(["EACCES", "EBUSY", "EPERM"]);
|
|
6
|
+
/**
|
|
7
|
+
* Writes JSON atomically: a temp file in the same folder, then a rename over the old one.
|
|
8
|
+
* On Windows the rename fails with EPERM/EBUSY/EACCES while a reader or an antivirus
|
|
9
|
+
* scanner has the target open, so it retries briefly.
|
|
10
|
+
*/
|
|
11
|
+
export async function writeJsonFileAtomically(target, value) {
|
|
12
|
+
await fs.mkdir(path.dirname(target), { recursive: true, mode: 0o700 });
|
|
13
|
+
const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;
|
|
14
|
+
try {
|
|
15
|
+
await fs.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
|
|
16
|
+
await withFsRetry(() => fs.rename(temporary, target));
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
await fs.rm(temporary, { force: true }).catch(() => undefined);
|
|
20
|
+
throw error;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** True when a process with this id exists. EPERM means it exists but belongs to someone else. */
|
|
24
|
+
export function isProcessAlive(pid) {
|
|
25
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
26
|
+
return false;
|
|
27
|
+
try {
|
|
28
|
+
process.kill(pid, 0);
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
return errorCode(error) === "EPERM";
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Retries an fs call that Windows refuses with EPERM/EBUSY/EACCES while another handle is open. */
|
|
36
|
+
export async function withFsRetry(operation, attempts = 8) {
|
|
37
|
+
for (let attempt = 1;; attempt += 1) {
|
|
38
|
+
try {
|
|
39
|
+
return await operation();
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
if (attempt >= attempts || !retryableFsCodes.has(errorCode(error)))
|
|
43
|
+
throw error;
|
|
44
|
+
await new Promise(resolve => setTimeout(resolve, 15 * attempt));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
export function errorCode(error) {
|
|
49
|
+
return error?.code ?? "";
|
|
50
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export declare const defaultStateLockTimeoutMs = 5000;
|
|
2
|
+
export interface BridgeStateLockOptions {
|
|
3
|
+
/** How long to wait for a lock another publisher holds. */
|
|
4
|
+
readonly timeoutMs?: number;
|
|
5
|
+
}
|
|
6
|
+
export declare class BridgeStateLockError extends Error {
|
|
7
|
+
}
|
|
8
|
+
/** Runs `critical` while this holder alone has the state file's lock. */
|
|
9
|
+
export declare function withBridgeStateLock<T>(statePath: string, critical: () => Promise<T>, options?: BridgeStateLockOptions): Promise<T>;
|
|
10
|
+
/** The lock's name for a state file: the same for every path that names the same file. */
|
|
11
|
+
export declare function bridgeStateLockName(canonicalPath: string, platform?: NodeJS.Platform): string;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import { constants as fsConstants } from "node:fs";
|
|
3
|
+
import net from "node:net";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
6
|
+
import { errorCode } from "./bridge-state-io.js";
|
|
7
|
+
// Serializes every read-decide-write of bridge.state.json across processes (PR #636 review).
|
|
8
|
+
// Two `connect` processes on one config, or an old bridge stopping while its replacement
|
|
9
|
+
// starts, must never interleave a read of the record with a write over it: the later one
|
|
10
|
+
// would publish a decision taken on a record that no longer exists (two "no conflict"
|
|
11
|
+
// records, or a "stopped" record over a newer bridge's "running" one).
|
|
12
|
+
//
|
|
13
|
+
// The lock is a name the operating system owns, not a file the bridge creates and deletes:
|
|
14
|
+
// - Linux: an abstract-namespace Unix socket ("\0forge-bridge-state-<hash>"). Binding it
|
|
15
|
+
// is atomic; a second bind fails with EADDRINUSE; it has no file, and the kernel frees it
|
|
16
|
+
// when the holder closes it or its process dies.
|
|
17
|
+
// - Windows: a named pipe (\\.\pipe\forge-bridge-state-<hash>), created as the first
|
|
18
|
+
// instance; a second creation fails (EADDRINUSE), and Windows frees it when the holder's
|
|
19
|
+
// handle closes, including when its process dies.
|
|
20
|
+
// - macOS and the BSDs: an O_EXLOCK (flock) open of `<state file>.lock`, never unlinked;
|
|
21
|
+
// the kernel drops the lock when the descriptor closes or the process dies.
|
|
22
|
+
// No holder ever removes or takes over another holder's lock, so there is no stale-lock
|
|
23
|
+
// takeover to race and no release that can free a successor's lock. A holder that hangs
|
|
24
|
+
// keeps it: publishers wait, then fail closed.
|
|
25
|
+
export const defaultStateLockTimeoutMs = 5_000;
|
|
26
|
+
// <sys/fcntl.h> on macOS and the BSDs; libuv passes open flags through to open(2).
|
|
27
|
+
const exclusiveFlockFlag = 0x20;
|
|
28
|
+
export class BridgeStateLockError extends Error {
|
|
29
|
+
}
|
|
30
|
+
/** Runs `critical` while this holder alone has the state file's lock. */
|
|
31
|
+
export async function withBridgeStateLock(statePath, critical, options = {}) {
|
|
32
|
+
const name = bridgeStateLockName(await canonicalStatePath(statePath));
|
|
33
|
+
const held = await acquire(name, options.timeoutMs ?? defaultStateLockTimeoutMs);
|
|
34
|
+
try {
|
|
35
|
+
return await critical();
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
await held.release();
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** The lock's name for a state file: the same for every path that names the same file. */
|
|
42
|
+
export function bridgeStateLockName(canonicalPath, platform = process.platform) {
|
|
43
|
+
// Windows paths (and pipe names) are case-insensitive.
|
|
44
|
+
const key = createHash("sha256").update(platform === "win32" ? canonicalPath.toLowerCase() : canonicalPath).digest("hex").slice(0, 40);
|
|
45
|
+
if (platform === "win32")
|
|
46
|
+
return `\\\\.\\pipe\\forge-bridge-state-${key}`;
|
|
47
|
+
if (platform === "linux")
|
|
48
|
+
return `\0forge-bridge-state-${key}`;
|
|
49
|
+
return `${canonicalPath}.lock`;
|
|
50
|
+
}
|
|
51
|
+
async function canonicalStatePath(statePath) {
|
|
52
|
+
const resolved = path.resolve(statePath);
|
|
53
|
+
await fs.mkdir(path.dirname(resolved), { recursive: true, mode: 0o700 });
|
|
54
|
+
return path.join(await fs.realpath(path.dirname(resolved)), path.basename(resolved));
|
|
55
|
+
}
|
|
56
|
+
async function acquire(name, timeoutMs) {
|
|
57
|
+
const deadline = Date.now() + timeoutMs;
|
|
58
|
+
for (let attempt = 1;; attempt += 1) {
|
|
59
|
+
const held = isSocketName(name) ? await tryListen(name) : await tryFlock(name);
|
|
60
|
+
if (held)
|
|
61
|
+
return held;
|
|
62
|
+
if (Date.now() >= deadline) {
|
|
63
|
+
throw new BridgeStateLockError(`Timed out after ${timeoutMs} ms waiting for the bridge state lock; another bridge process holds it.`);
|
|
64
|
+
}
|
|
65
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(50, 5 * attempt)));
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function isSocketName(name) {
|
|
69
|
+
return name.startsWith("\0") || name.startsWith("\\\\.\\pipe\\");
|
|
70
|
+
}
|
|
71
|
+
/** Binds the name, or null when another holder has it. */
|
|
72
|
+
function tryListen(name) {
|
|
73
|
+
return new Promise((resolve, reject) => {
|
|
74
|
+
const server = net.createServer(socket => socket.destroy());
|
|
75
|
+
server.once("error", error => {
|
|
76
|
+
const code = errorCode(error);
|
|
77
|
+
// EACCES: a pipe of that name made by another user. Held all the same.
|
|
78
|
+
if (code === "EADDRINUSE" || code === "EACCES")
|
|
79
|
+
resolve(null);
|
|
80
|
+
else
|
|
81
|
+
reject(error);
|
|
82
|
+
});
|
|
83
|
+
server.listen(name, () => {
|
|
84
|
+
server.removeAllListeners("error");
|
|
85
|
+
server.on("error", () => undefined);
|
|
86
|
+
server.unref();
|
|
87
|
+
resolve({ release: () => new Promise(done => server.close(() => done())) });
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
async function tryFlock(lockPath) {
|
|
92
|
+
const flags = fsConstants.O_RDWR | fsConstants.O_CREAT | fsConstants.O_NONBLOCK | exclusiveFlockFlag;
|
|
93
|
+
try {
|
|
94
|
+
const handle = await fs.open(lockPath, flags, 0o600);
|
|
95
|
+
return { release: () => handle.close() };
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (errorCode(error) === "EAGAIN" || errorCode(error) === "EWOULDBLOCK")
|
|
99
|
+
return null;
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface UnpublishedMarker {
|
|
2
|
+
readonly schemaVersion: 1;
|
|
3
|
+
readonly pid: number;
|
|
4
|
+
readonly publisherId: string;
|
|
5
|
+
readonly runnerInstanceId: string;
|
|
6
|
+
readonly since: string;
|
|
7
|
+
readonly updatedAt: string;
|
|
8
|
+
readonly publishIntervalMs: number;
|
|
9
|
+
readonly error: string;
|
|
10
|
+
}
|
|
11
|
+
export declare function unpublishedMarkerPathFor(statePath: string, publisherId: string): string;
|
|
12
|
+
export declare function writeUnpublishedMarker(statePath: string, marker: UnpublishedMarker): Promise<void>;
|
|
13
|
+
export declare function removeUnpublishedMarker(statePath: string, publisherId: string): Promise<void>;
|
|
14
|
+
/** Every marker beside the state file. Throws on one it can't trust: idle can't be confirmed then. */
|
|
15
|
+
export declare function readUnpublishedMarkers(statePath: string, now?: number): Promise<UnpublishedMarker[]>;
|
|
16
|
+
/** Removes valid markers whose process has exited: they can no longer hold anything back. */
|
|
17
|
+
export declare function removeExitedUnpublishedMarkers(statePath: string, pidAlive?: (pid: number) => boolean): Promise<void>;
|