velocious 1.0.755 → 1.0.757

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.
Files changed (34) hide show
  1. package/build/configuration-types.js +1 -1
  2. package/build/configuration.js +4 -1
  3. package/build/database/advisory-lock-lock-server-backend.js +52 -19
  4. package/build/database/advisory-lock-lock-server-local-client.js +28 -1
  5. package/build/environment-handlers/base.js +2 -0
  6. package/build/environment-handlers/node/advisory-lock-lock-server-local-server.js +260 -23
  7. package/build/environment-handlers/node.js +7 -4
  8. package/build/src/configuration-types.d.ts +3 -2
  9. package/build/src/configuration-types.d.ts.map +1 -1
  10. package/build/src/configuration-types.js +2 -2
  11. package/build/src/configuration.d.ts +2 -1
  12. package/build/src/configuration.d.ts.map +1 -1
  13. package/build/src/configuration.js +5 -2
  14. package/build/src/database/advisory-lock-lock-server-backend.d.ts +16 -9
  15. package/build/src/database/advisory-lock-lock-server-backend.d.ts.map +1 -1
  16. package/build/src/database/advisory-lock-lock-server-backend.js +55 -20
  17. package/build/src/database/advisory-lock-lock-server-local-client.d.ts +10 -1
  18. package/build/src/database/advisory-lock-lock-server-local-client.d.ts.map +1 -1
  19. package/build/src/database/advisory-lock-lock-server-local-client.js +25 -2
  20. package/build/src/environment-handlers/base.d.ts +7 -0
  21. package/build/src/environment-handlers/base.d.ts.map +1 -1
  22. package/build/src/environment-handlers/base.js +3 -1
  23. package/build/src/environment-handlers/node/advisory-lock-lock-server-local-server.js +239 -28
  24. package/build/src/environment-handlers/node.d.ts +5 -3
  25. package/build/src/environment-handlers/node.d.ts.map +1 -1
  26. package/build/src/environment-handlers/node.js +8 -5
  27. package/package.json +1 -1
  28. package/src/configuration-types.js +1 -1
  29. package/src/configuration.js +4 -1
  30. package/src/database/advisory-lock-lock-server-backend.js +52 -19
  31. package/src/database/advisory-lock-lock-server-local-client.js +28 -1
  32. package/src/environment-handlers/base.js +2 -0
  33. package/src/environment-handlers/node/advisory-lock-lock-server-local-server.js +260 -23
  34. package/src/environment-handlers/node.js +7 -4
@@ -916,7 +916,7 @@
916
916
  * behavior; the file backend is disabled by default and only selectable by
917
917
  * explicit configuration.
918
918
  * @typedef {object} AdvisoryLocksConfiguration
919
- * @property {{file?: {directory?: string, enabled?: boolean, leaseMs?: number, renewIntervalMs?: number}, lockServer?: {authToken?: string, connectTimeoutMs?: number, enabled?: boolean, host?: string, leaseMs?: number, mode?: "embedded" | "external" | "local", port?: number, reprobeCooldownMs?: number, socketPath?: string, url?: string}}} [backends] - Backend enablement. `file.enabled` defaults to false; enabling it is the deployment's explicit single-host declaration. `lockServer` defaults to enabled when a host/port/url or the `VELOCIOUS_LOCK_SERVER_HOST`/`_PORT` env pair is configured.
919
+ * @property {{file?: {directory?: string, enabled?: boolean, leaseMs?: number, renewIntervalMs?: number}, lockServer?: {authToken?: string, connectTimeoutMs?: number, enabled?: boolean, host?: string, leaseMs?: number, mode?: "embedded" | "external" | "local", port?: number, reprobeCooldownMs?: number, socketPath?: string, spawnEngine?: boolean, url?: string}}} [backends] - Backend enablement. `file.enabled` defaults to false; enabling it is the deployment's explicit single-host declaration. `lockServer` defaults to enabled when a host/port/url or the `VELOCIOUS_LOCK_SERVER_HOST`/`_PORT` env pair is configured. `lockServer.spawnEngine` is `local`-only and defaults to true; false means a supervisor owns the engine and this process never spawns one.
920
920
  * @property {import("./database/advisory-lock-backend-policy.js").AdvisoryLockBackendPolicyEntry[]} [policy] - Per-lock-name minimum/allowed/preferred tier rules (design §5).
921
921
  */
922
922
 
@@ -4333,7 +4333,7 @@ export default class VelociousConfiguration {
4333
4333
  * Full backward compatibility: an app that configures nothing gets today's
4334
4334
  * driver-native-only behavior — the file backend is **disabled by default**
4335
4335
  * and only ever selectable by explicit configuration.
4336
- * @returns {{backends: {file: {directory?: string, enabled: boolean, leaseMs: number, renewIntervalMs: number}, lockServer: {authToken: string, connectTimeoutMs: number, enabled: boolean, leaseMs: number, mode: "embedded" | "external" | "local", reprobeCooldownMs: number, socketPath: string, url: string}}, policy: import("./database/advisory-lock-backend-policy.js").AdvisoryLockBackendPolicyEntry[]}} - Advisory-lock configuration with defaults applied.
4336
+ * @returns {{backends: {file: {directory?: string, enabled: boolean, leaseMs: number, renewIntervalMs: number}, lockServer: {authToken: string, connectTimeoutMs: number, enabled: boolean, leaseMs: number, mode: "embedded" | "external" | "local", reprobeCooldownMs: number, socketPath: string, spawnEngine: boolean, url: string}}, policy: import("./database/advisory-lock-backend-policy.js").AdvisoryLockBackendPolicyEntry[]}} - Advisory-lock configuration with defaults applied.
4337
4337
  */
4338
4338
  getAdvisoryLockConfig() {
4339
4339
  const configured = this._advisoryLocks || {}
@@ -4379,6 +4379,8 @@ export default class VelociousConfiguration {
4379
4379
  leaseMs: typeof lockServerConfigured.leaseMs === "number" ? lockServerConfigured.leaseMs : 30_000,
4380
4380
  mode: lockServerMode,
4381
4381
  reprobeCooldownMs: typeof lockServerConfigured.reprobeCooldownMs === "number" ? lockServerConfigured.reprobeCooldownMs : 5000,
4382
+ // `local` mode spawns its engine on demand. Set false when a supervisor (a Rollbridge service, for example) owns the engine, so no client can put a second unsupervised authority on the same socket path.
4383
+ spawnEngine: typeof lockServerConfigured.spawnEngine === "boolean" ? lockServerConfigured.spawnEngine : true,
4382
4384
  socketPath: typeof lockServerConfigured.socketPath === "string" ? lockServerConfigured.socketPath : "",
4383
4385
  url: lockServerUrl
4384
4386
  }
@@ -4478,6 +4480,7 @@ export default class VelociousConfiguration {
4478
4480
  },
4479
4481
  reprobeCooldownMs: config.backends.lockServer.reprobeCooldownMs,
4480
4482
  socketPath: config.backends.lockServer.socketPath,
4483
+ spawnEngine: config.backends.lockServer.spawnEngine,
4481
4484
  url: config.backends.lockServer.url
4482
4485
  })
4483
4486
 
@@ -11,7 +11,7 @@ import {AdvisoryLockServiceUnavailableError} from "./advisory-lock-errors.js"
11
11
  * @property {() => Promise<void>} connect - Opens the transport.
12
12
  * @property {(type: string, args: {onMessage: (body: Record<string, unknown>) => void, params: Record<string, unknown>, timeoutMs: number}) => LockServerConnectionLike} openConnection - Opens the 1:1 connection.
13
13
  * @property {() => Promise<void> | void} [close] - Closes the transport.
14
- * @typedef {{epoch: number, name: string, timer: ReturnType<typeof setInterval>, leaseExpiresAt: number}} LockServerHold
14
+ * @typedef {{epoch: number, name: string, timer: ReturnType<typeof setTimeout> | null, leaseExpiresAt: number, renewing: boolean}} LockServerHold
15
15
  * @typedef {{status: "acquired", epoch: number, leaseExpiresAt: number} | {status: "already-held", epoch: number, leaseExpiresAt: number} | {status: "busy"} | {status: "timeout"}} LockServerAcquireResult
16
16
  */
17
17
 
@@ -74,7 +74,7 @@ export default class AdvisoryLockLockServerBackend {
74
74
  this.connectPromise = null
75
75
  /** @type {{reject: (error: Error) => void, resolve: () => void, timer: ReturnType<typeof setTimeout> | null} | null} */
76
76
  this.helloWaiter = null
77
- /** @type {Map<string, {epoch: number, name: string, timer: ReturnType<typeof setInterval>, leaseExpiresAt: number}>} */
77
+ /** @type {Map<string, LockServerHold>} */
78
78
  this.holds = new Map()
79
79
  /** @type {Map<string, {currentEpoch: number | null, epoch: number | null}>} */
80
80
  this.fencedHolds = new Map()
@@ -231,7 +231,7 @@ export default class AdvisoryLockLockServerBackend {
231
231
  if (!hold) return
232
232
 
233
233
  this.holds.delete(name)
234
- clearInterval(hold.timer)
234
+ if (hold.timer) clearTimeout(hold.timer)
235
235
 
236
236
  if (!this.connection) return
237
237
 
@@ -381,7 +381,7 @@ export default class AdvisoryLockLockServerBackend {
381
381
  if (!hold) return
382
382
 
383
383
  this.holds.delete(name)
384
- clearInterval(hold.timer)
384
+ if (hold.timer) clearTimeout(hold.timer)
385
385
  this.fencedHolds.set(name, {currentEpoch: Number(body.epoch ?? 0), epoch: hold.epoch})
386
386
 
387
387
  return
@@ -458,15 +458,34 @@ export default class AdvisoryLockLockServerBackend {
458
458
  startRenewal(name, epoch) {
459
459
  const existing = this.holds.get(name)
460
460
 
461
- if (existing) clearInterval(existing.timer)
461
+ if (existing?.timer) clearTimeout(existing.timer)
462
462
 
463
- const intervalMs = Math.max(250, Math.floor(this.leaseMs / 3))
464
- const timer = setInterval(() => {
465
- void this.renew(name, epoch)
466
- }, intervalMs)
463
+ this.holds.set(name, {epoch, leaseExpiresAt: Date.now() + this.leaseMs, name, renewing: false, timer: null})
464
+ this.scheduleRenewal(name, epoch)
465
+ }
466
+
467
+ /**
468
+ * Schedules the next lease renewal. A one-shot timer prevents overlapping
469
+ * renewal requests: under transport pressure, the old interval could start
470
+ * another request before the previous one settled, and one transient request
471
+ * timeout then incorrectly converted a still-valid lease into a fenced hold.
472
+ * @param {string} name - Lock name.
473
+ * @param {number} epoch - Granted epoch.
474
+ * @param {number} [delayMs] - Delay before the next renewal.
475
+ * @returns {void}
476
+ */
477
+ scheduleRenewal(name, epoch, delayMs = Math.max(250, Math.floor(this.leaseMs / 3))) {
478
+ const hold = this.holds.get(name)
467
479
 
468
- timer.unref?.()
469
- this.holds.set(name, {epoch, leaseExpiresAt: Date.now() + this.leaseMs, name, timer})
480
+ if (!hold || hold.epoch !== epoch) return
481
+
482
+ if (hold.timer) clearTimeout(hold.timer)
483
+
484
+ hold.timer = setTimeout(() => {
485
+ hold.timer = null
486
+ void this.renew(name, epoch)
487
+ }, delayMs)
488
+ hold.timer.unref?.()
470
489
  }
471
490
 
472
491
  /**
@@ -478,34 +497,48 @@ export default class AdvisoryLockLockServerBackend {
478
497
  async renew(name, epoch) {
479
498
  const hold = this.holds.get(name)
480
499
 
481
- if (!hold || !this.connection) return
500
+ if (!hold || hold.epoch !== epoch || hold.renewing || !this.connection) return
501
+
502
+ hold.renewing = true
482
503
 
483
504
  try {
484
- const response = await this.request("renew", {epoch, name}, this.connectTimeoutMs * 2)
505
+ const remainingMs = Math.max(1, hold.leaseExpiresAt - Date.now())
506
+ const response = await this.request("renew", {epoch, name}, Math.max(1, Math.min(this.connectTimeoutMs * 2, remainingMs)))
485
507
  const status = String(response.status)
486
508
 
487
509
  if (status === "renewed") {
488
510
  hold.leaseExpiresAt = Number(response.leaseExpiresAt)
511
+ this.scheduleRenewal(name, epoch)
489
512
 
490
513
  return
491
514
  }
492
515
 
493
516
  if (status === "lost" || status === "not-found") {
494
517
  this.holds.delete(name)
495
- clearInterval(hold.timer)
518
+ if (hold.timer) clearTimeout(hold.timer)
496
519
  this.fencedHolds.set(name, {currentEpoch: Number(response.currentEpoch ?? 0), epoch})
497
520
  }
498
521
  } catch (error) {
499
522
  if (!(error instanceof AdvisoryLockServiceUnavailableError)) throw error
500
523
 
501
- // A lease that cannot be renewed can no longer be proven to be ours: the
502
- // server may have fenced it while the transport was failing. Recording it
503
- // as lost is the only honest answer, and stops the renewal loop.
524
+ // A request timeout is not itself proof that the lease was fenced. Keep
525
+ // the hold until its server-granted expiry and retry the renewal while
526
+ // that lease remains valid. If the server did fence it, the next request
527
+ // returns `lost` (or the server's lost push records it); if the lease
528
+ // really expires, the next retry records the loss after that event.
529
+ if (Date.now() < hold.leaseExpiresAt && this.holds.get(name) === hold) {
530
+ this.scheduleRenewal(name, epoch, Math.max(250, Math.min(Math.floor(this.leaseMs / 3), hold.leaseExpiresAt - Date.now() - 100)))
531
+
532
+ return
533
+ }
534
+
504
535
  this.markUnavailable(error)
505
536
  this.holds.delete(name)
506
- clearInterval(hold.timer)
537
+ if (hold.timer) clearTimeout(hold.timer)
507
538
  this.fencedHolds.set(name, {currentEpoch: null, epoch})
508
539
  this.reportError(error)
540
+ } finally {
541
+ hold.renewing = false
509
542
  }
510
543
  }
511
544
 
@@ -526,7 +559,7 @@ export default class AdvisoryLockLockServerBackend {
526
559
  */
527
560
  teardown() {
528
561
  for (const [name, hold] of this.holds) {
529
- clearInterval(hold.timer)
562
+ if (hold.timer) clearTimeout(hold.timer)
530
563
  this.fencedHolds.set(name, {currentEpoch: null, epoch: hold.epoch})
531
564
  }
532
565
 
@@ -21,6 +21,12 @@ import {fileURLToPath} from "node:url"
21
21
  * acquisition after the cooldown reconnects — respawning the engine child when
22
22
  * the socket file is gone. The cooldown IS the restart backoff; there is no
23
23
  * separate respawn loop.
24
+ *
25
+ * With `spawnEngine: false` the engine belongs to a supervisor (a Rollbridge
26
+ * service, for example) and this client never spawns one, so exactly one
27
+ * process on the host can own the socket. A missing engine then surfaces as an
28
+ * outage, and the engine server's takeover path replaces a retiring authority
29
+ * without a window where nothing is listening.
24
30
  */
25
31
  export default class AdvisoryLockLockServerLocalClient {
26
32
  /**
@@ -30,13 +36,15 @@ export default class AdvisoryLockLockServerLocalClient {
30
36
  * @param {string} [args.authToken] - Shared secret forwarded in the hello params.
31
37
  * @param {number} [args.connectTimeoutMs] - Bounded wait for the socket/engine child to become ready.
32
38
  * @param {number} [args.leaseMs] - Lease duration the engine child should use.
39
+ * @param {boolean} [args.spawnEngine] - When false the engine is owned by a supervisor and this client never spawns one: a missing engine is reported as an outage instead of being replaced by an unsupervised child that would fight the supervisor for the socket.
33
40
  * @param {string} args.socketPath - Unix socket path of the local engine.
34
41
  */
35
- constructor({authToken = "", connectTimeoutMs = 3000, leaseMs = 30_000, socketPath}) {
42
+ constructor({authToken = "", connectTimeoutMs = 3000, leaseMs = 30_000, socketPath, spawnEngine = true}) {
36
43
  this.authToken = authToken
37
44
  this.connectTimeoutMs = connectTimeoutMs
38
45
  this.leaseMs = leaseMs
39
46
  this.socketPath = socketPath
47
+ this.spawnEngine = spawnEngine !== false
40
48
  this.connectionId = `client-${process.pid}-${Math.random().toString(36).slice(2, 10)}`
41
49
  /** @type {net.Socket | null} */
42
50
  this.socket = null
@@ -64,6 +72,13 @@ export default class AdvisoryLockLockServerLocalClient {
64
72
  } catch (error) {
65
73
  if (!this.socketMissingError(error)) throw error
66
74
 
75
+ if (!this.spawnEngine) {
76
+ // The engine is a supervised process: spawning a child here would put a
77
+ // second, unsupervised authority on the same socket path. Report the
78
+ // outage and let the supervisor's own restart heal it.
79
+ throw new Error(`No supervised local lock server is listening at ${this.socketPath}`, {cause: error})
80
+ }
81
+
67
82
  // No engine is listening (missing socket, or a stale socket file left by
68
83
  // a crashed engine): spawn the engine child and poll until it is live.
69
84
  this.spawnEngineChild()
@@ -222,6 +237,18 @@ export default class AdvisoryLockLockServerLocalClient {
222
237
  try {
223
238
  const parsed = /** @type {Record<string, unknown>} */ (JSON.parse(line))
224
239
 
240
+ if (parsed.type === "server-retiring") {
241
+ // The engine is handing the host over to its successor: drop this
242
+ // transport now so the next acquisition reconnects to the successor
243
+ // instead of staying bound to an engine that is on its way out.
244
+ const socket = this.socket
245
+
246
+ this.handleTransportDeath(new Error("Local lock server is retiring"))
247
+ socket?.destroy()
248
+
249
+ continue
250
+ }
251
+
225
252
  this.onMessage?.(parsed)
226
253
  } catch {
227
254
  // A malformed engine line is not a lock answer: the adapter's
@@ -39,6 +39,7 @@ import {validateTimeZone} from "../time-zone.js"
39
39
  * @property {(error: Error) => void} [onError] - Async error reporter.
40
40
  * @property {number} [reprobeCooldownMs] - How long an unavailable server is not re-probed.
41
41
  * @property {string} [socketPath] - Unix socket path for `local` mode (defaults to a short path under os.tmpdir()).
42
+ * @property {boolean} [spawnEngine] - `local` mode only: false when a supervisor owns the engine, so this process never spawns a rival authority on the socket path.
42
43
  * @property {string} url - Lock-server endpoint (websocket URL for external mode; informational for embedded/local modes).
43
44
  */
44
45
 
@@ -85,6 +86,7 @@ export default class VelociousEnvironmentHandlerBase {
85
86
  * @param {(error: Error) => void} [args.onError] - Async error reporter.
86
87
  * @param {number} [args.reprobeCooldownMs] - Unavailability cache window.
87
88
  * @param {string} [args.socketPath] - Unix socket path for `local` mode.
89
+ * @param {boolean} [args.spawnEngine] - `local` mode only: false when a supervisor owns the engine.
88
90
  * @param {string} args.url - Lock-server endpoint.
89
91
  * @returns {Promise<import("../database/advisory-lock-lock-server-backend.js").default>} - Resolves with the created backend in capable handlers.
90
92
  */
@@ -18,15 +18,26 @@ import net from "node:net"
18
18
  * has been gone for `VELOCIOUS_LOCK_SERVER_IDLE_SHUTDOWN_MS` — so a host never
19
19
  * accumulates orphan engines. SIGTERM/SIGINT shut it down cleanly.
20
20
  *
21
- * Startup is race-safe: if another live engine already owns the socket path,
22
- * this candidate exits quietly; a stale socket file from a crashed engine is
23
- * removed before listening.
21
+ * Two startup shapes, selected by `VELOCIOUS_LOCK_SERVER_TAKEOVER`:
22
+ *
23
+ * - unset (a client-spawned candidate): if another live engine already owns
24
+ * the socket path, this candidate exits quietly — that engine serves the
25
+ * host. A stale socket file from a crashed engine is removed before listening.
26
+ * - `1` (a supervisor-owned engine, e.g. a Rollbridge service): the candidate
27
+ * retires the incumbent instead of yielding to it. It asks the incumbent to
28
+ * stop accepting and tell its clients to reconnect, takes the socket path
29
+ * over while the incumbent finishes its in-flight requests, and binds. The
30
+ * incumbent's clients land on this engine, so a supervised authority can be
31
+ * replaced without a window where nothing is listening.
24
32
  */
25
33
 
26
34
  const socketPath = defaultLockServerSocketPath(process.env.VELOCIOUS_LOCK_SERVER_SOCKET_PATH)
27
35
  const leaseMsRaw = Number(process.env.CONSENS_LOCK_LEASE_MS)
28
36
  const idleShutdownMsRaw = Number(process.env.VELOCIOUS_LOCK_SERVER_IDLE_SHUTDOWN_MS)
29
37
  const idleShutdownMs = Number.isFinite(idleShutdownMsRaw) && idleShutdownMsRaw >= 0 ? idleShutdownMsRaw : 30_000
38
+ const drainTimeoutMsRaw = Number(process.env.VELOCIOUS_LOCK_SERVER_DRAIN_TIMEOUT_MS)
39
+ const drainTimeoutMs = Number.isFinite(drainTimeoutMsRaw) && drainTimeoutMsRaw >= 0 ? drainTimeoutMsRaw : 10_000
40
+ const takeoverRequested = /^(1|true|yes)$/i.test(String(process.env.VELOCIOUS_LOCK_SERVER_TAKEOVER || ""))
30
41
 
31
42
  const engine = new AdvisoryLockLockServerEngine({
32
43
  leaseMs: Number.isFinite(leaseMsRaw) && leaseMsRaw > 0 ? leaseMsRaw : 30_000
@@ -36,8 +47,15 @@ engine.startSweeper()
36
47
 
37
48
  let closing = false
38
49
  let connectionCount = 0
50
+ let listening = false
51
+ let retiring = false
52
+ // Set when this engine was retired by a successor: the successor owns the
53
+ // socket path now, so this engine must not unlink it on its way out.
54
+ let socketHandedOff = false
39
55
  /** @type {ReturnType<typeof setTimeout> | null} */
40
56
  let idleTimer = null
57
+ /** @type {Map<net.Socket, Set<string>>} */
58
+ const clientConnections = new Map()
41
59
 
42
60
  /**
43
61
  * Answers a startup race: is another live engine already listening on the
@@ -59,6 +77,15 @@ function probeExistingEngine() {
59
77
  })
60
78
  }
61
79
 
80
+ /**
81
+ * Waits for one protocol beat.
82
+ * @param {number} ms - Delay.
83
+ * @returns {Promise<void>} - Resolves after the delay.
84
+ */
85
+ function sleep(ms) {
86
+ return new Promise((resolve) => setTimeout(resolve, ms))
87
+ }
88
+
62
89
  /**
63
90
  * Cancels a pending idle-shutdown countdown (a client is back).
64
91
  * @returns {void}
@@ -77,13 +104,73 @@ function cancelIdleShutdown() {
77
104
  * @returns {void}
78
105
  */
79
106
  function scheduleIdleShutdown() {
80
- if (closing || connectionCount > 0) return
107
+ if (closing || retiring || connectionCount > 0) return
81
108
 
82
109
  cancelIdleShutdown()
83
110
  idleTimer = setTimeout(() => shutdown(), idleShutdownMs)
84
111
  idleTimer.unref?.()
85
112
  }
86
113
 
114
+ /**
115
+ * Tells every live client that this engine is going away, so its transport
116
+ * reconnects to the successor instead of discovering the outage request by
117
+ * request.
118
+ * @returns {void}
119
+ */
120
+ function notifyClientsRetiring() {
121
+ for (const [socket, connectionIds] of clientConnections) {
122
+ if (socket.destroyed) continue
123
+
124
+ for (const connectionId of connectionIds) {
125
+ try {
126
+ socket.write(`${JSON.stringify({connectionId, type: "server-retiring"})}\n`)
127
+ } catch {
128
+ // A transport that cannot take the notice is already gone; its leases
129
+ // are released by the engine close below.
130
+ }
131
+ }
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Removes this engine's socket file. Skipped after a handoff, because the
137
+ * successor already bound the same path and unlinking it would take the
138
+ * authority's address away from the host.
139
+ * @returns {void}
140
+ */
141
+ function releaseSocketPath() {
142
+ if (socketHandedOff) return
143
+
144
+ try {
145
+ fs.unlinkSync(socketPath)
146
+ } catch {
147
+ // The socket file may already be gone; nothing left to clean.
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Stops listening, releases the socket path, and exits.
153
+ * @returns {void}
154
+ */
155
+ function exitCleanly() {
156
+ if (listening) {
157
+ listening = false
158
+ server.close(() => {
159
+ releaseSocketPath()
160
+ process.exit(0)
161
+ })
162
+ setTimeout(() => {
163
+ releaseSocketPath()
164
+ process.exit(0)
165
+ }, 2000).unref?.()
166
+
167
+ return
168
+ }
169
+
170
+ releaseSocketPath()
171
+ process.exit(0)
172
+ }
173
+
87
174
  /**
88
175
  * Clean shutdown: close the engine, stop listening, remove the socket file.
89
176
  * @returns {void}
@@ -93,17 +180,146 @@ function shutdown() {
93
180
 
94
181
  closing = true
95
182
  cancelIdleShutdown()
183
+ notifyClientsRetiring()
96
184
  engine.close()
97
- server.close(() => {
98
- try {
99
- fs.unlinkSync(socketPath)
100
- } catch {
101
- // The socket file may already be gone; nothing left to clean.
102
- }
185
+ exitCleanly()
186
+ }
187
+
188
+ /**
189
+ * Retirement requested by the successor engine (or by an operator hook): stop
190
+ * accepting new connections, tell the live clients to reconnect elsewhere, let
191
+ * in-flight requests finish, then exit without taking the socket path away
192
+ * from the successor.
193
+ * @returns {void}
194
+ */
195
+ function beginRetire() {
196
+ if (closing || retiring) return
103
197
 
198
+ retiring = true
199
+ socketHandedOff = true
200
+ cancelIdleShutdown()
201
+ // A supervisor sees this exit as unexpected, so the reason has to be in the log it keeps.
202
+ process.stderr.write(`lock server retiring: handing ${socketPath} to a successor engine\n`)
203
+ notifyClientsRetiring()
204
+
205
+ if (listening) {
206
+ listening = false
207
+ server.close(() => {
208
+ engine.close()
209
+ releaseSocketPath()
210
+ process.exit(0)
211
+ })
212
+ }
213
+
214
+ // Clients close on the retiring notice. One that ignores it must not keep the
215
+ // retired engine — and the leases on its connections — alive past the drain
216
+ // bound, so the bound cuts the transports and lets `server.close()` settle.
217
+ setTimeout(() => {
218
+ for (const socket of clientConnections.keys()) socket.destroy()
219
+ }, drainTimeoutMs).unref?.()
220
+
221
+ // Hard ceiling: a transport that cannot settle after being cut must not hold
222
+ // this process open forever.
223
+ setTimeout(() => {
224
+ engine.close()
225
+ releaseSocketPath()
104
226
  process.exit(0)
227
+ }, drainTimeoutMs + 2000).unref?.()
228
+ }
229
+
230
+ /**
231
+ * Asks the incumbent engine on this socket path to retire, and waits until it
232
+ * has stopped listening so this candidate can bind.
233
+ *
234
+ * The incumbent's `retire-ack` is the handoff signal: it stops accepting and
235
+ * removes the socket file at that moment, so the successor binds as soon as the
236
+ * path stops answering. Waiting for the connection to close instead would make
237
+ * the handoff depend on when the incumbent happens to finish draining.
238
+ * @returns {Promise<boolean>} - True when the incumbent stopped listening.
239
+ */
240
+ async function retireIncumbentEngine() {
241
+ const acked = await new Promise((resolve) => {
242
+ const socket = net.connect(socketPath)
243
+ let buffer = ""
244
+ const deadline = setTimeout(() => {
245
+ socket.destroy()
246
+ resolve(false)
247
+ }, drainTimeoutMs + 5000)
248
+
249
+ deadline.unref?.()
250
+
251
+ const finish = (/** @type {boolean} */ result) => {
252
+ clearTimeout(deadline)
253
+ socket.destroy()
254
+ resolve(result)
255
+ }
256
+
257
+ socket.once("error", () => finish(false))
258
+ socket.once("connect", () => {
259
+ socket.write(`${JSON.stringify({connectionId: `takeover-${process.pid}`, type: "retire"})}\n`)
260
+ })
261
+ socket.setEncoding("utf8")
262
+ socket.on("data", (/** @type {string} */ chunk) => {
263
+ buffer += chunk
264
+
265
+ let newlineIndex = buffer.indexOf("\n")
266
+
267
+ while (newlineIndex >= 0) {
268
+ const line = buffer.slice(0, newlineIndex)
269
+
270
+ buffer = buffer.slice(newlineIndex + 1)
271
+
272
+ if (!line.trim()) {
273
+ newlineIndex = buffer.indexOf("\n")
274
+
275
+ continue
276
+ }
277
+
278
+ try {
279
+ const message = /** @type {Record<string, unknown>} */ (JSON.parse(line))
280
+
281
+ if (message.type === "retire-ack") {
282
+ finish(true)
283
+
284
+ return
285
+ }
286
+ } catch {
287
+ // Not a protocol answer; keep waiting for the ack until the deadline.
288
+ }
289
+
290
+ newlineIndex = buffer.indexOf("\n")
291
+ }
292
+ })
105
293
  })
106
- setTimeout(() => process.exit(0), 2000).unref?.()
294
+
295
+ if (!acked) return false
296
+
297
+ // The incumbent stopped accepting and removed its socket file; confirm the
298
+ // path really stopped answering before binding to it.
299
+ const deadline = Date.now() + drainTimeoutMs + 5000
300
+
301
+ while (Date.now() < deadline) {
302
+ if (!(await probeExistingEngine())) return true
303
+
304
+ await sleep(25)
305
+ }
306
+
307
+ return false
308
+ }
309
+
310
+ /**
311
+ * Binds this engine to the socket path, clearing a stale socket file first.
312
+ * @returns {void}
313
+ */
314
+ function bindSocketPath() {
315
+ try {
316
+ fs.unlinkSync(socketPath)
317
+ } catch {
318
+ // No stale socket to remove.
319
+ }
320
+
321
+ server.listen(socketPath)
322
+ listening = true
107
323
  }
108
324
 
109
325
  /**
@@ -119,6 +335,9 @@ function handleClientSocket(socket) {
119
335
 
120
336
  /** @type {Set<string>} */
121
337
  const socketConnectionIds = new Set()
338
+
339
+ clientConnections.set(socket, socketConnectionIds)
340
+
122
341
  let buffer = ""
123
342
 
124
343
  socket.on("data", (/** @type {string} */ chunk) => {
@@ -139,7 +358,16 @@ function handleClientSocket(socket) {
139
358
  if (connectionId) {
140
359
  socketConnectionIds.add(connectionId)
141
360
 
142
- if (message.type === "hello") {
361
+ // The retirement frame is a transport control message, not a lock
362
+ // request: it is answered here and never reaches the engine.
363
+ if (message.type === "retire") {
364
+ socket.write(`${JSON.stringify({connectionId, status: "retiring", type: "retire-ack"})}\n`)
365
+ beginRetire()
366
+ // The successor is not a client to drain: it is waiting for this
367
+ // connection to end, and keeping it open would hold the retired
368
+ // engine's own `server.close()` until the drain bound expires.
369
+ socket.end()
370
+ } else if (message.type === "hello") {
143
371
  socket.write(`${JSON.stringify({connectionId, leaseMs: engine.leaseMs, protocolVersion: LOCK_SERVER_PROTOCOL_VERSION, type: "hello-ack"})}\n`)
144
372
  } else {
145
373
  engine.ensureConnection(connectionId, {
@@ -162,6 +390,7 @@ function handleClientSocket(socket) {
162
390
 
163
391
  socket.on("close", () => {
164
392
  connectionCount -= 1
393
+ clientConnections.delete(socket)
165
394
 
166
395
  // The transport died: the engine releases every lease this socket held,
167
396
  // exactly like the external daemon does on a websocket close.
@@ -176,12 +405,19 @@ const server = net.createServer((socket) => handleClientSocket(socket))
176
405
 
177
406
  server.on("error", async (/** @type {{code?: string}} */ error) => {
178
407
  if (error.code === "EADDRINUSE") {
179
- // Either a live engine owns the path (quiet exit — that engine serves the
180
- // host) or a crashed one left a stale socket behind (remove and retry).
181
- if (await probeExistingEngine()) process.exit(0)
408
+ // Either a live engine owns the path or a crashed one left a stale socket
409
+ // behind. A supervisor-owned candidate retires the live engine; a
410
+ // client-spawned candidate yields to it and exits quietly.
411
+ if (await probeExistingEngine()) {
412
+ if (!takeoverRequested) process.exit(0)
413
+
414
+ if (!(await retireIncumbentEngine())) {
415
+ process.stderr.write(`lock-server takeover refused: the engine at ${socketPath} did not retire within ${drainTimeoutMs + 5000}ms\n`)
416
+ process.exit(1)
417
+ }
418
+ }
182
419
 
183
- fs.unlinkSync(socketPath)
184
- server.listen(socketPath)
420
+ bindSocketPath()
185
421
 
186
422
  return
187
423
  }
@@ -191,15 +427,16 @@ server.on("error", async (/** @type {{code?: string}} */ error) => {
191
427
 
192
428
  const alreadyLive = await probeExistingEngine()
193
429
 
194
- if (alreadyLive) process.exit(0)
430
+ if (alreadyLive) {
431
+ if (!takeoverRequested) process.exit(0)
195
432
 
196
- try {
197
- fs.unlinkSync(socketPath)
198
- } catch {
199
- // No stale socket to remove.
433
+ if (!(await retireIncumbentEngine())) {
434
+ process.stderr.write(`lock-server takeover refused: the engine at ${socketPath} did not retire within ${drainTimeoutMs + 5000}ms\n`)
435
+ process.exit(1)
436
+ }
200
437
  }
201
438
 
202
- server.listen(socketPath)
439
+ bindSocketPath()
203
440
 
204
441
  for (const signal of ["SIGTERM", "SIGINT"]) {
205
442
  process.on(signal, () => shutdown())
@@ -127,9 +127,11 @@ export default class VelociousEnvironmentHandlerNode extends Base{
127
127
  *
128
128
  * - `external` (default): the Node websocket transport to the shared
129
129
  * consens-lock daemon — unchanged behavior for existing configurations.
130
- * - `local`: spawns the engine as a child of this process over stdio
131
- * JSON-lines — no listening network port, lifecycle follows the
132
- * environment, crash detection via the adapter's unavailability cache.
130
+ * - `local`: connects to the engine server on a Unix socket, spawning it as
131
+ * a child of this process when nothing is listening — no listening network
132
+ * port, lifecycle follows the environment, crash detection via the
133
+ * adapter's unavailability cache. `spawnEngine: false` keeps a supervised
134
+ * engine (a Rollbridge service) as the only process that can own the socket.
133
135
  * - `embedded`: the base handler's in-process engine (no sockets at all).
134
136
  * @param {import("./base.js").AdvisoryLockLockServerBackendOptions} args - Backend options.
135
137
  * @returns {Promise<import("../database/advisory-lock-lock-server-backend.js").default>} - Created backend.
@@ -142,7 +144,8 @@ export default class VelociousEnvironmentHandlerNode extends Base{
142
144
  authToken,
143
145
  connectTimeoutMs: args.connectTimeoutMs,
144
146
  leaseMs: args.leaseMs,
145
- socketPath: args.socketPath || defaultLockServerSocketPath()
147
+ socketPath: args.socketPath || defaultLockServerSocketPath(),
148
+ spawnEngine: args.spawnEngine
146
149
  })
147
150
  })
148
151
  }