velocious 1.0.556 → 1.0.558
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 +16 -2
- package/build/background-jobs/forked-runner-child.js +20 -2
- package/build/background-jobs/main.js +35 -12
- package/build/background-jobs/pooled-runner-child.js +20 -2
- package/build/background-jobs/runner-graceful-shutdown.js +73 -0
- package/build/background-jobs/worker.js +53 -28
- package/build/configuration.js +77 -12
- package/build/database/advisory-lock-runner.js +12 -3
- package/build/database/record/index.js +12 -0
- package/build/frontend-models/base.js +192 -41
- package/build/http-client/websocket-client.js +48 -0
- package/build/src/background-jobs/forked-runner-child.js +20 -3
- package/build/src/background-jobs/main.d.ts +14 -1
- package/build/src/background-jobs/main.d.ts.map +1 -1
- package/build/src/background-jobs/main.js +37 -14
- package/build/src/background-jobs/pooled-runner-child.js +19 -3
- package/build/src/background-jobs/runner-graceful-shutdown.d.ts +49 -0
- package/build/src/background-jobs/runner-graceful-shutdown.d.ts.map +1 -0
- package/build/src/background-jobs/runner-graceful-shutdown.js +70 -0
- package/build/src/background-jobs/worker.d.ts +18 -1
- package/build/src/background-jobs/worker.d.ts.map +1 -1
- package/build/src/background-jobs/worker.js +55 -31
- package/build/src/configuration.d.ts +29 -0
- package/build/src/configuration.d.ts.map +1 -1
- package/build/src/configuration.js +71 -11
- package/build/src/database/advisory-lock-runner.d.ts.map +1 -1
- package/build/src/database/advisory-lock-runner.js +12 -4
- package/build/src/database/record/index.d.ts.map +1 -1
- package/build/src/database/record/index.js +9 -1
- package/build/src/frontend-models/base.d.ts +13 -4
- package/build/src/frontend-models/base.d.ts.map +1 -1
- package/build/src/frontend-models/base.js +173 -44
- package/build/src/http-client/websocket-client.d.ts +3 -0
- package/build/src/http-client/websocket-client.d.ts.map +1 -1
- package/build/src/http-client/websocket-client.js +42 -1
- package/build/src/tenants/tenant.d.ts +20 -9
- package/build/src/tenants/tenant.d.ts.map +1 -1
- package/build/src/tenants/tenant.js +47 -12
- package/build/src/testing/factory/factory-registry.d.ts +22 -3
- package/build/src/testing/factory/factory-registry.d.ts.map +1 -1
- package/build/src/testing/factory/factory-registry.js +32 -9
- package/build/src/testing/factory/factory-runner.d.ts +16 -4
- package/build/src/testing/factory/factory-runner.d.ts.map +1 -1
- package/build/src/testing/factory/factory-runner.js +33 -10
- package/build/src/utils/shutdown-lifecycle.d.ts +12 -0
- package/build/src/utils/shutdown-lifecycle.d.ts.map +1 -0
- package/build/src/utils/shutdown-lifecycle.js +36 -0
- package/build/tenants/tenant.js +51 -11
- package/build/testing/factory/factory-registry.js +33 -8
- package/build/testing/factory/factory-runner.js +38 -12
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/utils/shutdown-lifecycle.js +41 -0
- package/package.json +5 -4
- package/src/background-jobs/forked-runner-child.js +20 -2
- package/src/background-jobs/main.js +35 -12
- package/src/background-jobs/pooled-runner-child.js +20 -2
- package/src/background-jobs/runner-graceful-shutdown.js +73 -0
- package/src/background-jobs/worker.js +53 -28
- package/src/configuration.js +77 -12
- package/src/database/advisory-lock-runner.js +12 -3
- package/src/database/record/index.js +12 -0
- package/src/frontend-models/base.js +192 -41
- package/src/http-client/websocket-client.js +48 -0
- package/src/tenants/tenant.js +51 -11
- package/src/testing/factory/factory-registry.js +33 -8
- package/src/testing/factory/factory-runner.js +38 -12
- package/src/utils/shutdown-lifecycle.js +41 -0
|
@@ -12,7 +12,7 @@ import {deserializeFrontendModelTransportValue, serializeFrontendModelTransportV
|
|
|
12
12
|
import runWithTransportDeadline from "./transport-deadline.js"
|
|
13
13
|
import {REQUEST_TIME_ZONE_HEADER, validateTimeZone} from "../time-zone.js"
|
|
14
14
|
import VelociousWebsocketClient from "../http-client/websocket-client.js"
|
|
15
|
-
import {bufferOutgoingEvent, drainBufferedOutgoingEvents} from "./outgoing-event-buffer.js"
|
|
15
|
+
import {bufferOutgoingEvent, clearBufferedOutgoingEvents, drainBufferedOutgoingEvents} from "./outgoing-event-buffer.js"
|
|
16
16
|
import {defineModelScope} from "../utils/model-scope.js"
|
|
17
17
|
import isPlainObject from "../utils/plain-object.js"
|
|
18
18
|
import {readPayloadAssociationCount, readPayloadComputedAbility, readPayloadQueryData, setPayloadAssociationCount, setPayloadComputedAbility, setPayloadQueryData} from "../record-payload-values.js"
|
|
@@ -154,6 +154,64 @@ let frontendModelIdleResolvers = []
|
|
|
154
154
|
* Internal websocket client.
|
|
155
155
|
* @type {VelociousWebsocketClient | null} */
|
|
156
156
|
let internalWebsocketClient = null
|
|
157
|
+
/** @type {AbortSignal | null} */
|
|
158
|
+
let internalWebsocketClientSignal = null
|
|
159
|
+
/** @type {(() => void) | null} */
|
|
160
|
+
let internalWebsocketClientSignalCleanup = null
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Detaches an owned WebSocket client from the shared cache if it is still current.
|
|
164
|
+
* @param {VelociousWebsocketClient} client - Client whose ownership is ending.
|
|
165
|
+
* @returns {void}
|
|
166
|
+
*/
|
|
167
|
+
function detachInternalWebsocketClient(client) {
|
|
168
|
+
if (internalWebsocketClient !== client) return
|
|
169
|
+
|
|
170
|
+
internalWebsocketClient = null
|
|
171
|
+
internalWebsocketClientSignalCleanup?.()
|
|
172
|
+
internalWebsocketClientSignal = null
|
|
173
|
+
internalWebsocketClientSignalCleanup = null
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Disposes the owned WebSocket client before transport/session configuration changes.
|
|
178
|
+
* @returns {void}
|
|
179
|
+
*/
|
|
180
|
+
function resetInternalWebsocketClient() {
|
|
181
|
+
const client = internalWebsocketClient
|
|
182
|
+
|
|
183
|
+
if (!client) return
|
|
184
|
+
|
|
185
|
+
detachInternalWebsocketClient(client)
|
|
186
|
+
void client.disconnectAndStopReconnect()
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Binds the owned WebSocket client lifetime to the current session signal.
|
|
191
|
+
* @param {AbortSignal | undefined} sessionSignal - Current session signal.
|
|
192
|
+
* @returns {void}
|
|
193
|
+
*/
|
|
194
|
+
function bindInternalWebsocketClientSignal(sessionSignal) {
|
|
195
|
+
if (internalWebsocketClientSignal === sessionSignal) return
|
|
196
|
+
|
|
197
|
+
internalWebsocketClientSignalCleanup?.()
|
|
198
|
+
internalWebsocketClientSignal = sessionSignal || null
|
|
199
|
+
internalWebsocketClientSignalCleanup = null
|
|
200
|
+
|
|
201
|
+
if (!sessionSignal || !internalWebsocketClient) return
|
|
202
|
+
|
|
203
|
+
const client = internalWebsocketClient
|
|
204
|
+
const onSessionAbort = () => {
|
|
205
|
+
detachInternalWebsocketClient(client)
|
|
206
|
+
clearBufferedOutgoingEvents()
|
|
207
|
+
void client.disconnectAndStopReconnect()
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
sessionSignal.addEventListener("abort", onSessionAbort, {once: true})
|
|
211
|
+
internalWebsocketClientSignalCleanup = () => sessionSignal.removeEventListener("abort", onSessionAbort)
|
|
212
|
+
|
|
213
|
+
if (sessionSignal.aborted) onSessionAbort()
|
|
214
|
+
}
|
|
157
215
|
|
|
158
216
|
/**
|
|
159
217
|
* Runs frontend model transport is idle.
|
|
@@ -237,7 +295,13 @@ async function trackFrontendModelTransportRequest(callback) {
|
|
|
237
295
|
* @returns {VelociousWebsocketClient | null} Websocket client or null.
|
|
238
296
|
*/
|
|
239
297
|
function resolveInternalWebsocketClient() {
|
|
240
|
-
if (internalWebsocketClient)
|
|
298
|
+
if (internalWebsocketClient) {
|
|
299
|
+
const client = internalWebsocketClient
|
|
300
|
+
|
|
301
|
+
bindInternalWebsocketClientSignal(frontendModelTransportSignal())
|
|
302
|
+
|
|
303
|
+
return client
|
|
304
|
+
}
|
|
241
305
|
|
|
242
306
|
const websocketUrl = frontendModelTransportConfig.websocketUrl
|
|
243
307
|
|
|
@@ -248,41 +312,68 @@ function resolveInternalWebsocketClient() {
|
|
|
248
312
|
|
|
249
313
|
if (!resolvedUrl) return null
|
|
250
314
|
|
|
251
|
-
|
|
315
|
+
const client = new VelociousWebsocketClient({
|
|
252
316
|
autoReconnect: true,
|
|
253
317
|
sessionStore: frontendModelTransportConfig.sessionStore,
|
|
254
318
|
url: resolvedUrl
|
|
255
319
|
})
|
|
256
|
-
internalWebsocketClient
|
|
320
|
+
internalWebsocketClient = client
|
|
321
|
+
client.onReconnect = async () => await flushBufferedOutgoingEventsAfterReconnect(client)
|
|
257
322
|
|
|
258
|
-
|
|
323
|
+
bindInternalWebsocketClientSignal(frontendModelTransportSignal())
|
|
324
|
+
|
|
325
|
+
return client
|
|
259
326
|
}
|
|
260
327
|
|
|
261
328
|
/**
|
|
262
329
|
* Runs flush buffered outgoing events after reconnect.
|
|
330
|
+
* @param {VelociousWebsocketClient} client - Reconnected client that owns this flush.
|
|
263
331
|
* @returns {Promise<void>} */
|
|
264
|
-
async function flushBufferedOutgoingEventsAfterReconnect() {
|
|
265
|
-
if (
|
|
332
|
+
async function flushBufferedOutgoingEventsAfterReconnect(client) {
|
|
333
|
+
if (internalWebsocketClient !== client) return
|
|
266
334
|
|
|
267
335
|
const events = drainBufferedOutgoingEvents()
|
|
336
|
+
const sessionSignal = frontendModelTransportSignal()
|
|
268
337
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
338
|
+
await runWithTransportDeadline(
|
|
339
|
+
{
|
|
340
|
+
errorMessage: "Buffered frontend-model WebSocket flush timed out",
|
|
341
|
+
signal: sessionSignal,
|
|
342
|
+
timeoutMs: frontendModelTransportTimeoutMs()
|
|
343
|
+
},
|
|
344
|
+
async (signal) => {
|
|
345
|
+
for (let index = 0; index < events.length; index += 1) {
|
|
346
|
+
if (internalWebsocketClient !== client) return
|
|
274
347
|
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
}
|
|
348
|
+
try {
|
|
349
|
+
await client.post(events[index].customPath, events[index].payload, {signal})
|
|
278
350
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
351
|
+
if (internalWebsocketClient !== client) return
|
|
352
|
+
} catch {
|
|
353
|
+
if (internalWebsocketClient !== client) return
|
|
354
|
+
if (sessionSignal?.aborted) return
|
|
282
355
|
|
|
283
|
-
|
|
356
|
+
if (signal.aborted) {
|
|
357
|
+
for (let remaining = index; remaining < events.length; remaining += 1) {
|
|
358
|
+
bufferOutgoingEvent(events[remaining])
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
return
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const socketOpen = client.socket?.readyState === client.socket?.OPEN
|
|
365
|
+
|
|
366
|
+
if (socketOpen) continue
|
|
367
|
+
|
|
368
|
+
for (let remaining = index; remaining < events.length; remaining += 1) {
|
|
369
|
+
bufferOutgoingEvent(events[remaining])
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return
|
|
373
|
+
}
|
|
374
|
+
}
|
|
284
375
|
}
|
|
285
|
-
|
|
376
|
+
)
|
|
286
377
|
}
|
|
287
378
|
|
|
288
379
|
/**
|
|
@@ -1784,6 +1875,29 @@ function frontendModelTransportSignal() {
|
|
|
1784
1875
|
return configuredSignal || undefined
|
|
1785
1876
|
}
|
|
1786
1877
|
|
|
1878
|
+
/**
|
|
1879
|
+
* Resolves per-startup controls with the configured session cancellation.
|
|
1880
|
+
* @param {{timeoutMs?: number, signal?: AbortSignal}} controls - Call controls.
|
|
1881
|
+
* @returns {{timeoutMs?: number, signal?: AbortSignal}} - Effective startup controls.
|
|
1882
|
+
*/
|
|
1883
|
+
function frontendModelWebsocketStartupControls(controls) {
|
|
1884
|
+
const sessionSignal = frontendModelTransportSignal()
|
|
1885
|
+
let signal = controls.signal || sessionSignal
|
|
1886
|
+
|
|
1887
|
+
if (controls.signal && sessionSignal && controls.signal !== sessionSignal) {
|
|
1888
|
+
signal = AbortSignal.any([controls.signal, sessionSignal])
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
const configuredTimeoutMs = frontendModelTransportTimeoutMs()
|
|
1892
|
+
const timeoutMs = controls.timeoutMs === undefined
|
|
1893
|
+
? configuredTimeoutMs
|
|
1894
|
+
: configuredTimeoutMs === undefined
|
|
1895
|
+
? controls.timeoutMs
|
|
1896
|
+
: Math.min(controls.timeoutMs, configuredTimeoutMs)
|
|
1897
|
+
|
|
1898
|
+
return {signal, timeoutMs}
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1787
1901
|
/**
|
|
1788
1902
|
* Runs perform shared frontend model api request.
|
|
1789
1903
|
* @param {Record<string, ?>} requestPayload - Shared request payload.
|
|
@@ -2897,7 +3011,7 @@ export default class FrontendModelBase {
|
|
|
2897
3011
|
if (Object.prototype.hasOwnProperty.call(config, "websocketUrl")) {
|
|
2898
3012
|
frontendModelTransportConfig.websocketUrl = config.websocketUrl
|
|
2899
3013
|
// Reset cached internal client so the new URL takes effect on next subscribe
|
|
2900
|
-
|
|
3014
|
+
resetInternalWebsocketClient()
|
|
2901
3015
|
}
|
|
2902
3016
|
|
|
2903
3017
|
if (Object.prototype.hasOwnProperty.call(config, "requestHeaders")) {
|
|
@@ -2909,7 +3023,10 @@ export default class FrontendModelBase {
|
|
|
2909
3023
|
}
|
|
2910
3024
|
|
|
2911
3025
|
if (Object.prototype.hasOwnProperty.call(config, "signal")) {
|
|
2912
|
-
frontendModelTransportConfig.signal
|
|
3026
|
+
if (frontendModelTransportConfig.signal !== config.signal) {
|
|
3027
|
+
frontendModelTransportConfig.signal = config.signal
|
|
3028
|
+
resetInternalWebsocketClient()
|
|
3029
|
+
}
|
|
2913
3030
|
}
|
|
2914
3031
|
|
|
2915
3032
|
if (Object.prototype.hasOwnProperty.call(config, "timeZone")) {
|
|
@@ -2923,7 +3040,7 @@ export default class FrontendModelBase {
|
|
|
2923
3040
|
if (Object.prototype.hasOwnProperty.call(config, "sessionStore")) {
|
|
2924
3041
|
frontendModelTransportConfig.sessionStore = config.sessionStore
|
|
2925
3042
|
// Reset cached internal client so the new sessionStore is picked up.
|
|
2926
|
-
|
|
3043
|
+
resetInternalWebsocketClient()
|
|
2927
3044
|
}
|
|
2928
3045
|
|
|
2929
3046
|
if (Object.prototype.hasOwnProperty.call(config, "offlineSync")) {
|
|
@@ -2933,16 +3050,17 @@ export default class FrontendModelBase {
|
|
|
2933
3050
|
|
|
2934
3051
|
/**
|
|
2935
3052
|
* Connect the internal WebSocket and enable auto-reconnect.
|
|
3053
|
+
* @param {{timeoutMs?: number, signal?: AbortSignal}} [options] - Startup controls composed with the configured transport controls.
|
|
2936
3054
|
* @returns {Promise<void>} - Resolves when connected.
|
|
2937
3055
|
*/
|
|
2938
|
-
static async connectWebsocket() {
|
|
3056
|
+
static async connectWebsocket(options = {}) {
|
|
2939
3057
|
const client = resolveInternalWebsocketClient()
|
|
2940
3058
|
|
|
2941
3059
|
if (!client) {
|
|
2942
3060
|
throw new Error("connectWebsocket requires configureTransport({websocketUrl})")
|
|
2943
3061
|
}
|
|
2944
3062
|
|
|
2945
|
-
await client.connect()
|
|
3063
|
+
await client.connect(frontendModelWebsocketStartupControls(options))
|
|
2946
3064
|
}
|
|
2947
3065
|
|
|
2948
3066
|
/**
|
|
@@ -2952,7 +3070,10 @@ export default class FrontendModelBase {
|
|
|
2952
3070
|
static async disconnectWebsocket() {
|
|
2953
3071
|
if (!internalWebsocketClient) return
|
|
2954
3072
|
|
|
2955
|
-
|
|
3073
|
+
const client = internalWebsocketClient
|
|
3074
|
+
|
|
3075
|
+
detachInternalWebsocketClient(client)
|
|
3076
|
+
await client.disconnectAndStopReconnect()
|
|
2956
3077
|
}
|
|
2957
3078
|
|
|
2958
3079
|
/**
|
|
@@ -3026,7 +3147,7 @@ export default class FrontendModelBase {
|
|
|
3026
3147
|
* functions change (e.g. current-user sign-in/out). The handle
|
|
3027
3148
|
* retries when the WS client isn't ready and reopens on close.
|
|
3028
3149
|
* @param {string} connectionType - Connection class name registered on the server.
|
|
3029
|
-
* @param {{shouldConnect: () => boolean, params: () => Record<string, ?>, onMessage?: (body: ?) => void}} options - Connection lifecycle and payload callbacks.
|
|
3150
|
+
* @param {{shouldConnect: () => boolean, params: () => Record<string, ?>, signal?: AbortSignal, onMessage?: (body: ?) => void}} options - Connection lifecycle, cancellation, and payload callbacks.
|
|
3030
3151
|
* @returns {{sync: () => void, close: () => void}} - Handle used to resync or close the managed connection.
|
|
3031
3152
|
*/
|
|
3032
3153
|
static openManagedConnection(connectionType, options) {
|
|
@@ -3040,11 +3161,29 @@ export default class FrontendModelBase {
|
|
|
3040
3161
|
* @type {ReturnType<typeof setTimeout> | null} */
|
|
3041
3162
|
let retryTimer = null
|
|
3042
3163
|
let lastParamsJson = ""
|
|
3164
|
+
const controls = frontendModelWebsocketStartupControls({signal: options.signal})
|
|
3165
|
+
const clearRetryTimer = () => {
|
|
3166
|
+
if (retryTimer === null) return
|
|
3167
|
+
|
|
3168
|
+
globalThis.clearTimeout(retryTimer)
|
|
3169
|
+
retryTimer = null
|
|
3170
|
+
}
|
|
3171
|
+
|
|
3172
|
+
const close = () => {
|
|
3173
|
+
if (closed) return
|
|
3174
|
+
|
|
3175
|
+
closed = true
|
|
3176
|
+
clearRetryTimer()
|
|
3177
|
+
controls.signal?.removeEventListener("abort", close)
|
|
3178
|
+
if (connection && !connection.isClosed()) connection.close()
|
|
3179
|
+
connection = null
|
|
3180
|
+
}
|
|
3043
3181
|
|
|
3044
3182
|
const sync = () => {
|
|
3045
3183
|
if (closed) return
|
|
3046
3184
|
|
|
3047
3185
|
if (!options.shouldConnect()) {
|
|
3186
|
+
clearRetryTimer()
|
|
3048
3187
|
if (connection && !connection.isClosed()) connection.close()
|
|
3049
3188
|
connection = null
|
|
3050
3189
|
lastParamsJson = ""
|
|
@@ -3087,7 +3226,7 @@ export default class FrontendModelBase {
|
|
|
3087
3226
|
}
|
|
3088
3227
|
|
|
3089
3228
|
lastParamsJson = nextParamsJson
|
|
3090
|
-
connection =
|
|
3229
|
+
connection = client.openConnection(connectionType, {
|
|
3091
3230
|
params: nextParams,
|
|
3092
3231
|
onMessage: options.onMessage,
|
|
3093
3232
|
onClose: () => {
|
|
@@ -3100,14 +3239,13 @@ export default class FrontendModelBase {
|
|
|
3100
3239
|
})
|
|
3101
3240
|
}
|
|
3102
3241
|
|
|
3103
|
-
|
|
3104
|
-
closed = true
|
|
3105
|
-
if (retryTimer !== null) globalThis.clearTimeout(retryTimer)
|
|
3106
|
-
if (connection && !connection.isClosed()) connection.close()
|
|
3107
|
-
connection = null
|
|
3108
|
-
}
|
|
3242
|
+
controls.signal?.addEventListener("abort", close, {once: true})
|
|
3109
3243
|
|
|
3110
|
-
|
|
3244
|
+
if (controls.signal?.aborted) {
|
|
3245
|
+
close()
|
|
3246
|
+
} else {
|
|
3247
|
+
sync()
|
|
3248
|
+
}
|
|
3111
3249
|
|
|
3112
3250
|
return {sync, close}
|
|
3113
3251
|
}
|
|
@@ -3118,34 +3256,47 @@ export default class FrontendModelBase {
|
|
|
3118
3256
|
* `openConnection`. Apps use this for per-session state/messaging
|
|
3119
3257
|
* that doesn't fit the pub/sub Channel model (locale, presence).
|
|
3120
3258
|
* @param {string} connectionType - Name the server registered the class under.
|
|
3121
|
-
* @param {{params?: Record<string, ?>, onConnect?: () => void, onMessage?: (body: Record<string, unknown>) => void, onDisconnect?: () => void, onResume?: () => void, onClose?: (reason: string) => void}} [options] - Connection options and event handlers.
|
|
3259
|
+
* @param {{params?: Record<string, ?>, timeoutMs?: number, signal?: AbortSignal, onConnect?: () => void, onMessage?: (body: Record<string, unknown>) => void, onDisconnect?: () => void, onResume?: () => void, onClose?: (reason: string) => void}} [options] - Connection options, readiness controls, and event handlers. Connect the client first; the timeout covers server-confirmed readiness and the signal cancels readiness without entering the wire payload.
|
|
3122
3260
|
* @returns {{ready: Promise<void>, close: () => void}} - Websocket connection handle.
|
|
3123
3261
|
*/
|
|
3124
|
-
static openWebsocketConnection(connectionType, options) {
|
|
3262
|
+
static openWebsocketConnection(connectionType, options = {}) {
|
|
3125
3263
|
const client = /** @type {?} */ (frontendModelTransportConfig.websocketClient || resolveInternalWebsocketClient())
|
|
3126
3264
|
|
|
3127
3265
|
if (!client || typeof client.openConnection !== "function") {
|
|
3128
3266
|
throw new Error("openWebsocketConnection requires configureTransport({websocketUrl})")
|
|
3129
3267
|
}
|
|
3130
3268
|
|
|
3131
|
-
|
|
3269
|
+
const {signal, timeoutMs, ...connectionOptions} = options
|
|
3270
|
+
|
|
3271
|
+
return client.openConnection(connectionType, {
|
|
3272
|
+
...connectionOptions,
|
|
3273
|
+
...frontendModelWebsocketStartupControls({signal, timeoutMs})
|
|
3274
|
+
})
|
|
3132
3275
|
}
|
|
3133
3276
|
|
|
3134
3277
|
/**
|
|
3135
3278
|
* Subscribes to a pub/sub `WebsocketChannel`. Thin wrapper around
|
|
3136
3279
|
* the internal client's `subscribeChannel`.
|
|
3137
3280
|
* @param {string} channelType - Channel class name registered on the server.
|
|
3138
|
-
* @param {{params?: Record<string, ?>, onMessage?: (body: Record<string, unknown>) => void, onDisconnect?: () => void, onResume?: () => void, onClose?: (reason: string) => void}} [options] - Channel
|
|
3281
|
+
* @param {{params?: Record<string, ?>, timeoutMs?: number, signal?: AbortSignal, onMessage?: (body: Record<string, unknown>) => void, onDisconnect?: () => void, onResume?: () => void, onClose?: (reason: string) => void}} [options] - Channel options, startup controls, and event handlers. The timeout covers connect and server-confirmed readiness only; the signal cancels startup without entering the wire payload.
|
|
3139
3282
|
* @returns {{ready: Promise<void>, close: () => void}} - Websocket channel handle from the configured client.
|
|
3140
3283
|
*/
|
|
3141
|
-
static subscribeWebsocketChannel(channelType, options) {
|
|
3284
|
+
static subscribeWebsocketChannel(channelType, options = {}) {
|
|
3142
3285
|
const client = /** @type {?} */ (frontendModelTransportConfig.websocketClient || resolveInternalWebsocketClient())
|
|
3143
3286
|
|
|
3144
3287
|
if (!client || typeof client.subscribeChannel !== "function") {
|
|
3145
3288
|
throw new Error("subscribeWebsocketChannel requires configureTransport({websocketUrl})")
|
|
3146
3289
|
}
|
|
3147
3290
|
|
|
3148
|
-
|
|
3291
|
+
const {signal, timeoutMs, ...channelOptions} = options
|
|
3292
|
+
const startupControls = frontendModelWebsocketStartupControls({signal, timeoutMs})
|
|
3293
|
+
const handle = client.subscribeChannel(channelType, {...channelOptions, ...startupControls})
|
|
3294
|
+
|
|
3295
|
+
if (typeof client.connect === "function") {
|
|
3296
|
+
void client.connect(startupControls).catch(() => handle.close())
|
|
3297
|
+
}
|
|
3298
|
+
|
|
3299
|
+
return handle
|
|
3149
3300
|
}
|
|
3150
3301
|
|
|
3151
3302
|
/**
|
|
@@ -23,5 +23,53 @@ export default class VelociousWebsocketClient extends SnapReqWebSocketClient {
|
|
|
23
23
|
url: args.url ?? DEFAULT_URL,
|
|
24
24
|
deserialize: args.deserialize ?? deserializeFrontendModelTransportValue
|
|
25
25
|
})
|
|
26
|
+
this.reconnectGeneration = 0
|
|
27
|
+
/** @type {Set<Promise<void>>} */
|
|
28
|
+
this.runningReconnectTasks = new Set()
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Ignores an online result resolved after reconnect teardown began.
|
|
33
|
+
* @returns {Promise<boolean>} - Whether this client generation is online.
|
|
34
|
+
*/
|
|
35
|
+
async _isOnline() {
|
|
36
|
+
const generation = this.reconnectGeneration
|
|
37
|
+
const isOnline = await super._isOnline()
|
|
38
|
+
|
|
39
|
+
return generation === this.reconnectGeneration && isOnline
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Tracks automatic reconnect work so teardown can drain stale attempts.
|
|
44
|
+
* @returns {Promise<void>} - Resolves after the reconnect attempt settles.
|
|
45
|
+
*/
|
|
46
|
+
async _attemptReconnect() {
|
|
47
|
+
const reconnectTask = super._attemptReconnect()
|
|
48
|
+
|
|
49
|
+
this.runningReconnectTasks.add(reconnectTask)
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
await reconnectTask
|
|
53
|
+
} finally {
|
|
54
|
+
this.runningReconnectTasks.delete(reconnectTask)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Stops reconnect, drains work that already passed SnapReq's reconnect guard,
|
|
60
|
+
* and clears state changed by a stale attempt while it settled.
|
|
61
|
+
* @returns {Promise<void>} - Resolves once no reconnect can resurrect a socket.
|
|
62
|
+
*/
|
|
63
|
+
async disconnectAndStopReconnect() {
|
|
64
|
+
this.reconnectGeneration += 1
|
|
65
|
+
await super.disconnectAndStopReconnect()
|
|
66
|
+
|
|
67
|
+
if (this.runningReconnectTasks.size === 0) return
|
|
68
|
+
|
|
69
|
+
while (this.runningReconnectTasks.size > 0) {
|
|
70
|
+
await Promise.all(this.runningReconnectTasks)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
await super.disconnectAndStopReconnect()
|
|
26
74
|
}
|
|
27
75
|
}
|
package/src/tenants/tenant.js
CHANGED
|
@@ -11,19 +11,21 @@ import TenantIterator from "./tenant-iterator.js"
|
|
|
11
11
|
* class is the single discoverable home for switching into a tenant's context, reading the
|
|
12
12
|
* current one, iterating every tenant of a database identifier, and dropping a tenant's
|
|
13
13
|
* database. Switching delegates to {@link Current} (which owns the async-context tenant
|
|
14
|
-
* state) and additionally runs the callback inside `ensureConnections`,
|
|
14
|
+
* state) and additionally runs the callback inside `ensureConnections`, initializing registered
|
|
15
|
+
* tenant-switched models whose tables exist before the callback runs. Entering a tenant therefore
|
|
15
16
|
* makes its database immediately queryable — the apartment-style "switch" semantics — without
|
|
16
|
-
* the caller establishing connections itself; iteration and drop drive the
|
|
17
|
-
* database provider hooks.
|
|
17
|
+
* the caller establishing connections or model metadata itself; iteration and drop drive the
|
|
18
|
+
* app's tenant database provider hooks.
|
|
18
19
|
*/
|
|
19
20
|
export default class Tenant {
|
|
20
21
|
/**
|
|
21
22
|
* Runs `callback` with `tenant` as the current tenant, restoring the previous tenant after.
|
|
22
23
|
* The callback runs inside `ensureConnections`, so every database identifier the tenant
|
|
23
24
|
* activates (the global database plus the tenant's database) has a checked-out connection
|
|
24
|
-
* available for the callback's duration
|
|
25
|
-
* the
|
|
26
|
-
*
|
|
25
|
+
* available for the callback's duration. Registered tenant-switched models whose tables exist
|
|
26
|
+
* are initialized before the callback runs, so switching into a tenant makes it queryable
|
|
27
|
+
* without the caller wiring up connections or model metadata. Already-checked-out connections
|
|
28
|
+
* and in-progress model initialization promises are reused. The callback receives the active
|
|
27
29
|
* connections keyed by identifier, the same as `ensureConnections`.
|
|
28
30
|
* @template T
|
|
29
31
|
* @param {object} tenant Descriptor understood by the app's tenantDatabaseResolver.
|
|
@@ -33,7 +35,41 @@ export default class Tenant {
|
|
|
33
35
|
static async with(tenant, callback) {
|
|
34
36
|
const configuration = Current.configuration()
|
|
35
37
|
|
|
36
|
-
return await Current.withTenant(tenant, async () => await configuration.ensureConnections(
|
|
38
|
+
return await Current.withTenant(tenant, async () => await configuration.ensureConnections(async (connections) => {
|
|
39
|
+
await this._ensureCurrentTenantModelsInitialized(configuration)
|
|
40
|
+
|
|
41
|
+
return await callback(connections)
|
|
42
|
+
}))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Initializes registered tenant-switched models whose tables exist in the
|
|
47
|
+
* current tenant before runtime callbacks can build synchronous query scopes.
|
|
48
|
+
* Models for absent optional tables remain deferred until they are used.
|
|
49
|
+
* @param {import("../configuration.js").default} configuration - Current configuration.
|
|
50
|
+
* @returns {Promise<void>} - Resolves when available tenant models are initialized.
|
|
51
|
+
*/
|
|
52
|
+
static async _ensureCurrentTenantModelsInitialized(configuration) {
|
|
53
|
+
for (const modelClass of Object.values(configuration.getModelClasses())) {
|
|
54
|
+
if (modelClass.isInitialized() || !modelClass.hasTenantDatabaseIdentifierResolver()) continue
|
|
55
|
+
|
|
56
|
+
const databaseIdentifier = modelClass.getTenantDatabaseIdentifier()
|
|
57
|
+
|
|
58
|
+
if (!databaseIdentifier || !configuration.isDatabaseIdentifierActive(databaseIdentifier)) continue
|
|
59
|
+
|
|
60
|
+
const connection = modelClass.connection()
|
|
61
|
+
const table = await connection.getTableByName(modelClass.tableName(), {throwError: false})
|
|
62
|
+
|
|
63
|
+
if (!table) continue
|
|
64
|
+
|
|
65
|
+
if (Object.keys(modelClass.getTranslationsMap()).length > 0) {
|
|
66
|
+
const translationsTable = await connection.getTableByName(modelClass.getTranslationsTableName(), {throwError: false})
|
|
67
|
+
|
|
68
|
+
if (!translationsTable) continue
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
await modelClass.ensureInitialized({configuration})
|
|
72
|
+
}
|
|
37
73
|
}
|
|
38
74
|
|
|
39
75
|
/**
|
|
@@ -47,9 +83,10 @@ export default class Tenant {
|
|
|
47
83
|
/**
|
|
48
84
|
* Lists the tenants for a database identifier through the provider and runs `callback`
|
|
49
85
|
* within each tenant's context, optionally filtered and several at a time. Like
|
|
50
|
-
* {@link Tenant.with}, the callback runs inside `ensureConnections`
|
|
51
|
-
*
|
|
52
|
-
*
|
|
86
|
+
* {@link Tenant.with}, the callback runs inside `ensureConnections` after available
|
|
87
|
+
* tenant-switched models are initialized, so each tenant's database is queryable without the
|
|
88
|
+
* caller wiring up connections or model metadata. Returns how many tenants the callback ran
|
|
89
|
+
* for (after filtering).
|
|
53
90
|
* @param {{identifier: string, callback: function({databaseConfiguration: import("../configuration-types.js").DatabaseConfigurationType, tenant: ?}) : Promise<void>, parallel?: number, filter?: (tenant: ?) => boolean, configuration?: import("../configuration.js").default}} args - Tenant database identifier, per-tenant operation, filtering, and concurrency settings.
|
|
54
91
|
* @returns {Promise<number>} - Number of processed tenants.
|
|
55
92
|
*/
|
|
@@ -71,7 +108,10 @@ export default class Tenant {
|
|
|
71
108
|
// their callbacks, such as create, before the tenant database exists) while runtime
|
|
72
109
|
// iteration here gets the tenant's connections established the same way Tenant.with does.
|
|
73
110
|
return await iterator.run(tenants, async (callbackArgs) => {
|
|
74
|
-
await configuration.ensureConnections({name: `Tenant.each: ${identifier}`}, async () =>
|
|
111
|
+
await configuration.ensureConnections({name: `Tenant.each: ${identifier}`}, async () => {
|
|
112
|
+
await this._ensureCurrentTenantModelsInitialized(configuration)
|
|
113
|
+
await callback(callbackArgs)
|
|
114
|
+
})
|
|
75
115
|
})
|
|
76
116
|
}
|
|
77
117
|
|
|
@@ -333,17 +333,27 @@ export default class FactoryRegistry {
|
|
|
333
333
|
const {traits, overrides} = normalizeInvocationArgs(args)
|
|
334
334
|
/** @type {Array<?>} */
|
|
335
335
|
const results = []
|
|
336
|
+
/** @type {import("./factory-runner.js").CompiledPlan | undefined} */
|
|
337
|
+
let planTemplate
|
|
336
338
|
|
|
337
|
-
|
|
338
|
-
|
|
339
|
+
this._activeEvaluations += 1
|
|
340
|
+
|
|
341
|
+
try {
|
|
342
|
+
for (let index = 0; index < count; index++) {
|
|
343
|
+
const invocation = await this._runFactoryInvocation({factoryName, traits, overrides, strategy, planTemplate})
|
|
344
|
+
|
|
345
|
+
planTemplate = invocation.planTemplate
|
|
346
|
+
results.push(invocation.result)
|
|
347
|
+
}
|
|
348
|
+
} finally {
|
|
349
|
+
this._activeEvaluations -= 1
|
|
339
350
|
}
|
|
340
351
|
|
|
341
352
|
return results
|
|
342
353
|
}
|
|
343
354
|
|
|
344
355
|
/**
|
|
345
|
-
* Compiles and runs a factory invocation under a strategy
|
|
346
|
-
* evaluations for the mutation guard.
|
|
356
|
+
* Compiles and runs a factory invocation under a strategy.
|
|
347
357
|
* @param {object} args - Options.
|
|
348
358
|
* @param {string} args.factoryName - Factory name.
|
|
349
359
|
* @param {string[]} args.traits - Ordered traits.
|
|
@@ -351,7 +361,21 @@ export default class FactoryRegistry {
|
|
|
351
361
|
* @param {"attributesFor" | "build" | "create"} args.strategy - Strategy name.
|
|
352
362
|
* @returns {Promise<?>} - The strategy result.
|
|
353
363
|
*/
|
|
354
|
-
async _runFactory(
|
|
364
|
+
async _runFactory(args) {
|
|
365
|
+
return (await this._runFactoryInvocation(args)).result
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Runs one event-tracked invocation, optionally reusing declaration planning.
|
|
370
|
+
* @param {object} args - Options.
|
|
371
|
+
* @param {string} args.factoryName - Factory name.
|
|
372
|
+
* @param {string[]} args.traits - Ordered traits.
|
|
373
|
+
* @param {Record<string, ?>} args.overrides - Overrides.
|
|
374
|
+
* @param {"attributesFor" | "build" | "create"} args.strategy - Strategy name.
|
|
375
|
+
* @param {import("./factory-runner.js").CompiledPlan} [args.planTemplate] - Reusable declaration plan.
|
|
376
|
+
* @returns {Promise<{result: ?, planTemplate: import("./factory-runner.js").CompiledPlan}>} - Result and declaration plan.
|
|
377
|
+
*/
|
|
378
|
+
async _runFactoryInvocation({factoryName, traits, overrides, strategy, planTemplate}) {
|
|
355
379
|
this._activeEvaluations += 1
|
|
356
380
|
|
|
357
381
|
const invocationId = this._events.nextInvocationId()
|
|
@@ -360,12 +384,13 @@ export default class FactoryRegistry {
|
|
|
360
384
|
try {
|
|
361
385
|
this._events.emit("start", {invocationId, factory: factoryName, strategy, traits})
|
|
362
386
|
|
|
363
|
-
const
|
|
364
|
-
const
|
|
387
|
+
const compiledPlanTemplate = planTemplate || this._runner.compileTemplate(factoryName, traits)
|
|
388
|
+
const compiledPlan = this._runner.applyOverrides(compiledPlanTemplate, overrides)
|
|
389
|
+
const result = await this._strategies[strategy].run({registry: this, plan: compiledPlan})
|
|
365
390
|
|
|
366
391
|
this._events.emit("success", {invocationId, factory: factoryName, strategy, traits, durationMs: Date.now() - startedAt})
|
|
367
392
|
|
|
368
|
-
return result
|
|
393
|
+
return {result, planTemplate: compiledPlanTemplate}
|
|
369
394
|
} catch (error) {
|
|
370
395
|
this._events.emit("failure", {invocationId, factory: factoryName, strategy, traits, durationMs: Date.now() - startedAt, error})
|
|
371
396
|
|