@portqueue/core 1.0.1 → 1.0.2

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 (67) hide show
  1. package/README.md +5 -5
  2. package/dist/conformance/index.cjs +1 -1
  3. package/dist/conformance/index.mjs +1 -1
  4. package/dist/constants/storage.constants.d.ts +2 -2
  5. package/dist/drivers/driver-context.d.ts +1 -1
  6. package/dist/drivers/driver.interface.d.ts +1 -1
  7. package/dist/drivers/mysql/index.cjs +3 -3
  8. package/dist/drivers/mysql/index.cjs.map +1 -1
  9. package/dist/drivers/mysql/index.mjs +3 -3
  10. package/dist/drivers/mysql/index.mjs.map +1 -1
  11. package/dist/drivers/mysql/mysql-driver.d.ts +1 -1
  12. package/dist/drivers/oracle/index.cjs +3 -3
  13. package/dist/drivers/oracle/index.cjs.map +1 -1
  14. package/dist/drivers/oracle/index.mjs +3 -3
  15. package/dist/drivers/oracle/index.mjs.map +1 -1
  16. package/dist/drivers/oracle/oracle-driver.d.ts +1 -1
  17. package/dist/drivers/pglite/index.cjs +7 -7
  18. package/dist/drivers/pglite/index.cjs.map +1 -1
  19. package/dist/drivers/pglite/index.mjs +6 -6
  20. package/dist/drivers/pglite/index.mjs.map +1 -1
  21. package/dist/drivers/pglite/migrations.d.ts +2 -2
  22. package/dist/drivers/pglite/pglite-driver.d.ts +7 -7
  23. package/dist/drivers/postgresql/index.cjs +5 -0
  24. package/dist/drivers/postgresql/index.d.ts +2 -0
  25. package/dist/drivers/postgresql/index.mjs +5 -0
  26. package/dist/drivers/{postgres → postgresql}/migrations.d.ts +5 -5
  27. package/dist/drivers/{postgres/postgres-driver.d.ts → postgresql/postgresql-driver.d.ts} +7 -7
  28. package/dist/drivers/shared/base-driver.d.ts +4 -4
  29. package/dist/drivers/shared/migration-runner.service.d.ts +1 -1
  30. package/dist/drivers/sqlite/index.cjs +2 -2
  31. package/dist/drivers/sqlite/index.cjs.map +1 -1
  32. package/dist/drivers/sqlite/index.mjs +2 -2
  33. package/dist/drivers/sqlite/index.mjs.map +1 -1
  34. package/dist/drivers/table-names.d.ts +1 -1
  35. package/dist/index.cjs +2 -2
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.mjs +4 -4
  38. package/dist/index.mjs.map +1 -1
  39. package/dist/{migration-CWBCpwFH.cjs → migration-CoTjpgBl.cjs} +7 -7
  40. package/dist/migration-CoTjpgBl.cjs.map +1 -0
  41. package/dist/{migration-CQsAizIw.js → migration-D73ANkYV.js} +7 -7
  42. package/dist/migration-D73ANkYV.js.map +1 -0
  43. package/dist/options/enums.d.ts +1 -1
  44. package/dist/{postgres-driver-eWlY7pVg.js → postgresql-driver-BUHuyRYj.js} +14 -14
  45. package/dist/postgresql-driver-BUHuyRYj.js.map +1 -0
  46. package/dist/{postgres-driver-F9-TIi38.cjs → postgresql-driver-CIk94XCq.cjs} +14 -14
  47. package/dist/postgresql-driver-CIk94XCq.cjs.map +1 -0
  48. package/dist/{storage.constants-CIkf7BAJ.cjs → storage.constants-B5oQjxp5.cjs} +2 -2
  49. package/dist/storage.constants-B5oQjxp5.cjs.map +1 -0
  50. package/dist/{storage.constants-BDS_q-_N.js → storage.constants-DwSzjjMZ.js} +2 -2
  51. package/dist/storage.constants-DwSzjjMZ.js.map +1 -0
  52. package/dist/tx/index.cjs +8 -8
  53. package/dist/tx/index.cjs.map +1 -1
  54. package/dist/tx/index.mjs +8 -8
  55. package/dist/tx/index.mjs.map +1 -1
  56. package/package.json +6 -5
  57. package/dist/drivers/postgres/index.cjs +0 -5
  58. package/dist/drivers/postgres/index.d.ts +0 -2
  59. package/dist/drivers/postgres/index.mjs +0 -5
  60. package/dist/migration-CQsAizIw.js.map +0 -1
  61. package/dist/migration-CWBCpwFH.cjs.map +0 -1
  62. package/dist/postgres-driver-F9-TIi38.cjs.map +0 -1
  63. package/dist/postgres-driver-eWlY7pVg.js.map +0 -1
  64. package/dist/storage.constants-BDS_q-_N.js.map +0 -1
  65. package/dist/storage.constants-CIkf7BAJ.cjs.map +0 -1
  66. /package/dist/drivers/{postgres → postgresql}/index.cjs.map +0 -0
  67. /package/dist/drivers/{postgres → postgresql}/index.mjs.map +0 -0
@@ -1,5 +1,5 @@
1
1
  "use strict";
2
- const storage_constants = require("./storage.constants-CIkf7BAJ.cjs");
2
+ const storage_constants = require("./storage.constants-B5oQjxp5.cjs");
3
3
  const node_crypto = require("node:crypto");
4
4
  var PortQueueErrorCode = /* @__PURE__ */ ((PortQueueErrorCode2) => {
5
5
  PortQueueErrorCode2["NOT_STARTED"] = "NOT_STARTED";
@@ -287,7 +287,7 @@ class TableNames {
287
287
  /**
288
288
  * The name for an object an engine files *inside* the table's own schema — an index or a
289
289
  * constraint. `<prefix><table>_<suffix>`, unqualified, because qualifying it would name the
290
- * schema twice (`CREATE INDEX jobs.x ON jobs.pq_job` is an error on Postgres).
290
+ * schema twice (`CREATE INDEX jobs.x ON jobs.pq_job` is an error on PostgreSQL).
291
291
  */
292
292
  derived(table, suffix) {
293
293
  return `${this.bare(table)}_${suffix}`;
@@ -418,7 +418,7 @@ class BaseDriver {
418
418
  /**
419
419
  * The most bound parameters this engine accepts in one statement. The default is a floor that
420
420
  * every supported engine clears: SQLite's `SQLITE_MAX_VARIABLE_NUMBER` (32766 on a modern build),
421
- * Postgres' 16-bit parameter index (65535) and MySQL's `max_prepared_stmt_count` are all above it.
421
+ * PostgreSQL' 16-bit parameter index (65535) and MySQL's `max_prepared_stmt_count` are all above it.
422
422
  * A driver whose engine is tighter — Oracle's `INSERT ALL` — lowers it.
423
423
  */
424
424
  maxBindParams = 3e4;
@@ -484,7 +484,7 @@ class BaseDriver {
484
484
  * Split a batch so no single statement exceeds this engine's bound-parameter limit.
485
485
  *
486
486
  * A multi-row insert binds every column of every row, so a batch of a thousand jobs is tens of
487
- * thousands of parameters — past SQLite's `SQLITE_MAX_VARIABLE_NUMBER` and Postgres' 16-bit
487
+ * thousands of parameters — past SQLite's `SQLITE_MAX_VARIABLE_NUMBER` and PostgreSQL' 16-bit
488
488
  * parameter index. The caller loops over the chunks; each is still one round trip, so a large
489
489
  * batch costs `ceil(rows / chunk)` statements instead of `rows`.
490
490
  */
@@ -504,7 +504,7 @@ class BaseDriver {
504
504
  * tightest engine's `IN` limit, so a public batch is always one chunk; this is what keeps an
505
505
  * internal caller (or a driver with a lower ceiling) from emitting a statement the engine rejects —
506
506
  * `removeJobs` with 1001 ids used to raise ORA-01795 on Oracle and to blow past the parameter
507
- * index on Postgres and SQLite at a few tens of thousands.
507
+ * index on PostgreSQL and SQLite at a few tens of thousands.
508
508
  */
509
509
  chunkIds(keys) {
510
510
  const perChunk = Math.max(
@@ -572,7 +572,7 @@ class BaseDriver {
572
572
  * declared by the query's own `ESCAPE '!'` — so a user typing `100%` searches for that text rather
573
573
  * than matching everything. Still a bound parameter: nothing here is interpolated into SQL.
574
574
  *
575
- * The term is lower-cased for the engines whose query site lower-cases the column too; Postgres and
575
+ * The term is lower-cased for the engines whose query site lower-cases the column too; PostgreSQL and
576
576
  * PGLite use `ILIKE`, where the case folding is the operator's job and this is already inert.
577
577
  *
578
578
  * **A free-text search is a scan, and no index is declared for one.** The pattern has a leading
@@ -851,4 +851,4 @@ exports.secondsToMs = secondsToMs;
851
851
  exports.toMigrationSteps = toMigrationSteps;
852
852
  exports.wholeSeconds = wholeSeconds;
853
853
  exports.wholeSecondsToMs = wholeSecondsToMs;
854
- //# sourceMappingURL=migration-CWBCpwFH.cjs.map
854
+ //# sourceMappingURL=migration-CoTjpgBl.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-CoTjpgBl.cjs","sources":["../src/errors/error-codes.enum.ts","../src/errors/errors.ts","../src/drivers/table-names.ts","../src/drivers/driver-context.ts","../src/drivers/shared/retention-statuses.ts","../src/jobs/instance-affinity.ts","../src/util/uuid.ts","../src/util/seconds.ts","../src/drivers/shared/base-driver.ts","../src/drivers/shared/migration.ts"],"sourcesContent":["/**\n * Typed, importable error codes. No magic strings.\n *\n * Every code here is one an error class actually carries and something actually throws. A code that\n * nothing can produce is a promise to the reader that the library does not keep, so the\n * never-thrown placeholders (`ALREADY_STARTED`, `ALREADY_STOPPED`, `IDEMPOTENCY_CONFLICT`,\n * `SINGLETON_CONFLICT`, `MIGRATION_CHECKSUM_MISMATCH`) are gone: `init()` is idempotent, dedup\n * returns a result rather than raising, and migrations are identified by version alone.\n *\n * `JOB_NOT_FOUND` is thrown from exactly one place: {@link PortQueue.cancelJob}, which answers with\n * *what it did* rather than a boolean, and has no honest answer for an id that names nothing.\n * Everywhere else a missing job stays a return value — `getJob` gives `null`,\n * `removeJob`/`requeueJob` give `null`/`false` — which is both the nicer API and the one that lets a\n * batch skip a stale id instead of failing the rows beside it.\n */\nexport enum PortQueueErrorCode {\n NOT_STARTED = 'NOT_STARTED',\n INVALID_OPTIONS = 'INVALID_OPTIONS',\n UNSUPPORTED_CAPABILITY = 'UNSUPPORTED_CAPABILITY',\n SCHEMA_VERSION_MISMATCH = 'SCHEMA_VERSION_MISMATCH',\n MIGRATION_FAILED = 'MIGRATION_FAILED',\n DRIVER_CONNECTION_ERROR = 'DRIVER_CONNECTION_ERROR',\n DRIVER_QUERY_ERROR = 'DRIVER_QUERY_ERROR',\n JOB_NOT_FOUND = 'JOB_NOT_FOUND',\n QUEUE_NOT_FOUND = 'QUEUE_NOT_FOUND',\n QUEUE_PAUSED = 'QUEUE_PAUSED',\n QUEUE_IN_USE = 'QUEUE_IN_USE',\n INSTANCE_ACTIVE = 'INSTANCE_ACTIVE',\n SHUTDOWN_TIMEOUT = 'SHUTDOWN_TIMEOUT',\n LOCK_LOST = 'LOCK_LOST',\n MISSING_PEER_DEPENDENCY = 'MISSING_PEER_DEPENDENCY',\n}\n","import { PortQueueErrorCode } from './error-codes.enum';\n\n/** Typed details attached to an error. */\nexport interface ErrorContext {\n queue?: string;\n jobId?: string;\n scheduleId?: string;\n capability?: string;\n engine?: string;\n expectedVersion?: number;\n actualVersion?: number;\n [key: string]: unknown;\n}\n\nexport interface PortQueueErrorOptions {\n code: PortQueueErrorCode;\n context?: ErrorContext;\n cause?: unknown;\n}\n\n/**\n * Base error for everything the public surface throws. Carries an\n * enum `code`, typed `context`, and `cause`. Messages must state what/why/how-to-fix.\n */\nexport class PortQueueError extends Error {\n readonly code: PortQueueErrorCode;\n readonly context: ErrorContext;\n\n constructor(message: string, options: PortQueueErrorOptions) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = new.target.name;\n this.code = options.code;\n this.context = options.context ?? {};\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a method that needs a live connection is called before `init()`.\n *\n * Every public producing, consuming and reading method guards on this, so \"I forgot to await\n * `init()`\" surfaces as this message rather than as whatever the driver says about not being\n * connected.\n */\nexport class NotStartedError extends PortQueueError {\n constructor(method: string, context?: ErrorContext) {\n super(\n `Cannot call \\`${method}\\` before PortQueue has started. Call \\`await pq.init()\\` first — ` +\n `it connects the driver, applies migrations and starts the workers.`,\n { code: PortQueueErrorCode.NOT_STARTED, ...(context ? { context } : {}) },\n );\n }\n}\n\nexport class InvalidOptionsError extends PortQueueError {\n constructor(message: string, context?: ErrorContext, cause?: unknown) {\n super(message, {\n code: PortQueueErrorCode.INVALID_OPTIONS,\n ...(context ? { context } : {}),\n ...(cause !== undefined ? { cause } : {}),\n });\n }\n}\n\nexport class UnsupportedCapabilityError extends PortQueueError {\n constructor(capability: string, workaround: string, context?: ErrorContext) {\n super(`The configured driver does not support the '${capability}' capability. ${workaround}`, {\n code: PortQueueErrorCode.UNSUPPORTED_CAPABILITY,\n context: { capability, ...context },\n });\n }\n}\n\nexport class SchemaVersionMismatchError extends PortQueueError {\n constructor(actual: number | null, expected: number, context?: ErrorContext) {\n super(\n `Database schema is at version ${actual ?? 0} but this @portqueue/core expects version ${expected}. ` +\n `Run 'npx portqueue migrate' (or set migration: MigrationMode.AUTO). ` +\n `Startup aborted because migration mode is VALIDATE_ONLY.`,\n {\n code: PortQueueErrorCode.SCHEMA_VERSION_MISMATCH,\n context: { actualVersion: actual ?? 0, expectedVersion: expected, ...context },\n },\n );\n }\n}\n\nexport class MigrationFailedError extends PortQueueError {\n constructor(message: string, cause?: unknown, context?: ErrorContext) {\n super(message, {\n code: PortQueueErrorCode.MIGRATION_FAILED,\n ...(context ? { context } : {}),\n ...(cause !== undefined ? { cause } : {}),\n });\n }\n}\n\nexport class DriverConnectionError extends PortQueueError {\n constructor(message: string, cause?: unknown, context?: ErrorContext) {\n super(message, {\n code: PortQueueErrorCode.DRIVER_CONNECTION_ERROR,\n ...(context ? { context } : {}),\n ...(cause !== undefined ? { cause } : {}),\n });\n }\n}\n\nexport class DriverQueryError extends PortQueueError {\n constructor(message: string, cause?: unknown, context?: ErrorContext) {\n super(message, {\n code: PortQueueErrorCode.DRIVER_QUERY_ERROR,\n ...(context ? { context } : {}),\n ...(cause !== undefined ? { cause } : {}),\n });\n }\n}\n\n/**\n * Thrown when an **admin** client (the dashboard or the CLI, constructed with `_headless`) is asked\n * to produce onto a queue that has no row yet. A headless client never writes a queue row: creating\n * one is the application's declaration of intent, made with `createQueue`, and an admin tool\n * inventing queues would put rows in the database for names that no code consumes.\n */\nexport class QueueNotFoundError extends PortQueueError {\n constructor(queue: string) {\n super(\n `Queue '${queue}' does not exist. This client is headless (the dashboard or CLI), and a ` +\n `headless client never creates queues — declare it in your application with ` +\n `\\`pq.createQueue({ name: '${queue}' })\\` first.`,\n { code: PortQueueErrorCode.QUEUE_NOT_FOUND, context: { queue } },\n );\n }\n}\n\n/**\n * Thrown by {@link PortQueue.cancelJob} for an id that names no row.\n *\n * The one place a missing job is an error rather than a return value. `cancelJob` answers with what\n * it *did* — cancelled the row, or only signalled a running handler — and \"there was nothing to\n * cancel\" is not one of those answers. Every other by-id operation still reports a stale id as\n * `null`/`false`, so a batch can skip it.\n */\nexport class JobNotFoundError extends PortQueueError {\n constructor(jobId: string) {\n super(\n `Job '${jobId}' does not exist, so there was nothing to cancel. Its row may have been ` +\n `removed, or deleted by retention.`,\n { code: PortQueueErrorCode.JOB_NOT_FOUND, context: { jobId } },\n );\n }\n}\n\nexport class QueuePausedError extends PortQueueError {\n constructor(queue: string) {\n super(\n `Queue '${queue}' is paused with PauseMode.ALL and is refusing new jobs. ` +\n `Resume it with pq.resumeQueue({ queue }) (or the dashboard/CLI) to accept jobs again.`,\n { code: PortQueueErrorCode.QUEUE_PAUSED, context: { queue } },\n );\n }\n}\n\nexport class QueueInUseError extends PortQueueError {\n constructor(queue: string) {\n super(\n `Queue '${queue}' is still declared in this process (createQueue) and cannot ` +\n `be removed. Removal is a manual admin action for queues no longer used by any running ` +\n `code — stop referencing it everywhere first. The tool never removes queues on its own.`,\n { code: PortQueueErrorCode.QUEUE_IN_USE, context: { queue } },\n );\n }\n}\n\nexport class InstanceActiveError extends PortQueueError {\n constructor(instanceKey: string) {\n super(\n `Instance '${instanceKey}' is still active (heartbeat within the last 30 minutes) and cannot ` +\n `be removed. Only long-inactive instances can be removed from monitoring; wait until it ` +\n `has not been seen for 30 minutes.`,\n { code: PortQueueErrorCode.INSTANCE_ACTIVE, context: { instanceKey } },\n );\n }\n}\n\nexport class ShutdownTimeoutError extends PortQueueError {\n constructor(timeoutSeconds: number) {\n super(\n `Graceful shutdown timed out after ${timeoutSeconds}s; in-flight handlers were aborted and their locks released for reclaim.`,\n { code: PortQueueErrorCode.SHUTDOWN_TIMEOUT },\n );\n }\n}\n\n/**\n * A handler finished, but the job's row was no longer its to settle: the lock had lapsed and another\n * worker reclaimed the row, so the outcome was refused rather than written over the new run's.\n *\n * Surfaced on the `ERROR` event, never thrown at a caller — the handler itself did nothing wrong,\n * and the job is already running (or has already run) somewhere else. Seeing this repeatedly means\n * handlers are outliving their `lockDurationSeconds`.\n */\nexport class LockLostError extends PortQueueError {\n constructor(jobId: string, queue: string) {\n super(\n `Job '${jobId}' on queue '${queue}' finished after its claim was lost, so its outcome was not ` +\n `recorded — another worker had already reclaimed the row. Raise \\`lockDurationSeconds\\` for ` +\n `this queue, or make the handler observe \\`job.signal\\`.`,\n { code: PortQueueErrorCode.LOCK_LOST, context: { jobId, queue } },\n );\n }\n}\n\nexport class MissingPeerDependencyError extends PortQueueError {\n constructor(pkg: string, driver: string) {\n super(\n `The ${driver} driver requires the '${pkg}' package. Install it with \\`npm install ${pkg}\\`.`,\n { code: PortQueueErrorCode.MISSING_PEER_DEPENDENCY, context: { engine: driver } },\n );\n }\n}\n","import { DEFAULT_MAX_IDENTIFIER_LEN, DEFAULT_TABLE_PREFIX } from '../constants';\nimport { InvalidOptionsError } from '../errors/errors';\n\n/** Logical table names. Never a string literal at a query site. */\nexport enum TableName {\n QUEUE = 'queue',\n JOB = 'job',\n SCHEDULE = 'schedule',\n INSTANCE = 'instance',\n MIGRATION = 'migration',\n}\n\n/**\n * Physical column names, one enum per table. Drivers reference these instead of raw string\n * literals in queries so a rename is a single edit and a typo is a compile error. Exported for\n * driver authors and dashboard/reporting code that builds engine-agnostic column references.\n *\n * NOTE: migration DDL deliberately does NOT use these enums — see `drivers/<engine>/migrations.ts`.\n * A migration is a historical record of a schema that has already run; renaming an enum member must\n * never retroactively rewrite a past migration, so those files keep raw column-name strings.\n */\nexport enum QueueColumn {\n NAME = 'name',\n PROCESSING_PAUSED = 'processing_paused',\n ACCEPTING_PAUSED = 'accepting_paused',\n CREATED_AT = 'created_at',\n UPDATED_AT = 'updated_at',\n}\n\nexport enum JobColumn {\n ID = 'id',\n QUEUE_NAME = 'queue_name',\n STATUS = 'status',\n PRIORITY = 'priority',\n DATA = 'data',\n RETURN_VALUE = 'return_value',\n CREATED_AT = 'created_at',\n UPDATED_AT = 'updated_at',\n START_AFTER = 'start_after',\n EXPIRE_AT = 'expire_at',\n STARTED_AT = 'started_at',\n COMPLETED_AT = 'completed_at',\n FAILED_AT = 'failed_at',\n RETRIED_AT = 'retried_at',\n STALLED_AT = 'stalled_at',\n CANCELLED_AT = 'cancelled_at',\n EXPIRED_AT = 'expired_at',\n LOCKED_UNTIL = 'locked_until',\n /**\n * A fresh token written by every claim, and the fence every completion is guarded on.\n *\n * `locked_until` alone cannot say *whose* claim a row is under: a lock that lapses is reclaimed,\n * the row is claimed again, and it is `ACTIVE` with a future deadline once more — so a handler\n * from the first run that ignored its abort signal could still write its outcome over the second\n * run's. A token identifies the claim itself, so a stale completion matches nothing and is refused.\n */\n LOCK_TOKEN = 'lock_token',\n PREFERRED_INSTANCE_KEY_PATTERN = 'preferred_instance_key_pattern',\n PROCESSED_ON_INSTANCE_KEY = 'processed_on_instance_key',\n RETRY_ATTEMPT = 'retry_attempt',\n RETRY_MAX_ATTEMPTS = 'retry_max_attempts',\n RETRY_DELAY_SECONDS = 'retry_delay_seconds',\n RETRY_BACKOFF = 'retry_backoff',\n RETRY_BACKOFF_FACTOR = 'retry_backoff_factor',\n RETRY_MAX_DELAY_SECONDS = 'retry_max_delay_seconds',\n RETRY_JITTER = 'retry_jitter',\n FAILURE_MESSAGE = 'failure_message',\n /**\n * How long after finishing this job may be deleted, in whole seconds, or NULL to keep it forever.\n * NULL is the whole of \"no retention policy\" — there is no separate mode column to disagree with\n * it.\n */\n RETENTION_TTL_SECONDS = 'retention_ttl_seconds',\n /**\n * The finished statuses this job's retention policy may delete, as a comma-separated token list,\n * or NULL for \"every finished status\". Frozen onto the row like every other retention field, so a\n * policy change never retroactively re-scopes jobs that are already queued.\n */\n RETENTION_STATUSES = 'retention_statuses',\n IDEMPOTENCY_KEY = 'idempotency_key',\n SCHEDULE_ID = 'schedule_id',\n SINGLETON_KEY = 'singleton_key',\n}\n\nexport enum ScheduleColumn {\n ID = 'id',\n QUEUE_NAME = 'queue_name',\n CRON = 'cron',\n EVERY_SECONDS = 'every_seconds',\n TIMEZONE = 'timezone',\n DATA = 'data',\n PRIORITY = 'priority',\n RETRY_MAX_ATTEMPTS = 'retry_max_attempts',\n RETRY_DELAY_SECONDS = 'retry_delay_seconds',\n NEXT_RUN_AT = 'next_run_at',\n LAST_RUN_AT = 'last_run_at',\n ENABLED = 'enabled',\n IDEMPOTENCY_KEY = 'idempotency_key',\n JOB_OPTIONS = 'job_options',\n CREATED_AT = 'created_at',\n UPDATED_AT = 'updated_at',\n}\n\nexport enum InstanceColumn {\n INSTANCE_KEY = 'instance_key',\n PROCESSING_PAUSED = 'processing_paused',\n CREATED_AT = 'created_at',\n UPDATED_AT = 'updated_at',\n LAST_SEEN_AT = 'last_seen_at',\n CPU_PERCENT = 'cpu_percent',\n MEMORY_PERCENT = 'memory_percent',\n}\n\nexport enum MigrationColumn {\n VERSION = 'version',\n CREATED_AT = 'created_at',\n UPDATED_AT = 'updated_at',\n}\n\nconst IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Validate a user-influenced identifier (schema / tablePrefix) against a strict\n * allowlist. Fails fast with a clear error; never reaches SQL raw.\n */\nexport function validateIdentifier(\n kind: string,\n value: string,\n maxLen = DEFAULT_MAX_IDENTIFIER_LEN,\n): string {\n if (!IDENTIFIER_RE.test(value)) {\n throw new InvalidOptionsError(\n `Invalid ${kind} '${value}': must match ${IDENTIFIER_RE} (letters, digits, underscore; not starting with a digit).`,\n );\n }\n if (value.length > maxLen) {\n throw new InvalidOptionsError(\n `Invalid ${kind} '${value}': exceeds the ${maxLen}-character limit for this engine.`,\n );\n }\n return value;\n}\n\n/**\n * Resolves prefixed and (where the engine has them) schema-qualified object names once.\n *\n * Two accessors, because the two forms are not interchangeable:\n *\n * - {@link qualified} is what every query site uses. With `schema: 'jobs'` it returns\n * `jobs.pq_job`, so the tables really are created in and read from that schema.\n * - {@link bare} is the unqualified `pq_job`, for the places a schema prefix is wrong: naming a\n * *derived* object (an index, a constraint) that an engine files alongside its table, and\n * engine metadata lookups that take a schema and a table name as separate values.\n */\nexport class TableNames {\n readonly prefix: string;\n readonly schema?: string;\n\n constructor(options: { tablePrefix?: string; schema?: string; maxIdentifierLen?: number }) {\n this.prefix = validateIdentifier(\n 'tablePrefix',\n options.tablePrefix ?? DEFAULT_TABLE_PREFIX,\n options.maxIdentifierLen,\n );\n if (options.schema !== undefined) {\n this.schema = validateIdentifier('schema', options.schema, options.maxIdentifierLen);\n }\n }\n\n /** The bare (unqualified) physical table name, e.g. `pq_job`. */\n bare(table: TableName): string {\n return `${this.prefix}${table}`;\n }\n\n /**\n * The name a query must use: schema-qualified when a `schema` was configured, bare otherwise.\n * Both halves are allowlist-validated identifiers, so nothing here can be injected.\n */\n qualified(table: TableName): string {\n const name = this.bare(table);\n return this.schema ? `${this.schema}.${name}` : name;\n }\n\n /**\n * The name for an object an engine files *inside* the table's own schema — an index or a\n * constraint. `<prefix><table>_<suffix>`, unqualified, because qualifying it would name the\n * schema twice (`CREATE INDEX jobs.x ON jobs.pq_job` is an error on PostgreSQL).\n */\n derived(table: TableName, suffix: string): string {\n return `${this.bare(table)}_${suffix}`;\n }\n}\n","import { DEFAULT_NAMESPACE } from '../constants';\nimport { TableNames } from './table-names';\n\n/**\n * How a driver lays its data out in the database. Every field is per-engine: two drivers pointing\n * at different databases can use different schemas, prefixes, and namespaces, so these belong on\n * each driver's own options — not on the top-level client. Engines that have schemas honour\n * `schema` by qualifying every object name with it; SQLite has none and does not accept the option.\n */\nexport interface StorageOptions {\n /** DB schema/namespace (PostgreSQL/PGLite/MySQL/Oracle). */\n schema?: string;\n /** Prefix for all created tables (default 'pq_'). */\n tablePrefix?: string;\n /** Logical prefix for pub/sub channels when multiple PortQueues share one DB. */\n namespace?: string;\n}\n\n/**\n * Shared value object a driver builds from its {@link StorageOptions} so all object names are\n * computed once. Also carries the pub/sub namespace.\n */\nexport class DriverContext {\n readonly tableNames: TableNames;\n readonly namespace: string;\n\n constructor(options: {\n tablePrefix?: string;\n schema?: string;\n namespace?: string;\n maxIdentifierLen?: number;\n }) {\n this.tableNames = new TableNames({\n ...(options.tablePrefix !== undefined ? { tablePrefix: options.tablePrefix } : {}),\n ...(options.schema !== undefined ? { schema: options.schema } : {}),\n ...(options.maxIdentifierLen !== undefined\n ? { maxIdentifierLen: options.maxIdentifierLen }\n : {}),\n });\n this.namespace = options.namespace ?? DEFAULT_NAMESPACE;\n }\n}\n","import { FINISHED_STATUSES, JobStatus } from '../../jobs/job-state.enum';\n\n/**\n * How a job's `retention_statuses` column is encoded, and how a query matches against it.\n *\n * Retention is resolved **per job** and frozen onto its row, so the statuses a policy applies to have\n * to travel with the job rather than be re-read from a queue's live options. That is one small fixed\n * set per row, which rules out a side table (the no-JOIN invariant).\n *\n * The encoding is a **bitmask integer**, one bit per finished status. It used to be a comma-delimited\n * token list matched with `LIKE '%,COMPLETED,%'`, and that was the problem: a leading-wildcard `LIKE`\n * is unindexable on every engine here, and the retention sweep `OR`ed four of them — so each batch\n * ran four pattern matches per candidate row on top of the scan it could not avoid. A bitmask is one\n * integer test per row against a bound constant, in a fraction of the bytes.\n *\n * `NULL` still means \"every finished status\" — the default, and the cheapest row to store.\n *\n * This is encoding mechanism, not SQL: every driver builds its own statement and calls these to\n * produce the bound values.\n */\n\n/**\n * The bit for one finished status — its position in {@link FINISHED_STATUSES}.\n *\n * That order is now part of the stored format, so a status may be **appended** to that list but never\n * reordered or removed: doing so would silently re-interpret every row already written.\n */\nfunction bit(status: JobStatus): number {\n const index = FINISHED_STATUSES.indexOf(status);\n return index === -1 ? 0 : 1 << index;\n}\n\n/** Encode a resolved status list for storage, or `null` for \"every finished status\". */\nexport function encodeRetentionStatuses(statuses: readonly JobStatus[] | null): number | null {\n if (!statuses || statuses.length === 0) return null;\n // Deduplicated by construction — a bit is set or it isn't — so two equivalent policies always\n // produce the same stored value.\n const unique = FINISHED_STATUSES.filter((s) => statuses.includes(s));\n // \"All of them\" is the same policy as \"unscoped\", and NULL is the cheaper way to say it.\n if (unique.length === 0 || unique.length === FINISHED_STATUSES.length) return null;\n return unique.reduce((mask, status) => mask | bit(status), 0);\n}\n\n/** Decode a stored value back to the list a caller sees, or `null` when unscoped. */\nexport function decodeRetentionStatuses(value: unknown): JobStatus[] | null {\n if (value == null) return null;\n const mask = Number(value);\n if (!Number.isFinite(mask) || mask === 0) return null;\n const statuses = FINISHED_STATUSES.filter((status) => (mask & bit(status)) !== 0);\n return statuses.length ? statuses : null;\n}\n\n/**\n * The bound value a query tests `retention_statuses` against for one status: that status's bit. A row\n * is eligible when `retention_statuses & <bit> <> 0`, or when the column is NULL — which every\n * driver's predicate checks first.\n */\nexport function retentionStatusBit(status: JobStatus): number {\n return bit(status);\n}\n","/**\n * Claim-time instance affinity. Pure, engine-agnostic logic: portable SQL cannot evaluate regular\n * expressions, so the claim path selects candidates and applies affinity here in the tool.\n *\n * Affinity is a single **preferred key pattern**. A job with no pattern runs anywhere; a job with\n * a pattern runs only on an instance whose key matches it. There is no exact-key pin and no\n * fallback tier — a pattern already spans many instances, so the first live match takes the job,\n * and if none match it simply waits. Build patterns that scale (e.g. `ram-8gb.*cpu-4cor`) rather\n * than pinning to one server that might disappear.\n *\n * **Nothing is cached.** A pattern is compiled where it is used, from the value the candidate row\n * carries. A module-global compiled-regex map would be process-lifetime state shared by every\n * PortQueue in the process — which contradicts \"DI per PortQueue instance\" — and it bought nothing:\n * constructing a `RegExp` is cheap next to the round trip that fetched the row it came from.\n */\n\n/**\n * Does `selfKey` satisfy a preferred pattern? A `null` pattern means \"no constraint\" and matches\n * any instance. An invalid regex matches nothing (the job waits rather than running anywhere).\n */\nexport function matchesInstance(pattern: string | null, selfKey: string): boolean {\n if (pattern == null) return true;\n try {\n return new RegExp(pattern).test(selfKey);\n } catch {\n return false;\n }\n}\n","import { randomUUID } from 'node:crypto';\n\n/** Generate a v4 UUID via `node:crypto`. Used when the engine can't. */\nexport function uuid(): string {\n return randomUUID();\n}\n","import { InvalidOptionsError } from '../errors/errors';\n\n/**\n * Seconds are the only unit of time PortQueue accepts. Nothing is parsed: a duration option is a\n * plain number of seconds, so `'1m'` (which reads as a month to some and a minute to others) is a\n * type error rather than a silent misconfiguration.\n *\n * Every duration that describes a job — its delay, expiry, retry, retention, recurrence interval,\n * rate window — is a **whole** number of seconds, because that is how it is stored: the duration\n * columns are integers. Fractions are rejected by {@link wholeSeconds} rather than silently\n * truncated by the engine. The in-process loop cadences (tick, poll, lock, heartbeat, sampling,\n * shutdown timeout) are never stored and may be fractional — those go through {@link secondsToMs}.\n *\n * **This module is the only place seconds meet milliseconds.** The clock, `setTimeout`/`setInterval`\n * and every stored *instant* are epoch-ms, so a duration is multiplied by 1000 exactly once, here.\n * There is no inline `* 1000` anywhere else in the codebase.\n */\n\n/**\n * The one conversion factor. Named so the literal `1000` never floats free — including inside a\n * driver's SQL, where a per-row `retention_ttl_seconds` has to be scaled by the engine because the\n * value is a column rather than a bind.\n */\nexport const MS_PER_SECOND = 1000;\n\n/** Multiply a validated whole-second duration into milliseconds. */\nexport function wholeSecondsToMs(seconds: number, option: string): number {\n return wholeSeconds(seconds, option) * MS_PER_SECOND;\n}\n\n/** Validate a whole-second duration and return it unchanged. */\nexport function wholeSeconds(seconds: number, option: string): number {\n if (typeof seconds !== 'number' || !Number.isInteger(seconds) || seconds < 0) {\n throw new InvalidOptionsError(\n `Invalid '${option}' value ${JSON.stringify(seconds)}: expected a whole, non-negative ` +\n `number of seconds. PortQueue takes every duration in seconds and stores them as ` +\n `integers — pass 90, not '1m30s' and not 90.5.`,\n );\n }\n return seconds;\n}\n\n/**\n * Multiply a **possibly fractional** second duration into milliseconds. For the process-local\n * cadences and thresholds that never reach a row — timer intervals, sampling windows, the shutdown\n * budget — where a sub-second value is genuinely meaningful (`0.2` is a useful event-loop-delay\n * threshold; `1` is not). Negative values are allowed here and only here: `extendLock` releases a\n * lock by pushing its deadline into the past.\n */\nexport function secondsToMs(seconds: number, option: string): number {\n if (typeof seconds !== 'number' || !Number.isFinite(seconds)) {\n throw new InvalidOptionsError(\n `Invalid '${option}' value ${JSON.stringify(seconds)}: expected a finite number of ` +\n `seconds. PortQueue takes every duration in seconds — pass 0.2 for 200 ms, not '200ms'.`,\n );\n }\n return seconds * MS_PER_SECOND;\n}\n\n/**\n * Milliseconds back to seconds, for the one direction that goes the other way: reporting how long\n * something took. Keeps the `/ 1000` beside the `* 1000` rather than inline at the event site.\n */\nexport function msToSeconds(ms: number): number {\n return ms / MS_PER_SECOND;\n}\n","import { BackoffStrategy } from '../../options/enums';\nimport { emptyStatusCounts, JobStatus } from '../../jobs/job-state.enum';\nimport { DriverCapability, type DriverCapabilitySet } from '../driver-capabilities';\nimport { DriverContext } from '../driver-context';\nimport { InstanceColumn, JobColumn, QueueColumn, ScheduleColumn, TableName } from '../table-names';\nimport { decodeRetentionStatuses, encodeRetentionStatuses } from './retention-statuses';\nimport { matchesInstance } from '../../jobs/instance-affinity';\nimport { uuid } from '../../util/uuid';\nimport { secondsToMs } from '../../util/seconds';\nimport {\n AFFINITY_MAX_PAGES,\n AFFINITY_MIN_SCAN,\n AFFINITY_PAGE_FACTOR,\n AFFINITY_PAGE_MAX,\n AFFINITY_PAGE_MIN_HEADROOM,\n MAX_BATCH_IDS,\n} from '../../constants';\n\nimport type {\n InstanceRow,\n JobRecord,\n NewJobRecord,\n QueueRow,\n ScheduledJobOptions,\n ScheduleRow,\n} from '../../jobs/job-record';\nimport type { PageWindow } from '../driver.interface';\nimport type { TransactionHandle, TxQueryResult } from '../../tx/transaction-handle';\n\n/**\n * Binds a statement carrying an id list needs *besides* the list — a status guard, a timestamp, a\n * queue name. Small and fixed; the point is only that a chunk sized to the whole bind budget would\n * leave no room for them.\n */\nconst IN_LIST_BIND_HEADROOM = 16;\n\n/** A raw query result, normalized across every client library. */\nexport interface RawResult {\n rows: Array<Record<string, unknown>>;\n rowCount: number;\n}\n\n/** An opaque per-connection handle a driver threads through one transaction. */\nexport type Session = unknown;\n\n/** One row as the client library handed it over, keys already lower-cased. */\nexport type Row = Record<string, unknown>;\n\n/**\n * Every `job` column, in the order {@link BaseDriver.jobInsertValues} produces values for. Shared\n * because it is the *shape of a row*, not SQL: a column added to the schema must appear in the\n * insert of every engine, and one list makes that impossible to forget.\n */\nexport const JOB_COLUMNS: readonly JobColumn[] = [\n JobColumn.ID,\n JobColumn.QUEUE_NAME,\n JobColumn.STATUS,\n JobColumn.PRIORITY,\n JobColumn.DATA,\n JobColumn.RETURN_VALUE,\n JobColumn.CREATED_AT,\n JobColumn.UPDATED_AT,\n JobColumn.START_AFTER,\n JobColumn.EXPIRE_AT,\n JobColumn.STARTED_AT,\n JobColumn.COMPLETED_AT,\n JobColumn.FAILED_AT,\n JobColumn.RETRIED_AT,\n JobColumn.STALLED_AT,\n JobColumn.CANCELLED_AT,\n JobColumn.EXPIRED_AT,\n JobColumn.LOCKED_UNTIL,\n JobColumn.LOCK_TOKEN,\n JobColumn.PREFERRED_INSTANCE_KEY_PATTERN,\n JobColumn.PROCESSED_ON_INSTANCE_KEY,\n JobColumn.RETRY_ATTEMPT,\n JobColumn.RETRY_MAX_ATTEMPTS,\n JobColumn.RETRY_DELAY_SECONDS,\n JobColumn.RETRY_BACKOFF,\n JobColumn.RETRY_BACKOFF_FACTOR,\n JobColumn.RETRY_MAX_DELAY_SECONDS,\n JobColumn.RETRY_JITTER,\n JobColumn.FAILURE_MESSAGE,\n JobColumn.RETENTION_TTL_SECONDS,\n JobColumn.RETENTION_STATUSES,\n JobColumn.IDEMPOTENCY_KEY,\n JobColumn.SCHEDULE_ID,\n JobColumn.SINGLETON_KEY,\n];\n\n/** The columns a schedule insert writes, in {@link BaseDriver.scheduleInsertValues} order. */\nexport const SCHEDULE_INSERT_COLUMNS: readonly ScheduleColumn[] = [\n ScheduleColumn.ID,\n ScheduleColumn.QUEUE_NAME,\n ScheduleColumn.CRON,\n ScheduleColumn.EVERY_SECONDS,\n ScheduleColumn.TIMEZONE,\n ScheduleColumn.DATA,\n ScheduleColumn.JOB_OPTIONS,\n ScheduleColumn.PRIORITY,\n ScheduleColumn.RETRY_MAX_ATTEMPTS,\n ScheduleColumn.RETRY_DELAY_SECONDS,\n ScheduleColumn.NEXT_RUN_AT,\n ScheduleColumn.ENABLED,\n ScheduleColumn.IDEMPOTENCY_KEY,\n ScheduleColumn.CREATED_AT,\n ScheduleColumn.UPDATED_AT,\n];\n\n/**\n * What every driver shares — and **only** what every driver shares.\n *\n * The duplicate-over-share rule in CLAUDE.md is about *dialect and query SQL*: a change to one\n * engine's statement must never leak into another's. None of that lives here. What does live here is\n * the same category as `TableName`, the `MigrationRunner` and the value objects — row → record\n * mapping, value conversion, id generation, the affinity filter, and the paging arithmetic:\n *\n * - **Mapping** (`mapJob`, `mapQueue`, `mapSchedule`, `mapInstance`) turns a result row into the\n * record shape core consumes. It contains no SQL and cannot: it reads a `Row` by column name.\n * Duplicating it bought nothing and cost a real bug — a column added to the schema had to be\n * remembered in five files, and `retention_statuses` would have been missed in at least one.\n * - **Value conversion** (`toJson`, `boolIn`, `numOrNull`, …) is JS-side normalization of what a\n * client library hands back.\n * - **Insert values** (`jobInsertValues`) is the ordered value list matching {@link JOB_COLUMNS}.\n * Each driver still writes its own `INSERT` statement around it.\n * - **The affinity scan** (`affinityPlan`, `matchAffinity`) is the paging arithmetic and the regex\n * test. The driver supplies the `SELECT` — the part that is dialect.\n *\n * Everything a subclass must provide is abstract: the connection (`execute`, `transaction`),\n * the placeholder style (`ph`), and the paging tail (`window`). No statement string appears below.\n */\nexport abstract class BaseDriver {\n abstract readonly capabilities: DriverCapabilitySet;\n readonly context: DriverContext;\n\n /**\n * The most bound parameters this engine accepts in one statement. The default is a floor that\n * every supported engine clears: SQLite's `SQLITE_MAX_VARIABLE_NUMBER` (32766 on a modern build),\n * PostgreSQL' 16-bit parameter index (65535) and MySQL's `max_prepared_stmt_count` are all above it.\n * A driver whose engine is tighter — Oracle's `INSERT ALL` — lowers it.\n */\n protected readonly maxBindParams: number = 30_000;\n\n /**\n * The most expressions this engine allows in one `IN (...)` list.\n *\n * A separate limit from {@link maxBindParams}, and on Oracle a much tighter one — 1000 expressions,\n * whatever the bind budget — which is why {@link MAX_BATCH_IDS} caps a batch at that number for\n * every engine. A driver whose engine is tighter still lowers this.\n */\n protected readonly maxInListItems: number = MAX_BATCH_IDS;\n\n protected constructor(options: {\n tablePrefix?: string;\n schema?: string;\n namespace?: string;\n maxIdentifierLen?: number;\n }) {\n this.context = new DriverContext(options);\n }\n\n // --- Connection mechanism (each engine's own) ---\n\n /** Run one statement, on `session`'s connection when inside a transaction. */\n protected abstract execute(\n sql: string,\n params: readonly unknown[],\n session?: Session,\n ): Promise<RawResult>;\n\n /** Run `fn` inside one transaction, handing it the session its statements must use. */\n protected abstract transaction<T>(fn: (session: Session) => Promise<T>): Promise<T>;\n\n /** This engine's placeholder for the 0-based parameter at `index0` (`$1`, `?`, `:1`, …). */\n protected abstract ph(index0: number): string;\n\n /**\n * The trailing paging clause for a list read, appending each bound value to `params`. Dialect —\n * `LIMIT/OFFSET` on most engines, `OFFSET … ROWS FETCH NEXT … ROWS ONLY` on Oracle — so each\n * driver writes its own. Returns `''` when the caller asked for no window, so core's unpaged\n * reads emit no paging clause at all.\n */\n protected abstract window(page: PageWindow, params: unknown[]): string;\n\n // --- Naming ---\n\n /** The name a statement must reference: schema-qualified when a `schema` was configured. */\n protected t(table: TableName): string {\n return this.context.tableNames.qualified(table);\n }\n\n /**\n * Run one statement: on the caller's transaction when there is one, otherwise on its own.\n *\n * A lone statement needs no explicit `BEGIN` — every engine here runs it inside an implicit\n * transaction, so it is already all-or-nothing. What must never happen is a *sequence* of\n * statements outside a transaction; that is what {@link inTx} is for, and every multi-statement\n * driver method goes through it.\n */\n protected async runMaybeTx(\n sql: string,\n params: readonly unknown[],\n tx?: TransactionHandle,\n ): Promise<RawResult> {\n if (tx) {\n const res: TxQueryResult = await tx.execute(sql, [...params]);\n return { rows: res.rows, rowCount: res.rowCount };\n }\n return this.execute(sql, params);\n }\n\n /**\n * Run several statements as one unit: the caller's transaction when there is one, otherwise a\n * fresh one of ours. `run` issues each statement on whichever connection is correct.\n *\n * Every driver method that reads then writes — get-or-create, the dedup-plus-insert pair, the\n * heartbeat's update-then-insert, a claim's scan-then-update — uses this. Outside a transaction\n * those pairs can interleave with another instance's; inside one they cannot.\n */\n protected async inTx<T>(\n tx: TransactionHandle | undefined,\n fn: (run: (sql: string, params: readonly unknown[]) => Promise<RawResult>) => Promise<T>,\n ): Promise<T> {\n if (tx) {\n return fn(async (sql, params) => {\n const res = await tx.execute(sql, [...params]);\n return { rows: res.rows, rowCount: res.rowCount };\n });\n }\n return this.transaction((session) => fn((sql, params) => this.execute(sql, params, session)));\n }\n\n /** The capability keys this driver declares as on — what `probe()` reports as verified. */\n protected enabledCapabilities(): DriverCapability[] {\n return (Object.keys(this.capabilities) as DriverCapability[]).filter(\n (cap) => this.capabilities[cap],\n );\n }\n\n /** A comma-separated placeholder list for `count` params starting at `from`. */\n protected phList(count: number, from = 0): string {\n return Array.from({ length: count }, (_, i) => this.ph(from + i)).join(', ');\n }\n\n /**\n * Split a batch so no single statement exceeds this engine's bound-parameter limit.\n *\n * A multi-row insert binds every column of every row, so a batch of a thousand jobs is tens of\n * thousands of parameters — past SQLite's `SQLITE_MAX_VARIABLE_NUMBER` and PostgreSQL' 16-bit\n * parameter index. The caller loops over the chunks; each is still one round trip, so a large\n * batch costs `ceil(rows / chunk)` statements instead of `rows`.\n */\n protected chunkForBind<T>(items: T[], paramsPerItem: number): T[][] {\n const perChunk = Math.max(1, Math.floor(this.maxBindParams / Math.max(paramsPerItem, 1)));\n if (items.length <= perChunk) return [items];\n const chunks: T[][] = [];\n for (let i = 0; i < items.length; i += perChunk) chunks.push(items.slice(i, i + perChunk));\n return chunks;\n }\n\n /**\n * Split a key list so no single statement's `IN (...)` exceeds what the engine allows — both its\n * `IN`-list ceiling and its bound-parameter budget, with headroom for the handful of other binds a\n * statement carries beside the list.\n *\n * Every by-id batch goes through this. `MAX_BATCH_IDS` already refuses a *call* larger than the\n * tightest engine's `IN` limit, so a public batch is always one chunk; this is what keeps an\n * internal caller (or a driver with a lower ceiling) from emitting a statement the engine rejects —\n * `removeJobs` with 1001 ids used to raise ORA-01795 on Oracle and to blow past the parameter\n * index on PostgreSQL and SQLite at a few tens of thousands.\n */\n protected chunkIds<T>(keys: readonly T[]): T[][] {\n const perChunk = Math.max(\n 1,\n Math.min(this.maxInListItems, this.maxBindParams - IN_LIST_BIND_HEADROOM),\n );\n if (keys.length <= perChunk) return [[...keys]];\n const chunks: T[][] = [];\n for (let i = 0; i < keys.length; i += perChunk) chunks.push([...keys.slice(i, i + perChunk)]);\n return chunks;\n }\n\n /**\n * Run one statement per {@link chunkIds} chunk and concatenate what each returned.\n *\n * A single chunk — the case every capped public batch takes — runs exactly the statement it would\n * have without chunking, so nothing is paid for the guard. Several chunks are several statements:\n * inside the caller's transaction when there is one, and otherwise each atomic on its own, which\n * is the same trade every bounded sweep in the tool makes.\n */\n protected async overIdChunks<K, R>(\n keys: readonly K[],\n perChunk: (chunk: K[]) => Promise<R[]>,\n ): Promise<R[]> {\n const chunks = this.chunkIds(keys);\n if (chunks.length === 1) return perChunk(chunks[0]!);\n const out: R[] = [];\n for (const chunk of chunks) out.push(...(await perChunk(chunk)));\n return out;\n }\n\n // --- Value conversion ---\n\n protected toJson(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n return JSON.stringify(value);\n }\n\n protected fromJson(value: unknown): unknown {\n if (value === null || value === undefined) return null;\n if (typeof value === 'string') {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n }\n return value;\n }\n\n protected boolIn(value: boolean): number {\n return value ? 1 : 0;\n }\n\n protected boolOut(value: unknown): boolean {\n return value === 1 || value === true || value === '1' || value === 't';\n }\n\n protected numOrNull(value: unknown): number | null {\n return value == null ? null : Number(value);\n }\n\n protected strOrNull(value: unknown): string | null {\n return value == null ? null : String(value);\n }\n\n /** A fresh application-generated id. Every engine stores ids as strings. */\n protected newId(): string {\n return uuid();\n }\n\n /** A lock deadline `lockDurationSeconds` from `now` (negative releases the lock). */\n protected lockDeadline(now: number, lockDurationSeconds: number): number {\n return now + secondsToMs(lockDurationSeconds, 'limiter.lockDurationSeconds');\n }\n\n /**\n * A bound pattern for a case-insensitive substring search. `%`/`_`/`!` are escaped with `!` —\n * declared by the query's own `ESCAPE '!'` — so a user typing `100%` searches for that text rather\n * than matching everything. Still a bound parameter: nothing here is interpolated into SQL.\n *\n * The term is lower-cased for the engines whose query site lower-cases the column too; PostgreSQL and\n * PGLite use `ILIKE`, where the case folding is the operator's job and this is already inert.\n *\n * **A free-text search is a scan, and no index is declared for one.** The pattern has a leading\n * wildcard, which no B-tree can serve on any engine here — not even over a functional\n * `LOWER(column)` index — so declaring one would suggest a speed-up that cannot happen. What bounds\n * the cost is the `LIMIT` every search read carries, and the fact that only an operator triaging in\n * the dashboard or CLI ever issues one.\n */\n protected likePattern(term: string): string {\n const escaped = term.toLowerCase().replace(/[!%_]/g, (ch) => `!${ch}`);\n return `%${escaped}%`;\n }\n\n /**\n * A zeroed status breakdown, for a key a grouped count query returned nothing for. Delegates to\n * the one definition in `jobs/job-state.enum` — this used to be a second copy of the same object\n * literal, and a new status would have had to be remembered in both.\n */\n protected emptyStatusCounts(): Record<JobStatus, number> {\n return emptyStatusCounts();\n }\n\n // --- Row → record mapping ---\n\n protected mapJob(row: Row): JobRecord {\n return {\n id: String(row[JobColumn.ID]),\n queueName: String(row[JobColumn.QUEUE_NAME]),\n status: row[JobColumn.STATUS] as JobStatus,\n priority: Number(row[JobColumn.PRIORITY]),\n data: this.fromJson(row[JobColumn.DATA]),\n returnValue: this.fromJson(row[JobColumn.RETURN_VALUE]),\n createdAt: Number(row[JobColumn.CREATED_AT]),\n updatedAt: Number(row[JobColumn.UPDATED_AT]),\n startAfter: Number(row[JobColumn.START_AFTER]),\n expireAt: this.numOrNull(row[JobColumn.EXPIRE_AT]),\n startedAt: this.numOrNull(row[JobColumn.STARTED_AT]),\n completedAt: this.numOrNull(row[JobColumn.COMPLETED_AT]),\n failedAt: this.numOrNull(row[JobColumn.FAILED_AT]),\n retriedAt: this.numOrNull(row[JobColumn.RETRIED_AT]),\n stalledAt: this.numOrNull(row[JobColumn.STALLED_AT]),\n cancelledAt: this.numOrNull(row[JobColumn.CANCELLED_AT]),\n expiredAt: this.numOrNull(row[JobColumn.EXPIRED_AT]),\n lockedUntil: this.numOrNull(row[JobColumn.LOCKED_UNTIL]),\n lockToken: this.strOrNull(row[JobColumn.LOCK_TOKEN]),\n preferredInstanceKeyPattern: this.strOrNull(row[JobColumn.PREFERRED_INSTANCE_KEY_PATTERN]),\n processedOnInstanceKey: this.strOrNull(row[JobColumn.PROCESSED_ON_INSTANCE_KEY]),\n retryAttempt: Number(row[JobColumn.RETRY_ATTEMPT]),\n retryMaxAttempts: Number(row[JobColumn.RETRY_MAX_ATTEMPTS]),\n retryDelaySeconds: Number(row[JobColumn.RETRY_DELAY_SECONDS]),\n retryBackoff: row[JobColumn.RETRY_BACKOFF] as BackoffStrategy,\n retryBackoffFactor: this.numOrNull(row[JobColumn.RETRY_BACKOFF_FACTOR]),\n retryMaxDelaySeconds: this.numOrNull(row[JobColumn.RETRY_MAX_DELAY_SECONDS]),\n retryJitter: this.boolOut(row[JobColumn.RETRY_JITTER]),\n failureMessage: this.strOrNull(row[JobColumn.FAILURE_MESSAGE]),\n retentionTtlSeconds: this.numOrNull(row[JobColumn.RETENTION_TTL_SECONDS]),\n retentionStatuses: decodeRetentionStatuses(row[JobColumn.RETENTION_STATUSES]),\n idempotencyKey: this.strOrNull(row[JobColumn.IDEMPOTENCY_KEY]),\n scheduleId: this.strOrNull(row[JobColumn.SCHEDULE_ID]),\n singletonKey: this.strOrNull(row[JobColumn.SINGLETON_KEY]),\n };\n }\n\n protected mapQueue(row: Row): QueueRow {\n return {\n name: String(row[QueueColumn.NAME]),\n processingPaused: this.boolOut(row[QueueColumn.PROCESSING_PAUSED]),\n acceptingPaused: this.boolOut(row[QueueColumn.ACCEPTING_PAUSED]),\n createdAt: Number(row[QueueColumn.CREATED_AT]),\n updatedAt: Number(row[QueueColumn.UPDATED_AT]),\n };\n }\n\n protected mapInstance(row: Row): InstanceRow {\n return {\n instanceKey: String(row[InstanceColumn.INSTANCE_KEY]),\n processingPaused: this.boolOut(row[InstanceColumn.PROCESSING_PAUSED]),\n createdAt: Number(row[InstanceColumn.CREATED_AT]),\n updatedAt: Number(row[InstanceColumn.UPDATED_AT]),\n lastSeenAt: Number(row[InstanceColumn.LAST_SEEN_AT]),\n cpuPercent: this.numOrNull(row[InstanceColumn.CPU_PERCENT]),\n memoryPercent: this.numOrNull(row[InstanceColumn.MEMORY_PERCENT]),\n };\n }\n\n protected mapSchedule(row: Row): ScheduleRow {\n return {\n id: String(row[ScheduleColumn.ID]),\n queueName: String(row[ScheduleColumn.QUEUE_NAME]),\n cron: this.strOrNull(row[ScheduleColumn.CRON]),\n everySeconds: this.numOrNull(row[ScheduleColumn.EVERY_SECONDS]),\n timezone: this.strOrNull(row[ScheduleColumn.TIMEZONE]),\n data: this.fromJson(row[ScheduleColumn.DATA]),\n jobOptions:\n (this.fromJson(row[ScheduleColumn.JOB_OPTIONS]) as ScheduledJobOptions | null) ?? null,\n priority: this.numOrNull(row[ScheduleColumn.PRIORITY]),\n retryMaxAttempts: this.numOrNull(row[ScheduleColumn.RETRY_MAX_ATTEMPTS]),\n retryDelaySeconds: this.numOrNull(row[ScheduleColumn.RETRY_DELAY_SECONDS]),\n nextRunAt: this.numOrNull(row[ScheduleColumn.NEXT_RUN_AT]),\n lastRunAt: this.numOrNull(row[ScheduleColumn.LAST_RUN_AT]),\n enabled: this.boolOut(row[ScheduleColumn.ENABLED]),\n idempotencyKey: this.strOrNull(row[ScheduleColumn.IDEMPOTENCY_KEY]),\n createdAt: Number(row[ScheduleColumn.CREATED_AT]),\n updatedAt: Number(row[ScheduleColumn.UPDATED_AT]),\n };\n }\n\n /** A job's ref as the mutating methods return it. */\n protected mapJobRef(row: Row): { jobId: string; queueName: string } {\n return {\n jobId: String(row[JobColumn.ID]),\n queueName: String(row[JobColumn.QUEUE_NAME]),\n };\n }\n\n /** A schedule's ref as the mutating methods return it. */\n protected mapScheduleRef(row: Row): { scheduleId: string; queueName: string } {\n return {\n scheduleId: String(row[ScheduleColumn.ID]),\n queueName: String(row[ScheduleColumn.QUEUE_NAME]),\n };\n }\n\n // --- Insert value lists ---\n\n /** The ordered values for one job row, matching {@link JOB_COLUMNS} exactly. */\n protected jobInsertValues(job: NewJobRecord): { id: string; values: unknown[] } {\n const id = job.id ?? this.newId();\n const now = job.createdAt;\n return {\n id,\n values: [\n id,\n job.queueName,\n job.status,\n job.priority,\n this.toJson(job.data),\n null, // return_value\n now,\n now,\n job.startAfter,\n job.expireAt,\n null, // started_at\n null, // completed_at\n null, // failed_at\n null, // retried_at\n null, // stalled_at\n null, // cancelled_at\n null, // expired_at\n null, // locked_until\n null, // lock_token (written at claim time)\n job.preferredInstanceKeyPattern,\n null, // processed_on_instance_key (set at claim time)\n job.retryAttempt,\n job.retryMaxAttempts,\n job.retryDelaySeconds,\n job.retryBackoff,\n job.retryBackoffFactor,\n job.retryMaxDelaySeconds,\n this.boolIn(job.retryJitter),\n null, // failure_message\n job.retentionTtlSeconds,\n encodeRetentionStatuses(job.retentionStatuses),\n job.idempotencyKey,\n job.scheduleId,\n job.singletonKey,\n ],\n };\n }\n\n /** The ordered values for one schedule row, matching {@link SCHEDULE_INSERT_COLUMNS}. */\n protected scheduleInsertValues(\n schedule: import('../../jobs/job-record').NewScheduleRow,\n now: number,\n ): { id: string; values: unknown[] } {\n const id = schedule.id ?? this.newId();\n return {\n id,\n values: [\n id,\n schedule.queueName,\n schedule.cron,\n schedule.everySeconds,\n schedule.timezone,\n this.toJson(schedule.data),\n this.toJson(schedule.jobOptions),\n schedule.priority,\n schedule.retryMaxAttempts,\n schedule.retryDelaySeconds,\n schedule.nextRunAt,\n this.boolIn(schedule.enabled),\n schedule.idempotencyKey,\n now,\n now,\n ],\n };\n }\n\n // --- Multi-instance affinity ---\n\n /**\n * The page size and scan ceiling for the multi-instance claim scan.\n *\n * Affinity is a regex and portable SQL cannot evaluate one, so a named instance selects\n * candidates highest-priority-first and filters them here. Paging — rather than one capped\n * window — prevents starvation: when the top rows all target other instances, the jobs this\n * instance *can* run may sit past the first page. The ceiling stops a backlog of\n * exclusively-non-matching jobs from turning one tick into a full-table sweep; the next tick\n * resumes from the top.\n */\n protected affinityPlan(limit: number): { pageSize: number; maxScan: number } {\n const pageSize = Math.min(\n Math.max(limit * AFFINITY_PAGE_FACTOR, limit + AFFINITY_PAGE_MIN_HEADROOM),\n AFFINITY_PAGE_MAX,\n );\n return { pageSize, maxScan: Math.max(pageSize * AFFINITY_MAX_PAGES, AFFINITY_MIN_SCAN) };\n }\n\n /**\n * Collect the ids from one candidate page this instance's key is allowed to run, stopping at\n * `limit`. Returns whether the caller should keep paging.\n */\n protected collectAffinityMatches(\n rows: Row[],\n instanceKey: string,\n limit: number,\n into: Set<string>,\n ): void {\n for (const row of rows) {\n const pattern = this.strOrNull(row[JobColumn.PREFERRED_INSTANCE_KEY_PATTERN]);\n if (!matchesInstance(pattern, instanceKey)) continue;\n into.add(String(row[JobColumn.ID]));\n if (into.size >= limit) return;\n }\n }\n\n /** Claim order: highest priority first, then oldest due. Applied after a claim returns rows. */\n protected sortClaimed(jobs: JobRecord[]): JobRecord[] {\n return jobs.sort((a, b) => b.priority - a.priority || a.startAfter - b.startAfter);\n }\n}\n","import type { MigrationStep } from '../driver.interface';\nimport type { TableName } from '../table-names';\n\n/**\n * The naming helpers a migration's DDL needs.\n *\n * - `name(t)` is the name a statement must reference — schema-qualified when the driver was given a\n * `schema`, so the objects really are created in it.\n * - `derived(t, suffix)` names an object the engine files *inside* that table's own schema (an\n * index, a constraint), which must therefore stay unqualified.\n * - `schema` is the configured schema, for a flavour whose engine can create one.\n */\nexport interface MigrationNames {\n name(table: TableName): string;\n derived(table: TableName, suffix: string): string;\n schema: string | undefined;\n}\n\n/**\n * A predefined migration for one engine at one schema version. `statements` returns the DDL for\n * that step with object names resolved. Each driver authors its own array alongside the driver\n * (`drivers/<engine>/migrations.ts`) — never shared or generated at runtime, so a change to one\n * engine's DDL can never leak into another's.\n *\n * A migration is identified by its `version` and nothing else. There is deliberately no checksum:\n * nothing ever compared one, and a value written but never read states a guarantee the code does\n * not make.\n */\nexport interface FlavourMigration {\n version: number;\n statements(names: MigrationNames): string[];\n}\n\n/**\n * Wrap a driver's authored {@link FlavourMigration} list into the runner's {@link MigrationStep}\n * units — resolving object names against the live context, and nothing else. The driver's\n * `applyMigration` runs the statements *and* records the version in one transaction, so a crash\n * can never leave an applied-but-unrecorded migration. This is the only piece of the migration\n * path shared across engines: the mechanism, never the SQL.\n */\nexport function toMigrationSteps(migrations: FlavourMigration[]): MigrationStep[] {\n return migrations.map((migration) => ({\n version: migration.version,\n statements: (context) =>\n migration.statements({\n name: (t) => context.tableNames.qualified(t),\n derived: (t, suffix) => context.tableNames.derived(t, suffix),\n schema: context.tableNames.schema,\n }),\n }));\n}\n\n/** The highest version among a migration set (the schema version a build ships). */\nexport function latestVersion(migrations: MigrationStep[]): number {\n return migrations.reduce((max, m) => (m.version > max ? m.version : max), 0);\n}\n"],"names":["PortQueueErrorCode","TableName","QueueColumn","JobColumn","ScheduleColumn","InstanceColumn","MigrationColumn","DEFAULT_MAX_IDENTIFIER_LEN","DEFAULT_TABLE_PREFIX","DEFAULT_NAMESPACE","FINISHED_STATUSES","randomUUID","MAX_BATCH_IDS","emptyStatusCounts","AFFINITY_PAGE_FACTOR","AFFINITY_PAGE_MIN_HEADROOM","AFFINITY_PAGE_MAX","AFFINITY_MAX_PAGES","AFFINITY_MIN_SCAN"],"mappings":";;;AAeO,IAAK,uCAAAA,wBAAL;AACLA,sBAAA,aAAA,IAAc;AACdA,sBAAA,iBAAA,IAAkB;AAClBA,sBAAA,wBAAA,IAAyB;AACzBA,sBAAA,yBAAA,IAA0B;AAC1BA,sBAAA,kBAAA,IAAmB;AACnBA,sBAAA,yBAAA,IAA0B;AAC1BA,sBAAA,oBAAA,IAAqB;AACrBA,sBAAA,eAAA,IAAgB;AAChBA,sBAAA,iBAAA,IAAkB;AAClBA,sBAAA,cAAA,IAAe;AACfA,sBAAA,cAAA,IAAe;AACfA,sBAAA,iBAAA,IAAkB;AAClBA,sBAAA,kBAAA,IAAmB;AACnBA,sBAAA,WAAA,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_PAGE_MIN_HEADROOM, l as AFFINITY_PAGE_MAX } from "./storage.constants-BDS_q-_N.js";
1
+ import { d as DEFAULT_MAX_IDENTIFIER_LEN, e as DEFAULT_TABLE_PREFIX, f as DEFAULT_NAMESPACE, F as FINISHED_STATUSES, M as MAX_BATCH_IDS, g as emptyStatusCounts, h as AFFINITY_MAX_PAGES, i as AFFINITY_MIN_SCAN, j as AFFINITY_PAGE_FACTOR, k as AFFINITY_PAGE_MIN_HEADROOM, l as AFFINITY_PAGE_MAX } from "./storage.constants-DwSzjjMZ.js";
2
2
  import { randomUUID } from "node:crypto";
3
3
  var PortQueueErrorCode = /* @__PURE__ */ ((PortQueueErrorCode2) => {
4
4
  PortQueueErrorCode2["NOT_STARTED"] = "NOT_STARTED";
@@ -286,7 +286,7 @@ class TableNames {
286
286
  /**
287
287
  * The name for an object an engine files *inside* the table's own schema — an index or a
288
288
  * constraint. `<prefix><table>_<suffix>`, unqualified, because qualifying it would name the
289
- * schema twice (`CREATE INDEX jobs.x ON jobs.pq_job` is an error on Postgres).
289
+ * schema twice (`CREATE INDEX jobs.x ON jobs.pq_job` is an error on PostgreSQL).
290
290
  */
291
291
  derived(table, suffix) {
292
292
  return `${this.bare(table)}_${suffix}`;
@@ -417,7 +417,7 @@ class BaseDriver {
417
417
  /**
418
418
  * The most bound parameters this engine accepts in one statement. The default is a floor that
419
419
  * every supported engine clears: SQLite's `SQLITE_MAX_VARIABLE_NUMBER` (32766 on a modern build),
420
- * Postgres' 16-bit parameter index (65535) and MySQL's `max_prepared_stmt_count` are all above it.
420
+ * PostgreSQL' 16-bit parameter index (65535) and MySQL's `max_prepared_stmt_count` are all above it.
421
421
  * A driver whose engine is tighter — Oracle's `INSERT ALL` — lowers it.
422
422
  */
423
423
  maxBindParams = 3e4;
@@ -483,7 +483,7 @@ class BaseDriver {
483
483
  * Split a batch so no single statement exceeds this engine's bound-parameter limit.
484
484
  *
485
485
  * A multi-row insert binds every column of every row, so a batch of a thousand jobs is tens of
486
- * thousands of parameters — past SQLite's `SQLITE_MAX_VARIABLE_NUMBER` and Postgres' 16-bit
486
+ * thousands of parameters — past SQLite's `SQLITE_MAX_VARIABLE_NUMBER` and PostgreSQL' 16-bit
487
487
  * parameter index. The caller loops over the chunks; each is still one round trip, so a large
488
488
  * batch costs `ceil(rows / chunk)` statements instead of `rows`.
489
489
  */
@@ -503,7 +503,7 @@ class BaseDriver {
503
503
  * tightest engine's `IN` limit, so a public batch is always one chunk; this is what keeps an
504
504
  * internal caller (or a driver with a lower ceiling) from emitting a statement the engine rejects —
505
505
  * `removeJobs` with 1001 ids used to raise ORA-01795 on Oracle and to blow past the parameter
506
- * index on Postgres and SQLite at a few tens of thousands.
506
+ * index on PostgreSQL and SQLite at a few tens of thousands.
507
507
  */
508
508
  chunkIds(keys) {
509
509
  const perChunk = Math.max(
@@ -571,7 +571,7 @@ class BaseDriver {
571
571
  * declared by the query's own `ESCAPE '!'` — so a user typing `100%` searches for that text rather
572
572
  * than matching everything. Still a bound parameter: nothing here is interpolated into SQL.
573
573
  *
574
- * The term is lower-cased for the engines whose query site lower-cases the column too; Postgres and
574
+ * The term is lower-cased for the engines whose query site lower-cases the column too; PostgreSQL and
575
575
  * PGLite use `ILIKE`, where the case folding is the operator's job and this is already inert.
576
576
  *
577
577
  * **A free-text search is a scan, and no index is declared for one.** The pattern has a leading
@@ -852,4 +852,4 @@ export {
852
852
  wholeSecondsToMs as w,
853
853
  PortQueueErrorCode as x
854
854
  };
855
- //# sourceMappingURL=migration-CQsAizIw.js.map
855
+ //# sourceMappingURL=migration-D73ANkYV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-D73ANkYV.js","sources":["../src/errors/error-codes.enum.ts","../src/errors/errors.ts","../src/drivers/table-names.ts","../src/drivers/driver-context.ts","../src/drivers/shared/retention-statuses.ts","../src/jobs/instance-affinity.ts","../src/util/uuid.ts","../src/util/seconds.ts","../src/drivers/shared/base-driver.ts","../src/drivers/shared/migration.ts"],"sourcesContent":["/**\n * Typed, importable error codes. No magic strings.\n *\n * Every code here is one an error class actually carries and something actually throws. A code that\n * nothing can produce is a promise to the reader that the library does not keep, so the\n * never-thrown placeholders (`ALREADY_STARTED`, `ALREADY_STOPPED`, `IDEMPOTENCY_CONFLICT`,\n * `SINGLETON_CONFLICT`, `MIGRATION_CHECKSUM_MISMATCH`) are gone: `init()` is idempotent, dedup\n * returns a result rather than raising, and migrations are identified by version alone.\n *\n * `JOB_NOT_FOUND` is thrown from exactly one place: {@link PortQueue.cancelJob}, which answers with\n * *what it did* rather than a boolean, and has no honest answer for an id that names nothing.\n * Everywhere else a missing job stays a return value — `getJob` gives `null`,\n * `removeJob`/`requeueJob` give `null`/`false` — which is both the nicer API and the one that lets a\n * batch skip a stale id instead of failing the rows beside it.\n */\nexport enum PortQueueErrorCode {\n NOT_STARTED = 'NOT_STARTED',\n INVALID_OPTIONS = 'INVALID_OPTIONS',\n UNSUPPORTED_CAPABILITY = 'UNSUPPORTED_CAPABILITY',\n SCHEMA_VERSION_MISMATCH = 'SCHEMA_VERSION_MISMATCH',\n MIGRATION_FAILED = 'MIGRATION_FAILED',\n DRIVER_CONNECTION_ERROR = 'DRIVER_CONNECTION_ERROR',\n DRIVER_QUERY_ERROR = 'DRIVER_QUERY_ERROR',\n JOB_NOT_FOUND = 'JOB_NOT_FOUND',\n QUEUE_NOT_FOUND = 'QUEUE_NOT_FOUND',\n QUEUE_PAUSED = 'QUEUE_PAUSED',\n QUEUE_IN_USE = 'QUEUE_IN_USE',\n INSTANCE_ACTIVE = 'INSTANCE_ACTIVE',\n SHUTDOWN_TIMEOUT = 'SHUTDOWN_TIMEOUT',\n LOCK_LOST = 'LOCK_LOST',\n MISSING_PEER_DEPENDENCY = 'MISSING_PEER_DEPENDENCY',\n}\n","import { PortQueueErrorCode } from './error-codes.enum';\n\n/** Typed details attached to an error. */\nexport interface ErrorContext {\n queue?: string;\n jobId?: string;\n scheduleId?: string;\n capability?: string;\n engine?: string;\n expectedVersion?: number;\n actualVersion?: number;\n [key: string]: unknown;\n}\n\nexport interface PortQueueErrorOptions {\n code: PortQueueErrorCode;\n context?: ErrorContext;\n cause?: unknown;\n}\n\n/**\n * Base error for everything the public surface throws. Carries an\n * enum `code`, typed `context`, and `cause`. Messages must state what/why/how-to-fix.\n */\nexport class PortQueueError extends Error {\n readonly code: PortQueueErrorCode;\n readonly context: ErrorContext;\n\n constructor(message: string, options: PortQueueErrorOptions) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.name = new.target.name;\n this.code = options.code;\n this.context = options.context ?? {};\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when a method that needs a live connection is called before `init()`.\n *\n * Every public producing, consuming and reading method guards on this, so \"I forgot to await\n * `init()`\" surfaces as this message rather than as whatever the driver says about not being\n * connected.\n */\nexport class NotStartedError extends PortQueueError {\n constructor(method: string, context?: ErrorContext) {\n super(\n `Cannot call \\`${method}\\` before PortQueue has started. Call \\`await pq.init()\\` first — ` +\n `it connects the driver, applies migrations and starts the workers.`,\n { code: PortQueueErrorCode.NOT_STARTED, ...(context ? { context } : {}) },\n );\n }\n}\n\nexport class InvalidOptionsError extends PortQueueError {\n constructor(message: string, context?: ErrorContext, cause?: unknown) {\n super(message, {\n code: PortQueueErrorCode.INVALID_OPTIONS,\n ...(context ? { context } : {}),\n ...(cause !== undefined ? { cause } : {}),\n });\n }\n}\n\nexport class UnsupportedCapabilityError extends PortQueueError {\n constructor(capability: string, workaround: string, context?: ErrorContext) {\n super(`The configured driver does not support the '${capability}' capability. ${workaround}`, {\n code: PortQueueErrorCode.UNSUPPORTED_CAPABILITY,\n context: { capability, ...context },\n });\n }\n}\n\nexport class SchemaVersionMismatchError extends PortQueueError {\n constructor(actual: number | null, expected: number, context?: ErrorContext) {\n super(\n `Database schema is at version ${actual ?? 0} but this @portqueue/core expects version ${expected}. ` +\n `Run 'npx portqueue migrate' (or set migration: MigrationMode.AUTO). ` +\n `Startup aborted because migration mode is VALIDATE_ONLY.`,\n {\n code: PortQueueErrorCode.SCHEMA_VERSION_MISMATCH,\n context: { actualVersion: actual ?? 0, expectedVersion: expected, ...context },\n },\n );\n }\n}\n\nexport class MigrationFailedError extends PortQueueError {\n constructor(message: string, cause?: unknown, context?: ErrorContext) {\n super(message, {\n code: PortQueueErrorCode.MIGRATION_FAILED,\n ...(context ? { context } : {}),\n ...(cause !== undefined ? { cause } : {}),\n });\n }\n}\n\nexport class DriverConnectionError extends PortQueueError {\n constructor(message: string, cause?: unknown, context?: ErrorContext) {\n super(message, {\n code: PortQueueErrorCode.DRIVER_CONNECTION_ERROR,\n ...(context ? { context } : {}),\n ...(cause !== undefined ? { cause } : {}),\n });\n }\n}\n\nexport class DriverQueryError extends PortQueueError {\n constructor(message: string, cause?: unknown, context?: ErrorContext) {\n super(message, {\n code: PortQueueErrorCode.DRIVER_QUERY_ERROR,\n ...(context ? { context } : {}),\n ...(cause !== undefined ? { cause } : {}),\n });\n }\n}\n\n/**\n * Thrown when an **admin** client (the dashboard or the CLI, constructed with `_headless`) is asked\n * to produce onto a queue that has no row yet. A headless client never writes a queue row: creating\n * one is the application's declaration of intent, made with `createQueue`, and an admin tool\n * inventing queues would put rows in the database for names that no code consumes.\n */\nexport class QueueNotFoundError extends PortQueueError {\n constructor(queue: string) {\n super(\n `Queue '${queue}' does not exist. This client is headless (the dashboard or CLI), and a ` +\n `headless client never creates queues — declare it in your application with ` +\n `\\`pq.createQueue({ name: '${queue}' })\\` first.`,\n { code: PortQueueErrorCode.QUEUE_NOT_FOUND, context: { queue } },\n );\n }\n}\n\n/**\n * Thrown by {@link PortQueue.cancelJob} for an id that names no row.\n *\n * The one place a missing job is an error rather than a return value. `cancelJob` answers with what\n * it *did* — cancelled the row, or only signalled a running handler — and \"there was nothing to\n * cancel\" is not one of those answers. Every other by-id operation still reports a stale id as\n * `null`/`false`, so a batch can skip it.\n */\nexport class JobNotFoundError extends PortQueueError {\n constructor(jobId: string) {\n super(\n `Job '${jobId}' does not exist, so there was nothing to cancel. Its row may have been ` +\n `removed, or deleted by retention.`,\n { code: PortQueueErrorCode.JOB_NOT_FOUND, context: { jobId } },\n );\n }\n}\n\nexport class QueuePausedError extends PortQueueError {\n constructor(queue: string) {\n super(\n `Queue '${queue}' is paused with PauseMode.ALL and is refusing new jobs. ` +\n `Resume it with pq.resumeQueue({ queue }) (or the dashboard/CLI) to accept jobs again.`,\n { code: PortQueueErrorCode.QUEUE_PAUSED, context: { queue } },\n );\n }\n}\n\nexport class QueueInUseError extends PortQueueError {\n constructor(queue: string) {\n super(\n `Queue '${queue}' is still declared in this process (createQueue) and cannot ` +\n `be removed. Removal is a manual admin action for queues no longer used by any running ` +\n `code — stop referencing it everywhere first. The tool never removes queues on its own.`,\n { code: PortQueueErrorCode.QUEUE_IN_USE, context: { queue } },\n );\n }\n}\n\nexport class InstanceActiveError extends PortQueueError {\n constructor(instanceKey: string) {\n super(\n `Instance '${instanceKey}' is still active (heartbeat within the last 30 minutes) and cannot ` +\n `be removed. Only long-inactive instances can be removed from monitoring; wait until it ` +\n `has not been seen for 30 minutes.`,\n { code: PortQueueErrorCode.INSTANCE_ACTIVE, context: { instanceKey } },\n );\n }\n}\n\nexport class ShutdownTimeoutError extends PortQueueError {\n constructor(timeoutSeconds: number) {\n super(\n `Graceful shutdown timed out after ${timeoutSeconds}s; in-flight handlers were aborted and their locks released for reclaim.`,\n { code: PortQueueErrorCode.SHUTDOWN_TIMEOUT },\n );\n }\n}\n\n/**\n * A handler finished, but the job's row was no longer its to settle: the lock had lapsed and another\n * worker reclaimed the row, so the outcome was refused rather than written over the new run's.\n *\n * Surfaced on the `ERROR` event, never thrown at a caller — the handler itself did nothing wrong,\n * and the job is already running (or has already run) somewhere else. Seeing this repeatedly means\n * handlers are outliving their `lockDurationSeconds`.\n */\nexport class LockLostError extends PortQueueError {\n constructor(jobId: string, queue: string) {\n super(\n `Job '${jobId}' on queue '${queue}' finished after its claim was lost, so its outcome was not ` +\n `recorded — another worker had already reclaimed the row. Raise \\`lockDurationSeconds\\` for ` +\n `this queue, or make the handler observe \\`job.signal\\`.`,\n { code: PortQueueErrorCode.LOCK_LOST, context: { jobId, queue } },\n );\n }\n}\n\nexport class MissingPeerDependencyError extends PortQueueError {\n constructor(pkg: string, driver: string) {\n super(\n `The ${driver} driver requires the '${pkg}' package. Install it with \\`npm install ${pkg}\\`.`,\n { code: PortQueueErrorCode.MISSING_PEER_DEPENDENCY, context: { engine: driver } },\n );\n }\n}\n","import { DEFAULT_MAX_IDENTIFIER_LEN, DEFAULT_TABLE_PREFIX } from '../constants';\nimport { InvalidOptionsError } from '../errors/errors';\n\n/** Logical table names. Never a string literal at a query site. */\nexport enum TableName {\n QUEUE = 'queue',\n JOB = 'job',\n SCHEDULE = 'schedule',\n INSTANCE = 'instance',\n MIGRATION = 'migration',\n}\n\n/**\n * Physical column names, one enum per table. Drivers reference these instead of raw string\n * literals in queries so a rename is a single edit and a typo is a compile error. Exported for\n * driver authors and dashboard/reporting code that builds engine-agnostic column references.\n *\n * NOTE: migration DDL deliberately does NOT use these enums — see `drivers/<engine>/migrations.ts`.\n * A migration is a historical record of a schema that has already run; renaming an enum member must\n * never retroactively rewrite a past migration, so those files keep raw column-name strings.\n */\nexport enum QueueColumn {\n NAME = 'name',\n PROCESSING_PAUSED = 'processing_paused',\n ACCEPTING_PAUSED = 'accepting_paused',\n CREATED_AT = 'created_at',\n UPDATED_AT = 'updated_at',\n}\n\nexport enum JobColumn {\n ID = 'id',\n QUEUE_NAME = 'queue_name',\n STATUS = 'status',\n PRIORITY = 'priority',\n DATA = 'data',\n RETURN_VALUE = 'return_value',\n CREATED_AT = 'created_at',\n UPDATED_AT = 'updated_at',\n START_AFTER = 'start_after',\n EXPIRE_AT = 'expire_at',\n STARTED_AT = 'started_at',\n COMPLETED_AT = 'completed_at',\n FAILED_AT = 'failed_at',\n RETRIED_AT = 'retried_at',\n STALLED_AT = 'stalled_at',\n CANCELLED_AT = 'cancelled_at',\n EXPIRED_AT = 'expired_at',\n LOCKED_UNTIL = 'locked_until',\n /**\n * A fresh token written by every claim, and the fence every completion is guarded on.\n *\n * `locked_until` alone cannot say *whose* claim a row is under: a lock that lapses is reclaimed,\n * the row is claimed again, and it is `ACTIVE` with a future deadline once more — so a handler\n * from the first run that ignored its abort signal could still write its outcome over the second\n * run's. A token identifies the claim itself, so a stale completion matches nothing and is refused.\n */\n LOCK_TOKEN = 'lock_token',\n PREFERRED_INSTANCE_KEY_PATTERN = 'preferred_instance_key_pattern',\n PROCESSED_ON_INSTANCE_KEY = 'processed_on_instance_key',\n RETRY_ATTEMPT = 'retry_attempt',\n RETRY_MAX_ATTEMPTS = 'retry_max_attempts',\n RETRY_DELAY_SECONDS = 'retry_delay_seconds',\n RETRY_BACKOFF = 'retry_backoff',\n RETRY_BACKOFF_FACTOR = 'retry_backoff_factor',\n RETRY_MAX_DELAY_SECONDS = 'retry_max_delay_seconds',\n RETRY_JITTER = 'retry_jitter',\n FAILURE_MESSAGE = 'failure_message',\n /**\n * How long after finishing this job may be deleted, in whole seconds, or NULL to keep it forever.\n * NULL is the whole of \"no retention policy\" — there is no separate mode column to disagree with\n * it.\n */\n RETENTION_TTL_SECONDS = 'retention_ttl_seconds',\n /**\n * The finished statuses this job's retention policy may delete, as a comma-separated token list,\n * or NULL for \"every finished status\". Frozen onto the row like every other retention field, so a\n * policy change never retroactively re-scopes jobs that are already queued.\n */\n RETENTION_STATUSES = 'retention_statuses',\n IDEMPOTENCY_KEY = 'idempotency_key',\n SCHEDULE_ID = 'schedule_id',\n SINGLETON_KEY = 'singleton_key',\n}\n\nexport enum ScheduleColumn {\n ID = 'id',\n QUEUE_NAME = 'queue_name',\n CRON = 'cron',\n EVERY_SECONDS = 'every_seconds',\n TIMEZONE = 'timezone',\n DATA = 'data',\n PRIORITY = 'priority',\n RETRY_MAX_ATTEMPTS = 'retry_max_attempts',\n RETRY_DELAY_SECONDS = 'retry_delay_seconds',\n NEXT_RUN_AT = 'next_run_at',\n LAST_RUN_AT = 'last_run_at',\n ENABLED = 'enabled',\n IDEMPOTENCY_KEY = 'idempotency_key',\n JOB_OPTIONS = 'job_options',\n CREATED_AT = 'created_at',\n UPDATED_AT = 'updated_at',\n}\n\nexport enum InstanceColumn {\n INSTANCE_KEY = 'instance_key',\n PROCESSING_PAUSED = 'processing_paused',\n CREATED_AT = 'created_at',\n UPDATED_AT = 'updated_at',\n LAST_SEEN_AT = 'last_seen_at',\n CPU_PERCENT = 'cpu_percent',\n MEMORY_PERCENT = 'memory_percent',\n}\n\nexport enum MigrationColumn {\n VERSION = 'version',\n CREATED_AT = 'created_at',\n UPDATED_AT = 'updated_at',\n}\n\nconst IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * Validate a user-influenced identifier (schema / tablePrefix) against a strict\n * allowlist. Fails fast with a clear error; never reaches SQL raw.\n */\nexport function validateIdentifier(\n kind: string,\n value: string,\n maxLen = DEFAULT_MAX_IDENTIFIER_LEN,\n): string {\n if (!IDENTIFIER_RE.test(value)) {\n throw new InvalidOptionsError(\n `Invalid ${kind} '${value}': must match ${IDENTIFIER_RE} (letters, digits, underscore; not starting with a digit).`,\n );\n }\n if (value.length > maxLen) {\n throw new InvalidOptionsError(\n `Invalid ${kind} '${value}': exceeds the ${maxLen}-character limit for this engine.`,\n );\n }\n return value;\n}\n\n/**\n * Resolves prefixed and (where the engine has them) schema-qualified object names once.\n *\n * Two accessors, because the two forms are not interchangeable:\n *\n * - {@link qualified} is what every query site uses. With `schema: 'jobs'` it returns\n * `jobs.pq_job`, so the tables really are created in and read from that schema.\n * - {@link bare} is the unqualified `pq_job`, for the places a schema prefix is wrong: naming a\n * *derived* object (an index, a constraint) that an engine files alongside its table, and\n * engine metadata lookups that take a schema and a table name as separate values.\n */\nexport class TableNames {\n readonly prefix: string;\n readonly schema?: string;\n\n constructor(options: { tablePrefix?: string; schema?: string; maxIdentifierLen?: number }) {\n this.prefix = validateIdentifier(\n 'tablePrefix',\n options.tablePrefix ?? DEFAULT_TABLE_PREFIX,\n options.maxIdentifierLen,\n );\n if (options.schema !== undefined) {\n this.schema = validateIdentifier('schema', options.schema, options.maxIdentifierLen);\n }\n }\n\n /** The bare (unqualified) physical table name, e.g. `pq_job`. */\n bare(table: TableName): string {\n return `${this.prefix}${table}`;\n }\n\n /**\n * The name a query must use: schema-qualified when a `schema` was configured, bare otherwise.\n * Both halves are allowlist-validated identifiers, so nothing here can be injected.\n */\n qualified(table: TableName): string {\n const name = this.bare(table);\n return this.schema ? `${this.schema}.${name}` : name;\n }\n\n /**\n * The name for an object an engine files *inside* the table's own schema — an index or a\n * constraint. `<prefix><table>_<suffix>`, unqualified, because qualifying it would name the\n * schema twice (`CREATE INDEX jobs.x ON jobs.pq_job` is an error on PostgreSQL).\n */\n derived(table: TableName, suffix: string): string {\n return `${this.bare(table)}_${suffix}`;\n }\n}\n","import { DEFAULT_NAMESPACE } from '../constants';\nimport { TableNames } from './table-names';\n\n/**\n * How a driver lays its data out in the database. Every field is per-engine: two drivers pointing\n * at different databases can use different schemas, prefixes, and namespaces, so these belong on\n * each driver's own options — not on the top-level client. Engines that have schemas honour\n * `schema` by qualifying every object name with it; SQLite has none and does not accept the option.\n */\nexport interface StorageOptions {\n /** DB schema/namespace (PostgreSQL/PGLite/MySQL/Oracle). */\n schema?: string;\n /** Prefix for all created tables (default 'pq_'). */\n tablePrefix?: string;\n /** Logical prefix for pub/sub channels when multiple PortQueues share one DB. */\n namespace?: string;\n}\n\n/**\n * Shared value object a driver builds from its {@link StorageOptions} so all object names are\n * computed once. Also carries the pub/sub namespace.\n */\nexport class DriverContext {\n readonly tableNames: TableNames;\n readonly namespace: string;\n\n constructor(options: {\n tablePrefix?: string;\n schema?: string;\n namespace?: string;\n maxIdentifierLen?: number;\n }) {\n this.tableNames = new TableNames({\n ...(options.tablePrefix !== undefined ? { tablePrefix: options.tablePrefix } : {}),\n ...(options.schema !== undefined ? { schema: options.schema } : {}),\n ...(options.maxIdentifierLen !== undefined\n ? { maxIdentifierLen: options.maxIdentifierLen }\n : {}),\n });\n this.namespace = options.namespace ?? DEFAULT_NAMESPACE;\n }\n}\n","import { FINISHED_STATUSES, JobStatus } from '../../jobs/job-state.enum';\n\n/**\n * How a job's `retention_statuses` column is encoded, and how a query matches against it.\n *\n * Retention is resolved **per job** and frozen onto its row, so the statuses a policy applies to have\n * to travel with the job rather than be re-read from a queue's live options. That is one small fixed\n * set per row, which rules out a side table (the no-JOIN invariant).\n *\n * The encoding is a **bitmask integer**, one bit per finished status. It used to be a comma-delimited\n * token list matched with `LIKE '%,COMPLETED,%'`, and that was the problem: a leading-wildcard `LIKE`\n * is unindexable on every engine here, and the retention sweep `OR`ed four of them — so each batch\n * ran four pattern matches per candidate row on top of the scan it could not avoid. A bitmask is one\n * integer test per row against a bound constant, in a fraction of the bytes.\n *\n * `NULL` still means \"every finished status\" — the default, and the cheapest row to store.\n *\n * This is encoding mechanism, not SQL: every driver builds its own statement and calls these to\n * produce the bound values.\n */\n\n/**\n * The bit for one finished status — its position in {@link FINISHED_STATUSES}.\n *\n * That order is now part of the stored format, so a status may be **appended** to that list but never\n * reordered or removed: doing so would silently re-interpret every row already written.\n */\nfunction bit(status: JobStatus): number {\n const index = FINISHED_STATUSES.indexOf(status);\n return index === -1 ? 0 : 1 << index;\n}\n\n/** Encode a resolved status list for storage, or `null` for \"every finished status\". */\nexport function encodeRetentionStatuses(statuses: readonly JobStatus[] | null): number | null {\n if (!statuses || statuses.length === 0) return null;\n // Deduplicated by construction — a bit is set or it isn't — so two equivalent policies always\n // produce the same stored value.\n const unique = FINISHED_STATUSES.filter((s) => statuses.includes(s));\n // \"All of them\" is the same policy as \"unscoped\", and NULL is the cheaper way to say it.\n if (unique.length === 0 || unique.length === FINISHED_STATUSES.length) return null;\n return unique.reduce((mask, status) => mask | bit(status), 0);\n}\n\n/** Decode a stored value back to the list a caller sees, or `null` when unscoped. */\nexport function decodeRetentionStatuses(value: unknown): JobStatus[] | null {\n if (value == null) return null;\n const mask = Number(value);\n if (!Number.isFinite(mask) || mask === 0) return null;\n const statuses = FINISHED_STATUSES.filter((status) => (mask & bit(status)) !== 0);\n return statuses.length ? statuses : null;\n}\n\n/**\n * The bound value a query tests `retention_statuses` against for one status: that status's bit. A row\n * is eligible when `retention_statuses & <bit> <> 0`, or when the column is NULL — which every\n * driver's predicate checks first.\n */\nexport function retentionStatusBit(status: JobStatus): number {\n return bit(status);\n}\n","/**\n * Claim-time instance affinity. Pure, engine-agnostic logic: portable SQL cannot evaluate regular\n * expressions, so the claim path selects candidates and applies affinity here in the tool.\n *\n * Affinity is a single **preferred key pattern**. A job with no pattern runs anywhere; a job with\n * a pattern runs only on an instance whose key matches it. There is no exact-key pin and no\n * fallback tier — a pattern already spans many instances, so the first live match takes the job,\n * and if none match it simply waits. Build patterns that scale (e.g. `ram-8gb.*cpu-4cor`) rather\n * than pinning to one server that might disappear.\n *\n * **Nothing is cached.** A pattern is compiled where it is used, from the value the candidate row\n * carries. A module-global compiled-regex map would be process-lifetime state shared by every\n * PortQueue in the process — which contradicts \"DI per PortQueue instance\" — and it bought nothing:\n * constructing a `RegExp` is cheap next to the round trip that fetched the row it came from.\n */\n\n/**\n * Does `selfKey` satisfy a preferred pattern? A `null` pattern means \"no constraint\" and matches\n * any instance. An invalid regex matches nothing (the job waits rather than running anywhere).\n */\nexport function matchesInstance(pattern: string | null, selfKey: string): boolean {\n if (pattern == null) return true;\n try {\n return new RegExp(pattern).test(selfKey);\n } catch {\n return false;\n }\n}\n","import { randomUUID } from 'node:crypto';\n\n/** Generate a v4 UUID via `node:crypto`. Used when the engine can't. */\nexport function uuid(): string {\n return randomUUID();\n}\n","import { InvalidOptionsError } from '../errors/errors';\n\n/**\n * Seconds are the only unit of time PortQueue accepts. Nothing is parsed: a duration option is a\n * plain number of seconds, so `'1m'` (which reads as a month to some and a minute to others) is a\n * type error rather than a silent misconfiguration.\n *\n * Every duration that describes a job — its delay, expiry, retry, retention, recurrence interval,\n * rate window — is a **whole** number of seconds, because that is how it is stored: the duration\n * columns are integers. Fractions are rejected by {@link wholeSeconds} rather than silently\n * truncated by the engine. The in-process loop cadences (tick, poll, lock, heartbeat, sampling,\n * shutdown timeout) are never stored and may be fractional — those go through {@link secondsToMs}.\n *\n * **This module is the only place seconds meet milliseconds.** The clock, `setTimeout`/`setInterval`\n * and every stored *instant* are epoch-ms, so a duration is multiplied by 1000 exactly once, here.\n * There is no inline `* 1000` anywhere else in the codebase.\n */\n\n/**\n * The one conversion factor. Named so the literal `1000` never floats free — including inside a\n * driver's SQL, where a per-row `retention_ttl_seconds` has to be scaled by the engine because the\n * value is a column rather than a bind.\n */\nexport const MS_PER_SECOND = 1000;\n\n/** Multiply a validated whole-second duration into milliseconds. */\nexport function wholeSecondsToMs(seconds: number, option: string): number {\n return wholeSeconds(seconds, option) * MS_PER_SECOND;\n}\n\n/** Validate a whole-second duration and return it unchanged. */\nexport function wholeSeconds(seconds: number, option: string): number {\n if (typeof seconds !== 'number' || !Number.isInteger(seconds) || seconds < 0) {\n throw new InvalidOptionsError(\n `Invalid '${option}' value ${JSON.stringify(seconds)}: expected a whole, non-negative ` +\n `number of seconds. PortQueue takes every duration in seconds and stores them as ` +\n `integers — pass 90, not '1m30s' and not 90.5.`,\n );\n }\n return seconds;\n}\n\n/**\n * Multiply a **possibly fractional** second duration into milliseconds. For the process-local\n * cadences and thresholds that never reach a row — timer intervals, sampling windows, the shutdown\n * budget — where a sub-second value is genuinely meaningful (`0.2` is a useful event-loop-delay\n * threshold; `1` is not). Negative values are allowed here and only here: `extendLock` releases a\n * lock by pushing its deadline into the past.\n */\nexport function secondsToMs(seconds: number, option: string): number {\n if (typeof seconds !== 'number' || !Number.isFinite(seconds)) {\n throw new InvalidOptionsError(\n `Invalid '${option}' value ${JSON.stringify(seconds)}: expected a finite number of ` +\n `seconds. PortQueue takes every duration in seconds — pass 0.2 for 200 ms, not '200ms'.`,\n );\n }\n return seconds * MS_PER_SECOND;\n}\n\n/**\n * Milliseconds back to seconds, for the one direction that goes the other way: reporting how long\n * something took. Keeps the `/ 1000` beside the `* 1000` rather than inline at the event site.\n */\nexport function msToSeconds(ms: number): number {\n return ms / MS_PER_SECOND;\n}\n","import { BackoffStrategy } from '../../options/enums';\nimport { emptyStatusCounts, JobStatus } from '../../jobs/job-state.enum';\nimport { DriverCapability, type DriverCapabilitySet } from '../driver-capabilities';\nimport { DriverContext } from '../driver-context';\nimport { InstanceColumn, JobColumn, QueueColumn, ScheduleColumn, TableName } from '../table-names';\nimport { decodeRetentionStatuses, encodeRetentionStatuses } from './retention-statuses';\nimport { matchesInstance } from '../../jobs/instance-affinity';\nimport { uuid } from '../../util/uuid';\nimport { secondsToMs } from '../../util/seconds';\nimport {\n AFFINITY_MAX_PAGES,\n AFFINITY_MIN_SCAN,\n AFFINITY_PAGE_FACTOR,\n AFFINITY_PAGE_MAX,\n AFFINITY_PAGE_MIN_HEADROOM,\n MAX_BATCH_IDS,\n} from '../../constants';\n\nimport type {\n InstanceRow,\n JobRecord,\n NewJobRecord,\n QueueRow,\n ScheduledJobOptions,\n ScheduleRow,\n} from '../../jobs/job-record';\nimport type { PageWindow } from '../driver.interface';\nimport type { TransactionHandle, TxQueryResult } from '../../tx/transaction-handle';\n\n/**\n * Binds a statement carrying an id list needs *besides* the list — a status guard, a timestamp, a\n * queue name. Small and fixed; the point is only that a chunk sized to the whole bind budget would\n * leave no room for them.\n */\nconst IN_LIST_BIND_HEADROOM = 16;\n\n/** A raw query result, normalized across every client library. */\nexport interface RawResult {\n rows: Array<Record<string, unknown>>;\n rowCount: number;\n}\n\n/** An opaque per-connection handle a driver threads through one transaction. */\nexport type Session = unknown;\n\n/** One row as the client library handed it over, keys already lower-cased. */\nexport type Row = Record<string, unknown>;\n\n/**\n * Every `job` column, in the order {@link BaseDriver.jobInsertValues} produces values for. Shared\n * because it is the *shape of a row*, not SQL: a column added to the schema must appear in the\n * insert of every engine, and one list makes that impossible to forget.\n */\nexport const JOB_COLUMNS: readonly JobColumn[] = [\n JobColumn.ID,\n JobColumn.QUEUE_NAME,\n JobColumn.STATUS,\n JobColumn.PRIORITY,\n JobColumn.DATA,\n JobColumn.RETURN_VALUE,\n JobColumn.CREATED_AT,\n JobColumn.UPDATED_AT,\n JobColumn.START_AFTER,\n JobColumn.EXPIRE_AT,\n JobColumn.STARTED_AT,\n JobColumn.COMPLETED_AT,\n JobColumn.FAILED_AT,\n JobColumn.RETRIED_AT,\n JobColumn.STALLED_AT,\n JobColumn.CANCELLED_AT,\n JobColumn.EXPIRED_AT,\n JobColumn.LOCKED_UNTIL,\n JobColumn.LOCK_TOKEN,\n JobColumn.PREFERRED_INSTANCE_KEY_PATTERN,\n JobColumn.PROCESSED_ON_INSTANCE_KEY,\n JobColumn.RETRY_ATTEMPT,\n JobColumn.RETRY_MAX_ATTEMPTS,\n JobColumn.RETRY_DELAY_SECONDS,\n JobColumn.RETRY_BACKOFF,\n JobColumn.RETRY_BACKOFF_FACTOR,\n JobColumn.RETRY_MAX_DELAY_SECONDS,\n JobColumn.RETRY_JITTER,\n JobColumn.FAILURE_MESSAGE,\n JobColumn.RETENTION_TTL_SECONDS,\n JobColumn.RETENTION_STATUSES,\n JobColumn.IDEMPOTENCY_KEY,\n JobColumn.SCHEDULE_ID,\n JobColumn.SINGLETON_KEY,\n];\n\n/** The columns a schedule insert writes, in {@link BaseDriver.scheduleInsertValues} order. */\nexport const SCHEDULE_INSERT_COLUMNS: readonly ScheduleColumn[] = [\n ScheduleColumn.ID,\n ScheduleColumn.QUEUE_NAME,\n ScheduleColumn.CRON,\n ScheduleColumn.EVERY_SECONDS,\n ScheduleColumn.TIMEZONE,\n ScheduleColumn.DATA,\n ScheduleColumn.JOB_OPTIONS,\n ScheduleColumn.PRIORITY,\n ScheduleColumn.RETRY_MAX_ATTEMPTS,\n ScheduleColumn.RETRY_DELAY_SECONDS,\n ScheduleColumn.NEXT_RUN_AT,\n ScheduleColumn.ENABLED,\n ScheduleColumn.IDEMPOTENCY_KEY,\n ScheduleColumn.CREATED_AT,\n ScheduleColumn.UPDATED_AT,\n];\n\n/**\n * What every driver shares — and **only** what every driver shares.\n *\n * The duplicate-over-share rule in CLAUDE.md is about *dialect and query SQL*: a change to one\n * engine's statement must never leak into another's. None of that lives here. What does live here is\n * the same category as `TableName`, the `MigrationRunner` and the value objects — row → record\n * mapping, value conversion, id generation, the affinity filter, and the paging arithmetic:\n *\n * - **Mapping** (`mapJob`, `mapQueue`, `mapSchedule`, `mapInstance`) turns a result row into the\n * record shape core consumes. It contains no SQL and cannot: it reads a `Row` by column name.\n * Duplicating it bought nothing and cost a real bug — a column added to the schema had to be\n * remembered in five files, and `retention_statuses` would have been missed in at least one.\n * - **Value conversion** (`toJson`, `boolIn`, `numOrNull`, …) is JS-side normalization of what a\n * client library hands back.\n * - **Insert values** (`jobInsertValues`) is the ordered value list matching {@link JOB_COLUMNS}.\n * Each driver still writes its own `INSERT` statement around it.\n * - **The affinity scan** (`affinityPlan`, `matchAffinity`) is the paging arithmetic and the regex\n * test. The driver supplies the `SELECT` — the part that is dialect.\n *\n * Everything a subclass must provide is abstract: the connection (`execute`, `transaction`),\n * the placeholder style (`ph`), and the paging tail (`window`). No statement string appears below.\n */\nexport abstract class BaseDriver {\n abstract readonly capabilities: DriverCapabilitySet;\n readonly context: DriverContext;\n\n /**\n * The most bound parameters this engine accepts in one statement. The default is a floor that\n * every supported engine clears: SQLite's `SQLITE_MAX_VARIABLE_NUMBER` (32766 on a modern build),\n * PostgreSQL' 16-bit parameter index (65535) and MySQL's `max_prepared_stmt_count` are all above it.\n * A driver whose engine is tighter — Oracle's `INSERT ALL` — lowers it.\n */\n protected readonly maxBindParams: number = 30_000;\n\n /**\n * The most expressions this engine allows in one `IN (...)` list.\n *\n * A separate limit from {@link maxBindParams}, and on Oracle a much tighter one — 1000 expressions,\n * whatever the bind budget — which is why {@link MAX_BATCH_IDS} caps a batch at that number for\n * every engine. A driver whose engine is tighter still lowers this.\n */\n protected readonly maxInListItems: number = MAX_BATCH_IDS;\n\n protected constructor(options: {\n tablePrefix?: string;\n schema?: string;\n namespace?: string;\n maxIdentifierLen?: number;\n }) {\n this.context = new DriverContext(options);\n }\n\n // --- Connection mechanism (each engine's own) ---\n\n /** Run one statement, on `session`'s connection when inside a transaction. */\n protected abstract execute(\n sql: string,\n params: readonly unknown[],\n session?: Session,\n ): Promise<RawResult>;\n\n /** Run `fn` inside one transaction, handing it the session its statements must use. */\n protected abstract transaction<T>(fn: (session: Session) => Promise<T>): Promise<T>;\n\n /** This engine's placeholder for the 0-based parameter at `index0` (`$1`, `?`, `:1`, …). */\n protected abstract ph(index0: number): string;\n\n /**\n * The trailing paging clause for a list read, appending each bound value to `params`. Dialect —\n * `LIMIT/OFFSET` on most engines, `OFFSET … ROWS FETCH NEXT … ROWS ONLY` on Oracle — so each\n * driver writes its own. Returns `''` when the caller asked for no window, so core's unpaged\n * reads emit no paging clause at all.\n */\n protected abstract window(page: PageWindow, params: unknown[]): string;\n\n // --- Naming ---\n\n /** The name a statement must reference: schema-qualified when a `schema` was configured. */\n protected t(table: TableName): string {\n return this.context.tableNames.qualified(table);\n }\n\n /**\n * Run one statement: on the caller's transaction when there is one, otherwise on its own.\n *\n * A lone statement needs no explicit `BEGIN` — every engine here runs it inside an implicit\n * transaction, so it is already all-or-nothing. What must never happen is a *sequence* of\n * statements outside a transaction; that is what {@link inTx} is for, and every multi-statement\n * driver method goes through it.\n */\n protected async runMaybeTx(\n sql: string,\n params: readonly unknown[],\n tx?: TransactionHandle,\n ): Promise<RawResult> {\n if (tx) {\n const res: TxQueryResult = await tx.execute(sql, [...params]);\n return { rows: res.rows, rowCount: res.rowCount };\n }\n return this.execute(sql, params);\n }\n\n /**\n * Run several statements as one unit: the caller's transaction when there is one, otherwise a\n * fresh one of ours. `run` issues each statement on whichever connection is correct.\n *\n * Every driver method that reads then writes — get-or-create, the dedup-plus-insert pair, the\n * heartbeat's update-then-insert, a claim's scan-then-update — uses this. Outside a transaction\n * those pairs can interleave with another instance's; inside one they cannot.\n */\n protected async inTx<T>(\n tx: TransactionHandle | undefined,\n fn: (run: (sql: string, params: readonly unknown[]) => Promise<RawResult>) => Promise<T>,\n ): Promise<T> {\n if (tx) {\n return fn(async (sql, params) => {\n const res = await tx.execute(sql, [...params]);\n return { rows: res.rows, rowCount: res.rowCount };\n });\n }\n return this.transaction((session) => fn((sql, params) => this.execute(sql, params, session)));\n }\n\n /** The capability keys this driver declares as on — what `probe()` reports as verified. */\n protected enabledCapabilities(): DriverCapability[] {\n return (Object.keys(this.capabilities) as DriverCapability[]).filter(\n (cap) => this.capabilities[cap],\n );\n }\n\n /** A comma-separated placeholder list for `count` params starting at `from`. */\n protected phList(count: number, from = 0): string {\n return Array.from({ length: count }, (_, i) => this.ph(from + i)).join(', ');\n }\n\n /**\n * Split a batch so no single statement exceeds this engine's bound-parameter limit.\n *\n * A multi-row insert binds every column of every row, so a batch of a thousand jobs is tens of\n * thousands of parameters — past SQLite's `SQLITE_MAX_VARIABLE_NUMBER` and PostgreSQL' 16-bit\n * parameter index. The caller loops over the chunks; each is still one round trip, so a large\n * batch costs `ceil(rows / chunk)` statements instead of `rows`.\n */\n protected chunkForBind<T>(items: T[], paramsPerItem: number): T[][] {\n const perChunk = Math.max(1, Math.floor(this.maxBindParams / Math.max(paramsPerItem, 1)));\n if (items.length <= perChunk) return [items];\n const chunks: T[][] = [];\n for (let i = 0; i < items.length; i += perChunk) chunks.push(items.slice(i, i + perChunk));\n return chunks;\n }\n\n /**\n * Split a key list so no single statement's `IN (...)` exceeds what the engine allows — both its\n * `IN`-list ceiling and its bound-parameter budget, with headroom for the handful of other binds a\n * statement carries beside the list.\n *\n * Every by-id batch goes through this. `MAX_BATCH_IDS` already refuses a *call* larger than the\n * tightest engine's `IN` limit, so a public batch is always one chunk; this is what keeps an\n * internal caller (or a driver with a lower ceiling) from emitting a statement the engine rejects —\n * `removeJobs` with 1001 ids used to raise ORA-01795 on Oracle and to blow past the parameter\n * index on PostgreSQL and SQLite at a few tens of thousands.\n */\n protected chunkIds<T>(keys: readonly T[]): T[][] {\n const perChunk = Math.max(\n 1,\n Math.min(this.maxInListItems, this.maxBindParams - IN_LIST_BIND_HEADROOM),\n );\n if (keys.length <= perChunk) return [[...keys]];\n const chunks: T[][] = [];\n for (let i = 0; i < keys.length; i += perChunk) chunks.push([...keys.slice(i, i + perChunk)]);\n return chunks;\n }\n\n /**\n * Run one statement per {@link chunkIds} chunk and concatenate what each returned.\n *\n * A single chunk — the case every capped public batch takes — runs exactly the statement it would\n * have without chunking, so nothing is paid for the guard. Several chunks are several statements:\n * inside the caller's transaction when there is one, and otherwise each atomic on its own, which\n * is the same trade every bounded sweep in the tool makes.\n */\n protected async overIdChunks<K, R>(\n keys: readonly K[],\n perChunk: (chunk: K[]) => Promise<R[]>,\n ): Promise<R[]> {\n const chunks = this.chunkIds(keys);\n if (chunks.length === 1) return perChunk(chunks[0]!);\n const out: R[] = [];\n for (const chunk of chunks) out.push(...(await perChunk(chunk)));\n return out;\n }\n\n // --- Value conversion ---\n\n protected toJson(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n return JSON.stringify(value);\n }\n\n protected fromJson(value: unknown): unknown {\n if (value === null || value === undefined) return null;\n if (typeof value === 'string') {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n }\n return value;\n }\n\n protected boolIn(value: boolean): number {\n return value ? 1 : 0;\n }\n\n protected boolOut(value: unknown): boolean {\n return value === 1 || value === true || value === '1' || value === 't';\n }\n\n protected numOrNull(value: unknown): number | null {\n return value == null ? null : Number(value);\n }\n\n protected strOrNull(value: unknown): string | null {\n return value == null ? null : String(value);\n }\n\n /** A fresh application-generated id. Every engine stores ids as strings. */\n protected newId(): string {\n return uuid();\n }\n\n /** A lock deadline `lockDurationSeconds` from `now` (negative releases the lock). */\n protected lockDeadline(now: number, lockDurationSeconds: number): number {\n return now + secondsToMs(lockDurationSeconds, 'limiter.lockDurationSeconds');\n }\n\n /**\n * A bound pattern for a case-insensitive substring search. `%`/`_`/`!` are escaped with `!` —\n * declared by the query's own `ESCAPE '!'` — so a user typing `100%` searches for that text rather\n * than matching everything. Still a bound parameter: nothing here is interpolated into SQL.\n *\n * The term is lower-cased for the engines whose query site lower-cases the column too; PostgreSQL and\n * PGLite use `ILIKE`, where the case folding is the operator's job and this is already inert.\n *\n * **A free-text search is a scan, and no index is declared for one.** The pattern has a leading\n * wildcard, which no B-tree can serve on any engine here — not even over a functional\n * `LOWER(column)` index — so declaring one would suggest a speed-up that cannot happen. What bounds\n * the cost is the `LIMIT` every search read carries, and the fact that only an operator triaging in\n * the dashboard or CLI ever issues one.\n */\n protected likePattern(term: string): string {\n const escaped = term.toLowerCase().replace(/[!%_]/g, (ch) => `!${ch}`);\n return `%${escaped}%`;\n }\n\n /**\n * A zeroed status breakdown, for a key a grouped count query returned nothing for. Delegates to\n * the one definition in `jobs/job-state.enum` — this used to be a second copy of the same object\n * literal, and a new status would have had to be remembered in both.\n */\n protected emptyStatusCounts(): Record<JobStatus, number> {\n return emptyStatusCounts();\n }\n\n // --- Row → record mapping ---\n\n protected mapJob(row: Row): JobRecord {\n return {\n id: String(row[JobColumn.ID]),\n queueName: String(row[JobColumn.QUEUE_NAME]),\n status: row[JobColumn.STATUS] as JobStatus,\n priority: Number(row[JobColumn.PRIORITY]),\n data: this.fromJson(row[JobColumn.DATA]),\n returnValue: this.fromJson(row[JobColumn.RETURN_VALUE]),\n createdAt: Number(row[JobColumn.CREATED_AT]),\n updatedAt: Number(row[JobColumn.UPDATED_AT]),\n startAfter: Number(row[JobColumn.START_AFTER]),\n expireAt: this.numOrNull(row[JobColumn.EXPIRE_AT]),\n startedAt: this.numOrNull(row[JobColumn.STARTED_AT]),\n completedAt: this.numOrNull(row[JobColumn.COMPLETED_AT]),\n failedAt: this.numOrNull(row[JobColumn.FAILED_AT]),\n retriedAt: this.numOrNull(row[JobColumn.RETRIED_AT]),\n stalledAt: this.numOrNull(row[JobColumn.STALLED_AT]),\n cancelledAt: this.numOrNull(row[JobColumn.CANCELLED_AT]),\n expiredAt: this.numOrNull(row[JobColumn.EXPIRED_AT]),\n lockedUntil: this.numOrNull(row[JobColumn.LOCKED_UNTIL]),\n lockToken: this.strOrNull(row[JobColumn.LOCK_TOKEN]),\n preferredInstanceKeyPattern: this.strOrNull(row[JobColumn.PREFERRED_INSTANCE_KEY_PATTERN]),\n processedOnInstanceKey: this.strOrNull(row[JobColumn.PROCESSED_ON_INSTANCE_KEY]),\n retryAttempt: Number(row[JobColumn.RETRY_ATTEMPT]),\n retryMaxAttempts: Number(row[JobColumn.RETRY_MAX_ATTEMPTS]),\n retryDelaySeconds: Number(row[JobColumn.RETRY_DELAY_SECONDS]),\n retryBackoff: row[JobColumn.RETRY_BACKOFF] as BackoffStrategy,\n retryBackoffFactor: this.numOrNull(row[JobColumn.RETRY_BACKOFF_FACTOR]),\n retryMaxDelaySeconds: this.numOrNull(row[JobColumn.RETRY_MAX_DELAY_SECONDS]),\n retryJitter: this.boolOut(row[JobColumn.RETRY_JITTER]),\n failureMessage: this.strOrNull(row[JobColumn.FAILURE_MESSAGE]),\n retentionTtlSeconds: this.numOrNull(row[JobColumn.RETENTION_TTL_SECONDS]),\n retentionStatuses: decodeRetentionStatuses(row[JobColumn.RETENTION_STATUSES]),\n idempotencyKey: this.strOrNull(row[JobColumn.IDEMPOTENCY_KEY]),\n scheduleId: this.strOrNull(row[JobColumn.SCHEDULE_ID]),\n singletonKey: this.strOrNull(row[JobColumn.SINGLETON_KEY]),\n };\n }\n\n protected mapQueue(row: Row): QueueRow {\n return {\n name: String(row[QueueColumn.NAME]),\n processingPaused: this.boolOut(row[QueueColumn.PROCESSING_PAUSED]),\n acceptingPaused: this.boolOut(row[QueueColumn.ACCEPTING_PAUSED]),\n createdAt: Number(row[QueueColumn.CREATED_AT]),\n updatedAt: Number(row[QueueColumn.UPDATED_AT]),\n };\n }\n\n protected mapInstance(row: Row): InstanceRow {\n return {\n instanceKey: String(row[InstanceColumn.INSTANCE_KEY]),\n processingPaused: this.boolOut(row[InstanceColumn.PROCESSING_PAUSED]),\n createdAt: Number(row[InstanceColumn.CREATED_AT]),\n updatedAt: Number(row[InstanceColumn.UPDATED_AT]),\n lastSeenAt: Number(row[InstanceColumn.LAST_SEEN_AT]),\n cpuPercent: this.numOrNull(row[InstanceColumn.CPU_PERCENT]),\n memoryPercent: this.numOrNull(row[InstanceColumn.MEMORY_PERCENT]),\n };\n }\n\n protected mapSchedule(row: Row): ScheduleRow {\n return {\n id: String(row[ScheduleColumn.ID]),\n queueName: String(row[ScheduleColumn.QUEUE_NAME]),\n cron: this.strOrNull(row[ScheduleColumn.CRON]),\n everySeconds: this.numOrNull(row[ScheduleColumn.EVERY_SECONDS]),\n timezone: this.strOrNull(row[ScheduleColumn.TIMEZONE]),\n data: this.fromJson(row[ScheduleColumn.DATA]),\n jobOptions:\n (this.fromJson(row[ScheduleColumn.JOB_OPTIONS]) as ScheduledJobOptions | null) ?? null,\n priority: this.numOrNull(row[ScheduleColumn.PRIORITY]),\n retryMaxAttempts: this.numOrNull(row[ScheduleColumn.RETRY_MAX_ATTEMPTS]),\n retryDelaySeconds: this.numOrNull(row[ScheduleColumn.RETRY_DELAY_SECONDS]),\n nextRunAt: this.numOrNull(row[ScheduleColumn.NEXT_RUN_AT]),\n lastRunAt: this.numOrNull(row[ScheduleColumn.LAST_RUN_AT]),\n enabled: this.boolOut(row[ScheduleColumn.ENABLED]),\n idempotencyKey: this.strOrNull(row[ScheduleColumn.IDEMPOTENCY_KEY]),\n createdAt: Number(row[ScheduleColumn.CREATED_AT]),\n updatedAt: Number(row[ScheduleColumn.UPDATED_AT]),\n };\n }\n\n /** A job's ref as the mutating methods return it. */\n protected mapJobRef(row: Row): { jobId: string; queueName: string } {\n return {\n jobId: String(row[JobColumn.ID]),\n queueName: String(row[JobColumn.QUEUE_NAME]),\n };\n }\n\n /** A schedule's ref as the mutating methods return it. */\n protected mapScheduleRef(row: Row): { scheduleId: string; queueName: string } {\n return {\n scheduleId: String(row[ScheduleColumn.ID]),\n queueName: String(row[ScheduleColumn.QUEUE_NAME]),\n };\n }\n\n // --- Insert value lists ---\n\n /** The ordered values for one job row, matching {@link JOB_COLUMNS} exactly. */\n protected jobInsertValues(job: NewJobRecord): { id: string; values: unknown[] } {\n const id = job.id ?? this.newId();\n const now = job.createdAt;\n return {\n id,\n values: [\n id,\n job.queueName,\n job.status,\n job.priority,\n this.toJson(job.data),\n null, // return_value\n now,\n now,\n job.startAfter,\n job.expireAt,\n null, // started_at\n null, // completed_at\n null, // failed_at\n null, // retried_at\n null, // stalled_at\n null, // cancelled_at\n null, // expired_at\n null, // locked_until\n null, // lock_token (written at claim time)\n job.preferredInstanceKeyPattern,\n null, // processed_on_instance_key (set at claim time)\n job.retryAttempt,\n job.retryMaxAttempts,\n job.retryDelaySeconds,\n job.retryBackoff,\n job.retryBackoffFactor,\n job.retryMaxDelaySeconds,\n this.boolIn(job.retryJitter),\n null, // failure_message\n job.retentionTtlSeconds,\n encodeRetentionStatuses(job.retentionStatuses),\n job.idempotencyKey,\n job.scheduleId,\n job.singletonKey,\n ],\n };\n }\n\n /** The ordered values for one schedule row, matching {@link SCHEDULE_INSERT_COLUMNS}. */\n protected scheduleInsertValues(\n schedule: import('../../jobs/job-record').NewScheduleRow,\n now: number,\n ): { id: string; values: unknown[] } {\n const id = schedule.id ?? this.newId();\n return {\n id,\n values: [\n id,\n schedule.queueName,\n schedule.cron,\n schedule.everySeconds,\n schedule.timezone,\n this.toJson(schedule.data),\n this.toJson(schedule.jobOptions),\n schedule.priority,\n schedule.retryMaxAttempts,\n schedule.retryDelaySeconds,\n schedule.nextRunAt,\n this.boolIn(schedule.enabled),\n schedule.idempotencyKey,\n now,\n now,\n ],\n };\n }\n\n // --- Multi-instance affinity ---\n\n /**\n * The page size and scan ceiling for the multi-instance claim scan.\n *\n * Affinity is a regex and portable SQL cannot evaluate one, so a named instance selects\n * candidates highest-priority-first and filters them here. Paging — rather than one capped\n * window — prevents starvation: when the top rows all target other instances, the jobs this\n * instance *can* run may sit past the first page. The ceiling stops a backlog of\n * exclusively-non-matching jobs from turning one tick into a full-table sweep; the next tick\n * resumes from the top.\n */\n protected affinityPlan(limit: number): { pageSize: number; maxScan: number } {\n const pageSize = Math.min(\n Math.max(limit * AFFINITY_PAGE_FACTOR, limit + AFFINITY_PAGE_MIN_HEADROOM),\n AFFINITY_PAGE_MAX,\n );\n return { pageSize, maxScan: Math.max(pageSize * AFFINITY_MAX_PAGES, AFFINITY_MIN_SCAN) };\n }\n\n /**\n * Collect the ids from one candidate page this instance's key is allowed to run, stopping at\n * `limit`. Returns whether the caller should keep paging.\n */\n protected collectAffinityMatches(\n rows: Row[],\n instanceKey: string,\n limit: number,\n into: Set<string>,\n ): void {\n for (const row of rows) {\n const pattern = this.strOrNull(row[JobColumn.PREFERRED_INSTANCE_KEY_PATTERN]);\n if (!matchesInstance(pattern, instanceKey)) continue;\n into.add(String(row[JobColumn.ID]));\n if (into.size >= limit) return;\n }\n }\n\n /** Claim order: highest priority first, then oldest due. Applied after a claim returns rows. */\n protected sortClaimed(jobs: JobRecord[]): JobRecord[] {\n return jobs.sort((a, b) => b.priority - a.priority || a.startAfter - b.startAfter);\n }\n}\n","import type { MigrationStep } from '../driver.interface';\nimport type { TableName } from '../table-names';\n\n/**\n * The naming helpers a migration's DDL needs.\n *\n * - `name(t)` is the name a statement must reference — schema-qualified when the driver was given a\n * `schema`, so the objects really are created in it.\n * - `derived(t, suffix)` names an object the engine files *inside* that table's own schema (an\n * index, a constraint), which must therefore stay unqualified.\n * - `schema` is the configured schema, for a flavour whose engine can create one.\n */\nexport interface MigrationNames {\n name(table: TableName): string;\n derived(table: TableName, suffix: string): string;\n schema: string | undefined;\n}\n\n/**\n * A predefined migration for one engine at one schema version. `statements` returns the DDL for\n * that step with object names resolved. Each driver authors its own array alongside the driver\n * (`drivers/<engine>/migrations.ts`) — never shared or generated at runtime, so a change to one\n * engine's DDL can never leak into another's.\n *\n * A migration is identified by its `version` and nothing else. There is deliberately no checksum:\n * nothing ever compared one, and a value written but never read states a guarantee the code does\n * not make.\n */\nexport interface FlavourMigration {\n version: number;\n statements(names: MigrationNames): string[];\n}\n\n/**\n * Wrap a driver's authored {@link FlavourMigration} list into the runner's {@link MigrationStep}\n * units — resolving object names against the live context, and nothing else. The driver's\n * `applyMigration` runs the statements *and* records the version in one transaction, so a crash\n * can never leave an applied-but-unrecorded migration. This is the only piece of the migration\n * path shared across engines: the mechanism, never the SQL.\n */\nexport function toMigrationSteps(migrations: FlavourMigration[]): MigrationStep[] {\n return migrations.map((migration) => ({\n version: migration.version,\n statements: (context) =>\n migration.statements({\n name: (t) => context.tableNames.qualified(t),\n derived: (t, suffix) => context.tableNames.derived(t, suffix),\n schema: context.tableNames.schema,\n }),\n }));\n}\n\n/** The highest version among a migration set (the schema version a build ships). */\nexport function latestVersion(migrations: MigrationStep[]): number {\n return migrations.reduce((max, m) => (m.version > max ? m.version : max), 0);\n}\n"],"names":["PortQueueErrorCode","TableName","QueueColumn","JobColumn","ScheduleColumn","InstanceColumn","MigrationColumn"],"mappings":";;AAeO,IAAK,uCAAAA,wBAAL;AACLA,sBAAA,aAAA,IAAc;AACdA,sBAAA,iBAAA,IAAkB;AAClBA,sBAAA,wBAAA,IAAyB;AACzBA,sBAAA,yBAAA,IAA0B;AAC1BA,sBAAA,kBAAA,IAAmB;AACnBA,sBAAA,yBAAA,IAA0B;AAC1BA,sBAAA,oBAAA,IAAqB;AACrBA,sBAAA,eAAA,IAAgB;AAChBA,sBAAA,iBAAA,IAAkB;AAClBA,sBAAA,cAAA,IAAe;AACfA,sBAAA,cAAA,IAAe;AACfA,sBAAA,iBAAA,IAAkB;AAClBA,sBAAA,kBAAA,IAAmB;AACnBA,sBAAA,WAAA,IAAY;AACZA,sBAAA,yBAAA,IAA0B;AAfhB,SAAAA;AAAA,GAAA,sBAAA,CAAA,CAAA;ACSL,MAAM,uBAAuB,MAAM;AAAA,EAC/B;AAAA,EACA;AAAA,EAET,YAAY,SAAiB,SAAgC;AAC3D,UAAM,SAAS,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AE,CAAC,CAAC;AAClC,UAAI,KAAK,QAAQ,MAAO;AAAA,IAC1B;AAAA,EACF;AAAA;AAAA,EAGU,YAAY,MAAgC;AACpD,WAAO,KAAK,KAAK,CAAC,GAAG,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,aAAa,EAAE,UAAU;AAAA,EACnF;AACF;ACxiBO,SAAS,iBAAiB,YAAiD;AAChF,SAAO,WAAW,IAAI,CAAC,eAAe;AAAA,IACpC,SAAS,UAAU;AAAA,IACnB,YAAY,CAAC,YACX,UAAU,WAAW;AAAA,MACnB,MAAM,CAAC,MAAM,QAAQ,WAAW,UAAU,CAAC;AAAA,MAC3C,SAAS,CAAC,GAAG,WAAW,QAAQ,WAAW,QAAQ,GAAG,MAAM;AAAA,MAC5D,QAAQ,QAAQ,WAAW;AAAA,IAAA,CAC5B;AAAA,EAAA,EACH;AACJ;AAGO,SAAS,cAAc,YAAqC;AACjE,SAAO,WAAW,OAAO,CAAC,KAAK,MAAO,EAAE,UAAU,MAAM,EAAE,UAAU,KAAM,CAAC;AAC7E;"}
@@ -43,7 +43,7 @@ export declare enum MigrationMode {
43
43
  }
44
44
  /** Database engines a driver can advertise. */
45
45
  export declare enum DatabaseEngine {
46
- POSTGRES = "POSTGRES",
46
+ POSTGRESQL = "POSTGRESQL",
47
47
  PGLITE = "PGLITE",
48
48
  SQLITE = "SQLITE",
49
49
  ORACLE = "ORACLE",
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
- import { a as DatabaseEngine, c as capabilities, D as DriverCapability, b as DeduplicationReason, A as ACTIVE_STATUSES, J as JobStatus, F as FINISHED_STATUSES } from "./storage.constants-BDS_q-_N.js";
3
- import { T as TableName, B as BaseDriver, t as toMigrationSteps, M as MissingPeerDependencyError, D as DriverConnectionError, a as MigrationColumn, b as DriverQueryError, J as JOB_COLUMNS, c as JobColumn, Q as QueueColumn, S as ScheduleColumn, d as SCHEDULE_INSERT_COLUMNS, I as InstanceColumn, r as retentionStatusBit, e as MS_PER_SECOND } from "./migration-CQsAizIw.js";
2
+ import { a as DatabaseEngine, c as capabilities, D as DriverCapability, b as DeduplicationReason, A as ACTIVE_STATUSES, J as JobStatus, F as FINISHED_STATUSES } from "./storage.constants-DwSzjjMZ.js";
3
+ import { T as TableName, B as BaseDriver, t as toMigrationSteps, M as MissingPeerDependencyError, D as DriverConnectionError, a as MigrationColumn, b as DriverQueryError, J as JOB_COLUMNS, c as JobColumn, Q as QueueColumn, S as ScheduleColumn, d as SCHEDULE_INSERT_COLUMNS, I as InstanceColumn, r as retentionStatusBit, e as MS_PER_SECOND } from "./migration-D73ANkYV.js";
4
4
  function v1(names) {
5
5
  const t = names.name;
6
6
  const idx = names.derived;
@@ -114,11 +114,11 @@ function v1(names) {
114
114
  );
115
115
  return statements;
116
116
  }
117
- const POSTGRES_MIGRATIONS = [{ version: 1, statements: v1 }];
117
+ const POSTGRESQL_MIGRATIONS = [{ version: 1, statements: v1 }];
118
118
  const PG_UNDEFINED_TABLE = "42P01";
119
119
  const PG_UNDEFINED_SCHEMA = "3F000";
120
- class PostgresDriver extends BaseDriver {
121
- engine = DatabaseEngine.POSTGRES;
120
+ class PostgresqlDriver extends BaseDriver {
121
+ engine = DatabaseEngine.POSTGRESQL;
122
122
  capabilities = capabilities({
123
123
  [DriverCapability.SKIP_LOCKED]: true,
124
124
  [DriverCapability.RETURNING]: true,
@@ -126,7 +126,7 @@ class PostgresDriver extends BaseDriver {
126
126
  [DriverCapability.LISTEN_NOTIFY]: true,
127
127
  [DriverCapability.ADVISORY_LOCK]: true
128
128
  });
129
- migrations = toMigrationSteps(POSTGRES_MIGRATIONS);
129
+ migrations = toMigrationSteps(POSTGRESQL_MIGRATIONS);
130
130
  pool = null;
131
131
  listenClient = null;
132
132
  /**
@@ -155,7 +155,7 @@ class PostgresDriver extends BaseDriver {
155
155
  const mod = await import("pg");
156
156
  pg = mod.default ?? mod;
157
157
  } catch {
158
- throw new MissingPeerDependencyError("pg", "Postgres");
158
+ throw new MissingPeerDependencyError("pg", "PostgreSQL");
159
159
  }
160
160
  try {
161
161
  const config = { ...this.options.config };
@@ -163,7 +163,7 @@ class PostgresDriver extends BaseDriver {
163
163
  this.pool = new pg.Pool(config);
164
164
  await this.pool.query("SELECT 1");
165
165
  } catch (err) {
166
- throw new DriverConnectionError("Failed to connect to Postgres.", err);
166
+ throw new DriverConnectionError("Failed to connect to PostgreSQL.", err);
167
167
  }
168
168
  }
169
169
  async disconnect() {
@@ -177,13 +177,13 @@ class PostgresDriver extends BaseDriver {
177
177
  /** Run one statement. `protected` so a PG-wire subclass can swap in its own client. */
178
178
  async execute(sql, params, session) {
179
179
  const target = session ?? this.pool;
180
- if (!target) throw new DriverConnectionError("Postgres driver is not connected.");
180
+ if (!target) throw new DriverConnectionError("PostgreSQL driver is not connected.");
181
181
  const res = await target.query(sql, params);
182
182
  return { rows: res.rows ?? [], rowCount: res.rowCount ?? res.rows?.length ?? 0 };
183
183
  }
184
184
  /** Wrap `fn` in a transaction. `protected` so a PG-wire subclass can swap in its own client. */
185
185
  async transaction(fn) {
186
- if (!this.pool) throw new DriverConnectionError("Postgres driver is not connected.");
186
+ if (!this.pool) throw new DriverConnectionError("PostgreSQL driver is not connected.");
187
187
  const client = await this.pool.connect();
188
188
  try {
189
189
  await client.query("BEGIN");
@@ -197,7 +197,7 @@ class PostgresDriver extends BaseDriver {
197
197
  client.release();
198
198
  }
199
199
  }
200
- /** Postgres uses `$1`-style positional placeholders. */
200
+ /** PostgreSQL uses `$1`-style positional placeholders. */
201
201
  ph(index0) {
202
202
  return `$${index0 + 1}`;
203
203
  }
@@ -1116,7 +1116,7 @@ class PostgresDriver extends BaseDriver {
1116
1116
  ]);
1117
1117
  }
1118
1118
  async subscribe(options) {
1119
- if (!this.pool) throw new DriverConnectionError("Postgres driver is not connected.");
1119
+ if (!this.pool) throw new DriverConnectionError("PostgreSQL driver is not connected.");
1120
1120
  const ch = this.channel(options.channel);
1121
1121
  if (!this.listenClient) {
1122
1122
  this.listenClient = await this.pool.connect();
@@ -1203,7 +1203,7 @@ function advisoryKey(key) {
1203
1203
  }
1204
1204
  const ADVISORY_KEY_BYTES = 6;
1205
1205
  export {
1206
- PostgresDriver as P,
1206
+ PostgresqlDriver as P,
1207
1207
  v1 as v
1208
1208
  };
1209
- //# sourceMappingURL=postgres-driver-eWlY7pVg.js.map
1209
+ //# sourceMappingURL=postgresql-driver-BUHuyRYj.js.map