velocious 1.0.730 → 1.0.732

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.
@@ -21,7 +21,7 @@ import {
21
21
  rescheduledBackgroundJobAtMs,
22
22
  retryDelayMs
23
23
  } from "./job-semantics.js"
24
- import {buildQueuePriorityOrderSql} from "./queue-priority-order.js"
24
+ import {buildLaneFairnessOrderSql, buildQueuePriorityOrderSql} from "./queue-priority-order.js"
25
25
 
26
26
  export const LOCAL_BACKGROUND_JOBS_TABLE = "velocious_local_background_jobs"
27
27
  export const LOCAL_BACKGROUND_JOB_CONCURRENCY_TABLE = "velocious_local_background_job_concurrency"
@@ -67,7 +67,7 @@ const EXPECTED_JOB_COLUMNS = [
67
67
  "child_pid",
68
68
  "runner_hostname"
69
69
  ]
70
- const EXPECTED_CONCURRENCY_COLUMNS = ["concurrency_key", "max_concurrency", "active_count"]
70
+ const EXPECTED_CONCURRENCY_COLUMNS = ["concurrency_key", "max_concurrency", "active_count", "last_claimed_at_ms"]
71
71
  const EXPECTED_SCHEDULE_KEY_COLUMNS = ["schedule_key", "job_id"]
72
72
  /** @type {WeakMap<import("../configuration.js").default, Map<string, Promise<void>>>} */
73
73
  const deduplicatedEnqueueChains = new WeakMap()
@@ -228,6 +228,7 @@ export default class LocalBackgroundJobsStore {
228
228
  await db.createTable(this._concurrencyTableData())
229
229
  changed = true
230
230
  } else {
231
+ if (await this._ensureConcurrencyColumns(db)) changed = true
231
232
  await this._assertColumns(db, LOCAL_BACKGROUND_JOB_CONCURRENCY_TABLE, EXPECTED_CONCURRENCY_COLUMNS)
232
233
  }
233
234
 
@@ -258,12 +259,35 @@ export default class LocalBackgroundJobsStore {
258
259
  * @returns {Promise<boolean>} - Whether a column was added.
259
260
  */
260
261
  async _ensureJobColumns(db) {
262
+ return await this._ensureMissingColumns(db, LOCAL_BACKGROUND_JOBS_TABLE, this._jobsTableData())
263
+ }
264
+
265
+ /**
266
+ * Idempotently adds the concurrency-table columns an existing local table is missing,
267
+ * so an upgraded framework keeps its live counters instead of failing the assertion.
268
+ * @param {import("../database/drivers/base.js").default} db - Local SQLite connection.
269
+ * @returns {Promise<boolean>} - Whether a column was added.
270
+ */
271
+ async _ensureConcurrencyColumns(db) {
272
+ return await this._ensureMissingColumns(db, LOCAL_BACKGROUND_JOB_CONCURRENCY_TABLE, this._concurrencyTableData())
273
+ }
274
+
275
+ /**
276
+ * Idempotently adds columns from the current table definition that an existing local
277
+ * table is missing, so an upgraded framework finds a compatible schema instead of
278
+ * failing the column assertion.
279
+ * @param {import("../database/drivers/base.js").default} db - Local SQLite connection.
280
+ * @param {string} tableName - Table to upgrade.
281
+ * @param {TableData} definition - Current definition whose columns are required.
282
+ * @returns {Promise<boolean>} - Whether a column was added.
283
+ */
284
+ async _ensureMissingColumns(db, tableName, definition) {
261
285
  db.clearSchemaCache()
262
- const table = await db.getTableByNameOrFail(LOCAL_BACKGROUND_JOBS_TABLE)
263
- const tableData = new TableData(LOCAL_BACKGROUND_JOBS_TABLE)
286
+ const table = await db.getTableByNameOrFail(tableName)
287
+ const tableData = new TableData(tableName)
264
288
  let added = false
265
289
 
266
- for (const column of this._jobsTableData().getColumns()) {
290
+ for (const column of definition.getColumns()) {
267
291
  if (await table.getColumnByName(column.getName())) continue
268
292
  if (column.getPrimaryKey()) continue
269
293
 
@@ -355,6 +379,7 @@ export default class LocalBackgroundJobsStore {
355
379
  table.string("concurrency_key", {null: false, primaryKey: true})
356
380
  table.integer("max_concurrency", {null: false})
357
381
  table.integer("active_count", {null: false})
382
+ table.bigint("last_claimed_at_ms", {null: true})
358
383
  return table
359
384
  }
360
385
 
@@ -913,7 +938,17 @@ export default class LocalBackgroundJobsStore {
913
938
  `${concurrencyTable}.${db.quoteColumn("active_count")} < ${concurrencyTable}.${db.quoteColumn("max_concurrency")}))`
914
939
  )
915
940
 
916
- if (priorityOrder) query = query.order(`${priorityOrder} DESC`)
941
+ if (priorityOrder) {
942
+ query = query.order(`${priorityOrder} DESC`)
943
+
944
+ // The aging term levels every aged lane onto the same ceiling rank, so at the
945
+ // ceiling the configured priority no longer separates lanes and the claim would
946
+ // fall through to `scheduled_at_ms` — permanently won by whichever lane holds the
947
+ // deepest aged backlog. Break that tie by lane service instead.
948
+ const laneFairnessOrder = this._laneFairnessOrderSql(db, nowMs)
949
+
950
+ if (laneFairnessOrder) query = query.order(laneFairnessOrder)
951
+ }
917
952
 
918
953
  const rows = await query
919
954
  .order("scheduled_at_ms ASC")
@@ -1005,6 +1040,8 @@ export default class LocalBackgroundJobsStore {
1005
1040
  return null
1006
1041
  }
1007
1042
 
1043
+ await this._recordLaneClaim(db, job.concurrencyKey, handedOffAtMs)
1044
+
1008
1045
  return {handedOffAtMs, handoffId}
1009
1046
  }))
1010
1047
  }
@@ -1348,6 +1385,24 @@ export default class LocalBackgroundJobsStore {
1348
1385
  return affectedRows === 1
1349
1386
  }
1350
1387
 
1388
+ /**
1389
+ * Stamps the instant a lane received a claim so {@link _laneFairnessOrderSql} can break the
1390
+ * aging-ceiling tie by lane service rather than by backlog age. Only queue-derived counters
1391
+ * name a lane: an explicit `concurrencyKey` groups unrelated jobs, so stamping it would
1392
+ * couple lanes the queue configuration never joined.
1393
+ * @param {import("../database/drivers/base.js").default} db - Connection.
1394
+ * @param {string | null} concurrencyKey - Concurrency key of the job that just claimed.
1395
+ * @param {number} claimedAtMs - Claim instant.
1396
+ * @returns {Promise<void>} - Resolves when the lane counter is stamped.
1397
+ */
1398
+ async _recordLaneClaim(db, concurrencyKey, claimedAtMs) {
1399
+ if (!concurrencyKey || !concurrencyKey.startsWith(QUEUE_CONCURRENCY_KEY_PREFIX)) return
1400
+
1401
+ const table = db.quoteTable(LOCAL_BACKGROUND_JOB_CONCURRENCY_TABLE)
1402
+
1403
+ await db.query(`UPDATE ${table} SET ${db.quoteColumn("last_claimed_at_ms")} = ${Number(claimedAtMs)} WHERE ${db.quoteColumn("concurrency_key")} = ${db.quote(concurrencyKey)}`)
1404
+ }
1405
+
1351
1406
  /**
1352
1407
  * Releases one slot for a concurrency key.
1353
1408
  * @param {import("../database/drivers/base.js").default} db - Connection.
@@ -1412,6 +1467,23 @@ export default class LocalBackgroundJobsStore {
1412
1467
  return buildQueuePriorityOrderSql({configuration: this.configuration, db, nowMs})
1413
1468
  }
1414
1469
 
1470
+ /**
1471
+ * Builds the lane-fairness tie-break for the queued-job claim. See
1472
+ * {@link buildLaneFairnessOrderSql} for the ranking contract.
1473
+ * @param {import("../database/drivers/base.js").default} db - Connection.
1474
+ * @param {number} nowMs - Dispatch instant.
1475
+ * @returns {string | null} - Raw SQL `ORDER BY … DESC` term, or null when not applicable.
1476
+ */
1477
+ _laneFairnessOrderSql(db, nowMs) {
1478
+ return buildLaneFairnessOrderSql({
1479
+ configuration: this.configuration,
1480
+ db,
1481
+ nowMs,
1482
+ jobsTable: db.quoteTable(LOCAL_BACKGROUND_JOBS_TABLE),
1483
+ concurrencyTable: db.quoteTable(LOCAL_BACKGROUND_JOB_CONCURRENCY_TABLE)
1484
+ })
1485
+ }
1486
+
1415
1487
  /**
1416
1488
  * Checks whether a persisted handoff owns the supplied acknowledgement fence.
1417
1489
  * @param {import("./types.js").BackgroundJobRow | null} job - Persisted job.
@@ -94,3 +94,40 @@ export function buildQueuePriorityOrderSql({configuration, db, nowMs}) {
94
94
  `CASE WHEN ${scheduledAtColumn} <= (${db.quote(nowMs)} - ${agingCap}) THEN ${agingCap} ` +
95
95
  `ELSE (${db.quote(nowMs)} - ${scheduledAtColumn}) END)`
96
96
  }
97
+
98
+ /**
99
+ * Builds the lane-fairness tie-break term for the queued-job claim: how long the candidate's
100
+ * own lane has gone without receiving a claim, longest-starved-first.
101
+ *
102
+ * Reaching the aging ceiling is not the same as winning the claim. Because every lane converges
103
+ * on the same ceiling, all aged lanes tie, and a tie broken by `scheduled_at_ms` is won
104
+ * permanently by whichever lane holds the deepest aged backlog: a lane with one fresh row is
105
+ * only served when the backlog lane reaches its own `maxConcurrent` cap, which never happens
106
+ * when that cap is far above what the fleet can actually run. Ordering by time-since-last-claim
107
+ * makes the ceiling tie alternate between starved lanes.
108
+ *
109
+ * Intra-lane order is untouched, because every row of one lane shares the same counter row and
110
+ * the term is therefore constant within a lane. Lanes with no counter row (an uncapped queue)
111
+ * fall back to the row's own eligible wait, which reproduces the previous `scheduled_at_ms ASC`
112
+ * ordering exactly.
113
+ *
114
+ * Returns null when aging is opted out (`queuePriorityAgingUnitMs: null`): opting out asks for
115
+ * strict queue-priority ordering, so no time-based reordering is applied.
116
+ * @param {object} args - Options.
117
+ * @param {import("../configuration.js").default} args.configuration - Active configuration.
118
+ * @param {import("../database/drivers/base.js").default} args.db - Connection.
119
+ * @param {number} args.nowMs - Dispatch instant.
120
+ * @param {string} args.jobsTable - Quoted jobs table name.
121
+ * @param {string} args.concurrencyTable - Quoted concurrency counter table name.
122
+ * @returns {string | null} - Raw SQL `ORDER BY … DESC` term, or null when not applicable.
123
+ */
124
+ export function buildLaneFairnessOrderSql({configuration, db, nowMs, jobsTable, concurrencyTable}) {
125
+ if (queuePriorityAgingUnitMs(configuration) === null) return null
126
+
127
+ const keyColumn = db.quoteColumn("concurrency_key")
128
+ const lastClaimedLookup =
129
+ `(SELECT ${concurrencyTable}.${db.quoteColumn("last_claimed_at_ms")} FROM ${concurrencyTable} ` +
130
+ `WHERE ${concurrencyTable}.${keyColumn} = ${jobsTable}.${keyColumn})`
131
+
132
+ return `(${Number(nowMs)} - COALESCE(${lastClaimedLookup}, ${jobsTable}.${db.quoteColumn("scheduled_at_ms")})) DESC`
133
+ }
@@ -27,7 +27,7 @@ import {
27
27
  rescheduledBackgroundJobAtMs,
28
28
  retryDelayMs
29
29
  } from "./job-semantics.js"
30
- import {buildQueuePriorityOrderSql} from "./queue-priority-order.js"
30
+ import {buildLaneFairnessOrderSql, buildQueuePriorityOrderSql} from "./queue-priority-order.js"
31
31
  import {
32
32
  MAIL_DELIVERY_OPERATIONS_TABLE,
33
33
  mailDeliveryOperationForJob,
@@ -1218,7 +1218,17 @@ export default class BackgroundJobsStore extends BackgroundJobsAdapter {
1218
1218
  if (scheduledAtOperator === "<=") {
1219
1219
  const priorityOrder = this._queuePriorityOrderSql(db, now)
1220
1220
 
1221
- if (priorityOrder) query = query.order(`${priorityOrder} DESC`)
1221
+ if (priorityOrder) {
1222
+ query = query.order(`${priorityOrder} DESC`)
1223
+
1224
+ // The aging term levels every aged lane onto the same ceiling rank, so at the
1225
+ // ceiling the configured priority no longer separates lanes and the claim would
1226
+ // fall through to `scheduled_at_ms` — permanently won by whichever lane holds the
1227
+ // deepest aged backlog. Break that tie by lane service instead.
1228
+ const laneFairnessOrder = this._laneFairnessOrderSql(db, now)
1229
+
1230
+ if (laneFairnessOrder) query = query.order(laneFairnessOrder)
1231
+ }
1222
1232
 
1223
1233
  // Job-level priority applies inside the queue ranking above. A retry is
1224
1234
  // stored at RETRY_BACKGROUND_JOB_PRIORITY (-1), so it sorts behind every
@@ -1259,6 +1269,23 @@ export default class BackgroundJobsStore extends BackgroundJobsAdapter {
1259
1269
  return buildQueuePriorityOrderSql({configuration: this.configuration, db, nowMs})
1260
1270
  }
1261
1271
 
1272
+ /**
1273
+ * Builds the lane-fairness tie-break for the queued-job claim. See
1274
+ * {@link buildLaneFairnessOrderSql} for the ranking contract.
1275
+ * @param {import("../database/drivers/base.js").default} db - Connection.
1276
+ * @param {number} nowMs - Dispatch instant.
1277
+ * @returns {string | null} - Raw SQL `ORDER BY … DESC` term, or null when not applicable.
1278
+ */
1279
+ _laneFairnessOrderSql(db, nowMs) {
1280
+ return buildLaneFairnessOrderSql({
1281
+ configuration: this.configuration,
1282
+ db,
1283
+ nowMs,
1284
+ jobsTable: db.quoteTable(JOBS_TABLE),
1285
+ concurrencyTable: db.quoteTable(CONCURRENCY_TABLE)
1286
+ })
1287
+ }
1288
+
1262
1289
  /**
1263
1290
  * Reads the per-lane dispatch boundary for every queue holding eligible queued work:
1264
1291
  * backlog depth, the oldest eligible row, and how many jobs that lane actually claimed
@@ -1501,6 +1528,7 @@ export default class BackgroundJobsStore extends BackgroundJobsAdapter {
1501
1528
  return null
1502
1529
  }
1503
1530
 
1531
+ await this._recordLaneClaim(db, queuedJob.concurrencyKey, handedOffAtMs)
1504
1532
  await this._recordStatusTransition(db, "queued", "handed_off")
1505
1533
  /** @type {import("./types.js").BackgroundJobRow} */
1506
1534
  const handedOffJob = {
@@ -3642,14 +3670,47 @@ export default class BackgroundJobsStore extends BackgroundJobsAdapter {
3642
3670
  * @returns {Promise<void>} - Resolves when ready.
3643
3671
  */
3644
3672
  async _ensureConcurrencyTable(db) {
3645
- if (await db.tableExists(CONCURRENCY_TABLE)) return
3673
+ if (await db.tableExists(CONCURRENCY_TABLE)) {
3674
+ await this._ensureConcurrencyTableColumns(db)
3675
+ return
3676
+ }
3646
3677
  const table = new TableData(CONCURRENCY_TABLE, {ifNotExists: true})
3647
3678
  table.string("concurrency_key", {primaryKey: true})
3648
3679
  table.integer("max_concurrency", {null: false})
3649
3680
  table.integer("active_count", {null: false})
3681
+ table.bigint("last_claimed_at_ms", {null: true})
3650
3682
  await db.createTable(table)
3651
3683
  }
3652
3684
 
3685
+ /**
3686
+ * Idempotently adds the lane-service stamp column to a concurrency table created by an
3687
+ * earlier framework version. Existing counters carry live `active_count` values, so the
3688
+ * column is added in place under the same advisory lock the jobs-table column adds use.
3689
+ * @param {import("../database/drivers/base.js").default} db - Database connection.
3690
+ * @returns {Promise<void>} - Resolves when the column is present.
3691
+ */
3692
+ async _ensureConcurrencyTableColumns(db) {
3693
+ const lockName = `${MIGRATION_SCOPE}:concurrency_last_claimed_column`
3694
+ const acquired = await db.acquireAdvisoryLock(lockName)
3695
+
3696
+ if (!acquired) throw new Error("Failed to acquire background jobs lane-claim schema lock")
3697
+
3698
+ try {
3699
+ db.clearSchemaCache()
3700
+ const table = await db.getTableByNameOrFail(CONCURRENCY_TABLE)
3701
+
3702
+ if (!(await table.getColumnByName("last_claimed_at_ms"))) {
3703
+ const tableData = new TableData(CONCURRENCY_TABLE)
3704
+ tableData.bigint("last_claimed_at_ms", {null: true})
3705
+
3706
+ for (const sql of await db.alterTableSQLs(tableData)) await db.query(sql)
3707
+ db.clearSchemaCache()
3708
+ }
3709
+ } finally {
3710
+ await db.releaseAdvisoryLock(lockName)
3711
+ }
3712
+ }
3713
+
3653
3714
  /**
3654
3715
  * Ensures the stable schedule-key ownership table exists.
3655
3716
  * @param {import("../database/drivers/base.js").default} db - Database connection.
@@ -3970,6 +4031,24 @@ export default class BackgroundJobsStore extends BackgroundJobsAdapter {
3970
4031
  return affectedRows === 1
3971
4032
  }
3972
4033
 
4034
+ /**
4035
+ * Stamps the instant a lane received a claim so {@link _laneFairnessOrderSql} can break the
4036
+ * aging-ceiling tie by lane service rather than by backlog age. Only queue-derived counters
4037
+ * name a lane: an explicit `concurrencyKey` groups unrelated jobs, so stamping it would
4038
+ * couple lanes the queue configuration never joined.
4039
+ * @param {import("../database/drivers/base.js").default} db - Database connection.
4040
+ * @param {string | null} concurrencyKey - Concurrency key of the job that just claimed.
4041
+ * @param {number} claimedAtMs - Claim instant.
4042
+ * @returns {Promise<void>} - Resolves when the lane counter is stamped.
4043
+ */
4044
+ async _recordLaneClaim(db, concurrencyKey, claimedAtMs) {
4045
+ if (!concurrencyKey || !concurrencyKey.startsWith(QUEUE_CONCURRENCY_KEY_PREFIX)) return
4046
+
4047
+ const table = db.quoteTable(CONCURRENCY_TABLE)
4048
+
4049
+ await db.query(`UPDATE ${table} SET ${db.quoteColumn("last_claimed_at_ms")} = ${Number(claimedAtMs)} WHERE ${db.quoteColumn("concurrency_key")} = ${db.quote(concurrencyKey)}`)
4050
+ }
4051
+
3973
4052
  /**
3974
4053
  * Runs a portable update and returns its affected-row count.
3975
4054
  * @param {import("../database/drivers/base.js").default} db - Database connection.
@@ -65,6 +65,9 @@ export default class VelociousDatabaseDriversMysql extends Base{
65
65
  /** @type {import("mysql").Pool | undefined} */
66
66
  pool = undefined
67
67
 
68
+ /** @type {Map<string, import("../base.js").default>} */
69
+ _advisoryLockConnections = new Map()
70
+
68
71
  /** @type {string | null} */
69
72
  _desiredSessionTimeZone = "+00:00"
70
73
 
@@ -94,6 +97,20 @@ export default class VelociousDatabaseDriversMysql extends Base{
94
97
  * @returns {Promise<void>} - Resolves when complete.
95
98
  */
96
99
  async _close() {
100
+ for (const [lockName, connection] of this._advisoryLockConnections) {
101
+ this._advisoryLockConnections.delete(lockName)
102
+
103
+ if (connection === this) continue
104
+
105
+ try {
106
+ this.configuration.unregisterAdvisoryLockConnection(connection)
107
+ } catch {
108
+ // The configuration may already be closing its registered connections.
109
+ }
110
+
111
+ await connection.close()
112
+ }
113
+
97
114
  const pool = this.pool
98
115
 
99
116
  if (!pool) return
@@ -931,14 +948,25 @@ export default class VelociousDatabaseDriversMysql extends Base{
931
948
  const timeoutSeconds = typeof timeoutMs === "number" && timeoutMs >= 0
932
949
  ? Math.ceil(timeoutMs / 1000)
933
950
  : MYSQL_INDEFINITE_LOCK_TIMEOUT_SECONDS
934
- const rows = await this.query(`SELECT GET_LOCK(${this.quote(name)}, ${timeoutSeconds}) AS velocious_advisory_lock_result`)
935
- const result = rows?.[0]?.velocious_advisory_lock_result
951
+ const connection = await this.advisoryLockConnection(name)
936
952
 
937
- if (result === null || result === undefined) {
938
- throw new Error(`GET_LOCK returned NULL for advisory lock ${JSON.stringify(name)} (typically an out-of-memory or thread-killed condition)`)
939
- }
953
+ try {
954
+ const rows = await connection.query(`SELECT GET_LOCK(${this.quote(name)}, ${timeoutSeconds}) AS velocious_advisory_lock_result`)
955
+ const result = rows?.[0]?.velocious_advisory_lock_result
956
+
957
+ if (result === null || result === undefined) {
958
+ throw new Error(`GET_LOCK returned NULL for advisory lock ${JSON.stringify(name)} (typically an out-of-memory or thread-killed condition)`)
959
+ }
960
+
961
+ const acquired = Number(result) === 1
962
+
963
+ if (!acquired) await this.closeAdvisoryLockConnection(name, connection)
940
964
 
941
- return Number(result) === 1
965
+ return acquired
966
+ } catch (error) {
967
+ await this.closeAdvisoryLockConnection(name, connection)
968
+ throw error
969
+ }
942
970
  }
943
971
 
944
972
  /**
@@ -947,14 +975,25 @@ export default class VelociousDatabaseDriversMysql extends Base{
947
975
  * @returns {Promise<boolean>} - True if the lock was acquired, false if it was already held.
948
976
  */
949
977
  async _tryAcquireAdvisoryLock(name) {
950
- const rows = await this.query(`SELECT GET_LOCK(${this.quote(name)}, 0) AS velocious_advisory_lock_result`)
951
- const result = rows?.[0]?.velocious_advisory_lock_result
978
+ const connection = await this.advisoryLockConnection(name)
952
979
 
953
- if (result === null || result === undefined) {
954
- throw new Error(`GET_LOCK returned NULL for advisory lock ${JSON.stringify(name)} (typically an out-of-memory or thread-killed condition)`)
955
- }
980
+ try {
981
+ const rows = await connection.query(`SELECT GET_LOCK(${this.quote(name)}, 0) AS velocious_advisory_lock_result`)
982
+ const result = rows?.[0]?.velocious_advisory_lock_result
983
+
984
+ if (result === null || result === undefined) {
985
+ throw new Error(`GET_LOCK returned NULL for advisory lock ${JSON.stringify(name)} (typically an out-of-memory or thread-killed condition)`)
986
+ }
956
987
 
957
- return Number(result) === 1
988
+ const acquired = Number(result) === 1
989
+
990
+ if (!acquired) await this.closeAdvisoryLockConnection(name, connection)
991
+
992
+ return acquired
993
+ } catch (error) {
994
+ await this.closeAdvisoryLockConnection(name, connection)
995
+ throw error
996
+ }
958
997
  }
959
998
 
960
999
  /**
@@ -963,10 +1002,72 @@ export default class VelociousDatabaseDriversMysql extends Base{
963
1002
  * @returns {Promise<boolean>} - True if the lock was held by this session and has now been released.
964
1003
  */
965
1004
  async _releaseAdvisoryLock(name) {
966
- const rows = await this.query(`SELECT RELEASE_LOCK(${this.quote(name)}) AS velocious_advisory_lock_result`, {retry: false})
967
- const result = rows?.[0]?.velocious_advisory_lock_result
1005
+ const connection = this._advisoryLockConnections.get(name)
1006
+
1007
+ if (!connection) return false
1008
+
1009
+ try {
1010
+ const rows = await connection.query(`SELECT RELEASE_LOCK(${this.quote(name)}) AS velocious_advisory_lock_result`, {retry: false})
1011
+ const result = rows?.[0]?.velocious_advisory_lock_result
1012
+
1013
+ // Base#releaseAdvisoryLock removes one re-entrant count after this hook.
1014
+ // Keep the session for another counted release, but close it after the
1015
+ // final release so an idle pool connection cannot retain the lock.
1016
+ if ((this._heldAdvisoryLocks.get(name) || 0) <= 1) await this.closeAdvisoryLockConnection(name, connection)
1017
+
1018
+ return Number(result) === 1
1019
+ } catch (error) {
1020
+ await this.closeAdvisoryLockConnection(name, connection)
1021
+ throw error
1022
+ }
1023
+ }
1024
+
1025
+ /**
1026
+ * Opens one physical session for the named advisory lock and keeps it pinned
1027
+ * until the matching release. The model driver's ordinary queries continue
1028
+ * using its own pool, while GET_LOCK and RELEASE_LOCK are guaranteed to run
1029
+ * on the same MariaDB session.
1030
+ * @param {string} name - Lock name.
1031
+ * @returns {Promise<import("../base.js").default>} - Pinned lock connection.
1032
+ */
1033
+ async advisoryLockConnection(name) {
1034
+ const existing = this._advisoryLockConnections.get(name)
1035
+
1036
+ if (existing) return existing
1037
+
1038
+ // Lightweight driver doubles used by SQL-generation specs do not have a
1039
+ // configuration-owned pool. They already provide a stable query session.
1040
+ if (typeof this.configuration?.getDatabasePool !== "function") {
1041
+ this._advisoryLockConnections.set(name, this)
1042
+
1043
+ return this
1044
+ }
1045
+
1046
+ const connection = await this.configuration.getDatabasePool(this._databaseIdentifier || "default").spawnConnection()
1047
+
1048
+ this._advisoryLockConnections.set(name, connection)
1049
+ this.configuration.registerAdvisoryLockConnection(connection)
1050
+
1051
+ return connection
1052
+ }
1053
+
1054
+ /**
1055
+ * Closes the physical session owned by one advisory lock.
1056
+ * @param {string} name - Lock name.
1057
+ * @param {import("../base.js").default} connection - Pinned lock connection.
1058
+ * @returns {Promise<void>} - Resolves after unregistering and closing it.
1059
+ */
1060
+ async closeAdvisoryLockConnection(name, connection) {
1061
+ if (connection === this) {
1062
+ this._advisoryLockConnections.delete(name)
1063
+
1064
+ return
1065
+ }
1066
+ if (this._advisoryLockConnections.get(name) !== connection) return
968
1067
 
969
- return Number(result) === 1
1068
+ this._advisoryLockConnections.delete(name)
1069
+ this.configuration.unregisterAdvisoryLockConnection(connection)
1070
+ await connection.close()
970
1071
  }
971
1072
 
972
1073
  /**