velocious 1.0.699 → 1.0.701

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 (42) hide show
  1. package/README.md +1 -2
  2. package/build/configuration-types.js +12 -1
  3. package/build/configuration.js +174 -18
  4. package/build/database/advisory-lock-backend-policy.js +204 -0
  5. package/build/database/advisory-lock-file-backend.js +348 -0
  6. package/build/database/advisory-lock-runner.js +239 -16
  7. package/build/environment-handlers/base.js +13 -0
  8. package/build/environment-handlers/node.js +11 -0
  9. package/build/http-server/server-lock.js +21 -115
  10. package/build/src/configuration-types.d.ts +33 -2
  11. package/build/src/configuration-types.d.ts.map +1 -1
  12. package/build/src/configuration-types.js +12 -2
  13. package/build/src/configuration.d.ts +99 -1
  14. package/build/src/configuration.d.ts.map +1 -1
  15. package/build/src/configuration.js +161 -18
  16. package/build/src/database/advisory-lock-backend-policy.d.ts +145 -0
  17. package/build/src/database/advisory-lock-backend-policy.d.ts.map +1 -0
  18. package/build/src/database/advisory-lock-backend-policy.js +184 -0
  19. package/build/src/database/advisory-lock-file-backend.d.ts +194 -0
  20. package/build/src/database/advisory-lock-file-backend.d.ts.map +1 -0
  21. package/build/src/database/advisory-lock-file-backend.js +313 -0
  22. package/build/src/database/advisory-lock-runner.d.ts +116 -15
  23. package/build/src/database/advisory-lock-runner.d.ts.map +1 -1
  24. package/build/src/database/advisory-lock-runner.js +190 -17
  25. package/build/src/environment-handlers/base.d.ts +14 -0
  26. package/build/src/environment-handlers/base.d.ts.map +1 -1
  27. package/build/src/environment-handlers/base.js +13 -1
  28. package/build/src/environment-handlers/node.d.ts +11 -0
  29. package/build/src/environment-handlers/node.d.ts.map +1 -1
  30. package/build/src/environment-handlers/node.js +11 -1
  31. package/build/src/http-server/server-lock.d.ts +13 -37
  32. package/build/src/http-server/server-lock.d.ts.map +1 -1
  33. package/build/src/http-server/server-lock.js +22 -109
  34. package/package.json +1 -1
  35. package/src/configuration-types.js +12 -1
  36. package/src/configuration.js +174 -18
  37. package/src/database/advisory-lock-backend-policy.js +204 -0
  38. package/src/database/advisory-lock-file-backend.js +348 -0
  39. package/src/database/advisory-lock-runner.js +239 -16
  40. package/src/environment-handlers/base.js +13 -0
  41. package/src/environment-handlers/node.js +11 -0
  42. package/src/http-server/server-lock.js +21 -115
package/README.md CHANGED
@@ -4,8 +4,7 @@
4
4
  * Database framework with familiar MVC concepts
5
5
  * Database models with migrations and validations
6
6
  * Database models that work almost the same in frontend and backend, including online CRUD for [composite primary keys](docs/composite-primary-keys.md)
7
- * Connection-scoped advisory locks with automatic cleanup before pooled connections are reused or closed, a non-throwing `withAdvisoryLockOrDefer` result for contended hot paths, and event-driven slow acquire/hold duration telemetry with holder attribution (see [docs/advisory-locks.md](docs/advisory-locks.md)) (see [docs/advisory-locks.md](docs/advisory-locks.md))
8
- * Built-in record auditing for model lifecycle changes (see [docs/auditing.md](docs/auditing.md))
7
+ * Connection-scoped advisory locks with automatic cleanup before pooled connections are reused or closed, a non-throwing `withAdvisoryLockOrDefer` result for contended hot paths, event-driven slow acquire/hold duration telemetry with holder attribution, and an explicitly opt-in file-lock fallback tier with per-lock-name minimum-tier enforcement and acquisition provenance (see [docs/advisory-locks.md](docs/advisory-locks.md) and [docs/advisory-lock-backends.md](docs/advisory-lock-backends.md))* Built-in record auditing for model lifecycle changes (see [docs/auditing.md](docs/auditing.md))
9
8
  * Declarative state machines for models, with typed event methods generated into the base model (see [docs/state-machine.md](docs/state-machine.md))
10
9
  * Migrations for schema changes and UTC datetime storage, including caller-selected `pre-runtime` and `post-publication` execution sets and recorded `changeTable` batches that combine operations into one `ALTER` on bulk-capable drivers (see [docs/database-migrations.md](docs/database-migrations.md), [docs/migration-execution-phases.md](docs/migration-execution-phases.md), and [docs/change-table.md](docs/change-table.md))
11
10
  * Tenant-selected base-model and structure generation with one immutable, fail-closed physical database context; tenant-only model metadata initializes only after that context is active (see [docs/tenant-selected-database-generation.md](docs/tenant-selected-database-generation.md))
@@ -329,7 +329,7 @@
329
329
  * @property {string} [host] - Hostname to bind the HTTP server to.
330
330
  * @property {boolean} [inProcess] - Run HTTP handlers in the main thread instead of worker threads.
331
331
  * @property {number} [maxBufferedResponseBodyBytes] - Maximum UTF-8/binary byte length accepted by buffered response bodies. Unbounded when absent; streamed file responses are unaffected.
332
- * @property {number} [maxRequestBodyBytes] - Maximum decoded request-body bytes accepted before routing. Unbounded when absent.
332
+ * @property {number} [maxRequestBodyBytes] - Maximum decoded request-body bytes accepted before routing. Unbounded when absent, except the built-in MCP endpoint, which defaults to a 1 MiB cap that this option overrides.
333
333
  * @property {HttpRequestBodyPolicyResolver} [requestBodyPolicyResolver] - Optional synchronous header-stage resolver for per-request limits and raw-body handling.
334
334
  * @property {number} [maxWorkers] - Backward-compatible alias for workers.
335
335
  * @property {number} [port] - Port to bind the HTTP server to.
@@ -780,6 +780,16 @@
780
780
  * @property {(args: {configuration: import("./configuration.js").default, databaseConfiguration: DatabaseConfigurationType, identifier: string, migrationsApplied: number, tenant: ReturnType<typeof JSON.parse>}) => void | Promise<void>} [afterMigrateTenant] - Runs app-owned tenant work after generic migrations for one tenant. `migrationsApplied` is how many migrations actually ran (0 when the tenant was already up to date), so the app can skip expensive per-tenant work on no-op deploys.
781
781
  */
782
782
 
783
+ /**
784
+ * Advisory-lock backend chain configuration (STC-210 design §10, file tier
785
+ * implemented by STC-213). Everything defaults to today's driver-native-only
786
+ * behavior; the file backend is disabled by default and only selectable by
787
+ * explicit configuration.
788
+ * @typedef {object} AdvisoryLocksConfiguration
789
+ * @property {{file?: {directory?: string, enabled?: boolean, leaseMs?: number, renewIntervalMs?: number}}} [backends] - Backend enablement. `file.enabled` defaults to false; enabling it is the deployment's explicit single-host declaration.
790
+ * @property {import("./database/advisory-lock-backend-policy.js").AdvisoryLockBackendPolicyEntry[]} [policy] - Per-lock-name minimum/allowed/preferred tier rules (design §5).
791
+ */
792
+
783
793
  /**
784
794
  * @typedef {object} ConfigurationArgsType
785
795
  * @property {boolean} [autoload] - Globally enable auto-batch-preload of relationships on lazy access. Default true.
@@ -787,6 +797,7 @@
787
797
  * @property {string} [cookieSecret] - Secret for encrypting cookies.
788
798
  * @property {AbilityResourceClassType[]} [abilityResources] - Resource classes used to define abilities per model.
789
799
  * @property {AbilityResolverType} [abilityResolver] - Resolver for creating request-scoped ability instances.
800
+ * @property {AdvisoryLocksConfiguration} [advisoryLocks] - Advisory-lock backend chain configuration (backends + per-lock-name tier policy). Defaults to today's driver-native-only behavior.
790
801
  * @property {AttachmentsConfiguration} [attachments] - Attachment storage configuration.
791
802
  * @property {BackendProjectConfiguration[]} [backendProjects] - Backend project definitions used for frontend model generation.
792
803
  * @property {VelociousPackageConfiguration[]} [packages] - External Velocious packages that contribute models, frontend-model resources and migrations.
@@ -45,6 +45,7 @@ import VelociousPackage from "./packages/velocious-package.js"
45
45
  import FrontendTenantSqliteLifecycle from "./tenants/frontend-tenant-sqlite-lifecycle.js"
46
46
  import { resolveGenerationId, resolveInitialGenerationState, resolveLifecycleSocketPath } from "./background-jobs/generation-identity.js"
47
47
  import { runShutdownSteps } from "./utils/shutdown-lifecycle.js"
48
+ import { resolveAdvisoryLockBackendPolicy } from "./database/advisory-lock-backend-policy.js"
48
49
 
49
50
  export { CurrentConfigurationNotSetError }
50
51
 
@@ -228,6 +229,14 @@ function normalizeHttpCompression(value) {
228
229
  }
229
230
  }
230
231
 
232
+ /**
233
+ * Default request-body limit for the built-in MCP endpoint. JSON-RPC messages are small,
234
+ * so the framework caps them instead of making every app that enables `mcp: true` restate
235
+ * a request-body policy. Explicit `httpServer.maxRequestBodyBytes` or a resolver limit wins.
236
+ * @type {number}
237
+ */
238
+ const DEFAULT_MCP_MAX_REQUEST_BODY_BYTES = 1024 * 1024
239
+
231
240
  export default class VelociousConfiguration {
232
241
  /**
233
242
  * Close database connections promise.
@@ -245,6 +254,20 @@ export default class VelociousConfiguration {
245
254
  * @type {Set<import("./database/drivers/base.js").default>} */
246
255
  _advisoryLockConnections = new Set()
247
256
 
257
+ /**
258
+ * Lazily created file-tier advisory-lock backend (STC-213). Stays `undefined`
259
+ * unless `advisoryLocks.backends.file.enabled: true` is explicitly configured —
260
+ * the file tier is never auto-enabled, and a non-Node environment handler
261
+ * (browser/Expo, no `fs`) cannot create one at all.
262
+ * @type {import("./database/advisory-lock-file-backend.js").default | undefined} */
263
+ _advisoryLockFileBackend = undefined
264
+
265
+ /**
266
+ * Most recent advisory-lock acquisition per lock name — the "which backend
267
+ * served this lock" surface (design §3).
268
+ * @type {Map<string, {backend: import("./database/advisory-lock-backend-policy.js").AdvisoryLockTier, fencingSupported: boolean, servedAt: string}>} */
269
+ _advisoryLockAcquisitions = new Map()
270
+
248
271
  /** @type {Map<string, number>} */
249
272
  _schemaCacheGenerationsByReuseKey = new Map()
250
273
 
@@ -260,11 +283,12 @@ export default class VelociousConfiguration {
260
283
  * Runs constructor.
261
284
  * @param {import("./configuration-types.js").ConfigurationArgsType} args - Configuration arguments.
262
285
  */
263
- constructor({abilityResolver, abilityResources, attachments, autoload = true, backgroundJobs, backendProjects, beacon, cookieSecret, cors, database, debug = false, debugEndpoint = false, apiManifest = false, directory, enforceTenantDatabaseScopes = true, environment, environmentHandler, exposeInternalErrorsToClients, frontendTenantSqlite, httpServer, initializeModels, initializers, locale, localeFallbacks, locales, logging, mailerBackend, mcp = false, packages, requestTimeoutMs, routeResolverHooks, scheduledBackgroundJobs, secureFrontendModelErrors, structureSql, sync, tenantDatabaseProviders, tenantDatabaseResolver, tenantResolver, testTenantPools, testing, timeZone, timezoneOffsetMinutes, trustedProxies, websocketChannelResolver, websocketMessageHandlerResolver, ...restArgs}) {
286
+ constructor({abilityResolver, abilityResources, advisoryLocks, attachments, autoload = true, backgroundJobs, backendProjects, beacon, cookieSecret, cors, database, debug = false, debugEndpoint = false, apiManifest = false, directory, enforceTenantDatabaseScopes = true, environment, environmentHandler, exposeInternalErrorsToClients, frontendTenantSqlite, httpServer, initializeModels, initializers, locale, localeFallbacks, locales, logging, mailerBackend, mcp = false, packages, requestTimeoutMs, routeResolverHooks, scheduledBackgroundJobs, secureFrontendModelErrors, structureSql, sync, tenantDatabaseProviders, tenantDatabaseResolver, tenantResolver, testTenantPools, testing, timeZone, timezoneOffsetMinutes, trustedProxies, websocketChannelResolver, websocketMessageHandlerResolver, ...restArgs}) {
264
287
  restArgsError(restArgs)
265
288
 
266
289
  this._abilityResolver = abilityResolver
267
290
  this._abilityResources = abilityResources || []
291
+ this._advisoryLocks = advisoryLocks
268
292
  this._autoload = autoload
269
293
  this._backgroundJobs = backgroundJobs
270
294
  this._beacon = beacon
@@ -760,31 +784,58 @@ export default class VelociousConfiguration {
760
784
  resolveHttpRequestBodyPolicy(args) {
761
785
  const resolver = this.httpServer.requestBodyPolicyResolver
762
786
  const configuredPolicy = resolver ? resolver(args) : undefined
787
+ /** @type {import("./configuration-types.js").ResolvedHttpRequestBodyPolicy} */
788
+ let resolvedPolicy
763
789
 
764
790
  if (configuredPolicy === undefined) {
765
- return {maxRequestBodyBytes: this.httpServer.maxRequestBodyBytes, mode: "parsed"}
766
- }
791
+ resolvedPolicy = {maxRequestBodyBytes: this.httpServer.maxRequestBodyBytes, mode: "parsed"}
792
+ } else {
793
+ if (!configuredPolicy || typeof configuredPolicy !== "object" || Array.isArray(configuredPolicy)) {
794
+ throw new TypeError("httpServer.requestBodyPolicyResolver must return an object or undefined")
795
+ }
767
796
 
768
- if (!configuredPolicy || typeof configuredPolicy !== "object" || Array.isArray(configuredPolicy)) {
769
- throw new TypeError("httpServer.requestBodyPolicyResolver must return an object or undefined")
770
- }
797
+ const {maxRequestBodyBytes, mode = "parsed", ...restPolicy} = configuredPolicy
798
+ const unknownKeys = Object.keys(restPolicy)
771
799
 
772
- const {maxRequestBodyBytes, mode = "parsed", ...restPolicy} = configuredPolicy
773
- const unknownKeys = Object.keys(restPolicy)
800
+ if (unknownKeys.length > 0) {
801
+ throw new TypeError(`httpServer.requestBodyPolicyResolver returned unknown keys: ${unknownKeys.join(", ")} (supported: maxRequestBodyBytes, mode)`)
802
+ }
803
+ if (mode !== "parsed" && mode !== "raw") {
804
+ throw new TypeError(`httpServer.requestBodyPolicyResolver mode must be "parsed" or "raw", got: ${String(mode)}`)
805
+ }
774
806
 
775
- if (unknownKeys.length > 0) {
776
- throw new TypeError(`httpServer.requestBodyPolicyResolver returned unknown keys: ${unknownKeys.join(", ")} (supported: maxRequestBodyBytes, mode)`)
777
- }
778
- if (mode !== "parsed" && mode !== "raw") {
779
- throw new TypeError(`httpServer.requestBodyPolicyResolver mode must be "parsed" or "raw", got: ${String(mode)}`)
807
+ resolvedPolicy = {
808
+ maxRequestBodyBytes: maxRequestBodyBytes === undefined
809
+ ? this.httpServer.maxRequestBodyBytes
810
+ : optionalPositiveSafeInteger(maxRequestBodyBytes, "httpServer.requestBodyPolicyResolver maxRequestBodyBytes"),
811
+ mode
812
+ }
780
813
  }
781
814
 
782
- return {
783
- maxRequestBodyBytes: maxRequestBodyBytes === undefined
784
- ? this.httpServer.maxRequestBodyBytes
785
- : optionalPositiveSafeInteger(maxRequestBodyBytes, "httpServer.requestBodyPolicyResolver maxRequestBodyBytes"),
786
- mode
815
+ return this._applyMcpRequestBodyPolicyDefaults({args, policy: resolvedPolicy})
816
+ }
817
+
818
+ /**
819
+ * Enforces the built-in MCP endpoint's body contract without per-app plumbing: the
820
+ * JSON-RPC envelope is read from parsed params, so raw mode is rejected with an
821
+ * actionable error, and a framework default byte cap applies when the app configured none.
822
+ * @param {{args: import("./configuration-types.js").HttpRequestBodyPolicyResolverArgs, policy: import("./configuration-types.js").ResolvedHttpRequestBodyPolicy}} options - Resolution inputs.
823
+ * @returns {import("./configuration-types.js").ResolvedHttpRequestBodyPolicy} - Effective request policy.
824
+ */
825
+ _applyMcpRequestBodyPolicyDefaults({args, policy}) {
826
+ if (!this._mcp.enabled) return policy
827
+ if (args.httpMethod !== "POST") return policy
828
+ if (args.path.split("?")[0] !== this._mcp.path) return policy
829
+
830
+ if (policy.mode === "raw") {
831
+ throw new TypeError(
832
+ `The built-in MCP endpoint at ${this._mcp.path} requires parsed request bodies because its JSON-RPC envelope is read from params. Remove the raw-mode httpServer.requestBodyPolicyResolver entry for this path.`
833
+ )
787
834
  }
835
+
836
+ if (policy.maxRequestBodyBytes !== undefined) return policy
837
+
838
+ return {maxRequestBodyBytes: DEFAULT_MCP_MAX_REQUEST_BODY_BYTES, mode: policy.mode}
788
839
  }
789
840
 
790
841
  /**
@@ -4076,6 +4127,102 @@ export default class VelociousConfiguration {
4076
4127
  })
4077
4128
  }
4078
4129
 
4130
+ /**
4131
+ * Resolves the `advisoryLocks` configuration block (STC-210 design §10).
4132
+ * Full backward compatibility: an app that configures nothing gets today's
4133
+ * driver-native-only behavior — the file backend is **disabled by default**
4134
+ * and only ever selectable by explicit configuration.
4135
+ * @returns {{backends: {file: {directory?: string, enabled: boolean, leaseMs: number, renewIntervalMs: number}}, policy: import("./database/advisory-lock-backend-policy.js").AdvisoryLockBackendPolicyEntry[]}} - Advisory-lock configuration with defaults applied.
4136
+ */
4137
+ getAdvisoryLockConfig() {
4138
+ const configured = this._advisoryLocks || {}
4139
+ const fileConfigured = configured.backends?.file || {}
4140
+
4141
+ return {
4142
+ backends: {
4143
+ file: {
4144
+ directory: fileConfigured.directory,
4145
+ enabled: fileConfigured.enabled === true,
4146
+ leaseMs: typeof fileConfigured.leaseMs === "number" ? fileConfigured.leaseMs : 30_000,
4147
+ renewIntervalMs: typeof fileConfigured.renewIntervalMs === "number" ? fileConfigured.renewIntervalMs : 10_000
4148
+ }
4149
+ },
4150
+ policy: Array.isArray(configured.policy) ? configured.policy : []
4151
+ }
4152
+ }
4153
+
4154
+ /**
4155
+ * Runs get advisory lock policy.
4156
+ * @returns {import("./database/advisory-lock-backend-policy.js").AdvisoryLockBackendPolicyEntry[]} - Per-lock-name backend policy entries.
4157
+ */
4158
+ getAdvisoryLockPolicy() {
4159
+ return this.getAdvisoryLockConfig().policy
4160
+ }
4161
+
4162
+ /**
4163
+ * Resolves the effective backend policy for one lock name (design §5).
4164
+ * @param {string} lockName - Concrete lock name.
4165
+ * @returns {import("./database/advisory-lock-backend-policy.js").ResolvedAdvisoryLockBackendPolicy} - Resolved policy.
4166
+ */
4167
+ resolveAdvisoryLockPolicy(lockName) {
4168
+ return resolveAdvisoryLockBackendPolicy(lockName, this.getAdvisoryLockPolicy())
4169
+ }
4170
+
4171
+ /**
4172
+ * Returns the file-tier advisory-lock backend when this deployment has
4173
+ * explicitly enabled it (`advisoryLocks.backends.file.enabled: true`),
4174
+ * creating it on first use. Returns `undefined` when the tier is disabled
4175
+ * (the default) — callers must never fall back to it implicitly. Creation
4176
+ * goes through the environment handler so browser/Expo configurations
4177
+ * without `fs` fail loudly instead of half-working.
4178
+ * @returns {Promise<import("./database/advisory-lock-file-backend.js").default | undefined>} - Resolves with the enabled file backend, or undefined.
4179
+ */
4180
+ async getAdvisoryLockFileBackend() {
4181
+ const config = this.getAdvisoryLockConfig()
4182
+
4183
+ if (!config.backends.file.enabled) return undefined
4184
+ if (this._advisoryLockFileBackend) return this._advisoryLockFileBackend
4185
+
4186
+ const directory = config.backends.file.directory || `${this.getDirectory()}/tmp/advisory-locks`
4187
+
4188
+ this._advisoryLockFileBackend = await this.getEnvironmentHandler().createAdvisoryLockFileBackend({
4189
+ directory,
4190
+ leaseMs: config.backends.file.leaseMs,
4191
+ renewIntervalMs: config.backends.file.renewIntervalMs
4192
+ })
4193
+
4194
+ return this._advisoryLockFileBackend
4195
+ }
4196
+
4197
+ /**
4198
+ * Records which backend tier served one advisory-lock acquisition so
4199
+ * `getAdvisoryLockBackendStatus()` can answer "which backend served this
4200
+ * lock" (design §3).
4201
+ * @param {object} args - Acquisition record.
4202
+ * @param {string} args.lockName - Lock name.
4203
+ * @param {import("./database/advisory-lock-backend-policy.js").AdvisoryLockTier} args.backend - Tier that served the acquisition.
4204
+ * @param {boolean} args.fencingSupported - Whether the serving tier carries fencing tokens.
4205
+ * @returns {void}
4206
+ */
4207
+ recordAdvisoryLockAcquisition({lockName, backend, fencingSupported}) {
4208
+ this._advisoryLockAcquisitions.set(lockName, {backend, fencingSupported, servedAt: new Date().toISOString()})
4209
+ }
4210
+
4211
+ /**
4212
+ * The "which backend served this lock" diagnostics surface (design §3):
4213
+ * per lock name, the tier of the most recent acquisition, whether that tier
4214
+ * carries fencing tokens, and the resolved policy (minimum/allowed/preferred
4215
+ * tiers) for the name.
4216
+ * @param {string} lockName - Lock name.
4217
+ * @returns {{acquisition: {backend: import("./database/advisory-lock-backend-policy.js").AdvisoryLockTier, fencingSupported: boolean, servedAt: string} | null, policy: import("./database/advisory-lock-backend-policy.js").ResolvedAdvisoryLockBackendPolicy}} - Backend status for the name.
4218
+ */
4219
+ getAdvisoryLockBackendStatus(lockName) {
4220
+ return {
4221
+ acquisition: this._advisoryLockAcquisitions.get(lockName) ?? null,
4222
+ policy: this.resolveAdvisoryLockPolicy(lockName)
4223
+ }
4224
+ }
4225
+
4079
4226
  /**
4080
4227
  * Registers a dedicated connection that currently holds an advisory lock, so a
4081
4228
  * shutdown can close it and release the lock. See `_advisoryLockConnections`.
@@ -4155,6 +4302,15 @@ export default class VelociousConfiguration {
4155
4302
  // leave the rest of the connections open.
4156
4303
  await this._closeAdvisoryLockConnections()
4157
4304
  } finally {
4305
+ try {
4306
+ // Release file-tier advisory-lock holds explicitly (STC-213): the
4307
+ // lease would make them reclaimable anyway, but a clean shutdown
4308
+ // should not leave lock directories behind for the staleness path.
4309
+ await this._advisoryLockFileBackend?.releaseAllHeld()
4310
+ } catch (error) {
4311
+ closeErrors.push(error instanceof Error ? error : new Error(String(error)))
4312
+ }
4313
+
4158
4314
  for (const pool of Object.values(this.databasePools)) {
4159
4315
  if (!pool) continue
4160
4316
 
@@ -0,0 +1,204 @@
1
+ // @ts-check
2
+
3
+ /**
4
+ * Advisory-lock backend tiers (STC-210 design, `docs/advisory-lock-backends.md` §1/§9).
5
+ * `process-local` and `file` are host-local; `driver-native` and `lock-server` are
6
+ * cross-host. Tier strength order (strongest first):
7
+ * `lock-server` ≡ `driver-native` > `file` > `process-local`.
8
+ * @typedef {"process-local" | "file" | "driver-native" | "lock-server"} AdvisoryLockTier
9
+ */
10
+ /**
11
+ * One per-lock-name backend policy entry as declared in configuration (§5).
12
+ * @typedef {object} AdvisoryLockBackendPolicyEntry
13
+ * @property {string} name - Lock name or `*`-suffixed glob pattern (e.g. `background_jobs:*`).
14
+ * @property {AdvisoryLockTier} [minTier] - Weakest tier this name may ever be served by. Defaults to `driver-native` (default-deny).
15
+ * @property {AdvisoryLockTier[]} [allowedTiers] - Explicit whitelist of servable tiers. Defaults to every tier at or above `minTier`.
16
+ * @property {AdvisoryLockTier} [preferredTier] - Tier used when available; falling below it triggers the fallback report (§3). Defaults to `driver-native`.
17
+ */
18
+ /**
19
+ * Policy resolved for one concrete lock name, with tier gaps already closed:
20
+ * `allowedTiers` always contains every tier at or above `minTier`, so a
21
+ * cross-host-minimum name can never be served by `file` or `process-local`.
22
+ * @typedef {object} ResolvedAdvisoryLockBackendPolicy
23
+ * @property {AdvisoryLockTier} minTier - Weakest tier this name may be served by.
24
+ * @property {AdvisoryLockTier[]} allowedTiers - Tiers that may serve this name (minimum-closed).
25
+ * @property {AdvisoryLockTier} preferredTier - Tier preferred when available.
26
+ * @property {AdvisoryLockBackendPolicyEntry | null} entry - The matched configuration entry, or null for the default policy.
27
+ */
28
+
29
+ /**
30
+ * Thrown when an acquisition would have to be served by a tier below the
31
+ * lock name's declared minimum tier. Fail-closed refusal (§9): the name is
32
+ * never served by the weaker tier, and the refusal is reported on the
33
+ * framework-error channel as `advisory-lock-min-tier-refused`.
34
+ */
35
+ export class AdvisoryLockMinTierRefusedError extends Error {
36
+ /**
37
+ * Runs constructor.
38
+ * @param {string} message - Error message.
39
+ * @param {{lockName: string, requestedBackend: AdvisoryLockTier, minTier: AdvisoryLockTier}} args - Refusal details.
40
+ */
41
+ constructor(message, {lockName, requestedBackend, minTier}) {
42
+ super(message)
43
+ this.name = "AdvisoryLockMinTierRefusedError"
44
+ this.lockName = lockName
45
+ this.requestedBackend = requestedBackend
46
+ this.minTier = minTier
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Thrown when no enabled backend that satisfies the lock name's minimum tier
52
+ * is available (§9). Distinct from `AdvisoryLockTimeoutError` (a backend
53
+ * served the wait but the holder never released).
54
+ */
55
+ export class AdvisoryLockBackendUnavailableError extends Error {
56
+ /**
57
+ * Runs constructor.
58
+ * @param {string} message - Error message.
59
+ * @param {{lockName: string, minTier: AdvisoryLockTier, reasons: string[]}} args - Unavailability details.
60
+ */
61
+ constructor(message, {lockName, minTier, reasons}) {
62
+ super(message)
63
+ this.name = "AdvisoryLockBackendUnavailableError"
64
+ this.lockName = lockName
65
+ this.minTier = minTier
66
+ this.reasons = reasons
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Tier strength ranks (§9): higher rank is stronger. `lock-server` and
72
+ * `driver-native` are both cross-host and rank equal.
73
+ * @type {Record<AdvisoryLockTier, number>} */
74
+ const TIER_RANKS = {
75
+ "driver-native": 2,
76
+ file: 1,
77
+ "lock-server": 3,
78
+ "process-local": 0
79
+ }
80
+
81
+ /** All tiers ordered strongest-first. */
82
+ const TIERS_STRONGEST_FIRST = /** @type {AdvisoryLockTier[]} */ (["lock-server", "driver-native", "file", "process-local"])
83
+
84
+ /**
85
+ * Runs tier rank.
86
+ * @param {AdvisoryLockTier} tier - Tier to rank.
87
+ * @returns {number} - Strength rank (higher is stronger).
88
+ */
89
+ export function advisoryLockTierRank(tier) {
90
+ const rank = TIER_RANKS[tier]
91
+
92
+ if (rank === undefined) throw new Error(`Unknown advisory-lock tier ${JSON.stringify(String(tier))}`)
93
+
94
+ return rank
95
+ }
96
+
97
+ /**
98
+ * Runs tier is at least as strong as.
99
+ * @param {AdvisoryLockTier} tier - Candidate serving tier.
100
+ * @param {AdvisoryLockTier} minimum - Required minimum tier.
101
+ * @returns {boolean} - Whether `tier` satisfies the minimum.
102
+ */
103
+ export function advisoryLockTierSatisfies(tier, minimum) {
104
+ return advisoryLockTierRank(tier) >= advisoryLockTierRank(minimum)
105
+ }
106
+
107
+ /**
108
+ * Resolves the effective backend policy for one concrete lock name:
109
+ * longest-prefix glob match over the configured entries (exact names win),
110
+ * default-deny for undeclared names (`minTier: driver-native`,
111
+ * `preferredTier: driver-native`), and `allowedTiers` closed upward so a
112
+ * cross-host minimum can never be served by a host-local tier.
113
+ * @param {string} lockName - Concrete lock name.
114
+ * @param {AdvisoryLockBackendPolicyEntry[] | undefined} policy - Configured policy entries.
115
+ * @returns {ResolvedAdvisoryLockBackendPolicy} - Resolved policy.
116
+ */
117
+ export function resolveAdvisoryLockBackendPolicy(lockName, policy) {
118
+ const entry = matchAdvisoryLockPolicyEntry(lockName, policy)
119
+ const minTier = entry?.minTier ?? "driver-native"
120
+ const preferredTier = entry?.preferredTier ?? "driver-native"
121
+
122
+ // §9: eligibility filters to tier strength >= minTier even when a weaker
123
+ // tier was declared in `allowedTiers` — a cross-host minimum can never be
124
+ // served by `file` or `process-local`. A `preferredTier` below the minimum
125
+ // stays visible here so the runner can refuse it loudly before contacting
126
+ // the weaker backend.
127
+ const declaredAllowed = entry?.allowedTiers
128
+ const allowedTiers = TIERS_STRONGEST_FIRST.filter((tier) => {
129
+ if (!advisoryLockTierSatisfies(tier, minTier)) return false
130
+
131
+ if (!Array.isArray(declaredAllowed)) return true
132
+
133
+ return declaredAllowed.includes(tier)
134
+ })
135
+
136
+ return {allowedTiers, entry: entry ?? null, minTier, preferredTier}
137
+ }
138
+
139
+ /**
140
+ * Matches one policy entry for a lock name: exact `name` matches win;
141
+ * otherwise the longest `*`-suffixed prefix pattern wins.
142
+ * @param {string} lockName - Concrete lock name.
143
+ * @param {AdvisoryLockBackendPolicyEntry[] | undefined} policy - Configured policy entries.
144
+ * @returns {AdvisoryLockBackendPolicyEntry | null} - Matched entry or null.
145
+ */
146
+ function matchAdvisoryLockPolicyEntry(lockName, policy) {
147
+ if (!Array.isArray(policy)) return null
148
+
149
+ let bestPrefixMatch = null
150
+ let bestPrefixLength = -1
151
+
152
+ for (const entry of policy) {
153
+ if (typeof entry?.name !== "string") continue
154
+
155
+ if (entry.name === lockName) return entry
156
+
157
+ if (entry.name.endsWith("*")) {
158
+ const prefix = entry.name.slice(0, -1)
159
+
160
+ if (lockName.startsWith(prefix) && prefix.length > bestPrefixLength) {
161
+ bestPrefixMatch = entry
162
+ bestPrefixLength = prefix.length
163
+ }
164
+ }
165
+ }
166
+
167
+ return bestPrefixMatch
168
+ }
169
+
170
+ /**
171
+ * Refuses a downgrade below the lock name's minimum tier before any contact
172
+ * with the weaker backend (§9), reporting the refusal on the framework-error
173
+ * channel so a silent downgrade is impossible to hide.
174
+ * @param {object} args - Refusal args.
175
+ * @param {import("../configuration.js").default} args.configuration - Configuration owning the error channel.
176
+ * @param {string} args.lockName - Lock name.
177
+ * @param {AdvisoryLockTier} args.requestedBackend - Tier the acquisition would fall to.
178
+ * @param {AdvisoryLockTier} args.minTier - Declared minimum tier.
179
+ * @returns {never} - Always throws.
180
+ */
181
+ export function refuseAdvisoryLockTierBelowMinimum({configuration, lockName, requestedBackend, minTier}) {
182
+ const error = new AdvisoryLockMinTierRefusedError(
183
+ `Advisory lock ${JSON.stringify(lockName)} requires minimum tier ${JSON.stringify(minTier)}; the ${JSON.stringify(requestedBackend)} tier is refused. Enable a cross-host backend or declare minTier: "file" for this lock name (single-host deployments only).`,
184
+ {lockName, minTier, requestedBackend}
185
+ )
186
+
187
+ configuration.getErrorEvents().emit("framework-error", {
188
+ context: "advisory-lock-min-tier-refused",
189
+ error,
190
+ lockName,
191
+ minTier,
192
+ requestedBackend
193
+ })
194
+ configuration.getErrorEvents().emit("all-error", {
195
+ context: "advisory-lock-min-tier-refused",
196
+ error,
197
+ errorType: "framework-error",
198
+ lockName,
199
+ minTier,
200
+ requestedBackend
201
+ })
202
+
203
+ throw error
204
+ }