velocious 1.0.726 → 1.0.727

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 (71) hide show
  1. package/build/configuration-types.js +1 -1
  2. package/build/configuration.js +17 -2
  3. package/build/database/advisory-lock-lock-server-backend.js +30 -24
  4. package/build/database/advisory-lock-lock-server-embedded-client.js +74 -0
  5. package/build/database/advisory-lock-lock-server-engine.js +544 -0
  6. package/build/database/advisory-lock-lock-server-local-client.js +260 -0
  7. package/build/database/advisory-lock-lock-server-socket-path.js +17 -0
  8. package/build/database/advisory-lock-lock-server-transport.js +30 -0
  9. package/build/database/record/auditing.js +89 -11
  10. package/build/database/record/index.js +1 -1
  11. package/build/environment-handlers/base.js +50 -9
  12. package/build/environment-handlers/node/advisory-lock-lock-server-local-server.js +206 -0
  13. package/build/environment-handlers/node.js +30 -3
  14. package/build/http-server/server-lock.js +29 -16
  15. package/build/src/configuration-types.d.ts +3 -1
  16. package/build/src/configuration-types.d.ts.map +1 -1
  17. package/build/src/configuration-types.js +2 -2
  18. package/build/src/configuration.d.ts +3 -1
  19. package/build/src/configuration.d.ts.map +1 -1
  20. package/build/src/configuration.js +18 -3
  21. package/build/src/database/advisory-lock-lock-server-backend.d.ts +10 -3
  22. package/build/src/database/advisory-lock-lock-server-backend.d.ts.map +1 -1
  23. package/build/src/database/advisory-lock-lock-server-backend.js +25 -22
  24. package/build/src/database/advisory-lock-lock-server-embedded-client.d.ts +24 -0
  25. package/build/src/database/advisory-lock-lock-server-embedded-client.d.ts.map +1 -0
  26. package/build/src/database/advisory-lock-lock-server-embedded-client.js +64 -0
  27. package/build/src/database/advisory-lock-lock-server-engine.d.ts +285 -0
  28. package/build/src/database/advisory-lock-lock-server-engine.d.ts.map +1 -0
  29. package/build/src/database/advisory-lock-lock-server-engine.js +460 -0
  30. package/build/src/database/advisory-lock-lock-server-local-client.d.ts +114 -0
  31. package/build/src/database/advisory-lock-lock-server-local-client.d.ts.map +1 -0
  32. package/build/src/database/advisory-lock-lock-server-local-client.js +227 -0
  33. package/build/src/database/advisory-lock-lock-server-socket-path.d.ts +9 -0
  34. package/build/src/database/advisory-lock-lock-server-socket-path.d.ts.map +1 -0
  35. package/build/src/database/advisory-lock-lock-server-socket-path.js +16 -0
  36. package/build/src/database/advisory-lock-lock-server-transport.d.ts +18 -0
  37. package/build/src/database/advisory-lock-lock-server-transport.d.ts.map +1 -0
  38. package/build/src/database/advisory-lock-lock-server-transport.js +27 -0
  39. package/build/src/database/record/auditing.d.ts +14 -4
  40. package/build/src/database/record/auditing.d.ts.map +1 -1
  41. package/build/src/database/record/auditing.js +77 -12
  42. package/build/src/database/record/index.d.ts +4 -2
  43. package/build/src/database/record/index.d.ts.map +1 -1
  44. package/build/src/database/record/index.js +2 -2
  45. package/build/src/environment-handlers/base.d.ts +86 -7
  46. package/build/src/environment-handlers/base.d.ts.map +1 -1
  47. package/build/src/environment-handlers/base.js +48 -9
  48. package/build/src/environment-handlers/node/advisory-lock-lock-server-local-server.d.ts +2 -0
  49. package/build/src/environment-handlers/node/advisory-lock-lock-server-local-server.d.ts.map +1 -0
  50. package/build/src/environment-handlers/node/advisory-lock-lock-server-local-server.js +179 -0
  51. package/build/src/environment-handlers/node.d.ts +10 -4
  52. package/build/src/environment-handlers/node.d.ts.map +1 -1
  53. package/build/src/environment-handlers/node.js +30 -4
  54. package/build/src/http-server/server-lock.d.ts +22 -11
  55. package/build/src/http-server/server-lock.d.ts.map +1 -1
  56. package/build/src/http-server/server-lock.js +30 -17
  57. package/package.json +1 -1
  58. package/src/configuration-types.js +1 -1
  59. package/src/configuration.js +17 -2
  60. package/src/database/advisory-lock-lock-server-backend.js +30 -24
  61. package/src/database/advisory-lock-lock-server-embedded-client.js +74 -0
  62. package/src/database/advisory-lock-lock-server-engine.js +544 -0
  63. package/src/database/advisory-lock-lock-server-local-client.js +260 -0
  64. package/src/database/advisory-lock-lock-server-socket-path.js +17 -0
  65. package/src/database/advisory-lock-lock-server-transport.js +30 -0
  66. package/src/database/record/auditing.js +89 -11
  67. package/src/database/record/index.js +1 -1
  68. package/src/environment-handlers/base.js +50 -9
  69. package/src/environment-handlers/node/advisory-lock-lock-server-local-server.js +206 -0
  70. package/src/environment-handlers/node.js +30 -3
  71. package/src/http-server/server-lock.js +29 -16
@@ -0,0 +1,206 @@
1
+ // @ts-check
2
+
3
+ import AdvisoryLockLockServerEngine from "../../database/advisory-lock-lock-server-engine.js"
4
+ import {LOCK_SERVER_PROTOCOL_VERSION} from "../../database/advisory-lock-lock-server-backend.js"
5
+ import {defaultLockServerSocketPath} from "../../database/advisory-lock-lock-server-socket-path.js"
6
+ import fs from "node:fs"
7
+ import net from "node:net"
8
+
9
+ /**
10
+ * Local lock-server engine server for the `local` mode (STC-715): the shared
11
+ * `AdvisoryLockLockServerEngine` exposed over a Unix domain socket, one JSON
12
+ * line per protocol message tagged with the client's `connectionId`. No
13
+ * listening network port, no `ws`.
14
+ *
15
+ * Lifecycle follows the environment: `AdvisoryLockLockServerLocalClient`
16
+ * spawns this server as a child when no local engine is listening yet, and the
17
+ * server idles out (and removes its socket) once its last client connection
18
+ * has been gone for `VELOCIOUS_LOCK_SERVER_IDLE_SHUTDOWN_MS` — so a host never
19
+ * accumulates orphan engines. SIGTERM/SIGINT shut it down cleanly.
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.
24
+ */
25
+
26
+ const socketPath = defaultLockServerSocketPath(process.env.VELOCIOUS_LOCK_SERVER_SOCKET_PATH)
27
+ const leaseMsRaw = Number(process.env.CONSENS_LOCK_LEASE_MS)
28
+ const idleShutdownMsRaw = Number(process.env.VELOCIOUS_LOCK_SERVER_IDLE_SHUTDOWN_MS)
29
+ const idleShutdownMs = Number.isFinite(idleShutdownMsRaw) && idleShutdownMsRaw >= 0 ? idleShutdownMsRaw : 30_000
30
+
31
+ const engine = new AdvisoryLockLockServerEngine({
32
+ leaseMs: Number.isFinite(leaseMsRaw) && leaseMsRaw > 0 ? leaseMsRaw : 30_000
33
+ })
34
+
35
+ engine.startSweeper()
36
+
37
+ let closing = false
38
+ let connectionCount = 0
39
+ /** @type {ReturnType<typeof setTimeout> | null} */
40
+ let idleTimer = null
41
+
42
+ /**
43
+ * Answers a startup race: is another live engine already listening on the
44
+ * socket path?
45
+ * @returns {Promise<boolean>} - True when a live engine accepted a probe connection.
46
+ */
47
+ function probeExistingEngine() {
48
+ return new Promise((resolve) => {
49
+ const probe = net.connect(socketPath)
50
+
51
+ probe.once("connect", () => {
52
+ probe.destroy()
53
+ resolve(true)
54
+ })
55
+ probe.once("error", () => {
56
+ probe.destroy()
57
+ resolve(false)
58
+ })
59
+ })
60
+ }
61
+
62
+ /**
63
+ * Cancels a pending idle-shutdown countdown (a client is back).
64
+ * @returns {void}
65
+ */
66
+ function cancelIdleShutdown() {
67
+ if (!idleTimer) return
68
+
69
+ clearTimeout(idleTimer)
70
+ idleTimer = null
71
+ }
72
+
73
+ /**
74
+ * Starts the idle-shutdown countdown: with zero live connections the engine
75
+ * stops itself and removes the socket, so spawned engines follow their
76
+ * environment instead of outliving it.
77
+ * @returns {void}
78
+ */
79
+ function scheduleIdleShutdown() {
80
+ if (closing || connectionCount > 0) return
81
+
82
+ cancelIdleShutdown()
83
+ idleTimer = setTimeout(() => shutdown(), idleShutdownMs)
84
+ idleTimer.unref?.()
85
+ }
86
+
87
+ /**
88
+ * Clean shutdown: close the engine, stop listening, remove the socket file.
89
+ * @returns {void}
90
+ */
91
+ function shutdown() {
92
+ if (closing) return
93
+
94
+ closing = true
95
+ cancelIdleShutdown()
96
+ 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
+ }
103
+
104
+ process.exit(0)
105
+ })
106
+ setTimeout(() => process.exit(0), 2000).unref?.()
107
+ }
108
+
109
+ /**
110
+ * Wires one client socket into the engine's line protocol.
111
+ * @param {net.Socket} socket - Client connection.
112
+ * @returns {void}
113
+ */
114
+ function handleClientSocket(socket) {
115
+ connectionCount += 1
116
+ cancelIdleShutdown()
117
+
118
+ socket.setEncoding("utf8")
119
+
120
+ /** @type {Set<string>} */
121
+ const socketConnectionIds = new Set()
122
+ let buffer = ""
123
+
124
+ socket.on("data", (/** @type {string} */ chunk) => {
125
+ buffer += chunk
126
+
127
+ let newlineIndex = buffer.indexOf("\n")
128
+
129
+ while (newlineIndex >= 0) {
130
+ const line = buffer.slice(0, newlineIndex)
131
+
132
+ buffer = buffer.slice(newlineIndex + 1)
133
+
134
+ if (line.trim()) {
135
+ try {
136
+ const message = /** @type {Record<string, unknown>} */ (JSON.parse(line))
137
+ const connectionId = typeof message.connectionId === "string" ? message.connectionId : ""
138
+
139
+ if (connectionId) {
140
+ socketConnectionIds.add(connectionId)
141
+
142
+ if (message.type === "hello") {
143
+ socket.write(`${JSON.stringify({connectionId, leaseMs: engine.leaseMs, protocolVersion: LOCK_SERVER_PROTOCOL_VERSION, type: "hello-ack"})}\n`)
144
+ } else {
145
+ engine.ensureConnection(connectionId, {
146
+ send: (/** @type {Record<string, unknown>} */ body) => {
147
+ if (!socket.destroyed) socket.write(`${JSON.stringify({...body, connectionId})}\n`)
148
+ }
149
+ })
150
+ engine.handleMessage(connectionId, message)
151
+ }
152
+ }
153
+ } catch {
154
+ // A malformed line is not a lock request: unanswered requests time
155
+ // out loudly on the client side.
156
+ }
157
+ }
158
+
159
+ newlineIndex = buffer.indexOf("\n")
160
+ }
161
+ })
162
+
163
+ socket.on("close", () => {
164
+ connectionCount -= 1
165
+
166
+ // The transport died: the engine releases every lease this socket held,
167
+ // exactly like the external daemon does on a websocket close.
168
+ for (const connectionId of socketConnectionIds) engine.connectionClose(connectionId)
169
+
170
+ scheduleIdleShutdown()
171
+ })
172
+ socket.on("error", () => socket.destroy())
173
+ }
174
+
175
+ const server = net.createServer((socket) => handleClientSocket(socket))
176
+
177
+ server.on("error", async (/** @type {{code?: string}} */ error) => {
178
+ 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)
182
+
183
+ fs.unlinkSync(socketPath)
184
+ server.listen(socketPath)
185
+
186
+ return
187
+ }
188
+
189
+ process.exit(1)
190
+ })
191
+
192
+ const alreadyLive = await probeExistingEngine()
193
+
194
+ if (alreadyLive) process.exit(0)
195
+
196
+ try {
197
+ fs.unlinkSync(socketPath)
198
+ } catch {
199
+ // No stale socket to remove.
200
+ }
201
+
202
+ server.listen(socketPath)
203
+
204
+ for (const signal of ["SIGTERM", "SIGINT"]) {
205
+ process.on(signal, () => shutdown())
206
+ }
@@ -4,6 +4,9 @@ import "../database/annotations-async-hooks.js"
4
4
  import "../database/advisory-lock-reentrancy-node.js"
5
5
  import AdvisoryLockFileBackend from "../database/advisory-lock-file-backend.js"
6
6
  import AdvisoryLockLockServerBackend from "../database/advisory-lock-lock-server-backend.js"
7
+ import AdvisoryLockLockServerLocalClient from "../database/advisory-lock-lock-server-local-client.js"
8
+ import {defaultLockServerSocketPath} from "../database/advisory-lock-lock-server-socket-path.js"
9
+ import {createLockServerWebsocketTransport} from "../database/advisory-lock-lock-server-transport.js"
7
10
  import Base from "./base.js"
8
11
  import BackgroundJobsClient from "../background-jobs/client.js"
9
12
  import SqlBackgroundJobsAdapter from "../background-jobs/sql-adapter.js"
@@ -120,12 +123,36 @@ export default class VelociousEnvironmentHandlerNode extends Base{
120
123
  }
121
124
 
122
125
  /**
123
- * Creates the lock-server advisory-lock backend over the Node websocket transport.
124
- * @param {ConstructorParameters<typeof AdvisoryLockLockServerBackend>[0]} args - Backend options.
126
+ * Creates the lock-server advisory-lock backend for one of the STC-715 modes:
127
+ *
128
+ * - `external` (default): the Node websocket transport to the shared
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.
133
+ * - `embedded`: the base handler's in-process engine (no sockets at all).
134
+ * @param {import("./base.js").AdvisoryLockLockServerBackendOptions} args - Backend options.
125
135
  * @returns {Promise<import("../database/advisory-lock-lock-server-backend.js").default>} - Created backend.
126
136
  */
127
137
  async createAdvisoryLockLockServerBackend(args) {
128
- return new AdvisoryLockLockServerBackend(args)
138
+ if (args.mode === "local") {
139
+ return new AdvisoryLockLockServerBackend({
140
+ ...args,
141
+ clientFactory: ({authToken}) => new AdvisoryLockLockServerLocalClient({
142
+ authToken,
143
+ connectTimeoutMs: args.connectTimeoutMs,
144
+ leaseMs: args.leaseMs,
145
+ socketPath: args.socketPath || defaultLockServerSocketPath()
146
+ })
147
+ })
148
+ }
149
+
150
+ if (args.mode === "embedded") return await super.createAdvisoryLockLockServerBackend(args)
151
+
152
+ return new AdvisoryLockLockServerBackend({
153
+ ...args,
154
+ clientFactory: createLockServerWebsocketTransport
155
+ })
129
156
  }
130
157
 
131
158
  /**
@@ -4,16 +4,24 @@ import AdvisoryLockFileBackend from "../database/advisory-lock-file-backend.js"
4
4
  import path from "node:path"
5
5
 
6
6
  /**
7
- * Directory-based lock that allows only one HTTP server process per app
8
- * directory. Thin wrapper over the shared file-lock backend
9
- * (`src/database/advisory-lock-file-backend.js` — the STC-210 `file` tier
10
- * primitive generalized from this lock's original hand-rolled directory
11
- * protocol), so the server lock and the advisory-lock file tier share one
12
- * acquisition, owner-metadata, lease-renewal, and staleness implementation.
7
+ * Directory + environment-based lock that allows only one HTTP server process
8
+ * per (app directory, environment) pair. Thin wrapper over the shared
9
+ * file-lock backend (`src/database/advisory-lock-file-backend.js` — the
10
+ * STC-210 `file` tier primitive generalized from this lock's original
11
+ * hand-rolled directory protocol), so the server lock and the advisory-lock
12
+ * file tier share one acquisition, owner-metadata, lease-renewal, and
13
+ * staleness implementation.
14
+ *
15
+ * The lock name is scoped by the configuration's environment
16
+ * (`server.<environment>` → `tmp/server.<environment>.lock`) so a development
17
+ * server and a test-spawned backend in the same app directory coexist, while
18
+ * the single-server-per-(directory, environment) invariant still fails loudly
19
+ * for a duplicate within one environment (STC-697).
13
20
  */
14
21
  export default class VelociousHttpServerLock {
15
22
  /**
16
- * Build a lock for the configured application directory and server endpoint.
23
+ * Build a lock for the configured application directory, environment and
24
+ * server endpoint.
17
25
  * @param {object} args - Options object.
18
26
  * @param {import("../configuration.js").default} args.configuration - Configuration that owns the application directory.
19
27
  * @param {string} args.host - Configured HTTP host.
@@ -23,7 +31,11 @@ export default class VelociousHttpServerLock {
23
31
  this.configuration = configuration
24
32
  this.host = host
25
33
  this.port = port
26
- this.lockPath = path.join(configuration.getDirectory(), "tmp", "server.lock")
34
+ this.environment = String(configuration.getEnvironment())
35
+ // Scope the lock name by environment and keep the segment filesystem-safe,
36
+ // so odd environment names can never escape tmp/ or collide with each other.
37
+ this.lockName = `server.${this.environment.replace(/[^a-zA-Z0-9._-]/g, "_")}`
38
+ this.lockPath = path.join(configuration.getDirectory(), "tmp", `${this.lockName}.lock`)
27
39
  this.backend = new AdvisoryLockFileBackend({
28
40
  directory: path.join(configuration.getDirectory(), "tmp"),
29
41
  extraOwnerFields: {host: this.host, port: this.port},
@@ -33,13 +45,14 @@ export default class VelociousHttpServerLock {
33
45
  }
34
46
 
35
47
  /**
36
- * Acquires the app-directory HTTP server lock before startup side effects
37
- * run. A stale lock (dead local owner or expired lease) is reclaimed by the
38
- * backend; a live foreign owner fails loudly with the owner details.
48
+ * Acquires the app-directory + environment HTTP server lock before startup
49
+ * side effects run. A stale lock (dead local owner or expired lease) is
50
+ * reclaimed by the backend; a live foreign owner in the same environment
51
+ * fails loudly with the owner details.
39
52
  * @returns {Promise<void>} - Resolves after the lock has been acquired.
40
53
  */
41
54
  async acquire() {
42
- const acquired = await this.backend.acquire("server", {timeoutMs: 0})
55
+ const acquired = await this.backend.acquire(this.lockName, {timeoutMs: 0})
43
56
 
44
57
  if (!acquired) throw new Error(await this.lockHeldMessage())
45
58
 
@@ -47,14 +60,14 @@ export default class VelociousHttpServerLock {
47
60
  }
48
61
 
49
62
  /**
50
- * Releases the held HTTP server lock directory.
63
+ * Releases the held environment-scoped HTTP server lock directory.
51
64
  * @returns {Promise<void>} - Resolves after best-effort lock release.
52
65
  */
53
66
  async release() {
54
67
  if (!this.acquired) return
55
68
 
56
69
  this.acquired = false
57
- await this.backend.release("server")
70
+ await this.backend.release(this.lockName)
58
71
  }
59
72
 
60
73
  /**
@@ -62,7 +75,7 @@ export default class VelociousHttpServerLock {
62
75
  * @returns {Promise<import("../database/advisory-lock-file-backend.js").AdvisoryLockFileOwner | null>} - Parsed owner metadata, when readable.
63
76
  */
64
77
  async readOwnerMetadata() {
65
- return await this.backend.holderInfo("server")
78
+ return await this.backend.holderInfo(this.lockName)
66
79
  }
67
80
 
68
81
  /**
@@ -75,6 +88,6 @@ export default class VelociousHttpServerLock {
75
88
  ? `PID ${String(owner.pid)} on ${String(owner.hostname)} (${String(owner.host)}:${String(owner.port)})`
76
89
  : `lock directory ${this.lockPath}`
77
90
 
78
- return `A Velocious HTTP server is already running for this application (${details}). Remove ${this.lockPath} if the server is no longer running.`
91
+ return `A Velocious HTTP server is already running for this application in the ${this.environment} environment (${details}). Remove ${this.lockPath} if the server is no longer running.`
79
92
  }
80
93
  }