velocious 1.0.725 → 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.
- package/README.md +1 -1
- package/build/background-jobs/adapter.js +16 -0
- package/build/background-jobs/job-record.js +3 -1
- package/build/background-jobs/main.js +62 -2
- package/build/background-jobs/owner-liveness.js +27 -5
- package/build/background-jobs/store.js +74 -0
- package/build/background-jobs/types.js +3 -0
- package/build/configuration-types.js +1 -1
- package/build/configuration.js +53 -3
- package/build/database/advisory-lock-lock-server-backend.js +30 -24
- package/build/database/advisory-lock-lock-server-embedded-client.js +74 -0
- package/build/database/advisory-lock-lock-server-engine.js +544 -0
- package/build/database/advisory-lock-lock-server-local-client.js +260 -0
- package/build/database/advisory-lock-lock-server-socket-path.js +17 -0
- package/build/database/advisory-lock-lock-server-transport.js +30 -0
- package/build/database/record/auditing.js +89 -11
- package/build/database/record/index.js +1 -1
- package/build/environment-handlers/base.js +50 -9
- package/build/environment-handlers/node/advisory-lock-lock-server-local-server.js +206 -0
- package/build/environment-handlers/node.js +30 -3
- package/build/http-server/server-lock.js +29 -16
- package/build/src/background-jobs/adapter.d.ts +23 -0
- package/build/src/background-jobs/adapter.d.ts.map +1 -1
- package/build/src/background-jobs/adapter.js +15 -1
- package/build/src/background-jobs/job-record.d.ts +3 -1
- package/build/src/background-jobs/job-record.d.ts.map +1 -1
- package/build/src/background-jobs/job-record.js +4 -2
- package/build/src/background-jobs/main.d.ts +33 -0
- package/build/src/background-jobs/main.d.ts.map +1 -1
- package/build/src/background-jobs/main.js +59 -3
- package/build/src/background-jobs/owner-liveness.d.ts +25 -3
- package/build/src/background-jobs/owner-liveness.d.ts.map +1 -1
- package/build/src/background-jobs/owner-liveness.js +26 -7
- package/build/src/background-jobs/store.d.ts +39 -0
- package/build/src/background-jobs/store.d.ts.map +1 -1
- package/build/src/background-jobs/store.js +66 -1
- package/build/src/background-jobs/types.d.ts +6 -0
- package/build/src/background-jobs/types.d.ts.map +1 -1
- package/build/src/background-jobs/types.js +4 -1
- package/build/src/configuration-types.d.ts +3 -1
- package/build/src/configuration-types.d.ts.map +1 -1
- package/build/src/configuration-types.js +2 -2
- package/build/src/configuration.d.ts +25 -1
- package/build/src/configuration.d.ts.map +1 -1
- package/build/src/configuration.js +47 -4
- package/build/src/database/advisory-lock-lock-server-backend.d.ts +10 -3
- package/build/src/database/advisory-lock-lock-server-backend.d.ts.map +1 -1
- package/build/src/database/advisory-lock-lock-server-backend.js +25 -22
- package/build/src/database/advisory-lock-lock-server-embedded-client.d.ts +24 -0
- package/build/src/database/advisory-lock-lock-server-embedded-client.d.ts.map +1 -0
- package/build/src/database/advisory-lock-lock-server-embedded-client.js +64 -0
- package/build/src/database/advisory-lock-lock-server-engine.d.ts +285 -0
- package/build/src/database/advisory-lock-lock-server-engine.d.ts.map +1 -0
- package/build/src/database/advisory-lock-lock-server-engine.js +460 -0
- package/build/src/database/advisory-lock-lock-server-local-client.d.ts +114 -0
- package/build/src/database/advisory-lock-lock-server-local-client.d.ts.map +1 -0
- package/build/src/database/advisory-lock-lock-server-local-client.js +227 -0
- package/build/src/database/advisory-lock-lock-server-socket-path.d.ts +9 -0
- package/build/src/database/advisory-lock-lock-server-socket-path.d.ts.map +1 -0
- package/build/src/database/advisory-lock-lock-server-socket-path.js +16 -0
- package/build/src/database/advisory-lock-lock-server-transport.d.ts +18 -0
- package/build/src/database/advisory-lock-lock-server-transport.d.ts.map +1 -0
- package/build/src/database/advisory-lock-lock-server-transport.js +27 -0
- package/build/src/database/record/auditing.d.ts +14 -4
- package/build/src/database/record/auditing.d.ts.map +1 -1
- package/build/src/database/record/auditing.js +77 -12
- package/build/src/database/record/index.d.ts +4 -2
- package/build/src/database/record/index.d.ts.map +1 -1
- package/build/src/database/record/index.js +2 -2
- package/build/src/environment-handlers/base.d.ts +86 -7
- package/build/src/environment-handlers/base.d.ts.map +1 -1
- package/build/src/environment-handlers/base.js +48 -9
- package/build/src/environment-handlers/node/advisory-lock-lock-server-local-server.d.ts +2 -0
- package/build/src/environment-handlers/node/advisory-lock-lock-server-local-server.d.ts.map +1 -0
- package/build/src/environment-handlers/node/advisory-lock-lock-server-local-server.js +179 -0
- package/build/src/environment-handlers/node.d.ts +10 -4
- package/build/src/environment-handlers/node.d.ts.map +1 -1
- package/build/src/environment-handlers/node.js +30 -4
- package/build/src/http-server/server-lock.d.ts +22 -11
- package/build/src/http-server/server-lock.d.ts.map +1 -1
- package/build/src/http-server/server-lock.js +30 -17
- package/package.json +1 -1
- package/src/background-jobs/adapter.js +16 -0
- package/src/background-jobs/job-record.js +3 -1
- package/src/background-jobs/main.js +62 -2
- package/src/background-jobs/owner-liveness.js +27 -5
- package/src/background-jobs/store.js +74 -0
- package/src/background-jobs/types.js +3 -0
- package/src/configuration-types.js +1 -1
- package/src/configuration.js +53 -3
- package/src/database/advisory-lock-lock-server-backend.js +30 -24
- package/src/database/advisory-lock-lock-server-embedded-client.js +74 -0
- package/src/database/advisory-lock-lock-server-engine.js +544 -0
- package/src/database/advisory-lock-lock-server-local-client.js +260 -0
- package/src/database/advisory-lock-lock-server-socket-path.js +17 -0
- package/src/database/advisory-lock-lock-server-transport.js +30 -0
- package/src/database/record/auditing.js +89 -11
- package/src/database/record/index.js +1 -1
- package/src/environment-handlers/base.js +50 -9
- package/src/environment-handlers/node/advisory-lock-lock-server-local-server.js +206 -0
- package/src/environment-handlers/node.js +30 -3
- package/src/http-server/server-lock.js +29 -16
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
import net from "node:net"
|
|
4
|
+
import {spawn} from "node:child_process"
|
|
5
|
+
import {fileURLToPath} from "node:url"
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Unix-domain-socket transport client for the `local` lock-server mode
|
|
9
|
+
* (STC-715). It connects to the local engine server
|
|
10
|
+
* (`src/environment-handlers/node/advisory-lock-lock-server-local-server.js`)
|
|
11
|
+
* over a Unix socket — no listening network port, no `ws` — and spawns that
|
|
12
|
+
* server as a child of this environment when no local engine is running yet.
|
|
13
|
+
*
|
|
14
|
+
* One local engine serves every process on the host that points at the same
|
|
15
|
+
* socket path, which is what makes `local` mode the multi-process single-host
|
|
16
|
+
* answer (embedded mode only coordinates inside one JS realm).
|
|
17
|
+
*
|
|
18
|
+
* Crash detection and bounded restart: when the socket dies, the transport
|
|
19
|
+
* reports `transportClosed` to the backend adapter, which fails pending
|
|
20
|
+
* requests and starts its `reprobeCooldownMs` unavailability cache. The next
|
|
21
|
+
* acquisition after the cooldown reconnects — respawning the engine child when
|
|
22
|
+
* the socket file is gone. The cooldown IS the restart backoff; there is no
|
|
23
|
+
* separate respawn loop.
|
|
24
|
+
*/
|
|
25
|
+
export default class AdvisoryLockLockServerLocalClient {
|
|
26
|
+
/**
|
|
27
|
+
* Creates the local transport client. No socket or process is touched until
|
|
28
|
+
* `connect()` — constructing this object performs no I/O.
|
|
29
|
+
* @param {object} args - Client options.
|
|
30
|
+
* @param {string} [args.authToken] - Shared secret forwarded in the hello params.
|
|
31
|
+
* @param {number} [args.connectTimeoutMs] - Bounded wait for the socket/engine child to become ready.
|
|
32
|
+
* @param {number} [args.leaseMs] - Lease duration the engine child should use.
|
|
33
|
+
* @param {string} args.socketPath - Unix socket path of the local engine.
|
|
34
|
+
*/
|
|
35
|
+
constructor({authToken = "", connectTimeoutMs = 3000, leaseMs = 30_000, socketPath}) {
|
|
36
|
+
this.authToken = authToken
|
|
37
|
+
this.connectTimeoutMs = connectTimeoutMs
|
|
38
|
+
this.leaseMs = leaseMs
|
|
39
|
+
this.socketPath = socketPath
|
|
40
|
+
this.connectionId = `client-${process.pid}-${Math.random().toString(36).slice(2, 10)}`
|
|
41
|
+
/** @type {net.Socket | null} */
|
|
42
|
+
this.socket = null
|
|
43
|
+
/** @type {((body: Record<string, unknown>) => void) | null} */
|
|
44
|
+
this.onMessage = null
|
|
45
|
+
/** @type {import("node:child_process").ChildProcess | null} */
|
|
46
|
+
this.spawnedChild = null
|
|
47
|
+
this.closed = false
|
|
48
|
+
this.dead = false
|
|
49
|
+
this.stdoutBuffer = ""
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Connects to the local engine, spawning the engine child when the socket is
|
|
54
|
+
* not there yet.
|
|
55
|
+
* @returns {Promise<void>} - Resolves once the socket is connected.
|
|
56
|
+
*/
|
|
57
|
+
async connect() {
|
|
58
|
+
if (this.socket) return
|
|
59
|
+
|
|
60
|
+
try {
|
|
61
|
+
await this.openSocket()
|
|
62
|
+
|
|
63
|
+
return
|
|
64
|
+
} catch (error) {
|
|
65
|
+
if (!this.socketMissingError(error)) throw error
|
|
66
|
+
|
|
67
|
+
// No engine is listening (missing socket, or a stale socket file left by
|
|
68
|
+
// a crashed engine): spawn the engine child and poll until it is live.
|
|
69
|
+
this.spawnEngineChild()
|
|
70
|
+
|
|
71
|
+
const deadline = Date.now() + this.connectTimeoutMs
|
|
72
|
+
|
|
73
|
+
while (true) {
|
|
74
|
+
try {
|
|
75
|
+
await this.openSocket()
|
|
76
|
+
|
|
77
|
+
return
|
|
78
|
+
} catch (retryError) {
|
|
79
|
+
if (!this.socketMissingError(retryError)) throw retryError
|
|
80
|
+
|
|
81
|
+
if (Date.now() >= deadline) throw new Error(`Local lock server did not start at ${this.socketPath}`, {cause: retryError})
|
|
82
|
+
|
|
83
|
+
await new Promise((resolve) => setTimeout(resolve, 25))
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Opens the 1:1 view of the socket connection (one connection per
|
|
91
|
+
* transport, like the websocket adapter).
|
|
92
|
+
* @param {string} _type - Connection role (`lock`).
|
|
93
|
+
* @param {{onMessage: (body: Record<string, unknown>) => void, params: Record<string, unknown>}} args - Connection options.
|
|
94
|
+
* @returns {{ready: Promise<void>, sendMessage: (body: Record<string, unknown>) => void, close: () => void}} - Connection handle.
|
|
95
|
+
*/
|
|
96
|
+
openConnection(_type, args) {
|
|
97
|
+
this.onMessage = args.onMessage
|
|
98
|
+
|
|
99
|
+
// The connection-open frame carries auth and protocol version; the engine
|
|
100
|
+
// answers it with a hello-ack, exactly like the external daemon does over
|
|
101
|
+
// the websocket transport.
|
|
102
|
+
this.writeLine({connectionId: this.connectionId, params: args.params, type: "hello"})
|
|
103
|
+
|
|
104
|
+
return {
|
|
105
|
+
close: () => this.close(),
|
|
106
|
+
ready: Promise.resolve(),
|
|
107
|
+
sendMessage: (/** @type {Record<string, unknown>} */ body) => this.writeLine(body)
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Closes the socket and stops an engine child this client spawned. A child
|
|
113
|
+
* it did not spawn keeps serving the other processes on the host and idles
|
|
114
|
+
* out on its own once its last connection closes.
|
|
115
|
+
* @returns {void}
|
|
116
|
+
*/
|
|
117
|
+
close() {
|
|
118
|
+
this.closed = true
|
|
119
|
+
|
|
120
|
+
const socket = this.socket
|
|
121
|
+
|
|
122
|
+
this.socket = null
|
|
123
|
+
socket?.end()
|
|
124
|
+
socket?.destroy()
|
|
125
|
+
|
|
126
|
+
const child = this.spawnedChild
|
|
127
|
+
|
|
128
|
+
this.spawnedChild = null
|
|
129
|
+
child?.kill("SIGTERM")
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Opens the Unix socket and wires the line protocol.
|
|
134
|
+
* @returns {Promise<void>} - Resolves when connected.
|
|
135
|
+
*/
|
|
136
|
+
openSocket() {
|
|
137
|
+
return new Promise((resolve, reject) => {
|
|
138
|
+
const socket = net.connect(this.socketPath)
|
|
139
|
+
|
|
140
|
+
const timer = setTimeout(() => {
|
|
141
|
+
socket.destroy()
|
|
142
|
+
reject(new Error(`Timed out connecting to the local lock server at ${this.socketPath}`))
|
|
143
|
+
}, this.connectTimeoutMs)
|
|
144
|
+
|
|
145
|
+
timer.unref?.()
|
|
146
|
+
|
|
147
|
+
socket.once("connect", () => {
|
|
148
|
+
clearTimeout(timer)
|
|
149
|
+
this.socket = socket
|
|
150
|
+
this.dead = false
|
|
151
|
+
resolve()
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
socket.once("error", (/** @type {Error} */ error) => {
|
|
155
|
+
clearTimeout(timer)
|
|
156
|
+
|
|
157
|
+
if (this.socket === socket) this.socket = null
|
|
158
|
+
|
|
159
|
+
reject(error)
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
socket.setEncoding("utf8")
|
|
163
|
+
socket.on("data", (/** @type {string} */ chunk) => this.handleSocketChunk(chunk))
|
|
164
|
+
socket.on("close", () => this.handleTransportDeath(new Error("Local lock server socket closed")))
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Spawns the local engine server as a child of this environment.
|
|
170
|
+
* @returns {void}
|
|
171
|
+
*/
|
|
172
|
+
spawnEngineChild() {
|
|
173
|
+
if (this.spawnedChild) return
|
|
174
|
+
|
|
175
|
+
const serverModulePath = fileURLToPath(new URL("../environment-handlers/node/advisory-lock-lock-server-local-server.js", import.meta.url))
|
|
176
|
+
const child = spawn(process.execPath, [serverModulePath], {
|
|
177
|
+
env: {
|
|
178
|
+
...process.env,
|
|
179
|
+
CONSENS_LOCK_LEASE_MS: String(this.leaseMs),
|
|
180
|
+
VELOCIOUS_LOCK_SERVER_SOCKET_PATH: this.socketPath
|
|
181
|
+
},
|
|
182
|
+
stdio: ["ignore", "ignore", "ignore"]
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
child.on("error", () => {
|
|
186
|
+
// A failed spawn surfaces as a connect failure on the next socket wait.
|
|
187
|
+
})
|
|
188
|
+
child.unref()
|
|
189
|
+
this.spawnedChild = child
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Writes one protocol message as a JSON line to the socket.
|
|
194
|
+
* @param {Record<string, unknown>} body - Message to send.
|
|
195
|
+
* @returns {void}
|
|
196
|
+
*/
|
|
197
|
+
writeLine(body) {
|
|
198
|
+
const socket = this.socket
|
|
199
|
+
|
|
200
|
+
if (!socket || this.dead) throw new Error("Local lock server connection is not open")
|
|
201
|
+
|
|
202
|
+
socket.write(`${JSON.stringify({...body, connectionId: this.connectionId})}\n`)
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Buffers socket data and dispatches complete JSON lines to the message
|
|
207
|
+
* handler.
|
|
208
|
+
* @param {string} chunk - Raw socket chunk.
|
|
209
|
+
* @returns {void}
|
|
210
|
+
*/
|
|
211
|
+
handleSocketChunk(chunk) {
|
|
212
|
+
this.stdoutBuffer += chunk
|
|
213
|
+
|
|
214
|
+
let newlineIndex = this.stdoutBuffer.indexOf("\n")
|
|
215
|
+
|
|
216
|
+
while (newlineIndex >= 0) {
|
|
217
|
+
const line = this.stdoutBuffer.slice(0, newlineIndex)
|
|
218
|
+
|
|
219
|
+
this.stdoutBuffer = this.stdoutBuffer.slice(newlineIndex + 1)
|
|
220
|
+
|
|
221
|
+
if (line.trim()) {
|
|
222
|
+
try {
|
|
223
|
+
const parsed = /** @type {Record<string, unknown>} */ (JSON.parse(line))
|
|
224
|
+
|
|
225
|
+
this.onMessage?.(parsed)
|
|
226
|
+
} catch {
|
|
227
|
+
// A malformed engine line is not a lock answer: the adapter's
|
|
228
|
+
// request timeout surfaces it loudly instead of guessing.
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
newlineIndex = this.stdoutBuffer.indexOf("\n")
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Reports transport death to the adapter (crash detection).
|
|
238
|
+
* @param {Error} error - Death reason.
|
|
239
|
+
* @returns {void}
|
|
240
|
+
*/
|
|
241
|
+
handleTransportDeath(error) {
|
|
242
|
+
if (this.dead || this.closed) return
|
|
243
|
+
|
|
244
|
+
this.dead = true
|
|
245
|
+
this.socket = null
|
|
246
|
+
|
|
247
|
+
this.onMessage?.({error: error.message, status: "transport-closed", transportClosed: true, type: "response"})
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Whether a connect failure means "no engine is listening yet" (spawn it).
|
|
252
|
+
* @param {unknown} error - Connect error.
|
|
253
|
+
* @returns {boolean} - True for ENOENT / ECONNREFUSED on a missing socket.
|
|
254
|
+
*/
|
|
255
|
+
socketMissingError(error) {
|
|
256
|
+
const code = /** @type {{code?: string}} */ (error || {}).code
|
|
257
|
+
|
|
258
|
+
return code === "ENOENT" || code === "ECONNREFUSED"
|
|
259
|
+
}
|
|
260
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
import os from "node:os"
|
|
4
|
+
import path from "node:path"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Default Unix-socket path for the `local` lock-server mode (STC-715). Kept
|
|
8
|
+
* short on purpose: Unix socket paths are limited to ~104 characters, and a
|
|
9
|
+
* long scratch TMPDIR makes `net.connect` fail with `EINVAL`.
|
|
10
|
+
* @param {string} [configuredPath] - Explicit `advisoryLocks.backends.lockServer.socketPath`.
|
|
11
|
+
* @returns {string} - Socket path for the local lock-server engine.
|
|
12
|
+
*/
|
|
13
|
+
export function defaultLockServerSocketPath(configuredPath) {
|
|
14
|
+
if (typeof configuredPath === "string" && configuredPath) return configuredPath
|
|
15
|
+
|
|
16
|
+
return path.join(os.tmpdir(), "velocious-lock-server.sock")
|
|
17
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
|
|
3
|
+
import WebSocket from "ws"
|
|
4
|
+
|
|
5
|
+
import VelociousWebsocketClient from "../http-client/websocket-client.js"
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Default external transport factory for the lock-server backend: the
|
|
9
|
+
* framework websocket client with the Node `ws` implementation bound explicitly
|
|
10
|
+
* (no global mutation).
|
|
11
|
+
*
|
|
12
|
+
* This module is Node-only on purpose (STC-715): the `ws` dependency lives here
|
|
13
|
+
* instead of inside `advisory-lock-lock-server-backend.js`, so the backend
|
|
14
|
+
* module itself is transport-agnostic and browser/Expo bundles can statically
|
|
15
|
+
* import it for the embedded mode without pulling `ws` or Node builtins into
|
|
16
|
+
* the graph.
|
|
17
|
+
* @param {{authToken: string, url: string}} args - Connection args.
|
|
18
|
+
* @returns {import("./advisory-lock-lock-server-backend.js").LockServerClientLike} - Websocket client.
|
|
19
|
+
*/
|
|
20
|
+
export function createLockServerWebsocketTransport({url}) {
|
|
21
|
+
// Node's global WebSocket is not guaranteed to exist, so the implementation is
|
|
22
|
+
// bound explicitly instead of mutating `globalThis`.
|
|
23
|
+
const webSocketImplementation = /** @type {typeof globalThis.WebSocket} */ (/** @type {unknown} */ (WebSocket))
|
|
24
|
+
|
|
25
|
+
return /** @type {import("./advisory-lock-lock-server-backend.js").LockServerClientLike} */ (/** @type {unknown} */ (new VelociousWebsocketClient({
|
|
26
|
+
heartbeatIntervalMs: 10_000,
|
|
27
|
+
url,
|
|
28
|
+
webSocketImplementation
|
|
29
|
+
})))
|
|
30
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// @ts-check
|
|
2
2
|
|
|
3
3
|
import UUID from "pure-uuid"
|
|
4
|
+
import * as inflection from "inflection"
|
|
4
5
|
import HasManyRelationship from "./relationships/has-many.js"
|
|
5
6
|
import {scalarModelPrimaryKey, scalarModelPrimaryKeyValue} from "../../utils/model-primary-key.js"
|
|
6
7
|
|
|
@@ -39,10 +40,19 @@ import {scalarModelPrimaryKey, scalarModelPrimaryKeyValue} from "../../utils/mod
|
|
|
39
40
|
* @property {Record<string, ReturnType<typeof JSON.parse>> | null} [params] - Optional metadata to store with the audit.
|
|
40
41
|
*/
|
|
41
42
|
|
|
43
|
+
/**
|
|
44
|
+
* AuditedOptions type.
|
|
45
|
+
* @typedef {object} AuditedOptions
|
|
46
|
+
* @property {string[]} [only] - When set, only these attribute names are written to the audit trail.
|
|
47
|
+
* @property {string[]} [except] - Attribute names that must never be written to the audit trail.
|
|
48
|
+
*/
|
|
49
|
+
|
|
42
50
|
/**
|
|
43
51
|
* AuditedModelClass type.
|
|
44
52
|
* @typedef {typeof import("./index.js").default & {
|
|
45
53
|
* _auditCallbacks?: Record<string, AuditCallback[]>,
|
|
54
|
+
* _auditIncludedAttributes?: Set<string> | null,
|
|
55
|
+
* _auditExcludedAttributes?: Set<string>,
|
|
46
56
|
* _auditLifecycleCallbacksRegistered?: boolean,
|
|
47
57
|
* _auditTableResolved?: boolean,
|
|
48
58
|
* _auditTableData?: AuditTableData
|
|
@@ -207,12 +217,12 @@ async function buildAuditTableData(modelClass, connection, databaseIdentity) {
|
|
|
207
217
|
|
|
208
218
|
if (dedicatedExists) {
|
|
209
219
|
const auditClass = dedicatedAuditClass(modelClass, dedicatedTable)
|
|
210
|
-
const
|
|
220
|
+
const foreignKey = modelForeignKey(modelClass)
|
|
211
221
|
|
|
212
222
|
return {
|
|
213
223
|
auditClass,
|
|
214
224
|
dedicated: true,
|
|
215
|
-
foreignKey
|
|
225
|
+
foreignKey,
|
|
216
226
|
tableName: dedicatedTable
|
|
217
227
|
}
|
|
218
228
|
}
|
|
@@ -411,16 +421,59 @@ function modelParamKey(modelClass) {
|
|
|
411
421
|
return name.charAt(0).toLowerCase() + name.slice(1)
|
|
412
422
|
}
|
|
413
423
|
|
|
424
|
+
/**
|
|
425
|
+
* Returns the database foreign-key column for a model class.
|
|
426
|
+
* @param {AuditedModelClass} modelClass - Audited model class.
|
|
427
|
+
* @returns {string} e.g. "project_id" for "Project".
|
|
428
|
+
*/
|
|
429
|
+
function modelForeignKey(modelClass) {
|
|
430
|
+
return `${inflection.underscore(modelClass.getModelName())}_id`
|
|
431
|
+
}
|
|
432
|
+
|
|
414
433
|
// ---------------------------------------------------------------------------
|
|
415
434
|
// Registration (sync — callbacks only; table detection deferred)
|
|
416
435
|
// ---------------------------------------------------------------------------
|
|
417
436
|
|
|
437
|
+
/**
|
|
438
|
+
* Validates audited() options and returns the attribute filter sets.
|
|
439
|
+
* Fails loudly at registration time on invalid option shapes.
|
|
440
|
+
* @param {AuditedModelClass} modelClass - Model class being registered (used in error messages).
|
|
441
|
+
* @param {AuditedOptions} options - Raw options passed to audited().
|
|
442
|
+
* @returns {{excludedAttributes: Set<string>, includedAttributes: Set<string> | null}} Validated filter sets.
|
|
443
|
+
*/
|
|
444
|
+
function parseAuditAttributeFilterOptions(modelClass, options) {
|
|
445
|
+
if (options === null || typeof options !== "object" || Array.isArray(options)) {
|
|
446
|
+
throw new Error(`Invalid audited() options for ${modelClass.getModelName()}: expected an options object with 'only' and/or 'except' attribute name lists`)
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
for (const [optionName, optionValue] of [["only", options.only], ["except", options.except]]) {
|
|
450
|
+
if (optionValue === undefined) {
|
|
451
|
+
continue
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
if (!Array.isArray(optionValue) || optionValue.some((attributeName) => typeof attributeName !== "string" || attributeName.length <= 0)) {
|
|
455
|
+
throw new Error(`Invalid audited() '${optionName}' option for ${modelClass.getModelName()}: expected an array of attribute name strings`)
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const includedAttributes = options.only === undefined ? null : new Set(options.only)
|
|
460
|
+
const excludedAttributes = new Set(options.except || [])
|
|
461
|
+
|
|
462
|
+
for (const attributeName of excludedAttributes) {
|
|
463
|
+
if (includedAttributes?.has(attributeName)) {
|
|
464
|
+
throw new Error(`Invalid audited() options for ${modelClass.getModelName()}: '${attributeName}' appears in both 'only' and 'except'`)
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
return {excludedAttributes, includedAttributes}
|
|
469
|
+
}
|
|
470
|
+
|
|
418
471
|
/**
|
|
419
472
|
* Registers lifecycle callbacks for automatic create/update/destroy auditing.
|
|
420
473
|
* Table detection and relationship registration happen lazily on first usage.
|
|
421
474
|
* Called synchronously from Model.audited() at module-load time.
|
|
422
475
|
* @param {AuditedModelClass} modelClass - Model class to audit.
|
|
423
|
-
* @param {
|
|
476
|
+
* @param {AuditedOptions} [options] - Audit options: `only` lists the only attribute names written to the audit trail; `except` lists attribute names never written to the audit trail (e.g. high-frequency telemetry columns). Invalid option shapes throw at registration time.
|
|
424
477
|
* @returns {void}
|
|
425
478
|
*/
|
|
426
479
|
function registerAuditing(modelClass, options = {}) {
|
|
@@ -428,10 +481,12 @@ function registerAuditing(modelClass, options = {}) {
|
|
|
428
481
|
return
|
|
429
482
|
}
|
|
430
483
|
|
|
431
|
-
const
|
|
484
|
+
const {excludedAttributes, includedAttributes} = parseAuditAttributeFilterOptions(modelClass, options)
|
|
485
|
+
const auditableModelClass = /** @type {AuditedModelClass & {_auditIncludedAttributes?: Set<string> | null, _auditExcludedAttributes?: Set<string>}} */ (modelClass)
|
|
432
486
|
|
|
433
487
|
auditableModelClass._auditLifecycleCallbacksRegistered = true
|
|
434
|
-
auditableModelClass.
|
|
488
|
+
auditableModelClass._auditIncludedAttributes = includedAttributes
|
|
489
|
+
auditableModelClass._auditExcludedAttributes = excludedAttributes
|
|
435
490
|
registerAuditRelationship(modelClass)
|
|
436
491
|
modelClass.beforeCreate("captureCreateAuditChanges")
|
|
437
492
|
modelClass.afterCreate("createCreateAudit")
|
|
@@ -666,14 +721,14 @@ async function createAuditWithCurrentConnection(record, args, modelClass) {
|
|
|
666
721
|
const auditId = new UUID(4).format()
|
|
667
722
|
|
|
668
723
|
if (tableData.dedicated) {
|
|
669
|
-
const
|
|
724
|
+
const foreignKey = modelForeignKey(modelClass)
|
|
670
725
|
|
|
671
726
|
await db.query(db.insertSql({
|
|
672
727
|
returnLastInsertedColumnNames: ["id"],
|
|
673
728
|
tableName: tableData.tableName,
|
|
674
729
|
data: {
|
|
675
730
|
id: auditId,
|
|
676
|
-
[
|
|
731
|
+
[foreignKey]: recordId,
|
|
677
732
|
audit_action_id: auditActionId,
|
|
678
733
|
audited_changes: auditedChanges,
|
|
679
734
|
params,
|
|
@@ -805,8 +860,9 @@ function auditChangesForCurrentChanges(record) {
|
|
|
805
860
|
const changes = record.changes()
|
|
806
861
|
/** @type {AuditChanges} */
|
|
807
862
|
const auditedChanges = {}
|
|
808
|
-
const modelClass = /** @type {AuditedModelClass & {_auditExcludedAttributes?: Set<string>}} */ (record.getModelClass())
|
|
863
|
+
const modelClass = /** @type {AuditedModelClass & {_auditIncludedAttributes?: Set<string> | null, _auditExcludedAttributes?: Set<string>}} */ (record.getModelClass())
|
|
809
864
|
const columnNameToAttributeName = modelClass.getColumnNameToAttributeNameMap()
|
|
865
|
+
const includedAttributes = modelClass._auditIncludedAttributes || null
|
|
810
866
|
const excludedAttributes = modelClass._auditExcludedAttributes
|
|
811
867
|
|
|
812
868
|
for (const [attributeName, change] of Object.entries(changes)) {
|
|
@@ -816,6 +872,10 @@ function auditChangesForCurrentChanges(record) {
|
|
|
816
872
|
continue
|
|
817
873
|
}
|
|
818
874
|
|
|
875
|
+
if (includedAttributes && !(includedAttributes.has(auditedAttributeName) || includedAttributes.has(attributeName))) {
|
|
876
|
+
continue
|
|
877
|
+
}
|
|
878
|
+
|
|
819
879
|
auditedChanges[auditedAttributeName] = change[1]
|
|
820
880
|
}
|
|
821
881
|
|
|
@@ -828,7 +888,25 @@ function auditChangesForCurrentChanges(record) {
|
|
|
828
888
|
* @returns {AuditChanges} Current attributes keyed by attribute name.
|
|
829
889
|
*/
|
|
830
890
|
function auditChangesForDestroy(record) {
|
|
831
|
-
|
|
891
|
+
const modelClass = /** @type {AuditedModelClass & {_auditIncludedAttributes?: Set<string> | null, _auditExcludedAttributes?: Set<string>}} */ (record.getModelClass())
|
|
892
|
+
const includedAttributes = modelClass._auditIncludedAttributes || null
|
|
893
|
+
const excludedAttributes = modelClass._auditExcludedAttributes
|
|
894
|
+
/** @type {AuditChanges} */
|
|
895
|
+
const auditedChanges = {}
|
|
896
|
+
|
|
897
|
+
for (const [attributeName, value] of Object.entries(record.attributes())) {
|
|
898
|
+
if (excludedAttributes?.has(attributeName)) {
|
|
899
|
+
continue
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
if (includedAttributes && !includedAttributes.has(attributeName)) {
|
|
903
|
+
continue
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
auditedChanges[attributeName] = value
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
return auditedChanges
|
|
832
910
|
}
|
|
833
911
|
|
|
834
912
|
// ---------------------------------------------------------------------------
|
|
@@ -856,10 +934,10 @@ function withoutAudit(modelClass, action) {
|
|
|
856
934
|
const auditActionsActionSql = `${auditActionsTableSql}.${db.quoteColumn("action")}`
|
|
857
935
|
|
|
858
936
|
if (tableData?.dedicated) {
|
|
859
|
-
const
|
|
937
|
+
const foreignKey = modelForeignKey(modelClass)
|
|
860
938
|
const auditsTableSql = db.quoteTable(tableData.tableName)
|
|
861
939
|
const auditActionIdSql = `${auditsTableSql}.${db.quoteColumn("audit_action_id")}`
|
|
862
|
-
const modelIdSql = `${auditsTableSql}.${db.quoteColumn(
|
|
940
|
+
const modelIdSql = `${auditsTableSql}.${db.quoteColumn(foreignKey)}`
|
|
863
941
|
|
|
864
942
|
return modelClass
|
|
865
943
|
.all()
|
|
@@ -740,7 +740,7 @@ class VelociousDatabaseRecord {
|
|
|
740
740
|
|
|
741
741
|
/**
|
|
742
742
|
* Enables automatic create/update/destroy auditing for this model.
|
|
743
|
-
* @param {{except?: string[]}} [options] - Audit options: `except` lists attribute names that must never be written to the audit trail. Use it for high-frequency telemetry columns (heartbeats, progress counters) whose write volume turns the audit table into a deadlock partner for the parent row.
|
|
743
|
+
* @param {{except?: string[], only?: string[]}} [options] - Audit options: `except` lists attribute names that must never be written to the audit trail. Use it for high-frequency telemetry columns (heartbeats, progress counters) whose write volume turns the audit table into a deadlock partner for the parent row. `only` lists the only attribute names written to the audit trail; an update whose changes are all filtered out writes no audit row at all. `only` and `except` cannot be combined. Invalid option shapes throw at registration time.
|
|
744
744
|
* @returns {void}
|
|
745
745
|
*/
|
|
746
746
|
static audited(options = {}) {
|
|
@@ -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 {
|
|
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
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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
|
/**
|