velocious 1.0.726 → 1.0.728

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 (155) hide show
  1. package/README.md +2 -2
  2. package/bin/velocious.js +2 -19
  3. package/build/application.js +32 -3
  4. package/build/background-jobs/main.js +9 -1
  5. package/build/background-jobs/worker.js +69 -6
  6. package/build/bin/velocious.js +2 -19
  7. package/build/cli/process-args.js +34 -0
  8. package/build/configuration-types.js +1 -1
  9. package/build/configuration.js +43 -2
  10. package/build/database/advisory-lock-lock-server-backend.js +30 -24
  11. package/build/database/advisory-lock-lock-server-embedded-client.js +74 -0
  12. package/build/database/advisory-lock-lock-server-engine.js +544 -0
  13. package/build/database/advisory-lock-lock-server-local-client.js +260 -0
  14. package/build/database/advisory-lock-lock-server-socket-path.js +17 -0
  15. package/build/database/advisory-lock-lock-server-transport.js +30 -0
  16. package/build/database/drivers/base.js +34 -12
  17. package/build/database/drivers/mssql/index.js +17 -18
  18. package/build/database/drivers/mssql/table.js +28 -25
  19. package/build/database/drivers/mysql/index.js +15 -18
  20. package/build/database/drivers/mysql/table.js +31 -23
  21. package/build/database/drivers/pgsql/index.js +15 -18
  22. package/build/database/drivers/pgsql/table.js +28 -26
  23. package/build/database/drivers/sqlite/base.js +7 -9
  24. package/build/database/drivers/sqlite/table.js +32 -26
  25. package/build/database/pool/async-tracked-multi-connection.js +1 -0
  26. package/build/database/pool/base.js +14 -4
  27. package/build/database/pool/single-multi-use.js +1 -0
  28. package/build/database/record/auditing.js +89 -11
  29. package/build/database/record/index.js +1 -1
  30. package/build/environment-handlers/base.js +50 -9
  31. package/build/environment-handlers/node/advisory-lock-lock-server-local-server.js +206 -0
  32. package/build/environment-handlers/node/cli/commands/server.js +1 -0
  33. package/build/environment-handlers/node.js +30 -3
  34. package/build/http-server/server-lock.js +55 -18
  35. package/build/src/application.d.ts +7 -4
  36. package/build/src/application.d.ts.map +1 -1
  37. package/build/src/application.js +27 -4
  38. package/build/src/background-jobs/main.d.ts +2 -1
  39. package/build/src/background-jobs/main.d.ts.map +1 -1
  40. package/build/src/background-jobs/main.js +10 -2
  41. package/build/src/background-jobs/worker.d.ts +42 -0
  42. package/build/src/background-jobs/worker.d.ts.map +1 -1
  43. package/build/src/background-jobs/worker.js +61 -5
  44. package/build/src/cli/process-args.d.ts +11 -0
  45. package/build/src/cli/process-args.d.ts.map +1 -0
  46. package/build/src/cli/process-args.js +34 -0
  47. package/build/src/configuration-types.d.ts +3 -1
  48. package/build/src/configuration-types.d.ts.map +1 -1
  49. package/build/src/configuration-types.js +2 -2
  50. package/build/src/configuration.d.ts +16 -1
  51. package/build/src/configuration.d.ts.map +1 -1
  52. package/build/src/configuration.js +39 -3
  53. package/build/src/database/advisory-lock-lock-server-backend.d.ts +10 -3
  54. package/build/src/database/advisory-lock-lock-server-backend.d.ts.map +1 -1
  55. package/build/src/database/advisory-lock-lock-server-backend.js +25 -22
  56. package/build/src/database/advisory-lock-lock-server-embedded-client.d.ts +24 -0
  57. package/build/src/database/advisory-lock-lock-server-embedded-client.d.ts.map +1 -0
  58. package/build/src/database/advisory-lock-lock-server-embedded-client.js +64 -0
  59. package/build/src/database/advisory-lock-lock-server-engine.d.ts +285 -0
  60. package/build/src/database/advisory-lock-lock-server-engine.d.ts.map +1 -0
  61. package/build/src/database/advisory-lock-lock-server-engine.js +460 -0
  62. package/build/src/database/advisory-lock-lock-server-local-client.d.ts +114 -0
  63. package/build/src/database/advisory-lock-lock-server-local-client.d.ts.map +1 -0
  64. package/build/src/database/advisory-lock-lock-server-local-client.js +227 -0
  65. package/build/src/database/advisory-lock-lock-server-socket-path.d.ts +9 -0
  66. package/build/src/database/advisory-lock-lock-server-socket-path.d.ts.map +1 -0
  67. package/build/src/database/advisory-lock-lock-server-socket-path.js +16 -0
  68. package/build/src/database/advisory-lock-lock-server-transport.d.ts +18 -0
  69. package/build/src/database/advisory-lock-lock-server-transport.d.ts.map +1 -0
  70. package/build/src/database/advisory-lock-lock-server-transport.js +27 -0
  71. package/build/src/database/drivers/base.d.ts +15 -2
  72. package/build/src/database/drivers/base.d.ts.map +1 -1
  73. package/build/src/database/drivers/base.js +33 -13
  74. package/build/src/database/drivers/mssql/index.d.ts +2 -2
  75. package/build/src/database/drivers/mssql/index.d.ts.map +1 -1
  76. package/build/src/database/drivers/mssql/index.js +17 -18
  77. package/build/src/database/drivers/mssql/table.d.ts.map +1 -1
  78. package/build/src/database/drivers/mssql/table.js +25 -23
  79. package/build/src/database/drivers/mysql/index.d.ts +2 -2
  80. package/build/src/database/drivers/mysql/index.d.ts.map +1 -1
  81. package/build/src/database/drivers/mysql/index.js +16 -19
  82. package/build/src/database/drivers/mysql/table.d.ts.map +1 -1
  83. package/build/src/database/drivers/mysql/table.js +27 -22
  84. package/build/src/database/drivers/pgsql/index.d.ts +2 -2
  85. package/build/src/database/drivers/pgsql/index.d.ts.map +1 -1
  86. package/build/src/database/drivers/pgsql/index.js +16 -19
  87. package/build/src/database/drivers/pgsql/table.d.ts.map +1 -1
  88. package/build/src/database/drivers/pgsql/table.js +25 -23
  89. package/build/src/database/drivers/sqlite/base.d.ts.map +1 -1
  90. package/build/src/database/drivers/sqlite/base.js +8 -10
  91. package/build/src/database/drivers/sqlite/table.d.ts.map +1 -1
  92. package/build/src/database/drivers/sqlite/table.js +29 -25
  93. package/build/src/database/pool/async-tracked-multi-connection.d.ts.map +1 -1
  94. package/build/src/database/pool/async-tracked-multi-connection.js +2 -1
  95. package/build/src/database/pool/base.d.ts +6 -0
  96. package/build/src/database/pool/base.d.ts.map +1 -1
  97. package/build/src/database/pool/base.js +14 -5
  98. package/build/src/database/pool/single-multi-use.d.ts.map +1 -1
  99. package/build/src/database/pool/single-multi-use.js +2 -1
  100. package/build/src/database/record/auditing.d.ts +14 -4
  101. package/build/src/database/record/auditing.d.ts.map +1 -1
  102. package/build/src/database/record/auditing.js +77 -12
  103. package/build/src/database/record/index.d.ts +4 -2
  104. package/build/src/database/record/index.d.ts.map +1 -1
  105. package/build/src/database/record/index.js +2 -2
  106. package/build/src/environment-handlers/base.d.ts +86 -7
  107. package/build/src/environment-handlers/base.d.ts.map +1 -1
  108. package/build/src/environment-handlers/base.js +48 -9
  109. package/build/src/environment-handlers/node/advisory-lock-lock-server-local-server.d.ts +2 -0
  110. package/build/src/environment-handlers/node/advisory-lock-lock-server-local-server.d.ts.map +1 -0
  111. package/build/src/environment-handlers/node/advisory-lock-lock-server-local-server.js +179 -0
  112. package/build/src/environment-handlers/node/cli/commands/server.d.ts.map +1 -1
  113. package/build/src/environment-handlers/node/cli/commands/server.js +2 -1
  114. package/build/src/environment-handlers/node.d.ts +10 -4
  115. package/build/src/environment-handlers/node.d.ts.map +1 -1
  116. package/build/src/environment-handlers/node.js +30 -4
  117. package/build/src/http-server/server-lock.d.ts +43 -14
  118. package/build/src/http-server/server-lock.d.ts.map +1 -1
  119. package/build/src/http-server/server-lock.js +54 -19
  120. package/build/src/tenants/default-tenant-database-provisioning.d.ts.map +1 -1
  121. package/build/src/tenants/default-tenant-database-provisioning.js +7 -1
  122. package/build/tenants/default-tenant-database-provisioning.js +8 -0
  123. package/package.json +2 -2
  124. package/src/application.js +32 -3
  125. package/src/background-jobs/main.js +9 -1
  126. package/src/background-jobs/worker.js +69 -6
  127. package/src/cli/process-args.js +34 -0
  128. package/src/configuration-types.js +1 -1
  129. package/src/configuration.js +43 -2
  130. package/src/database/advisory-lock-lock-server-backend.js +30 -24
  131. package/src/database/advisory-lock-lock-server-embedded-client.js +74 -0
  132. package/src/database/advisory-lock-lock-server-engine.js +544 -0
  133. package/src/database/advisory-lock-lock-server-local-client.js +260 -0
  134. package/src/database/advisory-lock-lock-server-socket-path.js +17 -0
  135. package/src/database/advisory-lock-lock-server-transport.js +30 -0
  136. package/src/database/drivers/base.js +34 -12
  137. package/src/database/drivers/mssql/index.js +17 -18
  138. package/src/database/drivers/mssql/table.js +28 -25
  139. package/src/database/drivers/mysql/index.js +15 -18
  140. package/src/database/drivers/mysql/table.js +31 -23
  141. package/src/database/drivers/pgsql/index.js +15 -18
  142. package/src/database/drivers/pgsql/table.js +28 -26
  143. package/src/database/drivers/sqlite/base.js +7 -9
  144. package/src/database/drivers/sqlite/table.js +32 -26
  145. package/src/database/pool/async-tracked-multi-connection.js +1 -0
  146. package/src/database/pool/base.js +14 -4
  147. package/src/database/pool/single-multi-use.js +1 -0
  148. package/src/database/record/auditing.js +89 -11
  149. package/src/database/record/index.js +1 -1
  150. package/src/environment-handlers/base.js +50 -9
  151. package/src/environment-handlers/node/advisory-lock-lock-server-local-server.js +206 -0
  152. package/src/environment-handlers/node/cli/commands/server.js +1 -0
  153. package/src/environment-handlers/node.js +30 -3
  154. package/src/http-server/server-lock.js +55 -18
  155. package/src/tenants/default-tenant-database-provisioning.js +8 -0
@@ -1,7 +1,10 @@
1
1
  // @ts-check
2
2
 
3
+ import AdvisoryLockLockServerBackend from "../database/advisory-lock-lock-server-backend.js"
4
+ import AdvisoryLockLockServerEngine from "../database/advisory-lock-lock-server-engine.js"
3
5
  import BackgroundJobsAdapterClient from "../background-jobs/adapter-client.js"
4
- import { validateTimeZone } from "../time-zone.js"
6
+ import {createEmbeddedLockServerClientFactory} from "../database/advisory-lock-lock-server-embedded-client.js"
7
+ import {validateTimeZone} from "../time-zone.js"
5
8
 
6
9
  /**
7
10
  * CommandFileObjectType type.
@@ -24,6 +27,20 @@ import { validateTimeZone } from "../time-zone.js"
24
27
  * @property {() => ({revoked: boolean} | undefined)} getStore - Gets the inherited scope.
25
28
  * @property {(scope: {revoked: boolean} | undefined, callback: () => ReturnType<typeof JSON.parse>) => ReturnType<typeof JSON.parse>} run - Runs in the scope.
26
29
  */
30
+ /**
31
+ * Lock-server advisory-lock backend options as resolved by `Configuration`
32
+ * (STC-715). `mode` selects the transport the handler must provide.
33
+ * @typedef {object} AdvisoryLockLockServerBackendOptions
34
+ * @property {string} [authToken] - Shared secret; the server fails closed without a matching token.
35
+ * @property {(args: {authToken: string, url: string}) => import("../database/advisory-lock-lock-server-backend.js").LockServerClientLike} [clientFactory] - Transport override (specs inject a fake).
36
+ * @property {number} [connectTimeoutMs] - Handshake timeout.
37
+ * @property {number} [leaseMs] - Lease duration per grant.
38
+ * @property {"embedded" | "external" | "local"} [mode] - Lock-server mode. Defaults to `external`.
39
+ * @property {(error: Error) => void} [onError] - Async error reporter.
40
+ * @property {number} [reprobeCooldownMs] - How long an unavailable server is not re-probed.
41
+ * @property {string} [socketPath] - Unix socket path for `local` mode (defaults to a short path under os.tmpdir()).
42
+ * @property {string} url - Lock-server endpoint (websocket URL for external mode; informational for embedded/local modes).
43
+ */
27
44
 
28
45
  export class TestDatabaseAccessRevokedError extends Error {}
29
46
 
@@ -50,14 +67,38 @@ export default class VelociousEnvironmentHandlerBase {
50
67
  }
51
68
 
52
69
  /**
53
- * Creates the lock-server advisory-lock backend. Only Node environments can
54
- * provide this tier's websocket transport; browser and Expo bundles must never
55
- * pull the Node-only transport into their graph.
56
- * @param {object} _args - Backend options.
57
- * @returns {Promise<import("../database/advisory-lock-lock-server-backend.js").default>} - Resolves with the created backend in Node handlers.
58
- */
59
- async createAdvisoryLockLockServerBackend(_args) {
60
- throw new Error("The advisory-lock lock-server tier requires a Node environment handler")
70
+ * Creates the lock-server advisory-lock backend (STC-715 modes).
71
+ *
72
+ * `embedded` mode runs the shared lock-server engine inside this process
73
+ * over plain function calls — no sockets, no `ws`, no Node builtins — so
74
+ * browser and Expo environments can serve the tier too. Coordination stays
75
+ * inside this JS realm: it does not cross tabs, workers or processes unless
76
+ * an explicit transport (`external`/`local`) is configured.
77
+ *
78
+ * `external` and `local` modes need a transport only the Node handler can
79
+ * provide; other environments refuse loudly instead of half-working.
80
+ * @param {object} args - Backend options.
81
+ * @param {string} [args.authToken] - Shared secret.
82
+ * @param {number} [args.connectTimeoutMs] - Handshake timeout.
83
+ * @param {number} [args.leaseMs] - Lease duration.
84
+ * @param {"embedded" | "external" | "local"} [args.mode] - Lock-server mode. Defaults to `external`.
85
+ * @param {(error: Error) => void} [args.onError] - Async error reporter.
86
+ * @param {number} [args.reprobeCooldownMs] - Unavailability cache window.
87
+ * @param {string} [args.socketPath] - Unix socket path for `local` mode.
88
+ * @param {string} args.url - Lock-server endpoint.
89
+ * @returns {Promise<import("../database/advisory-lock-lock-server-backend.js").default>} - Resolves with the created backend in capable handlers.
90
+ */
91
+ async createAdvisoryLockLockServerBackend(args) {
92
+ if (args.mode === "embedded") {
93
+ const engine = new AdvisoryLockLockServerEngine({leaseMs: args.leaseMs})
94
+
95
+ return new AdvisoryLockLockServerBackend({
96
+ ...args,
97
+ clientFactory: createEmbeddedLockServerClientFactory(engine)
98
+ })
99
+ }
100
+
101
+ throw new Error(`The advisory-lock lock-server "${String(args.mode ?? "external")}" mode requires a Node environment handler`)
61
102
  }
62
103
 
63
104
  /**
@@ -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
+ }
@@ -145,6 +145,7 @@ export default class VelociousCliCommandsServer extends BaseCommand{
145
145
  const application = new Application({
146
146
  configuration,
147
147
  httpServer,
148
+ httpServerLockOptOut: parsedProcessArgs["no-server-lock"] === true,
148
149
  type: "server"
149
150
  })
150
151
  const environment = configuration.getEnvironment()
@@ -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,26 +4,45 @@ 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).
20
+ *
21
+ * A caller that knowingly wants a second server in the same
22
+ * (directory, environment) pair can opt out of this lock (STC-698). The lock
23
+ * itself is unchanged for every other caller: an opted-out lock never acquires
24
+ * and therefore never releases, so it can never remove a live owner's lock.
13
25
  */
14
26
  export default class VelociousHttpServerLock {
15
27
  /**
16
- * Build a lock for the configured application directory and server endpoint.
28
+ * Build a lock for the configured application directory, environment and
29
+ * server endpoint.
17
30
  * @param {object} args - Options object.
18
31
  * @param {import("../configuration.js").default} args.configuration - Configuration that owns the application directory.
19
32
  * @param {string} args.host - Configured HTTP host.
20
33
  * @param {number} args.port - Configured HTTP port.
34
+ * @param {boolean} [args.optOut] - Skip acquisition for this caller instead of contending for the lock.
21
35
  */
22
- constructor({configuration, host, port}) {
36
+ constructor({configuration, host, port, optOut = false}) {
23
37
  this.configuration = configuration
24
38
  this.host = host
25
39
  this.port = port
26
- this.lockPath = path.join(configuration.getDirectory(), "tmp", "server.lock")
40
+ this.optOut = optOut
41
+ this.environment = String(configuration.getEnvironment())
42
+ // Scope the lock name by environment and keep the segment filesystem-safe,
43
+ // so odd environment names can never escape tmp/ or collide with each other.
44
+ this.lockName = `server.${this.environment.replace(/[^a-zA-Z0-9._-]/g, "_")}`
45
+ this.lockPath = path.join(configuration.getDirectory(), "tmp", `${this.lockName}.lock`)
27
46
  this.backend = new AdvisoryLockFileBackend({
28
47
  directory: path.join(configuration.getDirectory(), "tmp"),
29
48
  extraOwnerFields: {host: this.host, port: this.port},
@@ -33,28 +52,36 @@ export default class VelociousHttpServerLock {
33
52
  }
34
53
 
35
54
  /**
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.
39
- * @returns {Promise<void>} - Resolves after the lock has been acquired.
55
+ * Acquires the app-directory + environment HTTP server lock before startup
56
+ * side effects run. An opted-out caller never touches the lock, so the live
57
+ * owner keeps it. A stale lock (dead local owner or expired lease) is
58
+ * reclaimed by the backend; a live foreign owner in the same environment
59
+ * fails loudly with the owner details.
60
+ * @returns {Promise<boolean>} - Whether this caller holds the lock.
40
61
  */
41
62
  async acquire() {
42
- const acquired = await this.backend.acquire("server", {timeoutMs: 0})
63
+ if (this.optOut) return false
64
+
65
+ const acquired = await this.backend.acquire(this.lockName, {timeoutMs: 0})
43
66
 
44
67
  if (!acquired) throw new Error(await this.lockHeldMessage())
45
68
 
46
69
  this.acquired = true
70
+
71
+ return true
47
72
  }
48
73
 
49
74
  /**
50
- * Releases the held HTTP server lock directory.
75
+ * Releases the held environment-scoped HTTP server lock directory. A lock
76
+ * that was never acquired (an opted-out caller) is a no-op, so it can never
77
+ * remove the live owner's lock on shutdown.
51
78
  * @returns {Promise<void>} - Resolves after best-effort lock release.
52
79
  */
53
80
  async release() {
54
81
  if (!this.acquired) return
55
82
 
56
83
  this.acquired = false
57
- await this.backend.release("server")
84
+ await this.backend.release(this.lockName)
58
85
  }
59
86
 
60
87
  /**
@@ -62,7 +89,7 @@ export default class VelociousHttpServerLock {
62
89
  * @returns {Promise<import("../database/advisory-lock-file-backend.js").AdvisoryLockFileOwner | null>} - Parsed owner metadata, when readable.
63
90
  */
64
91
  async readOwnerMetadata() {
65
- return await this.backend.holderInfo("server")
92
+ return await this.backend.holderInfo(this.lockName)
66
93
  }
67
94
 
68
95
  /**
@@ -75,6 +102,16 @@ export default class VelociousHttpServerLock {
75
102
  ? `PID ${String(owner.pid)} on ${String(owner.hostname)} (${String(owner.host)}:${String(owner.port)})`
76
103
  : `lock directory ${this.lockPath}`
77
104
 
78
- return `A Velocious HTTP server is already running for this application (${details}). Remove ${this.lockPath} if the server is no longer running.`
105
+ 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.`
106
+ }
107
+
108
+ /**
109
+ * Builds the warning emitted when a caller knowingly starts a server without
110
+ * the lock, so an unprotected production process is visible in the log rather
111
+ * than silently running without duplicate-server protection.
112
+ * @returns {string} - Warning message naming the application directory and port.
113
+ */
114
+ lockSkippedMessage() {
115
+ return `Skipping the HTTP server lock for ${this.configuration.getDirectory()} on ${this.host}:${String(this.port)} because the caller opted out. This server runs without duplicate-server protection for the ${this.environment} environment.`
79
116
  }
80
117
  }
@@ -14,6 +14,8 @@
14
14
  * driver's own `createDatabaseSql`/`dropDatabaseSql`.
15
15
  */
16
16
 
17
+ import PoolBase from "../database/pool/base.js"
18
+
17
19
  const SAFE_TENANT_DATABASE_NAME = /^[a-z0-9_]+$/
18
20
 
19
21
  /**
@@ -121,4 +123,10 @@ export async function dropTenantDatabase({configuration, databaseConfiguration})
121
123
  } finally {
122
124
  await connection.close()
123
125
  }
126
+
127
+ // The DROP DATABASE ran on the maintenance connection, so the dropped tenant's
128
+ // own shared schema-metadata cache was never invalidated by the DDL path. Clear
129
+ // it explicitly: recreating the tenant database later must re-introspect, not
130
+ // serve the dropped schema from the shared cache.
131
+ configuration.clearSchemaCachesForReuseKey(PoolBase.configurationReuseKey(databaseConfiguration))
124
132
  }