velocious 1.0.509 → 1.0.511

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 (49) hide show
  1. package/README.md +1 -0
  2. package/build/configuration-types.js +7 -0
  3. package/build/configuration.js +74 -2
  4. package/build/database/advisory-lock-runner.js +192 -0
  5. package/build/database/drivers/mysql/index.js +3 -0
  6. package/build/database/record/index.js +23 -111
  7. package/build/database/tenants/schema-cloner.js +49 -13
  8. package/build/frontend-models/resource-definition.js +144 -0
  9. package/build/routes/built-in/api-manifest/controller.js +14 -0
  10. package/build/src/configuration-types.d.ts +21 -1
  11. package/build/src/configuration-types.d.ts.map +1 -1
  12. package/build/src/configuration-types.js +7 -1
  13. package/build/src/configuration.d.ts +35 -2
  14. package/build/src/configuration.d.ts.map +1 -1
  15. package/build/src/configuration.js +68 -3
  16. package/build/src/database/advisory-lock-runner.d.ts +124 -0
  17. package/build/src/database/advisory-lock-runner.d.ts.map +1 -0
  18. package/build/src/database/advisory-lock-runner.js +176 -0
  19. package/build/src/database/drivers/mysql/index.d.ts +2 -2
  20. package/build/src/database/drivers/mysql/index.d.ts.map +1 -1
  21. package/build/src/database/drivers/mysql/index.js +3 -1
  22. package/build/src/database/record/attachments/handle.d.ts +1 -1
  23. package/build/src/database/record/index.d.ts +13 -61
  24. package/build/src/database/record/index.d.ts.map +1 -1
  25. package/build/src/database/record/index.js +24 -108
  26. package/build/src/database/tenants/schema-cloner.d.ts +11 -1
  27. package/build/src/database/tenants/schema-cloner.d.ts.map +1 -1
  28. package/build/src/database/tenants/schema-cloner.js +45 -13
  29. package/build/src/frontend-models/resource-definition.d.ts +9 -0
  30. package/build/src/frontend-models/resource-definition.d.ts.map +1 -1
  31. package/build/src/frontend-models/resource-definition.js +130 -1
  32. package/build/src/routes/built-in/api-manifest/controller.d.ts +9 -0
  33. package/build/src/routes/built-in/api-manifest/controller.d.ts.map +1 -0
  34. package/build/src/routes/built-in/api-manifest/controller.js +13 -0
  35. package/build/src/sync/sync-envelope-replay-service.d.ts +1 -1
  36. package/build/src/sync/sync-replay-upsert-applier.d.ts +2 -2
  37. package/build/src/sync/sync-resource-base.js +3 -3
  38. package/build/sync/sync-resource-base.js +2 -2
  39. package/build/tsconfig.tsbuildinfo +1 -1
  40. package/package.json +1 -1
  41. package/src/configuration-types.js +7 -0
  42. package/src/configuration.js +74 -2
  43. package/src/database/advisory-lock-runner.js +192 -0
  44. package/src/database/drivers/mysql/index.js +3 -0
  45. package/src/database/record/index.js +23 -111
  46. package/src/database/tenants/schema-cloner.js +49 -13
  47. package/src/frontend-models/resource-definition.js +144 -0
  48. package/src/routes/built-in/api-manifest/controller.js +14 -0
  49. package/src/sync/sync-resource-base.js +2 -2
@@ -31,6 +31,9 @@ import Update from "./sql/update.js"
31
31
  const MYSQL_INDEFINITE_LOCK_TIMEOUT_SECONDS = 60 * 60 * 24 * 365
32
32
 
33
33
  export default class VelociousDatabaseDriversMysql extends Base{
34
+ /** @type {import("mysql").Pool | undefined} */
35
+ pool = undefined
36
+
34
37
  /** @type {string | null} */
35
38
  _desiredSessionTimeZone = "+00:00"
36
39
 
@@ -24,7 +24,7 @@
24
24
 
25
25
  /** @typedef {import("../../configuration-types.js").TenantDatabaseProviderType} TenantDatabaseProviderType */
26
26
 
27
- import timeout from "awaitery/build/timeout.js"
27
+ import AdvisoryLockRunner, {AdvisoryLockBusyError, AdvisoryLockHoldTimeoutError, AdvisoryLockTimeoutError} from "../advisory-lock-runner.js"
28
28
  import BelongsToInstanceRelationship from "./instance-relationships/belongs-to.js"
29
29
  import BelongsToRelationship from "./relationships/belongs-to.js"
30
30
  import Configuration from "../../configuration.js"
@@ -164,60 +164,6 @@ function buildRelatedRecordWithInverse(parent, relationshipName, attributes, all
164
164
  return record
165
165
  }
166
166
 
167
- /**
168
- * Thrown by `Record.withAdvisoryLock` when the caller supplied a
169
- * `timeoutMs` and the lock was not granted before it elapsed.
170
- */
171
- class AdvisoryLockTimeoutError extends Error {
172
- /**
173
- * Runs constructor.
174
- * @param {string} message - Error message.
175
- * @param {{name: string}} args - The advisory lock name that timed out.
176
- */
177
- constructor(message, {name}) {
178
- super(message)
179
- this.name = "AdvisoryLockTimeoutError"
180
- this.lockName = name
181
- }
182
- }
183
-
184
- /**
185
- * Thrown by `Record.withAdvisoryLockOrFail` when the lock is already held
186
- * by another session at the moment of the call.
187
- */
188
- class AdvisoryLockBusyError extends Error {
189
- /**
190
- * Runs constructor.
191
- * @param {string} message - Error message.
192
- * @param {{name: string}} args - The advisory lock name that was already held.
193
- */
194
- constructor(message, {name}) {
195
- super(message)
196
- this.name = "AdvisoryLockBusyError"
197
- this.lockName = name
198
- }
199
- }
200
-
201
- /**
202
- * Thrown by `Record.withAdvisoryLock` / `withAdvisoryLockOrFail` when the
203
- * caller supplied a `holdTimeoutMs` and the callback ran longer than it. The
204
- * lock is released before this is thrown, so a hung holder can't block other
205
- * sessions indefinitely. Note: the callback itself is not cancelled — pass an
206
- * AbortSignal to the work if it needs to stop.
207
- */
208
- class AdvisoryLockHoldTimeoutError extends Error {
209
- /**
210
- * Runs constructor.
211
- * @param {string} message - Error message.
212
- * @param {{name: string}} args - The advisory lock name whose hold timed out.
213
- */
214
- constructor(message, {name}) {
215
- super(message)
216
- this.name = "AdvisoryLockHoldTimeoutError"
217
- this.lockName = name
218
- }
219
- }
220
-
221
167
  class TenantDatabaseScopeError extends Error {
222
168
  /**
223
169
  * Runs constructor.
@@ -2675,10 +2621,13 @@ class VelociousDatabaseRecord {
2675
2621
  }
2676
2622
 
2677
2623
  /**
2678
- * Runs the callback while holding a named advisory lock on the current
2679
- * connection. Advisory locks are cooperative and connection-scoped: they
2680
- * serialize callers that opt into the same `name`, without touching row
2681
- * or table locks, so unrelated traffic is free to proceed.
2624
+ * Runs the callback while holding a named advisory lock. Calls without
2625
+ * a positive `holdTimeoutMs` use the caller connection; calls with a positive
2626
+ * `holdTimeoutMs` use a dedicated lock connection so timeout cleanup can
2627
+ * release the lock even when callback database work is stuck. Advisory locks
2628
+ * are cooperative and session-scoped: they serialize callers that opt into
2629
+ * the same `name`, without touching row or table locks, so unrelated traffic
2630
+ * is free to proceed.
2682
2631
  *
2683
2632
  * The lock is acquired before the callback runs and released in a
2684
2633
  * `finally` block afterwards, so the callback's return value is
@@ -2694,18 +2643,13 @@ class VelociousDatabaseRecord {
2694
2643
  static async withAdvisoryLock(name, callback, args = {}) {
2695
2644
  await this.ensureInitialized()
2696
2645
 
2697
- const connection = this.connection()
2698
- const acquired = await connection.acquireAdvisoryLock(name, args)
2699
-
2700
- if (!acquired) {
2701
- throw new AdvisoryLockTimeoutError(`Timed out waiting for advisory lock ${JSON.stringify(name)}`, {name})
2702
- }
2646
+ const runner = new AdvisoryLockRunner({
2647
+ configuration: this._getConfiguration(),
2648
+ connectionProvider: () => this.connection(),
2649
+ databaseIdentifier: this.getDatabaseIdentifier()
2650
+ })
2703
2651
 
2704
- try {
2705
- return await this.runWithAdvisoryLockHoldTimeout(name, callback, args.holdTimeoutMs)
2706
- } finally {
2707
- await connection.releaseAdvisoryLock(name)
2708
- }
2652
+ return await runner.withAdvisoryLock(name, callback, args)
2709
2653
  }
2710
2654
 
2711
2655
  /**
@@ -2725,31 +2669,19 @@ class VelociousDatabaseRecord {
2725
2669
  static async withAdvisoryLockOrFail(name, callback, args = {}) {
2726
2670
  await this.ensureInitialized()
2727
2671
 
2728
- const connection = this.connection()
2729
- const acquired = await connection.tryAcquireAdvisoryLock(name)
2730
-
2731
- if (!acquired) {
2732
- throw new AdvisoryLockBusyError(`Advisory lock ${JSON.stringify(name)} is already held`, {name})
2733
- }
2672
+ const runner = new AdvisoryLockRunner({
2673
+ configuration: this._getConfiguration(),
2674
+ connectionProvider: () => this.connection(),
2675
+ databaseIdentifier: this.getDatabaseIdentifier()
2676
+ })
2734
2677
 
2735
- try {
2736
- return await this.runWithAdvisoryLockHoldTimeout(name, callback, args.holdTimeoutMs)
2737
- } finally {
2738
- await connection.releaseAdvisoryLock(name)
2739
- }
2678
+ return await runner.withAdvisoryLockOrFail(name, callback, args)
2740
2679
  }
2741
2680
 
2742
2681
  /**
2743
2682
  * Runs `callback`, rejecting with `AdvisoryLockHoldTimeoutError` if it has
2744
- * not settled within `holdTimeoutMs`. The caller's `finally` then releases
2745
- * the lock, so a hung holder can't block other sessions forever. The
2746
- * callback is not cancelled — this is a safety net, not cancellation.
2747
- *
2748
- * Uses `awaitery`'s shared `timeout` helper for the hard timeout, then
2749
- * translates its timeout into the typed `AdvisoryLockHoldTimeoutError` so
2750
- * callers can catch it like the other advisory-lock errors. A `callbackSettled`
2751
- * flag distinguishes the timeout from a rejection thrown by the callback
2752
- * itself, which is rethrown unchanged.
2683
+ * not settled within `holdTimeoutMs`. The callback is not cancelled — this is
2684
+ * a safety net, not cancellation.
2753
2685
  * @template T
2754
2686
  * @param {string} name - Lock name (for the error message).
2755
2687
  * @param {() => Promise<T>} callback - Callback holding the lock.
@@ -2757,27 +2689,7 @@ class VelociousDatabaseRecord {
2757
2689
  * @returns {Promise<T>}
2758
2690
  */
2759
2691
  static async runWithAdvisoryLockHoldTimeout(name, callback, holdTimeoutMs) {
2760
- if (!holdTimeoutMs || holdTimeoutMs <= 0) {
2761
- return await callback()
2762
- }
2763
-
2764
- let callbackSettled = false
2765
-
2766
- try {
2767
- return await timeout({timeout: holdTimeoutMs}, async () => {
2768
- try {
2769
- return await callback()
2770
- } finally {
2771
- callbackSettled = true
2772
- }
2773
- })
2774
- } catch (error) {
2775
- if (!callbackSettled) {
2776
- throw new AdvisoryLockHoldTimeoutError(`Advisory lock ${JSON.stringify(name)} held longer than ${holdTimeoutMs}ms`, {name})
2777
- }
2778
-
2779
- throw error
2780
- }
2692
+ return await AdvisoryLockRunner.runWithAdvisoryLockHoldTimeout(name, callback, holdTimeoutMs)
2781
2693
  }
2782
2694
 
2783
2695
  /**
@@ -152,7 +152,8 @@ export default class SchemaCloner {
152
152
 
153
153
  /**
154
154
  * Creates non-primary-key indexes present on the source but missing from the target,
155
- * and throws if an existing target index diverges from the source.
155
+ * and replaces target indexes whose definition (columns or uniqueness) drifted from
156
+ * the source.
156
157
  * @param {{sourceTable: import("../drivers/base-table.js").default, tableName: string}} args
157
158
  * @returns {Promise<void>}
158
159
  */
@@ -161,7 +162,7 @@ export default class SchemaCloner {
161
162
  /** @type {Map<string, import("../drivers/base-columns-index.js").default>} */
162
163
  const targetIndexesByName = new Map()
163
164
  const targetIndexSignatures = new Set()
164
- let createdIndex = false
165
+ let dirty = false
165
166
 
166
167
  for (const targetIndex of await targetTable.getIndexes()) {
167
168
  targetIndexesByName.set(targetIndex.getName(), targetIndex)
@@ -183,28 +184,63 @@ export default class SchemaCloner {
183
184
 
184
185
  const targetIndex = this.targetDb.getType() === "sqlite" ? undefined : targetIndexesByName.get(sourceIndex.getName())
185
186
 
186
- if (!targetIndex) {
187
- const createIndexSqls = await this.targetDb.createIndexSQLs(this.createIndexArgsFromSourceIndex({sourceIndex, tableName}))
188
-
189
- for (const createIndexSql of createIndexSqls) {
190
- await this.targetDb.query(createIndexSql)
187
+ if (targetIndex) {
188
+ if (!this.indexesMatch(sourceIndex, targetIndex)) {
189
+ // Replacing a non-unique index with a unique one is unsafe because
190
+ // the target may have duplicate values that will reject the new
191
+ // unique constraint, and the old index was already dropped by this
192
+ // point. The opposite direction (unique → non-unique) is always
193
+ // safe — non-unique indexes never fail on duplicate values.
194
+ if (sourceIndex.isUnique() && !targetIndex.isUnique()) {
195
+ throw new Error(`Schema clone index drift for ${tableName}.${sourceIndex.getName()}: cannot safely replace a non-unique index with a unique one.`)
196
+ }
197
+
198
+ await this.dropTargetIndex({tableName, targetIndex})
199
+ targetIndexesByName.delete(targetIndex.getName())
200
+ targetIndexSignatures.delete(this.indexSignature(targetIndex))
201
+ } else {
202
+ continue
191
203
  }
204
+ }
192
205
 
193
- createdIndex = true
194
- targetIndexSignatures.add(sourceIndexSignature)
195
- continue
206
+ // Drop any target index that shares the source name but survived the
207
+ // drift check above because the driver was skipped (SQLite).
208
+ const sameNameTargetIndex = targetIndexesByName.get(sourceIndex.getName())
209
+
210
+ if (sameNameTargetIndex) {
211
+ await this.dropTargetIndex({tableName, targetIndex: sameNameTargetIndex})
212
+ targetIndexesByName.delete(sameNameTargetIndex.getName())
213
+ targetIndexSignatures.delete(this.indexSignature(sameNameTargetIndex))
196
214
  }
197
215
 
198
- if (!this.indexesMatch(sourceIndex, targetIndex)) {
199
- throw new Error(`Schema clone index drift for ${tableName}.${sourceIndex.getName()}`)
216
+ const createIndexSqls = await this.targetDb.createIndexSQLs(this.createIndexArgsFromSourceIndex({sourceIndex, tableName}))
217
+
218
+ for (const createIndexSql of createIndexSqls) {
219
+ await this.targetDb.query(createIndexSql)
200
220
  }
221
+
222
+ dirty = true
223
+ targetIndexSignatures.add(sourceIndexSignature)
201
224
  }
202
225
 
203
- if (createdIndex) {
226
+ if (dirty) {
204
227
  this.targetDb.clearSchemaCache()
205
228
  }
206
229
  }
207
230
 
231
+ /**
232
+ * Drops an index on the target database.
233
+ * @param {{tableName: string, targetIndex: import("../drivers/base-columns-index.js").default}} args
234
+ * @returns {Promise<void>}
235
+ */
236
+ async dropTargetIndex({tableName, targetIndex}) {
237
+ const dropSqls = await this.targetDb.removeIndexSQLs({name: targetIndex.getName(), tableName})
238
+
239
+ for (const sql of dropSqls) {
240
+ await this.targetDb.query(sql)
241
+ }
242
+ }
243
+
208
244
  /**
209
245
  * Baselines the target ledger so the cloned schema is recorded as already-applied.
210
246
  * @returns {Promise<string[]>} The versions newly recorded on the target.
@@ -282,6 +282,150 @@ export function frontendModelSyncManifestForBackendProjects(backendProjects) {
282
282
  return manifest
283
283
  }
284
284
 
285
+ /**
286
+ * Builds a frontend-safe API manifest for all registered frontend-model
287
+ * resources. The manifest is deterministic (sorted model names, sorted
288
+ * attributes, sorted commands) and includes only public-safe metadata: no
289
+ * secrets, no server callbacks, no backend file paths.
290
+ * @param {import("../configuration-types.js").BackendProjectConfiguration[]} backendProjects - Backend projects to scan.
291
+ * @returns {Record<string, unknown>} - Frontend-safe API manifest.
292
+ */
293
+ export function frontendModelApiManifest(backendProjects) {
294
+ /** @type {Record<string, unknown>} */
295
+ const resources = {}
296
+
297
+ for (const backendProject of backendProjects) {
298
+ const projectResources = frontendModelResourcesForBackendProject(backendProject)
299
+
300
+ for (const configuredModelName of Object.keys(projectResources).sort()) {
301
+ const resourceDefinition = projectResources[configuredModelName]
302
+ const resourceConfiguration = frontendModelResourceConfigurationFromDefinition(resourceDefinition)
303
+
304
+ if (!resourceConfiguration) continue
305
+
306
+ const modelName = resourceConfiguration.modelName || configuredModelName
307
+ const resourcePath = `/${inflection.dasherize(inflection.pluralize(inflection.underscore(configuredModelName)))}`
308
+
309
+ /** @type {Record<string, unknown>} */
310
+ const entry = {
311
+ modelName,
312
+ path: resourcePath,
313
+ primaryKey: resourceConfiguration.primaryKey || "id",
314
+ attributes: manifestAttributes(resourceConfiguration.attributes),
315
+ abilities: resourceConfiguration.abilities,
316
+ builtInCommands: {
317
+ collection: resourceConfiguration.builtInCollectionCommands,
318
+ member: resourceConfiguration.builtInMemberCommands
319
+ }
320
+ }
321
+
322
+ const relationships = resourceConfiguration.relationships
323
+ if (relationships && relationships.length > 0) {
324
+ /** @type {Record<string, unknown>} */
325
+ const rels = {}
326
+ for (const relName of relationships) {
327
+ rels[relName] = {}
328
+ }
329
+ entry.relationships = rels
330
+ }
331
+
332
+ const attachments = resourceConfiguration.attachments
333
+ if (attachments && Object.keys(attachments).length > 0) {
334
+ entry.attachments = attachments
335
+ }
336
+
337
+ const collectionCommands = manifestCommandEntries({
338
+ commandMetadata: resourceConfiguration.commandMetadata || {},
339
+ commands: resourceConfiguration.collectionCommands,
340
+ resourcePath,
341
+ scope: "collection"
342
+ })
343
+ const memberCommands = manifestCommandEntries({
344
+ commandMetadata: resourceConfiguration.commandMetadata || {},
345
+ commands: resourceConfiguration.memberCommands,
346
+ resourcePath,
347
+ scope: "member"
348
+ })
349
+
350
+ if (collectionCommands.length > 0 || memberCommands.length > 0) {
351
+ /** @type {Record<string, unknown>} */
352
+ const cmds = {}
353
+ if (collectionCommands.length > 0) cmds["collection"] = collectionCommands
354
+ if (memberCommands.length > 0) cmds["member"] = memberCommands
355
+ entry.commands = cmds
356
+ }
357
+
358
+ if (resourceConfiguration.sync?.enabled) {
359
+ entry.sync = resourceConfiguration.sync
360
+ }
361
+
362
+ resources[configuredModelName] = entry
363
+ }
364
+ }
365
+
366
+ return {
367
+ formatVersion: 1,
368
+ resources: Object.keys(resources).sort().reduce((sorted, key) => {
369
+ /** @type {Record<string, unknown>} */ (sorted)[key] = resources[key]
370
+ return sorted
371
+ }, /** @type {Record<string, unknown>} */ ({}))
372
+ }
373
+ }
374
+
375
+ /**
376
+ * Normalizes resource attribute definitions into a sorted array of strings.
377
+ * @param {?} attributes - Raw attributes config (array or object).
378
+ * @returns {string[]} - Sorted attribute names.
379
+ */
380
+ function manifestAttributes(attributes) {
381
+ if (!attributes) return []
382
+
383
+ let names
384
+
385
+ if (Array.isArray(attributes)) {
386
+ names = attributes.map((entry) => typeof entry === "string" ? entry : entry.name).filter(Boolean)
387
+ } else if (attributes && typeof attributes === "object") {
388
+ names = Object.keys(attributes)
389
+ } else {
390
+ return []
391
+ }
392
+
393
+ return names.sort()
394
+ }
395
+
396
+ /**
397
+ * Builds manifest-safe command entry list.
398
+ * @param {object} args - Arguments.
399
+ * @param {Record<string, {args: Array<{name: string, type: string}>, returnType: string | null}>} args.commandMetadata - Per-command metadata.
400
+ * @param {Record<string, string>} args.commands - Method name → kebab slug map.
401
+ * @param {string} args.resourcePath - Resource path.
402
+ * @param {"collection" | "member"} args.scope - Command scope.
403
+ * @returns {Record<string, unknown>[]} - Manifest command entries.
404
+ */
405
+ function manifestCommandEntries({commandMetadata, commands, resourcePath, scope}) {
406
+ return Object.keys(commands).sort().map((methodName) => {
407
+ const slug = commands[methodName]
408
+ const metadata = commandMetadata[methodName] || {args: [], returnType: null}
409
+ const path = scope === "member"
410
+ ? `${resourcePath}/<id>/${slug}`
411
+ : `${resourcePath}/${slug}`
412
+
413
+ /** @type {Record<string, unknown>} */
414
+ const entry = {
415
+ methodName,
416
+ scope,
417
+ path,
418
+ args: metadata.args
419
+ }
420
+
421
+ if (metadata.returnType) {
422
+ entry.returnType = metadata.returnType
423
+ }
424
+
425
+ return entry
426
+ })
427
+ }
428
+
285
429
  /**
286
430
  * Normalizes sync policy metadata and computes a deterministic hash from safe policy inputs.
287
431
  * @param {import("../configuration-types.js").FrontendModelResourceConfiguration} resourceConfiguration - Raw resource configuration.
@@ -0,0 +1,14 @@
1
+ import Controller from "../../../controller.js"
2
+
3
+ export default class BuiltInApiManifestController extends Controller {
4
+ /**
5
+ * Runs show.
6
+ * @returns {Promise<void>} - Resolves when the manifest has been rendered.
7
+ */
8
+ async show() {
9
+ const manifest = await this.getConfiguration().getApiManifest()
10
+
11
+ this._response.setHeader("Content-Type", "application/json; charset=UTF-8")
12
+ this._response.setBody(`${JSON.stringify(manifest, null, 2)}\n`)
13
+ }
14
+ }
@@ -1,6 +1,6 @@
1
1
  // @ts-check
2
2
 
3
- import {forcedNonBlankStringParam} from "typanic"
3
+ import {forcedNonBlankString} from "typanic"
4
4
 
5
5
  import FrontendModelBaseResource from "../frontend-model-resource/base-resource.js"
6
6
  import SyncEnvelopeReplayService from "./sync-envelope-replay-service.js"
@@ -135,7 +135,7 @@ export default class SyncResourceBase extends FrontendModelBaseResource {
135
135
  }
136
136
 
137
137
  const scopeParams = /** @type {Record<string, ?>} */ (scope)
138
- const resourceType = forcedNonBlankStringParam(scopeParams, "resourceType")
138
+ const resourceType = forcedNonBlankString(scopeParams.resourceType, "resourceType")
139
139
  const conditions = scopeParams.conditions
140
140
 
141
141
  if (!conditions || typeof conditions !== "object" || Array.isArray(conditions)) {