rollbridge 0.1.82 → 0.1.84

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rollbridge",
3
- "version": "0.1.82",
3
+ "version": "0.1.84",
4
4
  "description": "Zero-downtime process supervisor and local traffic switcher for deploy-managed apps.",
5
5
  "keywords": [
6
6
  "deploy",
package/src/cli.js CHANGED
@@ -321,10 +321,7 @@ export async function runCli(argv) {
321
321
  .action(async (options) => {
322
322
  const configPath = await resolveConfigPath(options.config)
323
323
  const config = await loadConfig(configPath)
324
- const response = await sendControlCommand({
325
- command: {command: "status", ...(options.logs ? {} : {includeLogs: false})},
326
- path: config.control.path
327
- })
324
+ const response = await terminalControlCommand(config, {command: "status", ...(options.logs ? {} : {includeLogs: false})})
328
325
 
329
326
  console.log(JSON.stringify(response, null, 2))
330
327
  })
@@ -380,10 +377,7 @@ export async function runCli(argv) {
380
377
  .action(async (options) => {
381
378
  const configPath = await resolveConfigPath(options.config)
382
379
  const config = await loadConfig(configPath)
383
- const response = await sendControlCommand({
384
- command: {command: "shutdown"},
385
- path: config.control.path
386
- })
380
+ const response = await terminalControlCommand(config, {command: "shutdown"})
387
381
 
388
382
  console.log(JSON.stringify(response, null, 2))
389
383
  })
@@ -1064,6 +1058,25 @@ async function daemonStatus(config) {
1064
1058
  }
1065
1059
  }
1066
1060
 
1061
+ /**
1062
+ * Sends a terminal control command while classifying a stale or absent control socket.
1063
+ * @param {import("./config.js").RollbridgeConfig} config - Loaded config.
1064
+ * @param {Record<string, import("./json.js").JsonValue>} command - Control command.
1065
+ * @returns {Promise<Record<string, import("./json.js").JsonValue>>} Command response or no-daemon result.
1066
+ */
1067
+ async function terminalControlCommand(config, command) {
1068
+ try {
1069
+ return await sendControlCommand({command, path: config.control.path})
1070
+ } catch (error) {
1071
+ const errorWithCode = error && typeof error === "object"
1072
+ ? /** @type {{code?: string}} */ (error)
1073
+ : undefined
1074
+
1075
+ if (isMissingDaemonError(errorWithCode)) return {message: `No Rollbridge daemon is running on ${config.control.path}.`, status: "not-running"}
1076
+ throw error
1077
+ }
1078
+ }
1079
+
1067
1080
  /**
1068
1081
  * Starts the foreground daemon command as a detached child.
1069
1082
  * @param {object} args - Options.
@@ -1135,7 +1148,16 @@ async function readDaemonPid(pidPath) {
1135
1148
  const trimmed = value.trim()
1136
1149
 
1137
1150
  if (!/^\d+$/.test(trimmed)) throw new Error(`Daemon PID file ${pidPath} does not contain one positive integer`)
1138
- return positiveIntegerOrUndefined(trimmed, `daemon PID file ${pidPath}`)
1151
+ const pid = positiveIntegerOrUndefined(trimmed, `daemon PID file ${pidPath}`)
1152
+
1153
+ if (pid === undefined) return undefined
1154
+ try {
1155
+ process.kill(pid, 0)
1156
+ } catch (error) {
1157
+ if (error && typeof error === "object" && "code" in error && error.code === "ESRCH") return undefined
1158
+ throw error
1159
+ }
1160
+ return pid
1139
1161
  }
1140
1162
 
1141
1163
  /**
package/src/daemon.js CHANGED
@@ -38,7 +38,7 @@ const STATE_PERSIST_INTERVAL_MS = 5000
38
38
  * @typedef {{configDigest: string, format: number, guardian: {pid?: number, socketPath: string, token: string}, reconnectGraceMs: number}} OwnerRecoveryMetadata
39
39
  * @typedef {DaemonStatus & {recovery: OwnerRecoveryMetadata, serviceReleaseIds?: Record<string, string>, singletonReleaseIds?: Record<string, string>}} OwnerRecoverySnapshot
40
40
  * @typedef {{authority: JsonValue, config: import("./config.js").RollbridgeConfig, listenerConnectionSources?: Record<string, Record<string, {http: number, websocket: number}>>, listenerSourceId?: string, recovery?: {command: JsonValue, reconnectGraceMs: number, startupTimeoutMs: number}, releaseConfigs?: Record<string, import("./config.js").RollbridgeConfig>, retiredListenerHandoff?: number, serviceReleaseIds?: Record<string, string>, singletonReleaseIds?: Record<string, string>, snapshot: OwnerRecoverySnapshot}} PrivateOwnerState
41
- * @typedef {{boundaryCrossed: boolean, guardianVersion?: string, incumbentControl?: Awaited<ReturnType<typeof openControlSession>>, incumbentStartTime: string, legacyGuardian: GuardianClient, legacyInventory: {key: string, provenance: string, status: import("./managed-process.js").ManagedProcessStatus}[], legacyPrepared?: {ownerState: JsonValue, replacementId: string}, legacySnapshot: OwnerRecoverySnapshot, prepared: {ownerState: JsonValue, replacementId: string}, protocol: GuardianHandoffProtocol, recoverySnapshot: OwnerRecoverySnapshot}} LegacyOwnerBridge
41
+ * @typedef {{boundaryCrossed: boolean, guardianVersion?: string, incumbentControl?: Awaited<ReturnType<typeof openControlSession>>, incumbentStartTime?: string, legacyAuthority: {configDigest: string, runtime: import("./daemon-runtime.js").DaemonRuntimeIdentity | null}, legacyGuardian: GuardianClient, legacyInventory: {key: string, provenance: string, status: import("./managed-process.js").ManagedProcessStatus}[], legacyPrepared?: {ownerState: JsonValue, replacementId: string}, legacySnapshot: OwnerRecoverySnapshot, prepared: {ownerState: JsonValue, replacementId: string}, protocol: GuardianHandoffProtocol, recoverySnapshot: OwnerRecoverySnapshot}} LegacyOwnerBridge
42
42
  */
43
43
 
44
44
  export default class RollbridgeDaemon {
@@ -1013,25 +1013,29 @@ export default class RollbridgeDaemon {
1013
1013
  if (versionHandoff) throw this.guardianVersionHandoffRefusal(guardianVersion, "the handoff keeps the incumbent config identity unchanged and this deploy changes config authority")
1014
1014
  throw new Error("The one-time legacy guardian bridge requires the incumbent config identity unchanged; retry the config change after the bridge establishes split-3 authority")
1015
1015
  }
1016
- if (!this.legacyIncumbentPid) {
1017
- if (versionHandoff) throw this.guardianVersionHandoffRefusal(guardianVersion, "ensure-daemon reported no incumbent daemon to hand guardian ownership from")
1016
+ if (!this.legacyIncumbentPid && !versionHandoff) {
1018
1017
  throw new Error("The authenticated legacy guardian requires an exact incumbent PID from ensure-daemon for the disruptive bridge")
1019
1018
  }
1020
1019
  if (!this.guardianIdentity?.pid) throw new Error("The authenticated legacy guardian state is missing its exact guardian PID")
1021
1020
  await verifyLegacyGuardianProcess(this.guardianIdentity.pid, this.guardianIdentity.socketPath)
1022
1021
  let incumbentStartTime
1023
1022
 
1024
- try {
1025
- incumbentStartTime = await verifyLegacyDaemonProcess(this.legacyIncumbentPid, this.configPath, persisted.control.path)
1026
- } catch (error) {
1027
- if (!versionHandoff) throw error
1028
- throw this.guardianVersionHandoffRefusal(guardianVersion, `the incumbent daemon PID ${this.legacyIncumbentPid} is not the attested owner: ${error instanceof Error ? error.message : String(error)}`)
1023
+ if (this.legacyIncumbentPid) {
1024
+ try {
1025
+ incumbentStartTime = await verifyLegacyDaemonProcess(this.legacyIncumbentPid, this.configPath, persisted.control.path)
1026
+ } catch (error) {
1027
+ if (!versionHandoff) throw error
1028
+ throw this.guardianVersionHandoffRefusal(guardianVersion, `the incumbent daemon PID ${this.legacyIncumbentPid} is not the attested owner: ${error instanceof Error ? error.message : String(error)}`)
1029
+ }
1029
1030
  }
1030
1031
  if (legacyPrepared) assertLegacyPrivateOwnerState(legacyPrepared.ownerState, persisted, persistedAuthority)
1031
- try {
1032
- incumbentControl = await openControlSession(persisted.control.path)
1033
- } catch (error) {
1034
- if (!legacyPrepared || !error || typeof error !== "object" || !("code" in error) || error.code !== "ENOENT") throw error
1032
+ if (this.legacyIncumbentPid) {
1033
+ try {
1034
+ incumbentControl = await openControlSession(persisted.control.path)
1035
+ } catch (error) {
1036
+ const code = error && typeof error === "object" && "code" in error && typeof error.code === "string" ? error.code : undefined
1037
+ if (!legacyPrepared || !["ENOENT", "ECONNREFUSED"].includes(code ?? "")) throw error
1038
+ }
1035
1039
  }
1036
1040
  if (incumbentControl) {
1037
1041
  const incumbentStatus = await incumbentControl.request({command: "status"})
@@ -1078,7 +1082,7 @@ export default class RollbridgeDaemon {
1078
1082
  replacementId: prepared.replacementId,
1079
1083
  runtimeVersion: this.runtime?.version ?? "unknown"
1080
1084
  })
1081
- return {boundaryCrossed: false, guardianVersion, incumbentControl, incumbentStartTime, legacyGuardian, legacyInventory, legacyPrepared, legacySnapshot: persisted, prepared, protocol, recoverySnapshot}
1085
+ return {boundaryCrossed: false, guardianVersion, incumbentControl, incumbentStartTime, legacyAuthority: persistedAuthority, legacyGuardian, legacyInventory, legacyPrepared, legacySnapshot: persisted, prepared, protocol, recoverySnapshot}
1082
1086
  } catch (upgradeError) {
1083
1087
  incumbentControl?.close()
1084
1088
  let cleanupError
@@ -1119,13 +1123,15 @@ export default class RollbridgeDaemon {
1119
1123
  * @param {LegacyOwnerBridge} bridge - Prepared bridge.
1120
1124
  */
1121
1125
  async crossLegacyDisruptiveBoundary(bridge) {
1122
- if (!this.legacyIncumbentPid || !this.statePath) throw new Error("Legacy disruptive boundary is missing its exact incumbent identity")
1126
+ if (!this.statePath) throw new Error("Legacy disruptive boundary is missing its state path")
1123
1127
  if (!this.guardian) throw new Error("Legacy disruptive boundary is missing its authenticated upgraded guardian")
1124
1128
  if (!bridge.legacyGuardian.pid) throw new Error("Legacy disruptive boundary is missing its authenticated retained guardian PID")
1125
1129
  await verifyLegacyGuardianProcess(bridge.legacyGuardian.pid, bridge.legacyGuardian.socketPath)
1126
- const currentStartTime = await verifyLegacyDaemonProcess(this.legacyIncumbentPid, this.configPath, bridge.recoverySnapshot.control.path)
1130
+ if (this.legacyIncumbentPid) {
1131
+ const currentStartTime = await verifyLegacyDaemonProcess(this.legacyIncumbentPid, this.configPath, bridge.recoverySnapshot.control.path)
1127
1132
 
1128
- if (currentStartTime !== bridge.incumbentStartTime) throw new Error("Legacy incumbent PID identity changed before the disruptive boundary")
1133
+ if (currentStartTime !== bridge.incumbentStartTime) throw new Error("Legacy incumbent PID identity changed before the disruptive boundary")
1134
+ }
1129
1135
  if (!isDeepStrictEqual(await readState(this.statePath), bridge.legacySnapshot)) {
1130
1136
  throw new Error("Legacy owner recovery state changed before the disruptive boundary")
1131
1137
  }
@@ -1166,6 +1172,31 @@ export default class RollbridgeDaemon {
1166
1172
  }
1167
1173
  let legacyCommitted
1168
1174
 
1175
+ if (!this.legacyIncumbentPid) {
1176
+ await this.guardian.beginLegacyOwnerClaim(
1177
+ bridge.prepared.replacementId,
1178
+ bridge.recoverySnapshot.recovery.reconnectGraceMs,
1179
+ this.statePath,
1180
+ bridge.recoverySnapshot,
1181
+ bridge.legacyAuthority
1182
+ )
1183
+ await this.guardian.completeLegacyOwnerClaim(bridge.prepared.replacementId)
1184
+ bridge.legacyGuardian.disconnect()
1185
+ bridge.boundaryCrossed = true
1186
+ this.ownerTransition = /** @type {OwnerTransition} */ ({
1187
+ disruptive: true,
1188
+ mode: "guardian-version-handoff",
1189
+ reason: `retained guardian ${bridge.guardianVersion ?? "unknown"} recovered ownership after the incumbent daemon was absent`
1190
+ })
1191
+ this.logger("guardian upgrade bridge ready without incumbent daemon", {
1192
+ disruptive: true,
1193
+ guardianVersion: bridge.guardianVersion ?? "unknown",
1194
+ protocol: bridge.protocol,
1195
+ retainedGuardianPid: bridge.legacyGuardian.pid ?? null,
1196
+ runtimeVersion: this.runtime?.version ?? "unknown"
1197
+ })
1198
+ return
1199
+ }
1169
1200
  if (bridge.legacyPrepared) {
1170
1201
  const status = await bridge.legacyGuardian.replacementStatus()
1171
1202
 
@@ -1823,7 +1854,12 @@ export default class RollbridgeDaemon {
1823
1854
  if (this.stopping) throw new Error("Rollbridge is shutting down")
1824
1855
  } catch (error) {
1825
1856
  this.logger("deploy failed", {error: error instanceof Error ? error.message : String(error), releaseId: newReleaseId})
1826
- await release.stop()
1857
+ // A candidate that fails before it becomes authoritative is already a retired
1858
+ // generation. Apply the same bounded retirement decision used by handoff and
1859
+ // shutdown; an indefinite worker stop here leaves its processes behind while the
1860
+ // failed deploy is being unwound, which is exactly how a dead candidate kept
1861
+ // TensorBuzz's 7330/7331 generation ports occupied.
1862
+ await release.stop({retirementTimeoutMs: nextConfig.proxy.nonBlockingDrainTimeoutMs})
1827
1863
  await this.stopStartedServices(startedServices)
1828
1864
  throw error
1829
1865
  } finally {
@@ -303,9 +303,10 @@ export default class GuardianClient {
303
303
  * @param {number} graceMs - Event-driven incumbent disconnect grace.
304
304
  * @param {string} statePath - Durable public recovery state path.
305
305
  * @param {import("./json.js").JsonValue} recoverySnapshot - Discoverable coordinator state.
306
+ * @param {{configDigest: string, runtime: import("./daemon-runtime.js").DaemonRuntimeIdentity | null}} [legacyAuthority] - Committed legacy authority when the incumbent daemon is already absent.
306
307
  */
307
- async beginLegacyOwnerClaim(replacementId, graceMs, statePath, recoverySnapshot) {
308
- await this.request({command: "begin-legacy-owner-claim", graceMs, recoverySnapshot, replacementId, statePath})
308
+ async beginLegacyOwnerClaim(replacementId, graceMs, statePath, recoverySnapshot, legacyAuthority) {
309
+ await this.request({command: "begin-legacy-owner-claim", graceMs, legacyAuthority, recoverySnapshot, replacementId, statePath})
309
310
  }
310
311
 
311
312
  /**
@@ -49,6 +49,7 @@ const OWNER_MUTATION_LEASE_MS = 900000
49
49
  * @property {import("./json.js").JsonValue} [recoverySnapshot] - Public bridge recovery snapshot.
50
50
  * @property {string} [statePath] - Exact public recovery state path.
51
51
  * @property {import("./json.js").JsonValue} [authority] - Expected current authority.
52
+ * @property {import("./json.js").JsonValue} [legacyAuthority] - Committed legacy authority used when the incumbent daemon is already absent.
52
53
  * @property {import("./json.js").JsonValue} [nextAuthority] - Requested replacement authority.
53
54
  * @property {import("./managed-process.js").ManagedProcessStartReason} [reason] - Start reason.
54
55
  * @property {import("./managed-process.js").LifecycleRole} [lifecycleRole] - Desired generation role restored during start.
@@ -483,7 +484,7 @@ async function execute(request, socket) {
483
484
  assertBridgeRecoverySnapshot(request.recoverySnapshot)
484
485
  legacyRecoveryStatePath = request.statePath
485
486
  legacyRecoverySnapshot = request.recoverySnapshot
486
- legacyOwnerClaim = legacyGuardian.claimOwner(request.graceMs ?? 30000, replacementAuthority).then(
487
+ legacyOwnerClaim = legacyGuardian.claimOwner(request.graceMs ?? 30000, request.legacyAuthority ?? replacementAuthority).then(
487
488
  () => undefined,
488
489
  (error) => error instanceof Error ? error : new Error(String(error))
489
490
  )
@@ -145,6 +145,54 @@ test("version-drifted retained guardian is handed to a current-version coordinat
145
145
  }
146
146
  })
147
147
 
148
+ test("version-drifted guardian recovers when the incumbent daemon is already dead", async () => {
149
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "rollbridge-guardian-dead-incumbent-"))
150
+ const socketPath = path.join(root, "rollbridge.sock")
151
+ const statePath = path.join(root, "state.json")
152
+ const configPath = path.join(root, "rollbridge.cjs")
153
+ const daemonPidPath = path.join(root, "daemon.pid")
154
+ const releasePath = path.join(root, "v1")
155
+ const packagePath = path.join(root, "candidate-package")
156
+ const runtimePath = path.join(root, "runtime")
157
+ let owner
158
+ let replacement
159
+
160
+ try {
161
+ await fs.mkdir(releasePath)
162
+ await makeFifo(path.join(releasePath, "worker.fifo"))
163
+ await writeConfig(configPath, config({controlPath: socketPath, extraCompanion: false, statePath}))
164
+ owner = spawn(process.execPath, [binPath, "daemon", "--config", configPath], {stdio: ["ignore", "pipe", "pipe"]})
165
+ await waitForLog(owner, "control socket listening")
166
+ if (!owner.pid) throw new Error("Missing required fixture: owner.pid")
167
+ await fs.writeFile(daemonPidPath, `${owner.pid}\n`)
168
+ await sendControlCommand({command: {command: "deploy", releaseId: "v1", releasePath, revision: "v1"}, path: socketPath})
169
+ const ownerExit = once(owner, "exit")
170
+
171
+ owner.kill("SIGKILL")
172
+ await ownerExit
173
+ await prepareCandidatePackage(packagePath, {packageVersion: "9.9.9"})
174
+ const ensured = await runEnsureDaemon({configPath, daemonPidPath, logPath: path.join(root, "candidate.log"), packagePath, runtimePath})
175
+
176
+ expect({value: ensured.code, context: ensured.stderr}).toMatchObject({value: 0})
177
+ const status = await sendControlCommand({command: {command: "status"}, path: socketPath})
178
+
179
+ expect(status.activeReleaseId).toBe("v1")
180
+ expect(status.ownerTransition).toMatchObject({disruptive: true, mode: "guardian-version-handoff"})
181
+ const ownerTransition = /** @type {{reason?: string} | null | undefined} */ (status.ownerTransition)
182
+ expect(ownerTransition?.reason).toMatch(/incumbent daemon was absent/)
183
+ replacement = /** @type {number | undefined} */ (status.daemonPid)
184
+ const shutdown = sendControlCommand({command: {command: "shutdown"}, path: socketPath})
185
+ await fs.writeFile(path.join(releasePath, "worker.fifo"), "drained\n")
186
+ await shutdown
187
+ } finally {
188
+ if (replacement) {
189
+ try { process.kill(replacement, "SIGKILL") } catch { /* The replacement already exited. */ }
190
+ }
191
+ await stopGuardian(statePath)
192
+ await fs.rm(root, {force: true, recursive: true})
193
+ }
194
+ })
195
+
148
196
  test("partial owner-replacement guardian crosses the authenticated legacy bridge before retired-owner commit", async () => {
149
197
  const root = await fs.mkdtemp(path.join(os.tmpdir(), "rollbridge-owner-replacement-partial-"))
150
198
  const socketPath = path.join(root, "rollbridge.sock")
@@ -16,6 +16,33 @@ describe("release-runtime-retention", () => {
16
16
  const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
17
17
  const dummyAppPath = path.join(repoRoot, "test", "fixtures", "dummy-app.js")
18
18
 
19
+ test("status and shutdown classify a stale control socket as no daemon running", async () => {
20
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "rollbridge-stale-control-"))
21
+ const release = path.join(root, "release")
22
+ const socketPath = path.join(root, "control.sock")
23
+ const configPath = path.join(root, "rollbridge.js")
24
+ const staleListener = net.createServer()
25
+
26
+ try {
27
+ await prepareRelease(release, false)
28
+ await fs.writeFile(configPath, `export default ${JSON.stringify(basicConfig(socketPath), null, 2)}\n`)
29
+ await new Promise((resolve, reject) => {
30
+ staleListener.once("error", reject)
31
+ staleListener.listen(socketPath, () => resolve(undefined))
32
+ })
33
+ await new Promise((resolve, reject) => staleListener.close(error => error ? reject(error) : resolve(undefined)))
34
+
35
+ const status = JSON.parse(await runReleaseCli(release, ["status", "--config", configPath]))
36
+ const shutdown = JSON.parse(await runReleaseCli(release, ["shutdown", "--config", configPath]))
37
+
38
+ expect(status).toMatchObject({status: "not-running"})
39
+ expect(shutdown).toMatchObject({status: "not-running"})
40
+ } finally {
41
+ if (staleListener.listening) staleListener.close()
42
+ await fs.rm(root, {force: true, recursive: true})
43
+ }
44
+ })
45
+
19
46
  test("detached daemon survives deletion of the release-local Rollbridge installation", async () => {
20
47
  const root = await fs.mkdtemp(path.join(os.tmpdir(), "rollbridge-runtime-retention-"))
21
48
  const releaseA = path.join(root, "releases", "A")
@@ -393,7 +420,7 @@ function basicConfig(socketPath) {
393
420
  * Runs a release-local Rollbridge CLI to completion.
394
421
  * @param {string} releasePath - Release directory.
395
422
  * @param {string[]} args - CLI arguments.
396
- * @returns {Promise<void>} Resolves on success.
423
+ * @returns {Promise<string>} Combined output on success.
397
424
  */
398
425
  async function runReleaseCli(releasePath, args) {
399
426
  const binPath = path.join(releasePath, "node_modules", "rollbridge", "bin", "rollbridge")
@@ -405,6 +432,7 @@ async function runReleaseCli(releasePath, args) {
405
432
  const [code] = await once(child, "exit")
406
433
 
407
434
  if (code !== 0) throw new Error(output)
435
+ return output
408
436
  }
409
437
 
410
438
  /**