@portqueue/core 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/dist/conformance/index.cjs +1 -1
- package/dist/conformance/index.mjs +1 -1
- package/dist/constants/storage.constants.d.ts +2 -2
- package/dist/drivers/driver-context.d.ts +1 -1
- package/dist/drivers/driver.interface.d.ts +1 -1
- package/dist/drivers/mysql/index.cjs +3 -3
- package/dist/drivers/mysql/index.cjs.map +1 -1
- package/dist/drivers/mysql/index.mjs +3 -3
- package/dist/drivers/mysql/index.mjs.map +1 -1
- package/dist/drivers/mysql/mysql-driver.d.ts +1 -1
- package/dist/drivers/oracle/index.cjs +3 -3
- package/dist/drivers/oracle/index.cjs.map +1 -1
- package/dist/drivers/oracle/index.mjs +3 -3
- package/dist/drivers/oracle/index.mjs.map +1 -1
- package/dist/drivers/oracle/oracle-driver.d.ts +1 -1
- package/dist/drivers/pglite/index.cjs +7 -7
- package/dist/drivers/pglite/index.cjs.map +1 -1
- package/dist/drivers/pglite/index.mjs +6 -6
- package/dist/drivers/pglite/index.mjs.map +1 -1
- package/dist/drivers/pglite/migrations.d.ts +2 -2
- package/dist/drivers/pglite/pglite-driver.d.ts +7 -7
- package/dist/drivers/postgresql/index.cjs +5 -0
- package/dist/drivers/postgresql/index.d.ts +2 -0
- package/dist/drivers/postgresql/index.mjs +5 -0
- package/dist/drivers/{postgres → postgresql}/migrations.d.ts +5 -5
- package/dist/drivers/{postgres/postgres-driver.d.ts → postgresql/postgresql-driver.d.ts} +7 -7
- package/dist/drivers/shared/base-driver.d.ts +4 -4
- package/dist/drivers/shared/migration-runner.service.d.ts +1 -1
- package/dist/drivers/sqlite/index.cjs +2 -2
- package/dist/drivers/sqlite/index.cjs.map +1 -1
- package/dist/drivers/sqlite/index.mjs +2 -2
- package/dist/drivers/sqlite/index.mjs.map +1 -1
- package/dist/drivers/table-names.d.ts +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/dist/{migration-CWBCpwFH.cjs → migration-CoTjpgBl.cjs} +7 -7
- package/dist/migration-CoTjpgBl.cjs.map +1 -0
- package/dist/{migration-CQsAizIw.js → migration-D73ANkYV.js} +7 -7
- package/dist/migration-D73ANkYV.js.map +1 -0
- package/dist/options/enums.d.ts +1 -1
- package/dist/{postgres-driver-eWlY7pVg.js → postgresql-driver-BUHuyRYj.js} +14 -14
- package/dist/postgresql-driver-BUHuyRYj.js.map +1 -0
- package/dist/{postgres-driver-F9-TIi38.cjs → postgresql-driver-CIk94XCq.cjs} +14 -14
- package/dist/postgresql-driver-CIk94XCq.cjs.map +1 -0
- package/dist/{storage.constants-CIkf7BAJ.cjs → storage.constants-B5oQjxp5.cjs} +2 -2
- package/dist/storage.constants-B5oQjxp5.cjs.map +1 -0
- package/dist/{storage.constants-BDS_q-_N.js → storage.constants-DwSzjjMZ.js} +2 -2
- package/dist/storage.constants-DwSzjjMZ.js.map +1 -0
- package/dist/tx/index.cjs +8 -8
- package/dist/tx/index.cjs.map +1 -1
- package/dist/tx/index.mjs +8 -8
- package/dist/tx/index.mjs.map +1 -1
- package/package.json +6 -5
- package/dist/drivers/postgres/index.cjs +0 -5
- package/dist/drivers/postgres/index.d.ts +0 -2
- package/dist/drivers/postgres/index.mjs +0 -5
- package/dist/migration-CQsAizIw.js.map +0 -1
- package/dist/migration-CWBCpwFH.cjs.map +0 -1
- package/dist/postgres-driver-F9-TIi38.cjs.map +0 -1
- package/dist/postgres-driver-eWlY7pVg.js.map +0 -1
- package/dist/storage.constants-BDS_q-_N.js.map +0 -1
- package/dist/storage.constants-CIkf7BAJ.cjs.map +0 -1
- /package/dist/drivers/{postgres → postgresql}/index.cjs.map +0 -0
- /package/dist/drivers/{postgres → postgresql}/index.mjs.map +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","sources":["../src/constants/time.constants.ts","../src/constants/worker.constants.ts","../src/constants/paging.constants.ts","../src/constants/maintenance.constants.ts","../src/constants/job.constants.ts","../src/events/event-name.enum.ts","../src/logging/log-level.enum.ts","../src/logging/console-logger.ts","../src/events/event-bus.service.ts","../src/events/hooks.ts","../src/events/hook-runner.ts","../src/options/option-resolver.ts","../src/pubsub/wakeup.ts","../src/producer/queue-registry.ts","../src/pubsub/channels.ts","../src/pubsub/notifier.service.ts","../src/scheduling/cron.ts","../src/producer/producer.service.ts","../src/jobs/snapshot.ts","../src/monitoring/stats.service.ts","../src/util/backoff.ts","../src/consumer/completion.service.ts","../src/client/client-registry.service.ts","../src/pubsub/subscriber.service.ts","../src/scheduling/scheduler.service.ts","../src/retention/retention.service.ts","../src/monitoring/system-monitor.service.ts","../src/client/instance.service.ts","../src/drivers/shared/migration-runner.service.ts","../src/client/client-lifecycle.service.ts","../src/client/background-work.ts","../src/util/batch-ids.ts","../src/dashboard/dashboard-results.ts","../src/dashboard/dashboard.service.ts","../src/cli/cli.service.ts","../src/producer/queue.ts","../src/monitoring/rate-limiter.service.ts","../src/consumer/execution.service.ts","../src/consumer/worker.ts","../src/util/clock.ts","../src/port-queue.ts"],"sourcesContent":["/**\n * Default cadences and time windows, all **in seconds** (the only unit the API speaks).\n *\n * Every default lives in `constants/` rather than inline at its use site so there is exactly one\n * place to change a policy — the heartbeat window in particular was previously copied into four\n * files that could drift apart.\n */\n\n/** Maintenance tick (scheduler + retention + expiry) cadence. `PortQueueOptions.tickIntervalSeconds`. */\nexport const DEFAULT_TICK_INTERVAL_SECONDS = 5;\n\n/** The floor the pub/sub poller falls back to when the tick interval is shorter. */\nexport const MIN_SUBSCRIBER_POLL_SECONDS = 5;\n\n/** Instance heartbeat cadence. `InstanceOptions.heartbeatIntervalSeconds`. */\nexport const DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 15;\n\n/**\n * How many missed heartbeats an instance may accumulate before it reads as stale. Three, so a\n * single slow beat (a long query, a GC pause) never flips a healthy instance to \"stale\".\n */\nexport const HEARTBEAT_STALE_BEATS = 3;\n\n/** How long an instance must have been unheard-from before it can be manually removed. */\nexport const INSTANCE_REMOVAL_STALE_SECONDS = 30 * 60;\n\n/** Graceful-shutdown budget for in-flight handlers and background work. `ShutdownOptions.timeoutSeconds`. */\nexport const DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 30;\n\n/** Health sampling cadence. `SystemLimiterOptions.sampleIntervalSeconds`. */\nexport const DEFAULT_SAMPLE_INTERVAL_SECONDS = 2;\n\n/** How long a migration runner waits for another instance to finish migrating. */\nexport const MIGRATION_WAIT_TIMEOUT_SECONDS = 30;\n\n/**\n * Milliseconds → microseconds, for the one reading that is measured in microseconds: `cpuUsage()`.\n * Deliberately *not* in `util/seconds` — that module owns the seconds↔milliseconds boundary the API\n * invariant is about, and this is a different pair of units.\n */\nexport const MICROS_PER_MS = 1000;\n\n/** How often that wait re-reads the applied schema version. */\nexport const MIGRATION_WAIT_POLL_SECONDS = 0.2;\n","/** Worker throughput and claim defaults. Durations are **in seconds**. */\n\n/** Handlers a worker runs at once. `LimiterOptions.concurrency`. */\nexport const DEFAULT_CONCURRENCY = 1;\n\n/**\n * Poll cadence when nothing wakes the worker. LISTEN/NOTIFY engines wake instantly and only fall\n * back to this as a safety net; non-notify engines poll on it. `LimiterOptions.pollIntervalSeconds`.\n */\nexport const DEFAULT_POLL_INTERVAL_SECONDS = 5;\n\n/** Visibility timeout / heartbeat window for a claimed job. `LimiterOptions.lockDurationSeconds`. */\nexport const DEFAULT_LOCK_DURATION_SECONDS = 30;\n\n/** Beats per lock window — a job's lock is extended this many times before it would lapse. */\nexport const LOCK_HEARTBEATS_PER_WINDOW = 3;\n\n/** The fastest a lock heartbeat ever beats, whatever the lock window. */\nexport const MIN_LOCK_HEARTBEAT_SECONDS = 1;\n\n/** How often a graceful drain re-checks whether the last handler has finished. */\nexport const DRAIN_POLL_SECONDS = 0.025;\n\n/**\n * How long shutdown waits after aborting a handler before deciding it is not going to stop.\n *\n * A handler that observes `job.signal` settles its own row within a tick or two of the abort, and\n * needs no lock released. Only what is still running after this window has its lock cut short so\n * another instance can reclaim the job quickly.\n */\nexport const ABORT_GRACE_SECONDS = 0.25;\n\n/**\n * The lock duration that *releases* a lock: a deadline in the past, so a reclaim sees the row as\n * stalled immediately. `secondsToMs` accepts the negative value for exactly this reason.\n */\nexport const LOCK_RELEASE_SECONDS = -1;\n","/** Paging defaults. One window shape (`limit`/`offset`) for every list read. */\n\n/** Rows a list read returns when the caller names no `limit`. */\nexport const DEFAULT_PAGE_LIMIT = 50;\n\n/** The ceiling a caller-supplied `limit` is clamped to on the public API. */\nexport const MAX_PAGE_LIMIT = 500;\n\n/** The ceiling the dashboard facade clamps its own pages to (its tables never show more). */\nexport const DASHBOARD_MAX_PAGE_LIMIT = 200;\n","/**\n * Batch sizes for the maintenance work the tick drives. Every sweep is bounded per statement and\n * loops until a short batch, so a backlog is drained across round trips instead of in one\n * table-wide transaction.\n */\n\n/** Rows one retention delete removes. */\nexport const RETENTION_BATCH_SIZE = 500;\n\n/** How many retention batches one tick will run before leaving the rest to the next tick. */\nexport const RETENTION_MAX_BATCHES = 20;\n\n/** Due schedules fired per batch. */\nexport const SCHEDULE_BATCH_SIZE = 100;\n\n/** How many schedule batches one tick will fire before leaving the rest to the next tick. */\nexport const SCHEDULE_MAX_BATCHES = 20;\n\n/** Rows one `expireDueJobs` / `reclaimStalledJobs` statement touches. */\nexport const MAINTENANCE_BATCH_SIZE = 500;\n\n/** How many expire/reclaim batches one tick will run. */\nexport const MAINTENANCE_MAX_BATCHES = 20;\n","import { FailureDetail } from '../options/enums';\n\n/** Per-job resolution defaults — what a job gets when neither it nor its queue says otherwise. */\n\n/** Higher runs first. `JobOptions.priority`. */\nexport const DEFAULT_PRIORITY = 0;\n\n/** Attempts including the first, so the default is \"run once, never retry\". `retry.maxAttempts`. */\nexport const DEFAULT_RETRY_MAX_ATTEMPTS = 1;\n\n/** Delay before a retry, **in seconds**. `retry.delaySeconds`. */\nexport const DEFAULT_RETRY_DELAY_SECONDS = 0;\n\n/** Growth factor an EXPONENTIAL backoff uses when none is given. `retry.backoff.factor`. */\nexport const DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * What a queue stores on a failed row when it names no `failureDetail`: the stack, because a\n * developer reading a failure wants the throw site, and the cost is bounded by the cap below.\n */\nexport const DEFAULT_FAILURE_DETAIL = FailureDetail.STACK;\n\n/**\n * How much of a failure's stack is kept in `failure_message`. A stack is unbounded and every\n * failed row stores one, so it is truncated to a size that still shows the throw site and the\n * frames around it.\n */\nexport const FAILURE_MESSAGE_MAX_CHARS = 4000;\n\n/** Marker appended to a truncated failure message so a reader knows frames were dropped. */\nexport const FAILURE_MESSAGE_TRUNCATION_SUFFIX = '… [truncated]';\n","import type { JobStatus } from '../jobs/job-state.enum';\n\n/**\n * All observable lifecycle events. Emitted on the PortQueue instance.\n * Every listener receives one typed payload object.\n */\nexport enum PortQueueEvent {\n CLIENT_STARTED = 'CLIENT_STARTED',\n CLIENT_STOPPING = 'CLIENT_STOPPING',\n CLIENT_STOPPED = 'CLIENT_STOPPED',\n MIGRATION_APPLIED = 'MIGRATION_APPLIED',\n ERROR = 'ERROR',\n\n JOB_ADDED = 'JOB_ADDED',\n JOB_ACTIVE = 'JOB_ACTIVE',\n JOB_COMPLETED = 'JOB_COMPLETED',\n JOB_FAILED = 'JOB_FAILED',\n JOB_RETRYING = 'JOB_RETRYING',\n JOB_STALLED = 'JOB_STALLED',\n JOB_EXPIRED = 'JOB_EXPIRED',\n JOB_CANCELLED = 'JOB_CANCELLED',\n JOB_REMOVED = 'JOB_REMOVED',\n\n SCHEDULE_CREATED = 'SCHEDULE_CREATED',\n SCHEDULE_UPDATED = 'SCHEDULE_UPDATED',\n SCHEDULE_REMOVED = 'SCHEDULE_REMOVED',\n SCHEDULE_FIRED = 'SCHEDULE_FIRED',\n\n QUEUE_PAUSED = 'QUEUE_PAUSED',\n QUEUE_RESUMED = 'QUEUE_RESUMED',\n QUEUE_REMOVED = 'QUEUE_REMOVED',\n INSTANCE_PAUSED = 'INSTANCE_PAUSED',\n INSTANCE_RESUMED = 'INSTANCE_RESUMED',\n INSTANCE_REMOVED = 'INSTANCE_REMOVED',\n WORKER_STARTED = 'WORKER_STARTED',\n WORKER_STOPPED = 'WORKER_STOPPED',\n SYSTEM_PRESSURE_HIGH = 'SYSTEM_PRESSURE_HIGH',\n SYSTEM_PRESSURE_NORMAL = 'SYSTEM_PRESSURE_NORMAL',\n}\n\n/** Source of an internal error surfaced via {@link PortQueueEvent.ERROR}. */\nexport type ErrorSource =\n | 'claim'\n | 'execution'\n | 'completion'\n | 'scheduler'\n | 'retention'\n | 'subscriber'\n | 'notifier'\n | 'listener'\n | 'hook'\n | 'monitor'\n | 'migration';\n\n/** The typed payload for every event. */\nexport interface PortQueueEventPayloads {\n [PortQueueEvent.CLIENT_STARTED]: { instanceKey: string | null };\n [PortQueueEvent.CLIENT_STOPPING]: { instanceKey: string | null };\n [PortQueueEvent.CLIENT_STOPPED]: { instanceKey: string | null };\n [PortQueueEvent.MIGRATION_APPLIED]: { from: number | null; to: number };\n [PortQueueEvent.ERROR]: { error: unknown; source: ErrorSource };\n\n [PortQueueEvent.JOB_ADDED]: { jobId: string; queue: string; deduplicated: boolean };\n [PortQueueEvent.JOB_ACTIVE]: {\n jobId: string;\n queue: string;\n retryAttempt: number;\n instanceKey: string | null;\n };\n [PortQueueEvent.JOB_COMPLETED]: {\n jobId: string;\n queue: string;\n returnValue: unknown;\n durationSeconds: number;\n };\n [PortQueueEvent.JOB_FAILED]: {\n jobId: string;\n queue: string;\n error: unknown;\n retryAttempt: number;\n };\n [PortQueueEvent.JOB_RETRYING]: {\n jobId: string;\n queue: string;\n retryAttempt: number;\n nextRunAt: Date;\n };\n [PortQueueEvent.JOB_STALLED]: {\n jobId: string;\n queue: string;\n previousInstanceKey: string | null;\n };\n [PortQueueEvent.JOB_EXPIRED]: { jobId: string; queue: string };\n [PortQueueEvent.JOB_CANCELLED]: { jobId: string; queue: string };\n [PortQueueEvent.JOB_REMOVED]: { jobId: string; queue: string };\n\n [PortQueueEvent.SCHEDULE_CREATED]: { scheduleId: string; queue: string };\n [PortQueueEvent.SCHEDULE_UPDATED]: { scheduleId: string; queue: string };\n [PortQueueEvent.SCHEDULE_REMOVED]: { scheduleId: string; queue: string };\n [PortQueueEvent.SCHEDULE_FIRED]: { scheduleId: string; jobId: string; queue: string };\n\n [PortQueueEvent.QUEUE_PAUSED]: { queue: string; mode: string };\n [PortQueueEvent.QUEUE_RESUMED]: { queue: string };\n [PortQueueEvent.QUEUE_REMOVED]: { queue: string };\n [PortQueueEvent.INSTANCE_PAUSED]: { instanceKey: string };\n [PortQueueEvent.INSTANCE_RESUMED]: { instanceKey: string };\n [PortQueueEvent.INSTANCE_REMOVED]: { instanceKey: string };\n [PortQueueEvent.WORKER_STARTED]: { queue: string };\n [PortQueueEvent.WORKER_STOPPED]: { queue: string };\n [PortQueueEvent.SYSTEM_PRESSURE_HIGH]: { metric: string; value: number; threshold: number };\n [PortQueueEvent.SYSTEM_PRESSURE_NORMAL]: Record<string, never>;\n}\n\n/** Job status re-export helper used in event/payload typing contexts. */\nexport type { JobStatus };\n\nexport type EventListener<E extends PortQueueEvent> = (payload: PortQueueEventPayloads[E]) => void;\nexport type Unsubscribe = () => void;\n","/** Log levels. Ordered lowest → highest severity. */\nexport enum LogLevel {\n TRACE = 'TRACE',\n DEBUG = 'DEBUG',\n INFO = 'INFO',\n WARN = 'WARN',\n ERROR = 'ERROR',\n FATAL = 'FATAL',\n}\n\n/** Numeric severity for gating, lower = more verbose. */\nexport const LOG_LEVEL_SEVERITY: Record<LogLevel, number> = {\n [LogLevel.TRACE]: 10,\n [LogLevel.DEBUG]: 20,\n [LogLevel.INFO]: 30,\n [LogLevel.WARN]: 40,\n [LogLevel.ERROR]: 50,\n [LogLevel.FATAL]: 60,\n};\n","import { LOG_LEVEL_SEVERITY, LogLevel } from './log-level.enum';\nimport type { Logger, LogContext, LoggerOptions } from './logger.interface';\n\n/**\n * Zero-dependency default logger. Writes structured lines to\n * stdout/stderr honoring the configured level.\n */\nexport class ConsoleLogger implements Logger {\n private readonly minSeverity: number;\n private readonly pretty: boolean;\n\n constructor(options: LoggerOptions = {}) {\n const level = options.level ?? LogLevel.INFO;\n this.minSeverity = LOG_LEVEL_SEVERITY[level];\n this.pretty = options.pretty ?? Boolean(process.stdout.isTTY);\n }\n\n trace(message: string, context?: LogContext): void {\n this.write(LogLevel.TRACE, message, context);\n }\n debug(message: string, context?: LogContext): void {\n this.write(LogLevel.DEBUG, message, context);\n }\n info(message: string, context?: LogContext): void {\n this.write(LogLevel.INFO, message, context);\n }\n warn(message: string, context?: LogContext): void {\n this.write(LogLevel.WARN, message, context);\n }\n error(message: string, context?: LogContext): void {\n this.write(LogLevel.ERROR, message, context);\n }\n fatal(message: string, context?: LogContext): void {\n this.write(LogLevel.FATAL, message, context);\n }\n\n private write(level: LogLevel, message: string, context?: LogContext): void {\n if (LOG_LEVEL_SEVERITY[level] < this.minSeverity) return;\n const stream =\n LOG_LEVEL_SEVERITY[level] >= LOG_LEVEL_SEVERITY[LogLevel.ERROR]\n ? process.stderr\n : process.stdout;\n const normalized = context ? normalizeContext(context) : undefined;\n if (this.pretty) {\n const suffix =\n normalized && Object.keys(normalized).length ? ` ${JSON.stringify(normalized)}` : '';\n stream.write(`[portqueue] ${level} ${message}${suffix}\\n`);\n } else {\n stream.write(\n `${JSON.stringify({ ts: new Date().toISOString(), level, msg: message, ...normalized })}\\n`,\n );\n }\n }\n}\n\n/** Serialize an Error in `err` to a plain object so it survives JSON logging. */\nfunction normalizeContext(context: LogContext): Record<string, unknown> {\n const out: Record<string, unknown> = { ...context };\n if (out.err instanceof Error) {\n out.err = { name: out.err.name, message: out.err.message, stack: out.err.stack };\n }\n return out;\n}\n\n/** A logger that discards everything — handy for tests. */\nexport class NoopLogger implements Logger {\n trace(): void {}\n debug(): void {}\n info(): void {}\n warn(): void {}\n error(): void {}\n fatal(): void {}\n}\n","import {\n PortQueueEvent,\n type EventListener,\n type PortQueueEventPayloads,\n type Unsubscribe,\n} from './event-name.enum';\nimport type { Logger } from '../logging/logger.interface';\n\ninterface Registration {\n listener: (payload: unknown) => void;\n queue?: string;\n once: boolean;\n}\n\n/** One event's listeners, plus how many of them are `once` registrations. */\ninterface Bucket {\n registrations: Set<Registration>;\n /** Kept in step with the set, so `emit` knows whether removal during iteration is possible. */\n onceCount: number;\n}\n\n/**\n * Typed event bus. Synchronous fan-out; listeners may be async but the\n * bus never awaits them (observation must not block the hot path). A throwing listener is\n * caught, logged, and re-surfaced as {@link PortQueueEvent.ERROR} — never breaks emission.\n *\n * Four to six events fire per job, so `emit` is a hot path. It iterates the registration set\n * **directly** and only snapshots it when the set actually holds a `once` listener — the one case\n * where emission mutates what it is iterating. Tracking that with a counter turns the common case\n * (plain `on` listeners, or none) from an allocation per event into none at all.\n */\nexport class EventBusService {\n private readonly buckets = new Map<PortQueueEvent, Bucket>();\n\n constructor(private readonly logger: Logger) {}\n\n on<E extends PortQueueEvent>(\n event: E,\n listener: EventListener<E>,\n filter?: { queue?: string },\n ): Unsubscribe {\n return this.add(event, listener as (p: unknown) => void, filter?.queue, false);\n }\n\n once<E extends PortQueueEvent>(\n event: E,\n listener: EventListener<E>,\n filter?: { queue?: string },\n ): Unsubscribe {\n return this.add(event, listener as (p: unknown) => void, filter?.queue, true);\n }\n\n off<E extends PortQueueEvent>(event: E, listener: EventListener<E>): void {\n const bucket = this.buckets.get(event);\n if (!bucket) return;\n // Snapshot, then delete. Mutating a Set mid-iteration is legal, but doing it here while `emit`\n // copies the set for exactly that reason would leave the two reading as inconsistent about the\n // same hazard.\n const matches = [...bucket.registrations].filter(\n (reg) => reg.listener === (listener as (p: unknown) => void),\n );\n for (const reg of matches) this.remove(bucket, reg);\n }\n\n private add(\n event: PortQueueEvent,\n listener: (p: unknown) => void,\n queue: string | undefined,\n once: boolean,\n ): Unsubscribe {\n let bucket = this.buckets.get(event);\n if (!bucket) {\n bucket = { registrations: new Set(), onceCount: 0 };\n this.buckets.set(event, bucket);\n }\n const reg: Registration = { listener, once, ...(queue !== undefined ? { queue } : {}) };\n bucket.registrations.add(reg);\n if (once) bucket.onceCount += 1;\n const target = bucket;\n return () => this.remove(target, reg);\n }\n\n private remove(bucket: Bucket, reg: Registration): void {\n if (!bucket.registrations.delete(reg)) return;\n if (reg.once) bucket.onceCount -= 1;\n }\n\n emit<E extends PortQueueEvent>(event: E, payload: PortQueueEventPayloads[E]): void {\n const bucket = this.buckets.get(event);\n if (!bucket || bucket.registrations.size === 0) return;\n const queue = (payload as { queue?: string }).queue;\n // Only a `once` listener is removed while we iterate, so only then is a snapshot needed.\n const targets: Iterable<Registration> =\n bucket.onceCount > 0 ? [...bucket.registrations] : bucket.registrations;\n for (const reg of targets) {\n if (reg.queue !== undefined && reg.queue !== queue) continue;\n if (reg.once) this.remove(bucket, reg);\n try {\n reg.listener(payload);\n } catch (err) {\n // Isolate listener errors and re-surface (avoid infinite loop on ERROR itself).\n this.logger.error('Event listener threw; isolated.', { err, event });\n if (event !== PortQueueEvent.ERROR) {\n this.emit(PortQueueEvent.ERROR, { error: err, source: 'listener' });\n }\n }\n }\n }\n}\n","import type { AddJobOptions, JobOptions } from '../options/job-options';\nimport type { Job } from '../jobs/job';\nimport type { AddJobResult } from '../producer/results';\n\n/** Hook lifecycle phases. */\nexport enum HookPhase {\n BEFORE_ADD = 'BEFORE_ADD',\n AFTER_ADD = 'AFTER_ADD',\n BEFORE_PROCESS = 'BEFORE_PROCESS',\n AFTER_PROCESS = 'AFTER_PROCESS',\n}\n\n/** Outcome descriptor passed to AFTER_PROCESS hooks. */\nexport type ProcessOutcome =\n | { kind: 'completed'; returnValue: unknown }\n | { kind: 'failed'; error: unknown }\n | { kind: 'retry'; error: unknown; nextRunAt: Date };\n\n/** A modified add — a BEFORE_ADD hook may return this to mutate the outgoing job. */\nexport interface BeforeAddResult<TData = unknown> {\n options?: Partial<AddJobOptions<TData>>;\n}\n\n/**\n * Participation-hook registration. Hooks are awaited, run in\n * registration order, and can mutate BEFORE_ADD/BEFORE_PROCESS or veto by throwing.\n */\nexport interface HookRegistration {\n phase: HookPhase;\n /** Optional queue scope. */\n queue?: string;\n handler: HookHandler;\n}\n\nexport type HookHandler =\n | ((ctx: {\n queue: string;\n options: AddJobOptions<unknown>;\n }) => Promise<BeforeAddResult | void> | BeforeAddResult | void)\n | ((ctx: { result: AddJobResult }) => Promise<void> | void)\n | ((ctx: { job: Job }) => Promise<void> | void)\n | ((ctx: { job: Job; outcome: ProcessOutcome }) => Promise<void> | void);\n\n/** Convenience typed registration builders (all optional to use). */\nexport interface BeforeAddHook<TData = unknown> {\n phase: HookPhase.BEFORE_ADD;\n queue?: string;\n handler: (ctx: {\n queue: string;\n options: AddJobOptions<TData>;\n }) => Promise<BeforeAddResult<TData> | void> | BeforeAddResult<TData> | void;\n}\n\nexport type { JobOptions };\n","import {\n HookPhase,\n type BeforeAddResult,\n type HookRegistration,\n type ProcessOutcome,\n} from './hooks';\nimport type { AddJobOptions } from '../options/job-options';\nimport type { Job } from '../jobs/job';\nimport type { AddJobResult } from '../producer/results';\nimport type { Logger } from '../logging/logger.interface';\nimport type { EventBusService } from './event-bus.service';\nimport { PortQueueEvent } from './event-name.enum';\n\n/** The shared empty result for a phase nothing registered against — never allocated per call. */\nconst EMPTY: readonly HookRegistration[] = [];\n\n/**\n * Runs participation hooks. Hooks are awaited, in registration order.\n * A BEFORE_* throw aborts the operation; an AFTER_* throw is logged and surfaced via ERROR\n * but does not undo the completed operation.\n *\n * Hooks are **indexed by phase at registration time**. `forPhase` runs four times per job, and\n * filtering the whole array each time meant an allocation and a full scan per job even for an\n * application with no hooks at all; now the no-hook case is a `Map` miss and an early return.\n */\nexport class HookRunner {\n private readonly byPhase = new Map<HookPhase, HookRegistration[]>();\n\n constructor(\n private readonly logger: Logger,\n private readonly events: EventBusService,\n ) {}\n\n register(hook: HookRegistration): () => void {\n const bucket = this.byPhase.get(hook.phase);\n if (bucket) bucket.push(hook);\n else this.byPhase.set(hook.phase, [hook]);\n return () => {\n const current = this.byPhase.get(hook.phase);\n if (!current) return;\n const i = current.indexOf(hook);\n if (i >= 0) current.splice(i, 1);\n if (current.length === 0) this.byPhase.delete(hook.phase);\n };\n }\n\n /**\n * The hooks for one phase that apply to `queue`, in registration order. Returns the phase's own\n * array untouched when every hook in it is unscoped — the common case — so no array is built.\n */\n private forPhase(phase: HookPhase, queue: string): readonly HookRegistration[] {\n const bucket = this.byPhase.get(phase);\n if (!bucket || bucket.length === 0) return EMPTY;\n if (bucket.every((h) => h.queue === undefined)) return bucket;\n return bucket.filter((h) => h.queue === undefined || h.queue === queue);\n }\n\n /** Run BEFORE_ADD hooks; may mutate options or veto by throwing. Returns merged options. */\n async runBeforeAdd<TData>(\n queue: string,\n options: AddJobOptions<TData>,\n ): Promise<AddJobOptions<TData>> {\n let current = options;\n for (const hook of this.forPhase(HookPhase.BEFORE_ADD, queue)) {\n const result = (await (hook.handler as (ctx: unknown) => Promise<BeforeAddResult | void>)({\n queue,\n options: current,\n })) as BeforeAddResult<TData> | void;\n if (result?.options) current = { ...current, ...result.options };\n }\n return current;\n }\n\n async runAfterAdd(queue: string, result: AddJobResult): Promise<void> {\n for (const hook of this.forPhase(HookPhase.AFTER_ADD, queue)) {\n await this.safeAfter(hook, { result });\n }\n }\n\n /** Run BEFORE_PROCESS hooks; a throw skips/fails the job before the handler runs. */\n async runBeforeProcess(queue: string, job: Job): Promise<void> {\n for (const hook of this.forPhase(HookPhase.BEFORE_PROCESS, queue)) {\n await (hook.handler as (ctx: unknown) => Promise<void>)({ job });\n }\n }\n\n async runAfterProcess(queue: string, job: Job, outcome: ProcessOutcome): Promise<void> {\n for (const hook of this.forPhase(HookPhase.AFTER_PROCESS, queue)) {\n await this.safeAfter(hook, { job, outcome });\n }\n }\n\n private async safeAfter(hook: HookRegistration, ctx: unknown): Promise<void> {\n try {\n await (hook.handler as (c: unknown) => Promise<void>)(ctx);\n } catch (err) {\n this.logger.error('AFTER hook threw; isolated.', { err, phase: hook.phase });\n this.events.emit(PortQueueEvent.ERROR, { error: err, source: 'hook' });\n }\n }\n}\n","import { BackoffStrategy } from './enums';\nimport type { JobOptions } from './job-options';\nimport type { RetentionOptions } from './common';\nimport type { JobStatus } from '../jobs/job-state.enum';\nimport { wholeSeconds, wholeSecondsToMs } from '../util/seconds';\nimport {\n DEFAULT_PRIORITY,\n DEFAULT_RETRY_DELAY_SECONDS,\n DEFAULT_RETRY_MAX_ATTEMPTS,\n} from '../constants';\n\n/**\n * The fully-resolved per-job settings frozen onto a `job` row. Instants (`startAfter`, `expireAt`)\n * are epoch ms; every duration is a whole number of seconds, exactly as the\n * caller gave it.\n */\nexport interface ResolvedJobOptions {\n priority: number;\n startAfter: number;\n expireAt: number | null;\n retryMaxAttempts: number;\n retryDelaySeconds: number;\n retryBackoff: BackoffStrategy;\n retryBackoffFactor: number | null;\n retryMaxDelaySeconds: number | null;\n retryJitter: boolean;\n /** The TTL after finishing before this job is deleted, or null to keep it forever. */\n retentionTtlSeconds: number | null;\n /** The finished statuses retention may delete this job in, or null for every finished status. */\n retentionStatuses: JobStatus[] | null;\n idempotencyKey: string | null;\n singletonKey: string | null;\n}\n\n/**\n * Merges queue → job options (job wins) and freezes resolved values.\n * Resolution happens once, at insert time. There is no client-level default layer — job\n * defaults and retention are set per queue so nothing is silently inherited client-wide.\n */\nexport class OptionResolver {\n resolve(options: {\n job: JobOptions;\n queueDefaults?: JobOptions;\n queueRetention?: RetentionOptions;\n /** One-off start delay in seconds from the job's `schedule` group (not a mergeable default). */\n startAfterSeconds?: number;\n now: number;\n }): ResolvedJobOptions {\n const { job, queueDefaults, queueRetention, now } = options;\n const merged: JobOptions = { ...queueDefaults, ...job };\n\n const startAfter = this.resolveStartAfter(options.startAfterSeconds, now);\n const expireAt =\n merged.expireInSeconds != null\n ? startAfter + wholeSecondsToMs(merged.expireInSeconds, 'expireInSeconds')\n : null;\n\n const backoff = merged.retry?.backoff;\n // Retention is chosen whole, never merged field by field: a per-job policy replaces the\n // queue's rather than inheriting half of it.\n const retention = merged.retention ?? queueRetention;\n\n return {\n priority: merged.priority ?? DEFAULT_PRIORITY,\n startAfter,\n expireAt,\n retryMaxAttempts: merged.retry?.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS,\n retryDelaySeconds:\n merged.retry?.delaySeconds != null\n ? wholeSeconds(merged.retry.delaySeconds, 'retry.delaySeconds')\n : DEFAULT_RETRY_DELAY_SECONDS,\n retryBackoff: backoff?.strategy ?? BackoffStrategy.FIXED,\n retryBackoffFactor: backoff?.factor ?? null,\n retryMaxDelaySeconds:\n backoff?.maxDelaySeconds != null\n ? wholeSeconds(backoff.maxDelaySeconds, 'retry.backoff.maxDelaySeconds')\n : null,\n retryJitter: backoff?.jitter ?? false,\n retentionTtlSeconds:\n retention != null ? wholeSeconds(retention.ttlSeconds, 'retention.ttlSeconds') : null,\n // Null, not a defaulted list: \"the caller didn't scope this\" is a distinct state from \"the\n // caller asked for exactly these\", and the column stores null for the common case.\n retentionStatuses: retention?.statuses?.length ? [...retention.statuses] : null,\n idempotencyKey: merged.idempotencyKey ?? null,\n singletonKey: merged.singletonKey ?? null,\n };\n }\n\n private resolveStartAfter(startAfterSeconds: number | undefined, now: number): number {\n if (startAfterSeconds == null) return now;\n return now + wholeSecondsToMs(startAfterSeconds, 'schedule.startAfterSeconds');\n }\n}\n","/**\n * A debounced \"there is work\" signal that wakes claim loops.\n * Per-queue subscribers are notified when a job is added or a NOTIFY/poll fires.\n */\nexport class Wakeup {\n private readonly subscribers = new Map<string, Set<() => void>>();\n\n subscribe(queue: string, callback: () => void): () => void {\n let set = this.subscribers.get(queue);\n if (!set) {\n set = new Set();\n this.subscribers.set(queue, set);\n }\n const subscribers = set;\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n // Drop the queue's entry once its last subscriber goes, and only if it is still *this* set: a\n // resubscribe between the two would have installed a new one, and deleting that would strand\n // a live listener. An emptied set left in the map is small, but `signalAll` then walks it\n // forever in a process that declares and tears down queues.\n if (subscribers.size === 0 && this.subscribers.get(queue) === subscribers) {\n this.subscribers.delete(queue);\n }\n };\n }\n\n /** Wake all loops for one queue. */\n signal(queue: string): void {\n const set = this.subscribers.get(queue);\n if (set) for (const cb of set) cb();\n }\n\n /** Wake every loop (e.g. on system-pressure-normal). */\n signalAll(): void {\n for (const set of this.subscribers.values()) {\n for (const cb of set) cb();\n }\n }\n\n /**\n * How many queues currently have a subscriber. `@internal` — it exists so a test can assert the\n * map does not grow with every queue a process declares and tears down.\n */\n get queueCount(): number {\n return this.subscribers.size;\n }\n}\n","import { secondsToMs } from '../util/seconds';\nimport { DEFAULT_TICK_INTERVAL_SECONDS } from '../constants';\nimport { QueueNotFoundError } from '../errors/errors';\nimport type { Driver } from '../drivers/driver.interface';\nimport type { QueueRow } from '../jobs/job-record';\nimport type { QueueOptions } from '../options/queue-options';\nimport type { Clock } from '../util/clock';\n\ninterface QueueEntry {\n row: QueueRow;\n options: QueueOptions;\n /** When the cached pause flags were last read from the database. */\n refreshedAt: number;\n}\n\n/**\n * Caches queue name → row + in-memory options, and owns the cached pause flags the claim loop reads.\n *\n * Three things this class is deliberate about:\n *\n * - **`declare` is only ever reached from the developer's own `createQueue`.** Declared options are\n * *replaced*, because `createQueue` is a declaration: the caller states what the queue is, and the\n * last declaration wins. That is only safe because nothing internal calls it — no admin action, no\n * pause, no read path — so a `pauseQueue` can never blank the defaults a `createQueue` set.\n * - **The pause flags are cached with a TTL, not re-read per claim.** The claim loop used to issue a\n * `getQueueByName` on every pump — per worker, per poll, and again on every freed concurrency slot\n * — which on an idle queue meant more queue reads than job claims. They are refreshed on the\n * maintenance tick (and immediately by a pause/resume made here), and {@link pauseState} answers\n * from cache with no I/O at all.\n * - **A headless registry never writes.** For the dashboard and CLI (see `PortQueueOptions._headless`)\n * `declare` is a no-op, `ensure` reads the row instead of creating it, and `isRegistered` is always\n * false — an admin tool must not create queue rows or claim ownership of a queue it merely inspects.\n */\nexport class QueueRegistry {\n private readonly entries = new Map<string, QueueEntry>();\n private readonly ensuring = new Map<string, Promise<QueueRow>>();\n private readonly pendingOptions = new Map<string, QueueOptions>();\n /** How stale a cached pause flag may get before the tick refreshes it. */\n private readonly staleAfterMs: number;\n\n constructor(\n private readonly driver: Driver,\n private readonly clock: Clock,\n options: { tickIntervalSeconds?: number; headless?: boolean } = {},\n ) {\n this.staleAfterMs = secondsToMs(\n options.tickIntervalSeconds ?? DEFAULT_TICK_INTERVAL_SECONDS,\n 'tickIntervalSeconds',\n );\n this.headless = options.headless ?? false;\n }\n\n private readonly headless: boolean;\n\n /**\n * Record a queue's declared options (no I/O). **Only `PortQueue.createQueue` calls this** — see the\n * class comment. Options replace any previous declaration for the same name. A no-op on a headless\n * client, which declares nothing.\n */\n declare(name: string, options: QueueOptions): void {\n if (this.headless) return;\n const existing = this.entries.get(name);\n if (existing) {\n existing.options = options;\n return;\n }\n this.pendingOptions.set(name, options);\n }\n\n getOptions(name: string): QueueOptions {\n return this.entries.get(name)?.options ?? this.pendingOptions.get(name) ?? {};\n }\n\n /**\n * Resolve (and cache) the queue row. Idempotent under concurrency.\n *\n * Creates the row when absent — except on a headless client, where it reads and throws\n * {@link QueueNotFoundError} if the queue was never declared by an application.\n */\n async ensure(name: string): Promise<QueueRow> {\n const cached = this.entries.get(name);\n if (cached) return cached.row;\n const inflight = this.ensuring.get(name);\n if (inflight) return inflight;\n const options = this.pendingOptions.get(name);\n const promise = this.resolveRow(name, options)\n .then((row) => {\n this.entries.set(name, {\n row,\n options: options ?? {},\n refreshedAt: this.clock.now(),\n });\n this.pendingOptions.delete(name);\n this.ensuring.delete(name);\n return row;\n })\n .catch((err: unknown) => {\n // Don't strand a rejected promise in the map — the next caller must be able to retry.\n this.ensuring.delete(name);\n throw err;\n });\n this.ensuring.set(name, promise);\n return promise;\n }\n\n private async resolveRow(name: string, options: QueueOptions | undefined): Promise<QueueRow> {\n if (this.headless) {\n const row = await this.driver.getQueueByName({ name });\n if (!row) throw new QueueNotFoundError(name);\n return row;\n }\n return this.driver.ensureQueue({\n name,\n ...(options ? { options } : {}),\n now: this.clock.now(),\n });\n }\n\n /**\n * The cached pause flags for a queue, with **no I/O**. Read on the hot path by every worker pump.\n * `null` when the queue has not been ensured in this process yet, which a worker never sees — it\n * awaits `ensure()` before its first pump.\n */\n pauseState(name: string): { processingPaused: boolean; acceptingPaused: boolean } | null {\n const entry = this.entries.get(name);\n if (!entry) return null;\n return {\n processingPaused: entry.row.processingPaused,\n acceptingPaused: entry.row.acceptingPaused,\n };\n }\n\n /** Overwrite the cached row from one a driver just returned (a pause/resume this process made). */\n update(row: QueueRow): void {\n const entry = this.entries.get(row.name);\n if (entry) {\n entry.row = row;\n entry.refreshedAt = this.clock.now();\n }\n }\n\n /** Re-read one queue's flags from the database. */\n async refresh(name: string): Promise<QueueRow | null> {\n const row = await this.driver.getQueueByName({ name });\n if (row) this.update(row);\n return row;\n }\n\n /**\n * Refresh every declared queue whose cached flags have gone stale. Driven by the maintenance tick,\n * so a pause made by another instance is observed within one tick interval.\n *\n * **One query for the whole set**, not one per queue: a process declaring 50 queues was issuing 50\n * `getQueueByName` calls every tick to read two booleans each. `listQueues` returns every row, and\n * the names this process cares about are already known here — so the tick costs one round trip\n * whatever the declaration count. A name whose row has since been removed simply keeps its cached\n * flags, exactly as the per-queue refresh did when it answered `null`.\n */\n async refreshStale(): Promise<void> {\n const now = this.clock.now();\n const stale = new Set(\n [...this.entries.entries()]\n .filter(([, entry]) => now - entry.refreshedAt >= this.staleAfterMs)\n .map(([name]) => name),\n );\n if (!stale.size) return;\n try {\n const rows = await this.driver.listQueues();\n for (const row of rows) if (stale.has(row.name)) this.update(row);\n } catch {\n // A transient read failure leaves the cached flags in place; the next tick tries again.\n }\n }\n\n /**\n * Whether this queue was declared in *this* process (via `createQueue`), whether or not its row\n * has been ensured yet. Used to block manual queue removal of an in-use queue: a running process\n * that still references the queue must not have it deleted from under it. Always false on a\n * headless client — an admin tool never owns a queue.\n */\n isRegistered(name: string): boolean {\n if (this.headless) return false;\n return this.entries.has(name) || this.pendingOptions.has(name) || this.ensuring.has(name);\n }\n}\n","/** Logical pub/sub channels. Never a string literal at a notify/subscribe site. */\nexport enum PubSubChannel {\n /** New/changed jobs — carries a lightweight `{ queue }` signal, never the payload. */\n JOBS = 'jobs',\n}\n","import type { Driver } from '../drivers/driver.interface';\nimport type { Logger } from '../logging/logger.interface';\nimport { PubSubChannel } from './channels';\n\n/**\n * Emits DB notifications on new/changed jobs. Notifications carry only\n * a lightweight signal (`{ queue, pattern? }`), never the payload. The optional preferred-instance\n * pattern lets subscribers skip waking for jobs they can't claim.\n */\nexport class NotifierService {\n constructor(\n private readonly driver: Driver,\n private readonly logger: Logger,\n private readonly capable: boolean,\n ) {}\n\n async notifyJobAdded(queue: string, preferredInstanceKeyPattern?: string | null): Promise<void> {\n if (!this.capable) return;\n try {\n const signal =\n preferredInstanceKeyPattern != null\n ? { queue, pattern: preferredInstanceKeyPattern }\n : { queue };\n await this.driver.notify({ channel: PubSubChannel.JOBS, payload: JSON.stringify(signal) });\n } catch (err) {\n this.logger.debug('notify failed (non-fatal; poll backstops).', { err, queue });\n }\n }\n}\n","import { CronExpressionParser } from 'cron-parser';\nimport { InvalidOptionsError } from '../errors/errors';\n\n/**\n * A thin wrapper over the `cron-parser` package — the parsing and the calendar walk are its job,\n * not ours. What this class adds is the two things core depends on:\n * - **eager validation** with a PortQueue-shaped `InvalidOptionsError`, so a bad expression fails\n * at `addJob` rather than silently at the first tick;\n * - a **plain epoch-ms `next()`**, so the scheduler never handles a library date type.\n *\n * Supported syntax is whatever `cron-parser` supports: 5-field\n * (minute hour day-of-month month day-of-week), an optional leading seconds field (6-field), plus\n * ranges, lists, steps, names (`MON`, `JAN`), and the specials `L`, `#`, `W`, `?`.\n *\n * `next-run` is computed in the schedule's IANA timezone (default UTC) and is DST-correct.\n *\n * Catch-up on restart: recurrences are **fire-once, no backfill**. If the process was down across\n * one or more due slots, on restart the schedule fires a single time and then advances to the next\n * future slot — every intermediate missed occurrence is skipped, not replayed. (See\n * `SchedulerService.fire`.)\n */\nexport class CronExpression {\n constructor(\n readonly expression: string,\n readonly timezone: string = 'UTC',\n ) {\n // Validate the timezone before the expression so an unknown zone gets its own clear message.\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: timezone });\n } catch {\n throw new InvalidOptionsError(\n `Invalid timezone '${timezone}' for cron expression '${expression}'.`,\n );\n }\n // Parse once up front so a malformed expression is rejected at add time.\n this.parse(0);\n }\n\n /** The next fire time strictly after `fromMs` (epoch ms). */\n next(fromMs: number): number {\n try {\n return this.parse(fromMs).next().getTime();\n } catch (err) {\n throw new InvalidOptionsError(\n `Cron expression '${this.expression}' has no upcoming run (possibly an impossible date): ${messageOf(err)}`,\n );\n }\n }\n\n private parse(fromMs: number): ReturnType<typeof CronExpressionParser.parse> {\n try {\n return CronExpressionParser.parse(this.expression, {\n currentDate: new Date(fromMs),\n tz: this.timezone,\n });\n } catch (err) {\n throw new InvalidOptionsError(\n `Invalid cron expression '${this.expression}': ${messageOf(err)}. ` +\n `Expected 5 fields (minute hour day-of-month month day-of-week), ` +\n `or 6 with a leading seconds field.`,\n );\n }\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import { JobStatus } from '../jobs/job-state.enum';\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { DeduplicationReason } from '../options/enums';\nimport { InvalidOptionsError, QueuePausedError } from '../errors/errors';\nimport { wholeSeconds, wholeSecondsToMs } from '../util/seconds';\nimport { DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT } from '../constants';\nimport { CronExpression } from '../scheduling/cron';\nimport type { AddJobOptions, CronSpec, ScheduleOptions } from '../options/job-options';\nimport type { AddJobResult, GetSchedulesQuery, Page, ScheduleInfo } from './results';\nimport type { NewJobRecord, NewScheduleRow, ScheduledJobOptions } from '../jobs/job-record';\nimport type { Runtime } from '../client/runtime';\nimport type { NotifierService } from '../pubsub/notifier.service';\n\n/**\n * Insert/dedup/schedule logic behind the producing half of `PortQueue`.\n *\n * Nothing here has a side effect a caller would not expect from its name: in particular the schedule\n * *reads* do not ensure a queue row, so listing the schedules of a name that was never used no\n * longer creates that queue.\n */\nexport class ProducerService {\n constructor(\n private readonly runtime: Runtime,\n private readonly notifier: NotifierService,\n ) {}\n\n async addJob<TData>(queue: string, options: AddJobOptions<TData>): Promise<AddJobResult> {\n const { registry, clock, driver, events, hooks } = this.runtime;\n const merged = await hooks.runBeforeAdd(queue, options as AddJobOptions<unknown>);\n const opts = merged as AddJobOptions<TData>;\n\n if (opts.schedule) this.rejectUnknownScheduleKeys(queue, opts.schedule);\n\n const isRecurring = opts.schedule?.startEverySeconds != null || opts.schedule?.cron != null;\n if (isRecurring && opts.schedule?.startAfterSeconds != null) {\n throw new InvalidOptionsError(\n `Cannot combine 'schedule.startAfterSeconds' with a recurring ` +\n `'schedule.startEverySeconds'/'schedule.cron' on queue '${queue}'. ` +\n `A start delay applies to a one-off job; recurring modes schedule repeated runs.`,\n { queue },\n );\n }\n\n const queueOptions = registry.getOptions(queue);\n\n // Idempotency dedup is queue-scoped and per-entity: a one-off add (no recurring options)\n // dedups against the jobs table; a recurring add dedups against the schedule table. Each key is\n // unique only within its own entity's table, so a one-off job and a schedule may share a key\n // without colliding. First writer wins within that table — a later add with the same key\n // returns the existing entity instead of creating a new one. (Jobs a schedule produces are\n // never stamped with the key, so a recurring schedule keeps producing every run.)\n if (opts.idempotencyKey != null) {\n const dup = await this.findIdempotencyDuplicate(\n queue,\n opts.idempotencyKey,\n isRecurring,\n opts.tx,\n );\n if (dup) {\n // Only a job match carries a jobId the JOB_ADDED event needs; a schedule match is silent.\n if (dup.jobId != null) {\n events.emit(PortQueueEvent.JOB_ADDED, { jobId: dup.jobId, queue, deduplicated: true });\n }\n await hooks.runAfterAdd(queue, dup);\n return dup;\n }\n }\n\n // Scheduling mode: create a recurring definition instead of a one-off insert.\n if (isRecurring) {\n const result = await this.createSchedule(queue, opts);\n await hooks.runAfterAdd(queue, result);\n return result;\n }\n\n const row = await registry.ensure(queue);\n if (row.acceptingPaused) throw new QueuePausedError(queue);\n\n const now = clock.now();\n const job = this.buildJob(queue, opts, queueOptions, now);\n const inserted = await driver.insertJob({ job, ...(opts.tx ? { tx: opts.tx } : {}) });\n\n const result: AddJobResult = {\n jobId: inserted.id,\n queue,\n status: inserted.status,\n startAfter: new Date(inserted.startAfter),\n deduplicated: inserted.deduplicated,\n ...(inserted.deduplicationReason\n ? { deduplicationReason: inserted.deduplicationReason }\n : {}),\n };\n\n if (!inserted.deduplicated) {\n this.announce(queue, [job.preferredInstanceKeyPattern], opts.tx);\n }\n events.emit(PortQueueEvent.JOB_ADDED, {\n jobId: inserted.id,\n queue,\n deduplicated: inserted.deduplicated,\n });\n\n await hooks.runAfterAdd(queue, result);\n return result;\n }\n\n /**\n * Add many one-off jobs to one queue in a **single** insert.\n *\n * This is the batch path `Driver.insertJobs` exists for: one dedup lookup and one multi-row insert\n * for the whole set, rather than the two round trips per job a loop over {@link addJob} costs.\n *\n * Recurring options are rejected here rather than silently ignored — a batch of schedules is a\n * different operation, and each recurrence needs its own `addJob` so its result carries a\n * `scheduleId`. BEFORE_ADD/AFTER_ADD hooks still run per job, in order, exactly as they do for a\n * single add.\n *\n * **The batch is validated before any hook runs.** A hook is allowed to have a side effect (the\n * documented use is enriching options, but nothing enforces purity), and the checks below reject\n * the whole call — so running hooks first fired them for jobs that were never going to be\n * inserted.\n */\n async addJobs<TData>(queue: string, jobs: Array<AddJobOptions<TData>>): Promise<AddJobResult[]> {\n const { registry, clock, driver, events, hooks } = this.runtime;\n if (!jobs.length) return [];\n\n this.validateBatch(queue, jobs);\n // One transaction has to be shared by every entry, so a batch cannot mix caller transactions.\n const tx = jobs.find((opts) => opts.tx)?.tx;\n\n const prepared: Array<AddJobOptions<TData>> = [];\n for (const options of jobs) {\n const opts = (await hooks.runBeforeAdd(\n queue,\n options as AddJobOptions<unknown>,\n )) as AddJobOptions<TData>;\n // A hook may have introduced a recurrence, so the shape is checked again on what it returned.\n this.rejectRecurring(queue, opts);\n prepared.push(opts);\n }\n\n const row = await registry.ensure(queue);\n if (row.acceptingPaused) throw new QueuePausedError(queue);\n\n const now = clock.now();\n const queueOptions = registry.getOptions(queue);\n const records = prepared.map((opts) => this.buildJob(queue, opts, queueOptions, now));\n const inserted = await driver.insertJobs({ jobs: records, ...(tx ? { tx } : {}) });\n\n const results: AddJobResult[] = inserted.map((entry) => ({\n jobId: entry.id,\n queue,\n status: entry.status,\n startAfter: new Date(entry.startAfter),\n deduplicated: entry.deduplicated,\n ...(entry.deduplicationReason ? { deduplicationReason: entry.deduplicationReason } : {}),\n }));\n\n const freshPatterns = records\n .filter((_, index) => !inserted[index]!.deduplicated)\n .map((record) => record.preferredInstanceKeyPattern);\n if (freshPatterns.length) this.announce(queue, freshPatterns, tx);\n\n // Event then hook, per job — the same order `addJob` uses. Two sequential loops emitted every\n // event before any hook ran, so a caller listening to both saw a different ordering from a batch\n // than from a single add.\n for (const result of results) {\n events.emit(PortQueueEvent.JOB_ADDED, {\n jobId: result.jobId!,\n queue,\n deduplicated: result.deduplicated,\n });\n await hooks.runAfterAdd(queue, result);\n }\n return results;\n }\n\n /**\n * Reject a batch whose shape is wrong, before a single hook has run: an entry asking for a\n * recurrence, or entries carrying different transactions.\n */\n private validateBatch<TData>(queue: string, jobs: Array<AddJobOptions<TData>>): void {\n for (const opts of jobs) this.rejectRecurring(queue, opts);\n const tx = jobs.find((opts) => opts.tx)?.tx;\n if (tx && jobs.some((opts) => opts.tx && opts.tx !== tx)) {\n throw new InvalidOptionsError(\n `addJobs on queue '${queue}' received more than one distinct 'tx'. A batch is one insert, ` +\n `so every entry must share the same transaction (or none of them set one).`,\n { queue },\n );\n }\n }\n\n /** One entry's schedule keys: known, and not a recurrence (which `addJobs` cannot express). */\n private rejectRecurring<TData>(queue: string, opts: AddJobOptions<TData>): void {\n if (!opts.schedule) return;\n this.rejectUnknownScheduleKeys(queue, opts.schedule);\n if (opts.schedule.startEverySeconds != null || opts.schedule.cron != null) {\n throw new InvalidOptionsError(\n `addJobs on queue '${queue}' cannot create recurring jobs: one of the entries sets ` +\n `'schedule.cron'/'schedule.startEverySeconds'. Add each recurrence with addJob, whose ` +\n `result carries the scheduleId a batch insert has no place to return.`,\n { queue },\n );\n }\n }\n\n /** Resolve one job's options into the row to insert. */\n private buildJob<TData>(\n queue: string,\n opts: AddJobOptions<TData>,\n queueOptions: ReturnType<Runtime['registry']['getOptions']>,\n now: number,\n ): NewJobRecord {\n const affinity = this.resolveAffinity(queue, opts as AddJobOptions<unknown>);\n const resolved = this.runtime.resolver.resolve({\n job: opts,\n ...(queueOptions.defaultJobOptions ? { queueDefaults: queueOptions.defaultJobOptions } : {}),\n ...(queueOptions.retention ? { queueRetention: queueOptions.retention } : {}),\n ...(opts.schedule?.startAfterSeconds != null\n ? { startAfterSeconds: opts.schedule.startAfterSeconds }\n : {}),\n now,\n });\n return {\n queueName: queue,\n status: JobStatus.PENDING,\n priority: resolved.priority,\n data: opts.data,\n startAfter: resolved.startAfter,\n expireAt: resolved.expireAt,\n retryAttempt: 0,\n retryMaxAttempts: resolved.retryMaxAttempts,\n retryDelaySeconds: resolved.retryDelaySeconds,\n retryBackoff: resolved.retryBackoff,\n retryBackoffFactor: resolved.retryBackoffFactor,\n retryMaxDelaySeconds: resolved.retryMaxDelaySeconds,\n retryJitter: resolved.retryJitter,\n retentionTtlSeconds: resolved.retentionTtlSeconds,\n retentionStatuses: resolved.retentionStatuses,\n idempotencyKey: resolved.idempotencyKey,\n scheduleId: null,\n singletonKey: resolved.singletonKey,\n preferredInstanceKeyPattern: affinity.preferredInstanceKeyPattern,\n createdAt: now,\n };\n }\n\n /**\n * Wake local workers and NOTIFY the cluster that new work landed. With a caller transaction the\n * announcement is deferred to commit, so a rolled-back insert never wakes anyone.\n */\n private announce(\n queue: string,\n patterns: Array<string | null>,\n tx: AddJobOptions<unknown>['tx'],\n ): void {\n const fire = (): void => {\n this.runtime.wakeup.signal(queue);\n // One NOTIFY per distinct affinity pattern: a listener filters on it, so collapsing them\n // would tell the wrong instances to wake.\n for (const pattern of new Set(patterns)) {\n this.runtime.background.run(() => this.notifier.notifyJobAdded(queue, pattern));\n }\n };\n if (tx?.onCommit) tx.onCommit(fire);\n else if (!tx) fire();\n }\n\n /**\n * Validate and normalize the multi-instance affinity option. Affinity is only meaningful when\n * this PortQueue declared an `instanceKey`; a job targets instances by a single regex pattern.\n */\n private resolveAffinity(\n queue: string,\n opts: AddJobOptions<unknown>,\n ): {\n preferredInstanceKeyPattern: string | null;\n } {\n const { preferredInstanceKeyPattern } = opts;\n if (preferredInstanceKeyPattern != null && !this.runtime.instanceKey) {\n throw new InvalidOptionsError(\n `Job on queue '${queue}' sets 'preferredInstanceKeyPattern', but this process has no ` +\n `instance key. Pass \\`instance: { instanceKey }\\` to the PortQueue constructor to name it.`,\n { queue },\n );\n }\n if (preferredInstanceKeyPattern != null) {\n try {\n new RegExp(preferredInstanceKeyPattern);\n } catch (err) {\n throw new InvalidOptionsError(\n `Job on queue '${queue}' has an invalid 'preferredInstanceKeyPattern' regular expression: ${String(err)}`,\n { queue },\n );\n }\n }\n return { preferredInstanceKeyPattern: preferredInstanceKeyPattern ?? null };\n }\n\n /**\n * The idempotency lookup behind {@link addJob}. A one-off add checks the jobs table; a recurring\n * add checks the schedule table — a key is unique only within its own entity's table. Returns a\n * deduplicated result shaped for the matched entity, or null when the key is free in that table.\n */\n private async findIdempotencyDuplicate(\n queue: string,\n idempotencyKey: string,\n isRecurring: boolean,\n tx?: AddJobOptions<unknown>['tx'],\n ): Promise<AddJobResult | null> {\n const { driver } = this.runtime;\n if (isRecurring) {\n const schedule = await driver.findScheduleByIdempotencyKey({\n queueName: queue,\n idempotencyKey,\n ...(tx ? { tx } : {}),\n });\n if (!schedule) return null;\n return {\n queue,\n scheduleId: schedule.id,\n nextRunAt: schedule.nextRunAt != null ? new Date(schedule.nextRunAt) : null,\n deduplicated: true,\n deduplicationReason: DeduplicationReason.IDEMPOTENCY,\n };\n }\n const job = await driver.findJobByIdempotencyKey({\n queueName: queue,\n idempotencyKey,\n ...(tx ? { tx } : {}),\n });\n if (!job) return null;\n return {\n jobId: job.id,\n queue,\n status: job.status,\n startAfter: new Date(job.startAfter),\n deduplicated: true,\n deduplicationReason: DeduplicationReason.IDEMPOTENCY,\n };\n }\n\n private async createSchedule<TData>(\n queue: string,\n opts: AddJobOptions<TData>,\n ): Promise<AddJobResult> {\n this.validateSchedule(queue, opts);\n const { registry, driver, clock, resolver, events } = this.runtime;\n await registry.ensure(queue);\n const queueOptions = registry.getOptions(queue);\n const affinity = this.resolveAffinity(queue, opts);\n const now = clock.now();\n const resolved = resolver.resolve({\n job: opts,\n ...(queueOptions.defaultJobOptions ? { queueDefaults: queueOptions.defaultJobOptions } : {}),\n ...(queueOptions.retention ? { queueRetention: queueOptions.retention } : {}),\n now,\n });\n const cron = opts.schedule?.cron != null ? normalizeCron(opts.schedule.cron) : null;\n const everySeconds =\n opts.schedule?.startEverySeconds != null\n ? wholeSeconds(opts.schedule.startEverySeconds, 'schedule.startEverySeconds')\n : null;\n // No pattern-based dedup: identical recurrences on a queue are allowed to coexist. When the\n // caller wants exactly one, they pass an idempotencyKey — that dedup ran in addJob() above, so\n // reaching here means the key was free (or absent) and we always insert a fresh schedule.\n const nextRunAt = this.computeNextRun(opts.schedule!, now);\n\n // Every option that shapes the *produced* jobs (beyond the columns below) rides along with the\n // schedule and is stamped onto each run — the schedule row itself is never expired/retained by\n // these; they govern the spawned jobs. `expireInSeconds` is stored as a duration and re-applied\n // relative to each run's fire time. See {@link ScheduledJobOptions}.\n const jobOptions: ScheduledJobOptions = {\n expireInSeconds:\n opts.expireInSeconds != null ? wholeSeconds(opts.expireInSeconds, 'expireInSeconds') : null,\n retryBackoff: resolved.retryBackoff,\n retryBackoffFactor: resolved.retryBackoffFactor,\n retryMaxDelaySeconds: resolved.retryMaxDelaySeconds,\n retryJitter: resolved.retryJitter,\n retentionTtlSeconds: resolved.retentionTtlSeconds,\n retentionStatuses: resolved.retentionStatuses,\n singletonKey: resolved.singletonKey,\n preferredInstanceKeyPattern: affinity.preferredInstanceKeyPattern,\n };\n\n const newSchedule: NewScheduleRow = {\n queueName: queue,\n cron: cron?.pattern ?? null,\n everySeconds,\n timezone: cron?.tz ?? null,\n data: opts.data,\n priority: resolved.priority,\n retryMaxAttempts: resolved.retryMaxAttempts,\n retryDelaySeconds: resolved.retryDelaySeconds,\n nextRunAt,\n enabled: true,\n idempotencyKey: resolved.idempotencyKey,\n jobOptions,\n };\n const saved = await driver.insertSchedule({\n schedule: newSchedule,\n ...(opts.tx ? { tx: opts.tx } : {}),\n });\n events.emit(PortQueueEvent.SCHEDULE_CREATED, {\n scheduleId: saved.id,\n queue,\n });\n return {\n queue,\n scheduleId: saved.id,\n nextRunAt: saved.nextRunAt != null ? new Date(saved.nextRunAt) : null,\n deduplicated: false,\n };\n }\n\n /**\n * Reject any key the `schedule` group doesn't define. Without this an unknown key — a typo, or an\n * option that no longer exists like the old absolute-`Date` `startAfter` — is silently dropped and\n * the job runs immediately, which looks like the scheduler losing it. TypeScript already catches\n * this; the check is for JavaScript callers and hand-built payloads.\n */\n private rejectUnknownScheduleKeys(queue: string, schedule: ScheduleOptions): void {\n const allowed: ReadonlySet<string> = new Set<keyof ScheduleOptions>([\n 'startAfterSeconds',\n 'startEverySeconds',\n 'cron',\n ]);\n const unknown = Object.keys(schedule).filter((key) => !allowed.has(key));\n if (unknown.length > 0) {\n throw new InvalidOptionsError(\n `Unknown 'schedule' option${unknown.length > 1 ? 's' : ''} on queue '${queue}': ` +\n `${unknown.map((k) => `'${k}'`).join(', ')}. Valid keys are 'startAfterSeconds' (a ` +\n `one-off delay in seconds), 'startEverySeconds' (a recurring interval in seconds) and ` +\n `'cron'. Every duration is a whole number of seconds; there is no absolute-Date form.`,\n { queue },\n );\n }\n }\n\n private validateSchedule(queue: string, opts: AddJobOptions<unknown>): void {\n if (opts.schedule?.cron != null && opts.schedule?.startEverySeconds != null) {\n throw new InvalidOptionsError(\n `A recurring job on queue '${queue}' must set exactly one of 'schedule.cron' or 'schedule.startEverySeconds' — not both.`,\n { queue },\n );\n }\n }\n\n computeNextRun(schedule: ScheduleOptions, now: number): number {\n if (schedule.cron != null) {\n const { pattern, tz } = normalizeCron(schedule.cron);\n return new CronExpression(pattern, tz).next(now);\n }\n return now + wholeSecondsToMs(schedule.startEverySeconds!, 'schedule.startEverySeconds');\n }\n\n /**\n * A page of schedules — one queue's when `queue` is given, every queue's otherwise. Filtering and\n * paging both happen in the database; the count is a second query rather than a JOIN or a\n * whole-table read. **This is a read and behaves like one:** it does not ensure the queue row, so\n * listing the schedules of a name that was never used does not create it.\n */\n async getSchedules(query: GetSchedulesQuery = {}): Promise<Page<ScheduleInfo>> {\n const limit = Math.min(\n Math.max(Math.trunc(query.limit ?? DEFAULT_PAGE_LIMIT), 1),\n MAX_PAGE_LIMIT,\n );\n const offset = Math.max(Math.trunc(query.offset ?? 0), 0);\n const filter = {\n ...(query.queue ? { queueName: query.queue } : {}),\n ...(query.enabled !== undefined ? { enabled: query.enabled } : {}),\n };\n const [rows, total] = await Promise.all([\n this.runtime.driver.listSchedules({ ...filter, limit, offset }),\n this.runtime.driver.countSchedules(filter),\n ]);\n return { items: rows.map((s) => toScheduleInfo(s)), total };\n }\n\n /** One schedule by id, or null when no schedule has that id. */\n async getSchedule(scheduleId: string): Promise<ScheduleInfo | null> {\n const row = await this.runtime.driver.getSchedule({ scheduleId });\n return row ? toScheduleInfo(row) : null;\n }\n}\n\n/** Map a schedule row to the public {@link ScheduleInfo}. */\nfunction toScheduleInfo(s: {\n id: string;\n queueName: string;\n cron: string | null;\n everySeconds: number | null;\n timezone: string | null;\n nextRunAt: number | null;\n lastRunAt: number | null;\n enabled: boolean;\n idempotencyKey: string | null;\n}): ScheduleInfo {\n return {\n scheduleId: s.id,\n queue: s.queueName,\n cron: s.cron,\n everySeconds: s.everySeconds,\n timezone: s.timezone,\n nextRunAt: s.nextRunAt != null ? new Date(s.nextRunAt) : null,\n lastRunAt: s.lastRunAt != null ? new Date(s.lastRunAt) : null,\n enabled: s.enabled,\n idempotencyKey: s.idempotencyKey,\n };\n}\n\n/** Normalize a {@link CronSpec} (string or `{ pattern, tz }`) to a pattern + IANA tz. */\nfunction normalizeCron(cron: CronSpec): { pattern: string; tz: string } {\n if (typeof cron === 'string') return { pattern: cron, tz: 'UTC' };\n return { pattern: cron.pattern, tz: cron.tz ?? 'UTC' };\n}\n","import type { JobRecord } from './job-record';\nimport type { JobSnapshot } from '../producer/results';\nimport { JobStatus } from './job-state.enum';\n\nconst d = (ms: number | null | undefined): Date | null => (ms == null ? null : new Date(ms));\n\n/** Map an internal {@link JobRecord} to a public {@link JobSnapshot}. */\nexport function toSnapshot<TData = unknown>(\n record: JobRecord,\n queueName: string,\n now: number,\n): JobSnapshot<TData> {\n const stalled =\n record.status === JobStatus.ACTIVE && record.lockedUntil != null && record.lockedUntil < now;\n return {\n id: record.id,\n queue: queueName,\n status: record.status,\n data: record.data as TData,\n returnValue: record.returnValue,\n priority: record.priority,\n retryAttempt: record.retryAttempt,\n retryMaxAttempts: record.retryMaxAttempts,\n createdAt: new Date(record.createdAt),\n updatedAt: new Date(record.updatedAt),\n startAfter: new Date(record.startAfter),\n startedAt: d(record.startedAt),\n completedAt: d(record.completedAt),\n failedAt: d(record.failedAt),\n cancelledAt: d(record.cancelledAt),\n expiredAt: d(record.expiredAt),\n retriedAt: d(record.retriedAt),\n stalledAt: d(record.stalledAt),\n lockedUntil: d(record.lockedUntil),\n preferredInstanceKeyPattern: record.preferredInstanceKeyPattern,\n processedOnInstanceKey: record.processedOnInstanceKey,\n failureMessage: record.failureMessage,\n idempotencyKey: record.idempotencyKey,\n scheduleId: record.scheduleId,\n stalled,\n };\n}\n","import { emptyStatusCounts, JobStatus } from '../jobs/job-state.enum';\nimport { toSnapshot } from '../jobs/snapshot';\nimport { secondsToMs } from '../util/seconds';\nimport {\n DEFAULT_HEARTBEAT_INTERVAL_SECONDS,\n DEFAULT_PAGE_LIMIT,\n HEARTBEAT_STALE_BEATS,\n MAX_PAGE_LIMIT,\n} from '../constants';\nimport type { Runtime } from '../client/runtime';\nimport type { InstanceRow, QueueRow } from '../jobs/job-record';\nimport type { JobListFilter } from '../drivers/driver.interface';\nimport type { PortQueueOptions } from '../options/client-options';\nimport type {\n GetInstancesQuery,\n GetJobsQuery,\n GetQueuesQuery,\n InstanceInfo,\n JobSnapshot,\n Page,\n QueueInfo,\n QueueStats,\n} from '../producer/results';\n\n/**\n * How long an instance may go unheard-from before it counts as stale: {@link HEARTBEAT_STALE_BEATS}\n * heartbeats, so a single missed beat (a slow query, a GC pause) doesn't flip a healthy instance.\n *\n * Exported because the dashboard facade needs the identical window to build the same `alive` flag —\n * this policy used to live as a literal `15` and a literal `× 3` in four separate files.\n */\nexport function instanceStaleAfterMs(options: PortQueueOptions): number {\n const beatSeconds =\n options.instance?.heartbeatIntervalSeconds ?? DEFAULT_HEARTBEAT_INTERVAL_SECONDS;\n return secondsToMs(beatSeconds * HEARTBEAT_STALE_BEATS, 'instance.heartbeatIntervalSeconds');\n}\n\n/**\n * Map an `instance` row to the public {@link InstanceInfo}. One mapper, used by both the public read\n * and the dashboard facade — the two used to build byte-identical objects from their own copies of\n * the same liveness arithmetic.\n */\nexport function toInstanceInfo(\n row: InstanceRow,\n counts: Record<JobStatus, number> | undefined,\n seenSince: number,\n): InstanceInfo {\n return {\n instanceKey: row.instanceKey,\n processingPaused: row.processingPaused,\n alive: row.lastSeenAt >= seenSince,\n createdAt: new Date(row.createdAt),\n updatedAt: new Date(row.updatedAt),\n lastSeenAt: new Date(row.lastSeenAt),\n cpuPercent: row.cpuPercent,\n memoryPercent: row.memoryPercent,\n counts: counts ?? emptyStatusCounts(),\n };\n}\n\n/** Map a `queue` row to the public {@link QueueInfo}. */\nexport function toQueueInfo(\n row: QueueRow,\n counts: Record<JobStatus, number> | undefined,\n inUse: boolean,\n): QueueInfo {\n return {\n name: row.name,\n processingPaused: row.processingPaused,\n acceptingPaused: row.acceptingPaused,\n counts: counts ?? emptyStatusCounts(),\n inUse,\n };\n}\n\n/** Clamp a caller-supplied page window to something the database is happy to serve. */\nexport function pageWindow(\n query: { limit?: number; offset?: number },\n maxLimit = MAX_PAGE_LIMIT,\n): { limit: number; offset: number } {\n return {\n limit: Math.min(Math.max(Math.trunc(query.limit ?? DEFAULT_PAGE_LIMIT), 1), maxLimit),\n offset: Math.max(Math.trunc(query.offset ?? 0), 0),\n };\n}\n\n/**\n * Read-side aggregations for the API, dashboard, and CLI. A job carries its\n * `queueName` directly, so there is no id→name lookup and never a JOIN.\n */\nexport class ReadService {\n constructor(private readonly runtime: Runtime) {}\n\n async getJob<TData = unknown>(jobId: string): Promise<JobSnapshot<TData> | null> {\n const record = await this.runtime.driver.getJob({ jobId });\n if (!record) return null;\n return toSnapshot<TData>(record, record.queueName, this.runtime.clock.now());\n }\n\n /**\n * A page of jobs, newest first.\n *\n * `instanceKey` and `search` are not part of the public `GetJobsQuery` — they are here for the\n * dashboard facade, whose instance detail view reads jobs by the instance that claimed them and\n * whose table offers a free-text filter. Both are pushed into SQL, so a search pages in the\n * database rather than streaming the table into this process.\n */\n async getJobs<TData = unknown>(\n query: GetJobsQuery & { instanceKey?: string; search?: string },\n ): Promise<Page<JobSnapshot<TData>>> {\n const { limit, offset } = pageWindow(query);\n const filter: JobListFilter = {\n ...(query.queue ? { queueName: query.queue } : {}),\n ...(query.statuses ? { statuses: query.statuses } : {}),\n ...(query.scheduleId ? { scheduleId: query.scheduleId } : {}),\n ...(query.instanceKey ? { processedOnInstanceKey: query.instanceKey } : {}),\n ...(query.search ? { search: query.search } : {}),\n };\n // `total` is a real `COUNT` over the same predicate as the page, always. It used to be inferred\n // from the page when nothing followed it — `offset + page.length` — which is only the count of\n // anything on a forward walk: jumping straight to `offset: 1000` on a 20-row table reported\n // `total: 1000`. Both the dashboard's pagination and the CLI's \"… more\" hint read this number.\n const [records, total] = await Promise.all([\n this.runtime.driver.getJobs({ ...filter, limit, offset }),\n this.runtime.driver.countJobs(filter),\n ]);\n const now = this.runtime.clock.now();\n return { items: records.map((r) => toSnapshot<TData>(r, r.queueName, now)), total };\n }\n\n async getQueueStats(queue?: string): Promise<QueueStats> {\n const counts = await this.runtime.driver.countJobsByStatus(queue ? { queueName: queue } : {});\n return { ...(queue ? { queue } : {}), counts };\n }\n\n /**\n * A page of queues with their per-status counts, plus the total across every page. Same\n * `limit`/`offset` window as the job, schedule and instance reads.\n */\n async getQueues(query: GetQueuesQuery = {}): Promise<Page<QueueInfo>> {\n const { limit, offset } = pageWindow(query);\n // The filter goes to both calls, so the page and its total can never disagree about what they\n // are describing — and a caller looking for paused queues narrows in SQL instead of paging the\n // whole table and filtering here.\n const filter = {\n ...(query.search ? { search: query.search } : {}),\n ...(query.processingPaused !== undefined ? { processingPaused: query.processingPaused } : {}),\n };\n const [rows, total] = await Promise.all([\n this.runtime.driver.listQueues({ ...filter, limit, offset }),\n this.runtime.driver.countQueues(filter),\n ]);\n if (!rows.length) return { items: [], total };\n // One grouped count for the whole page rather than a query per queue.\n const counts = await this.runtime.driver.countJobsByStatusPerQueue({\n queueNames: rows.map((r) => r.name),\n });\n return {\n items: rows.map((row) =>\n toQueueInfo(row, counts[row.name], this.runtime.registry.isRegistered(row.name)),\n ),\n total,\n };\n }\n\n /** One queue by name, with the same counts and `inUse` flag the list carries. Null if unknown. */\n async getQueue(name: string): Promise<QueueInfo | null> {\n const row = await this.runtime.driver.getQueueByName({ name });\n if (!row) return null;\n const counts = await this.runtime.driver.countJobsByStatusPerQueue({ queueNames: [row.name] });\n return toQueueInfo(row, counts[row.name], this.runtime.registry.isRegistered(row.name));\n }\n\n /**\n * A page of instances with liveness and per-instance job attribution, plus the total across\n * every page. Same `limit`/`offset` window as the job and schedule reads.\n */\n async getInstances(query: GetInstancesQuery = {}): Promise<Page<InstanceInfo>> {\n const { limit, offset } = pageWindow(query);\n const filter = {\n ...(query.search ? { search: query.search } : {}),\n ...(query.processingPaused !== undefined ? { processingPaused: query.processingPaused } : {}),\n ...(query.alive !== undefined\n ? {\n alive: query.alive,\n seenSince: this.runtime.clock.now() - instanceStaleAfterMs(this.runtime.options),\n }\n : {}),\n };\n const [rows, total] = await Promise.all([\n this.runtime.driver.listInstances({ ...filter, limit, offset }),\n this.runtime.driver.countInstances(filter),\n ]);\n if (!rows.length) return { items: [], total };\n const seenSince = this.runtime.clock.now() - instanceStaleAfterMs(this.runtime.options);\n // One grouped count for the whole page rather than a query per instance.\n const counts = await this.runtime.driver.countJobsByStatusPerInstance({\n instanceKeys: rows.map((r) => r.instanceKey),\n });\n return {\n items: rows.map((row) => toInstanceInfo(row, counts[row.instanceKey], seenSince)),\n total,\n };\n }\n\n /** One instance by key, with the same liveness, health and attribution the list carries. */\n async getInstance(instanceKey: string): Promise<InstanceInfo | null> {\n const row = await this.runtime.driver.getInstance({ instanceKey });\n if (!row) return null;\n const seenSince = this.runtime.clock.now() - instanceStaleAfterMs(this.runtime.options);\n const counts = await this.runtime.driver.countJobsByStatusPerInstance({\n instanceKeys: [row.instanceKey],\n });\n return toInstanceInfo(row, counts[row.instanceKey], seenSince);\n }\n}\n\nexport { JobStatus };\n","import { BackoffStrategy } from '../options/enums';\nimport { DEFAULT_BACKOFF_FACTOR } from '../constants';\n\nexport interface BackoffInput {\n strategy: BackoffStrategy;\n /** The attempt number that just failed (1-based). */\n attempt: number;\n /** Base delay in seconds. */\n baseDelaySeconds: number;\n /** Growth factor for EXPONENTIAL (ignored for FIXED). */\n factor?: number | null;\n /** Cap on the computed delay, in seconds. */\n maxDelaySeconds?: number | null;\n /** Whether to apply jitter. */\n jitter?: boolean;\n /** Random source in [0,1) — injectable for deterministic tests. */\n random?: () => number;\n}\n\n/**\n * Compute the delay in **seconds** before the next retry. Fractions are preserved — the caller\n * converts to the epoch-ms instant, so rounding here would quantise sub-second retries away.\n * - FIXED: `baseDelaySeconds` each time.\n * - EXPONENTIAL: `baseDelaySeconds * factor^(attempt-1)`, capped at `maxDelaySeconds`.\n * Optional full jitter multiplies the result by a random factor in [0,1].\n */\nexport function computeBackoffSeconds(input: BackoffInput): number {\n const { strategy, attempt, baseDelaySeconds } = input;\n const factor = input.factor ?? DEFAULT_BACKOFF_FACTOR;\n let delay: number;\n if (strategy === BackoffStrategy.EXPONENTIAL) {\n delay = baseDelaySeconds * Math.pow(factor, Math.max(0, attempt - 1));\n } else {\n delay = baseDelaySeconds;\n }\n if (input.maxDelaySeconds != null) {\n delay = Math.min(delay, input.maxDelaySeconds);\n }\n if (input.jitter) {\n const rand = input.random ?? Math.random;\n // Full jitter: uniform in [0, delay].\n delay = delay * rand();\n }\n return Math.max(0, delay);\n}\n","import { JobStatus } from '../jobs/job-state.enum';\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { computeBackoffSeconds } from '../util/backoff';\nimport { msToSeconds, secondsToMs } from '../util/seconds';\nimport { LockLostError } from '../errors/errors';\nimport {\n DEFAULT_FAILURE_DETAIL,\n FAILURE_MESSAGE_MAX_CHARS,\n FAILURE_MESSAGE_TRUNCATION_SUFFIX,\n} from '../constants';\nimport { FailureDetail } from '../options/enums';\nimport type { ErrorClass } from '../options/queue-options';\nimport type { JobRecord } from '../jobs/job-record';\nimport type { Runtime } from '../client/runtime';\nimport type { ProcessOutcome } from '../events/hooks';\n\n/**\n * Marks complete/failed/retry atomically and emits the matching event.\n *\n * Every write is fenced on the claim the run was made under (`record.lockToken`), and the driver\n * reports whether the row was actually settled. When it was not — the lock lapsed, another worker\n * reclaimed the row and is running the job now — this run's outcome is **not** the job's outcome, so\n * no lifecycle event is emitted for it and the `ERROR` event carries a {@link LockLostError}\n * instead. Emitting `JOB_COMPLETED` there would tell every listener a job had finished while its\n * second run was still going.\n */\nexport class CompletionService {\n constructor(private readonly runtime: Runtime) {}\n\n async complete(\n record: JobRecord,\n queueName: string,\n returnValue: unknown,\n startTs: number,\n ): Promise<ProcessOutcome> {\n const now = this.runtime.clock.now();\n const settled = await this.runtime.driver.completeJob({\n jobId: record.id,\n returnValue,\n now,\n lockToken: record.lockToken,\n });\n if (!settled) return this.claimLost(record, queueName, { kind: 'completed', returnValue });\n this.runtime.events.emit(PortQueueEvent.JOB_COMPLETED, {\n jobId: record.id,\n queue: queueName,\n returnValue,\n durationSeconds: msToSeconds(now - startTs),\n });\n return { kind: 'completed', returnValue };\n }\n\n /** Decide retry-vs-fail after a handler throw. */\n async failOrRetry(\n record: JobRecord,\n queueName: string,\n error: unknown,\n dontAutoretryFor: Array<ErrorClass | string>,\n failureDetail: FailureDetail = DEFAULT_FAILURE_DETAIL,\n ): Promise<ProcessOutcome> {\n const now = this.runtime.clock.now();\n const message = errorToMessage(error, failureDetail);\n const attemptsMade = record.retryAttempt + 1;\n const nonRetryable = matchesNonRetryable(error, dontAutoretryFor);\n const canRetry = !nonRetryable && attemptsMade < record.retryMaxAttempts;\n\n if (canRetry) {\n const delaySeconds = computeBackoffSeconds({\n strategy: record.retryBackoff,\n attempt: attemptsMade,\n baseDelaySeconds: record.retryDelaySeconds,\n factor: record.retryBackoffFactor,\n maxDelaySeconds: record.retryMaxDelaySeconds,\n jitter: record.retryJitter,\n });\n const nextRunAt = now + Math.round(secondsToMs(delaySeconds, 'retry delay'));\n const outcome: ProcessOutcome = { kind: 'retry', error, nextRunAt: new Date(nextRunAt) };\n const armed = await this.runtime.driver.retryJob({\n jobId: record.id,\n nextRunAt,\n retryAttempt: attemptsMade,\n lastError: message,\n now,\n lockToken: record.lockToken,\n });\n if (!armed) return this.claimLost(record, queueName, outcome);\n this.runtime.events.emit(PortQueueEvent.JOB_RETRYING, {\n jobId: record.id,\n queue: queueName,\n retryAttempt: attemptsMade,\n nextRunAt: new Date(nextRunAt),\n });\n // Wake the loop; the claim query still gates on start_after so a delayed retry waits.\n this.runtime.wakeup.signal(queueName);\n return outcome;\n }\n\n const failed = await this.runtime.driver.failJob({\n jobId: record.id,\n lastError: message,\n now,\n lockToken: record.lockToken,\n });\n if (!failed) return this.claimLost(record, queueName, { kind: 'failed', error });\n this.runtime.events.emit(PortQueueEvent.JOB_FAILED, {\n jobId: record.id,\n queue: queueName,\n error,\n retryAttempt: record.retryAttempt,\n });\n return { kind: 'failed', error };\n }\n\n /**\n * Report a settle the row refused, and hand back the outcome unchanged.\n *\n * The outcome still describes what *this handler* did, which is what an `AFTER_PROCESS` hook is\n * asking about; what it no longer describes is the row, so nothing is emitted for the job.\n */\n private claimLost(record: JobRecord, queueName: string, outcome: ProcessOutcome): ProcessOutcome {\n this.runtime.events.emit(PortQueueEvent.ERROR, {\n error: new LockLostError(record.id, queueName),\n source: 'completion',\n });\n return outcome;\n }\n}\n\n/**\n * Normalize any thrown value to the message stored on the row, **truncated**.\n *\n * Includes the stack by default, because that is what anyone diagnosing a failure opens the job to\n * read. A stack from a deep async chain runs to tens of kilobytes, so it is capped — and a queue that\n * fails often and predictably can drop the frames altogether with\n * `createQueue({ failureDetail: FailureDetail.MESSAGE })`, since even the capped form is ~4 KB on\n * every failed row.\n */\nexport function errorToMessage(\n error: unknown,\n detail: FailureDetail = DEFAULT_FAILURE_DETAIL,\n): string {\n return truncate(rawErrorMessage(error, detail));\n}\n\nfunction rawErrorMessage(error: unknown, detail: FailureDetail): string {\n if (error instanceof Error) {\n const named = `${error.name}: ${error.message}`;\n // `MESSAGE` is the choice a queue makes when its handler fails often: the frames are noise, and\n // ~4 KB per failed row is not.\n if (detail === FailureDetail.MESSAGE) return named;\n return error.stack ?? named;\n }\n if (typeof error === 'string') return error;\n try {\n return JSON.stringify(error) ?? String(error);\n } catch {\n return String(error);\n }\n}\n\n/**\n * Cut a message to the cap **on a code-point boundary**.\n *\n * `slice` counts UTF-16 code units, so cutting mid-surrogate-pair stores a lone surrogate — which is\n * not valid text, and which some engines (Oracle in particular) refuse on write. An emoji or a\n * non-BMP character landing exactly on the boundary is enough to hit it. Dropping the trailing high\n * surrogate keeps the message one character shorter and always writable.\n */\nfunction truncate(message: string): string {\n if (message.length <= FAILURE_MESSAGE_MAX_CHARS) return message;\n let end = FAILURE_MESSAGE_MAX_CHARS;\n const last = message.charCodeAt(end - 1);\n const isHighSurrogate = last >= 0xd800 && last <= 0xdbff;\n if (isHighSurrogate) end -= 1;\n return message.slice(0, end) + FAILURE_MESSAGE_TRUNCATION_SUFFIX;\n}\n\nfunction matchesNonRetryable(error: unknown, list: Array<ErrorClass | string>): boolean {\n if (!list.length) return false;\n const name = error instanceof Error ? error.name : undefined;\n for (const entry of list) {\n if (typeof entry === 'string') {\n if (name === entry) return true;\n } else if (typeof entry === 'function' && error instanceof entry) {\n return true;\n }\n }\n return false;\n}\n\nexport { JobStatus };\n","import type { Worker } from '../consumer/worker';\nimport type { Queue } from '../producer/queue';\n\n/**\n * Tracks this process's queue declarations and their consumers, for graceful shutdown, stats and\n * cooperative cancellation.\n *\n * A queue has **at most one** consumer per process, so the consumers are keyed by queue name.\n * `PortQueue.createQueue` builds one when a declaration carries a `handler`, and {@link hasWorker} is\n * how it refuses a second one before it gets here — replacing a live consumer would strand its claim\n * loop outside {@link allWorkers}, where nothing would ever drain it.\n */\nexport class ClientRegistryService {\n private readonly workers = new Map<string, Worker>();\n private readonly queues = new Map<string, Queue<unknown>>();\n\n addWorker(queueName: string, worker: Worker): void {\n this.workers.set(queueName, worker);\n }\n\n hasWorker(queueName: string): boolean {\n return this.workers.has(queueName);\n }\n\n addQueue(name: string, queue: Queue<unknown>): void {\n this.queues.set(name, queue);\n }\n\n getQueue(name: string): Queue<unknown> | undefined {\n return this.queues.get(name);\n }\n\n allWorkers(): IterableIterator<Worker> {\n return this.workers.values();\n }\n\n /** Try to cooperatively cancel an active job across every queue consumed on this instance. */\n cancelRunning(jobId: string): boolean {\n for (const worker of this.workers.values()) {\n if (worker.cancelRunning(jobId)) return true;\n }\n return false;\n }\n\n /**\n * Whether a job is currently running *in this process*. The read-only half of\n * {@link cancelRunning}, which both tests and acts and so can't be used as a probe.\n */\n isRunning(jobId: string): boolean {\n for (const worker of this.workers.values()) {\n if (worker.executor.active.has(jobId)) return true;\n }\n return false;\n }\n}\n","import type { Driver, Subscription } from '../drivers/driver.interface';\nimport { DriverCapability } from '../drivers/driver-capabilities';\nimport { matchesInstance } from '../jobs/instance-affinity';\nimport type { Logger } from '../logging/logger.interface';\nimport type { Wakeup } from './wakeup';\nimport { PubSubChannel } from './channels';\n\n/**\n * Listens for DB notifications and wakes claim loops. When LISTEN/NOTIFY\n * is unavailable it relies on each worker's interval poller; a \"safety poll\" also runs even\n * when LISTEN is available to catch missed notifications (delayed jobs, stalled reclaims).\n */\nexport class SubscriberService {\n private subscription: Subscription | null = null;\n private safetyTimer: NodeJS.Timeout | null = null;\n\n constructor(\n private readonly driver: Driver,\n private readonly logger: Logger,\n private readonly wakeup: Wakeup,\n private readonly safetyPollMs: number,\n private readonly instanceKey: string | null,\n ) {}\n\n async start(): Promise<void> {\n if (this.driver.capabilities[DriverCapability.LISTEN_NOTIFY]) {\n try {\n this.subscription = await this.driver.subscribe({\n channel: PubSubChannel.JOBS,\n onNotification: (payload) => {\n try {\n const { queue, pattern } = JSON.parse(payload) as {\n queue?: string;\n pattern?: string | null;\n };\n if (!queue) {\n this.wakeup.signalAll();\n return;\n }\n // Skip the wakeup when the added job targets a pattern this instance can't match —\n // claiming it would find nothing. Jobs meant for us fire their own notify, and the\n // safety poll backstops anything missed. Null pattern (or single-instance) → wake.\n if (pattern != null && this.instanceKey != null) {\n if (!matchesInstance(pattern, this.instanceKey)) return;\n }\n this.wakeup.signal(queue);\n } catch {\n this.wakeup.signalAll();\n }\n },\n });\n } catch (err) {\n this.logger.warn('LISTEN/NOTIFY subscribe failed; relying on polling.', { err });\n }\n } else {\n this.logger.debug('Driver has no LISTEN/NOTIFY; using interval polling.');\n }\n // Safety poll backstops missed notifications and delayed/stalled jobs on every driver.\n this.safetyTimer = setInterval(() => this.wakeup.signalAll(), this.safetyPollMs);\n this.safetyTimer.unref?.();\n }\n\n async stop(): Promise<void> {\n if (this.safetyTimer) {\n clearInterval(this.safetyTimer);\n this.safetyTimer = null;\n }\n if (this.subscription) {\n await this.subscription.unsubscribe().catch(() => undefined);\n this.subscription = null;\n }\n }\n}\n","import { JobStatus } from '../jobs/job-state.enum';\nimport { BackoffStrategy } from '../options/enums';\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { CronExpression } from './cron';\nimport { secondsToMs } from '../util/seconds';\nimport {\n MAINTENANCE_BATCH_SIZE,\n MAINTENANCE_MAX_BATCHES,\n SCHEDULE_BATCH_SIZE,\n SCHEDULE_MAX_BATCHES,\n} from '../constants';\nimport type { NewJobRecord, ScheduleRow } from '../jobs/job-record';\nimport type { Runtime } from '../client/runtime';\n\n/**\n * Turns due schedules into concrete jobs. Production is exactly-once per\n * tick across the cluster (guarded `advanceSchedule`). A missed schedule fires once and\n * advances to the next future slot — it never backfills every missed occurrence.\n * The tick also owns expiring due-but-unstarted jobs and reclaiming stalled jobs.\n *\n * **Every sweep here is batched and looped.** Each pass takes a bounded number of rows and repeats\n * until a batch comes back short, so a backlog drains across round trips rather than either waiting\n * for the next tick (which one capped batch did to the 101st due schedule) or arriving as a single\n * unbounded transfer (which an uncapped `expireDueJobs` did to a 100k-row backlog).\n */\nexport class SchedulerService {\n constructor(private readonly runtime: Runtime) {}\n\n async tick(): Promise<void> {\n await this.produceDue();\n await this.expireDue();\n await this.reclaimStalled();\n }\n\n /**\n * Fire every schedule that is due, in batches. The loop matters: with more than one batch worth of\n * due schedules, the remainder used to wait a full tick interval — so a hundred hourly crons all\n * set for the same minute drifted apart from one another.\n */\n private async produceDue(): Promise<void> {\n for (let batch = 0; batch < SCHEDULE_MAX_BATCHES; batch += 1) {\n const now = this.runtime.clock.now();\n const due = await this.runtime.driver.getDueSchedules({ now, limit: SCHEDULE_BATCH_SIZE });\n for (const schedule of due) {\n try {\n await this.fire(schedule, now);\n } catch (err) {\n this.runtime.events.emit(PortQueueEvent.ERROR, { error: err, source: 'scheduler' });\n }\n }\n if (due.length < SCHEDULE_BATCH_SIZE) return;\n }\n this.runtime.logger.debug(\n `Scheduler stopped after ${SCHEDULE_MAX_BATCHES} batches; the rest fire on the next tick.`,\n );\n }\n\n private async fire(schedule: ScheduleRow, now: number): Promise<void> {\n const previous = schedule.nextRunAt;\n if (previous == null) return;\n\n // Compute the next future slot (fire-once semantics; no backfill). A null disarms the schedule:\n // it fires this once and never again.\n const nextRunAt = this.computeNext(schedule, now);\n\n // Claim this tick — only one instance wins the guarded advance.\n const won = await this.runtime.driver.advanceSchedule({\n scheduleId: schedule.id,\n nextRunAt,\n lastRunAt: now,\n fromNextRunAt: previous,\n });\n if (!won) return;\n\n // Stamp every option the recurring add carried (see ScheduledJobOptions) onto this run. These\n // shape the produced job, never the schedule itself; `expireInSeconds` becomes an absolute\n // deadline relative to *this* run. Produced jobs are never given the schedule's idempotencyKey,\n // so the recurrence keeps firing.\n const t = schedule.jobOptions;\n const queueName = schedule.queueName;\n const job: NewJobRecord = {\n queueName: schedule.queueName,\n status: JobStatus.PENDING,\n priority: schedule.priority ?? 0,\n data: schedule.data,\n startAfter: now,\n expireAt:\n t?.expireInSeconds != null ? now + secondsToMs(t.expireInSeconds, 'expireInSeconds') : null,\n retryAttempt: 0,\n retryMaxAttempts: schedule.retryMaxAttempts ?? 1,\n retryDelaySeconds: schedule.retryDelaySeconds ?? 0,\n retryBackoff: t?.retryBackoff ?? BackoffStrategy.FIXED,\n retryBackoffFactor: t?.retryBackoffFactor ?? null,\n retryMaxDelaySeconds: t?.retryMaxDelaySeconds ?? null,\n retryJitter: t?.retryJitter ?? false,\n retentionTtlSeconds: t?.retentionTtlSeconds ?? null,\n retentionStatuses: t?.retentionStatuses ?? null,\n idempotencyKey: null,\n scheduleId: schedule.id,\n singletonKey: t?.singletonKey ?? null,\n preferredInstanceKeyPattern: t?.preferredInstanceKeyPattern ?? null,\n createdAt: now,\n };\n const inserted = await this.runtime.driver.insertJob({ job });\n this.runtime.events.emit(PortQueueEvent.SCHEDULE_FIRED, {\n scheduleId: schedule.id,\n jobId: inserted.id,\n queue: queueName,\n });\n this.runtime.wakeup.signal(queueName);\n }\n\n private computeNext(schedule: ScheduleRow, now: number): number | null {\n if (schedule.cron) {\n return new CronExpression(schedule.cron, schedule.timezone ?? 'UTC').next(now);\n }\n if (schedule.everySeconds != null) {\n return now + secondsToMs(schedule.everySeconds, 'schedule.startEverySeconds');\n }\n return null;\n }\n\n /**\n * Expire due-but-unstarted jobs past their deadline, in batches. The driver returns ids and queue\n * names rather than whole rows: those two are all that is used, and a backlog of a hundred\n * thousand expired jobs would otherwise transfer every column of every one of them.\n */\n private async expireDue(): Promise<void> {\n for (let batch = 0; batch < MAINTENANCE_MAX_BATCHES; batch += 1) {\n const expired = await this.runtime.driver.expireDueJobs({\n now: this.runtime.clock.now(),\n limit: MAINTENANCE_BATCH_SIZE,\n });\n for (const job of expired) {\n this.runtime.events.emit(PortQueueEvent.JOB_EXPIRED, {\n jobId: job.jobId,\n queue: job.queueName,\n });\n }\n if (expired.length < MAINTENANCE_BATCH_SIZE) return;\n }\n this.runtime.logger.debug(\n `Expiry stopped after ${MAINTENANCE_MAX_BATCHES} batches; the rest expire on the next tick.`,\n );\n }\n\n /** Return stalled jobs to PENDING, in batches, and wake the queues that gained work. */\n private async reclaimStalled(): Promise<void> {\n for (let batch = 0; batch < MAINTENANCE_MAX_BATCHES; batch += 1) {\n const reclaimed = await this.runtime.driver.reclaimStalledJobs({\n now: this.runtime.clock.now(),\n limit: MAINTENANCE_BATCH_SIZE,\n });\n const queues = new Set<string>();\n for (const job of reclaimed) {\n this.runtime.events.emit(PortQueueEvent.JOB_STALLED, {\n jobId: job.jobId,\n queue: job.queueName,\n previousInstanceKey: job.previousInstanceKey,\n });\n queues.add(job.queueName);\n }\n // One wakeup per queue rather than per row: a batch of stalled jobs on one queue only needs to\n // tell that queue's workers once.\n for (const queue of queues) this.runtime.wakeup.signal(queue);\n if (reclaimed.length < MAINTENANCE_BATCH_SIZE) return;\n }\n this.runtime.logger.debug(\n `Reclaim stopped after ${MAINTENANCE_MAX_BATCHES} batches; the rest reclaim on the next tick.`,\n );\n }\n}\n","import { RETENTION_BATCH_SIZE, RETENTION_MAX_BATCHES } from '../constants';\nimport type { Runtime } from '../client/runtime';\n\n/**\n * Hard-deletes finished jobs per retention policy, in bounded batches. A job with no retention\n * policy is kept forever; only jobs that carry a TTL, and whose TTL has elapsed, are removed.\n * Cluster-coordinated by running on the same interval tick.\n *\n * **Which statuses a job may be deleted in is the job's own setting**, not this sweeper's. The\n * caller's `retention.statuses` is resolved per job and frozen onto its row, so this passes no status\n * list at all — which is what makes `statuses: [COMPLETED]` really leave the failed jobs alone, where\n * a sweeper that always passed every finished status deleted them too.\n */\nexport class RetentionService {\n constructor(private readonly runtime: Runtime) {}\n\n async sweep(): Promise<number> {\n const now = this.runtime.clock.now();\n let total = 0;\n // Bounded batches so the table is never long-locked.\n for (let batch = 0; batch < RETENTION_MAX_BATCHES; batch += 1) {\n const removed = await this.runtime.driver.deleteFinishedJobs({\n olderThan: now,\n limit: RETENTION_BATCH_SIZE,\n });\n total += removed;\n if (removed < RETENTION_BATCH_SIZE) break;\n }\n if (total > 0) this.runtime.logger.debug(`Retention removed ${total} finished jobs.`);\n return total;\n }\n}\n","import { availableParallelism } from 'node:os';\nimport { monitorEventLoopDelay, performance } from 'node:perf_hooks';\nimport { cpuUsage } from 'node:process';\nimport { getHeapStatistics } from 'node:v8';\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { secondsToMs } from '../util/seconds';\nimport { DEFAULT_SAMPLE_INTERVAL_SECONDS, MICROS_PER_MS } from '../constants';\nimport type { SystemLimiterOptions } from '../options/common';\nimport type { EventBusService } from '../events/event-bus.service';\nimport type { Logger } from '../logging/logger.interface';\n\ntype EventLoopDelayMonitor = ReturnType<typeof monitorEventLoopDelay>;\n\n/**\n * One sample of **this Node process's** health, not the machine's.\n *\n * Per-process is the only reading that means anything here. A host figure says \"the box is at 92%\"\n * on a machine where the OS has merely *allocated* nearly all of RAM to page cache and other\n * processes — which is what Linux and macOS both do, so `os.freemem()` sits above 90% used on an\n * idle laptop and a memory threshold fires forever. It also says nothing about the process that is\n * actually running the jobs: a container with a 512 MB cap on a 64 GB host reads as healthy right\n * up to the moment it is killed.\n */\nexport interface SystemMetrics {\n /**\n * CPU this process burned since the previous sample as a share of **every core available to\n * it**, 0-100: core-seconds used over cores × wall time.\n *\n * `top`'s per-core figure was the obvious alternative and is the wrong one here — it reads past\n * 100 whenever work spreads across libuv or worker threads, so it can't be compared between a\n * 2-core container and a 64-core box or shown beside a memory percentage.\n */\n cpuPercent: number;\n /**\n * Heap this process is holding as a share of the heap V8 will let it grow to\n * (`v8.getHeapStatistics().heap_size_limit`, which `--max-old-space-size` sets), 0-100.\n * 100 is the OOM abort, so this is the memory number worth throttling on — unlike a share of\n * machine RAM, which a process is never allowed to reach.\n */\n memoryPercent: number;\n /** Mean event-loop delay in seconds, or null when it isn't being watched. */\n eventLoopDelaySeconds: number | null;\n}\n\n/** A configured threshold and the reading taken against it. */\ninterface Reading {\n metric: string;\n value: number;\n threshold: number;\n}\n\n/**\n * Samples **this process's** health, and optionally throttles on it.\n *\n * **Monitoring is unconditional.** Process CPU and heap are sampled for as long as the client runs,\n * because the instance heartbeat persists them — that is what makes the dashboard's per-instance\n * metrics possible, so there is no option to turn it off. Both numbers belong to the process that\n * took them, so two PortQueue processes on one box report their own figures and the instance row\n * says whose reading it was.\n *\n * **Limiting is opt-in.** Only when the caller passes `systemLimiter` does a breached threshold\n * raise the backpressure flag that stops workers claiming, and clearing every threshold lower it\n * again. Event-loop delay is the one metric that isn't sampled unless asked for: reading it means\n * keeping a `perf_hooks` histogram enabled for the process's lifetime, so it is enabled only when\n * `maxEventLoopDelaySeconds` gives it a purpose.\n *\n * Uses only Node built-ins. Pressure transitions are observed via the event bus, never a callback.\n */\nexport class SystemMonitorService {\n private timer: NodeJS.Timeout | null = null;\n private histogram: EventLoopDelayMonitor | null = null;\n private lastCpu = cpuUsage();\n // `performance.now()` rather than the clock: a monotonic origin, so a system clock that steps\n // backwards mid-sample can't produce a negative window and a CPU percentage to match.\n private lastSampleAt = performance.now();\n // Cores this process may actually run on — `availableParallelism()` honours CPU affinity and\n // container limits, where `cpus().length` reports the whole host. Read once: it can't change\n // for a running process, and `|| 1` keeps a hostile value from producing a division by zero.\n private readonly cores = availableParallelism() || 1;\n private _pressureHigh = false;\n private _metrics: SystemMetrics = {\n cpuPercent: 0,\n memoryPercent: 0,\n eventLoopDelaySeconds: null,\n };\n\n constructor(\n /** Thresholds that make workers pause. Undefined means monitor only, never throttle. */\n private readonly limiter: SystemLimiterOptions | undefined,\n private readonly events: EventBusService,\n private readonly logger: Logger,\n private readonly onResume: () => void,\n ) {}\n\n /** The most recent sample. Zeroed until the first one lands. */\n get metrics(): SystemMetrics {\n return this._metrics;\n }\n\n get pressureHigh(): boolean {\n return this._pressureHigh;\n }\n\n start(): void {\n if (this.limiter?.maxEventLoopDelaySeconds != null) {\n this.histogram = monitorEventLoopDelay({ resolution: 20 });\n this.histogram.enable();\n }\n this.timer = setInterval(\n () => this.sample(),\n secondsToMs(\n this.limiter?.sampleIntervalSeconds ?? DEFAULT_SAMPLE_INTERVAL_SECONDS,\n 'systemLimiter.sampleIntervalSeconds',\n ),\n );\n this.timer.unref?.();\n // Take one sample immediately so the first heartbeat has real numbers to persist.\n this.sample();\n }\n\n stop(): void {\n if (this.timer) clearInterval(this.timer);\n this.timer = null;\n this.histogram?.disable();\n this.histogram = null;\n }\n\n private sample(): void {\n this._metrics = this.measure();\n if (!this.limiter) return; // monitoring only\n\n const readings = this.readings(this._metrics);\n const breached = readings.find((r) => r.value > r.threshold);\n\n if (breached) {\n if (!this._pressureHigh) {\n this._pressureHigh = true;\n this.logger.warn('System pressure high; workers pause claiming until it clears.', {\n metric: breached.metric,\n value: breached.value,\n threshold: breached.threshold,\n });\n this.events.emit(PortQueueEvent.SYSTEM_PRESSURE_HIGH, breached);\n }\n return;\n }\n\n // Nothing breached: every watched metric is back at or under its own threshold, so claiming\n // resumes on the very next sample that clears.\n if (this._pressureHigh) {\n this._pressureHigh = false;\n this.logger.info('System pressure normal; workers resume claiming.');\n this.events.emit(PortQueueEvent.SYSTEM_PRESSURE_NORMAL, {});\n this.onResume();\n }\n }\n\n /** Read every metric, whether or not a threshold watches it. */\n private measure(): SystemMetrics {\n // `cpuUsage()` is cumulative microseconds of CPU time (user + system) since the process\n // started. Over the wall time of the window that is \"cores busy\"; divided again by the cores\n // available it is a 0-100 share of this process's whole CPU budget. Read the absolute value\n // once and subtract, rather than taking `cpuUsage(previous)` and re-reading: two reads would\n // leave the microseconds between them out of the next window.\n const now = performance.now();\n const current = cpuUsage();\n // Milliseconds to *microseconds*, to match what `cpuUsage()` reports — not the seconds↔ms\n // conversion the seconds invariant is about, so `MICROS_PER_MS` rather than `secondsToMs`.\n const elapsedMicros = (now - this.lastSampleAt) * MICROS_PER_MS;\n const usedMicros = current.user - this.lastCpu.user + (current.system - this.lastCpu.system);\n this.lastCpu = current;\n this.lastSampleAt = now;\n // Two samples inside one timer resolution leave no wall time to divide by; keeping the previous\n // reading is honest, where reporting 0% would claim an idle process. The clamp covers CPU\n // accounting and the monotonic clock being sampled separately, which can put a window a\n // fraction over its own core-time budget.\n const cpuPercent =\n elapsedMicros > 0\n ? Math.min(100, (usedMicros / (elapsedMicros * this.cores)) * 100)\n : this._metrics.cpuPercent;\n\n // The heap limit, not machine RAM: it is the ceiling this process actually dies at, and the one\n // `--max-old-space-size` moves. `used_heap_size` is what V8 reports as live after its last GC.\n const heap = getHeapStatistics();\n\n let eventLoopDelaySeconds: number | null = null;\n if (this.histogram) {\n // The histogram reports nanoseconds and is reset each sample, so this is the mean since the\n // previous one rather than since the process started.\n eventLoopDelaySeconds = this.histogram.mean / 1e9;\n this.histogram.reset();\n }\n return {\n cpuPercent,\n memoryPercent: (heap.used_heap_size / heap.heap_size_limit) * 100,\n eventLoopDelaySeconds,\n };\n }\n\n /**\n * The configured thresholds paired with this sample's values. Only thresholds the caller set are\n * included — an unset one is never a reason to throttle, and never blocks a recovery either.\n */\n private readings(metrics: SystemMetrics): Reading[] {\n const limiter = this.limiter;\n if (!limiter) return [];\n const readings: Reading[] = [];\n if (limiter.maxEventLoopDelaySeconds != null && metrics.eventLoopDelaySeconds != null) {\n readings.push({\n metric: 'eventLoopDelaySeconds',\n value: metrics.eventLoopDelaySeconds,\n threshold: limiter.maxEventLoopDelaySeconds,\n });\n }\n if (limiter.maxCpuPercent != null) {\n readings.push({\n metric: 'cpuPercent',\n value: metrics.cpuPercent,\n threshold: limiter.maxCpuPercent,\n });\n }\n if (limiter.maxMemoryPercent != null) {\n readings.push({\n metric: 'memoryPercent',\n value: metrics.memoryPercent,\n threshold: limiter.maxMemoryPercent,\n });\n }\n return readings;\n }\n}\n","import { secondsToMs } from '../util/seconds';\nimport type { Runtime } from './runtime';\nimport type { SystemMetrics } from '../monitoring/system-monitor.service';\n\n/**\n * Multi-instance liveness, health reporting + per-instance pause. Active only when the\n * PortQueue was given an `instanceKey`. Registers this process's `instance` row, then\n * heartbeats on a timer: each beat bumps `last_seen_at`, records the latest CPU / memory sample for\n * **this Node process** alongside it, and refreshes this instance's cached\n * `processingPaused` flag, which the worker's claim loop reads on the hot path. The dashboard can\n * pause an instance by flipping its row; the next heartbeat picks it up.\n *\n * The metrics ride along with the heartbeat rather than on their own timer: they are only useful as\n * \"how was this instance doing when we last heard from it\", which is exactly what a beat means.\n */\nexport class InstanceService {\n private timer: NodeJS.Timeout | null = null;\n private _processingPaused = false;\n\n constructor(\n private readonly runtime: Runtime,\n readonly instanceKey: string,\n private readonly intervalSeconds: number,\n /** This process's latest health sample; null before the first one lands. */\n private readonly readMetrics: () => SystemMetrics | null,\n ) {}\n\n /** This instance's cached pause flag (refreshed each heartbeat). */\n get processingPaused(): boolean {\n return this._processingPaused;\n }\n\n /** Register the row and begin heartbeating. */\n async start(): Promise<void> {\n await this.beat();\n this.timer = setInterval(\n () => this.runtime.background.run(() => this.beat()),\n secondsToMs(this.intervalSeconds, 'instance.heartbeatIntervalSeconds'),\n );\n this.timer.unref?.();\n }\n\n async stop(): Promise<void> {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * One heartbeat: bump last_seen_at + metrics and refresh the cached pause flag. Never throws.\n *\n * **One round trip.** `upsertInstance` returns the resulting row, so the flag comes from the write\n * itself; the follow-up `getInstance` this used to issue read back exactly what had just been\n * returned, doubling the query count of a beat that runs every 15 s per instance.\n */\n async beat(): Promise<void> {\n try {\n const now = this.runtime.clock.now();\n const metrics = this.readMetrics();\n const row = await this.runtime.driver.upsertInstance({\n instanceKey: this.instanceKey,\n now,\n ...(metrics\n ? {\n metrics: {\n cpuPercent: metrics.cpuPercent,\n memoryPercent: metrics.memoryPercent,\n },\n }\n : {}),\n });\n this._processingPaused = row.processingPaused;\n } catch (err) {\n this.runtime.logger.debug('Instance heartbeat failed; keeping cached pause state.', { err });\n }\n }\n}\n","import { MigrationMode } from '../../options/enums';\nimport { PortQueueEvent } from '../../events/event-name.enum';\nimport { MigrationFailedError, SchemaVersionMismatchError } from '../../errors/errors';\nimport { DriverCapability } from '../driver-capabilities';\nimport { latestVersion } from './migration';\nimport { MIGRATION_WAIT_POLL_SECONDS, MIGRATION_WAIT_TIMEOUT_SECONDS } from '../../constants';\nimport { secondsToMs } from '../../util/seconds';\nimport type { Driver } from '../driver.interface';\nimport type { DriverContext } from '../driver-context';\nimport type { Logger } from '../../logging/logger.interface';\nimport type { EventBusService } from '../../events/event-bus.service';\nimport type { Clock } from '../../util/clock';\n\n/**\n * Applies a driver's ordered migrations. The steps come from the driver itself\n * (`driver.migrations`) — each engine authors its own DDL alongside its driver; this is the single\n * shared mechanism that runs them. A migration is identified by its version and nothing else.\n * Supports AUTO / MANUAL / VALIDATE_ONLY.\n *\n * **Two rules make `MAX(version)` a truthful answer**, which matters because that is what\n * `getSchemaVersion` reads and what decides what is still pending:\n *\n * - Versions are applied in ascending order, and\n * - each one is **confirmed recorded** before the next is attempted. So the applied set is always a\n * contiguous prefix, and there is no way to reach \"v1 and v3 applied, v2 not\" — the state in which\n * a maximum would read as complete while a version was missing.\n *\n * **Concurrency.** Where the engine has a named lock (Postgres' `pg_try_advisory_lock`, MySQL's\n * `GET_LOCK`) one instance migrates and the rest wait for the version to land. Where it does not\n * (Oracle, SQLite, PGLite) every instance proceeds, which is safe only because each engine's DDL is\n * written to be idempotent — `IF NOT EXISTS`, `MERGE`, PL/SQL-guarded `CREATE INDEX` — and because\n * the confirmation above turns a half-applied step into an error rather than a silent skip. For a\n * multi-instance Oracle deployment, running `portqueue migrate` once before starting workers is\n * still the recommendation; see the production docs.\n */\nexport class MigrationRunner {\n constructor(\n private readonly driver: Driver,\n private readonly context: DriverContext,\n private readonly logger: Logger,\n private readonly events: EventBusService,\n private readonly clock: Clock,\n ) {}\n\n /** The schema version this driver's migration set ships (its latest step). */\n private get targetVersion(): number {\n return latestVersion(this.driver.migrations);\n }\n\n async run(mode: MigrationMode): Promise<void> {\n if (mode === MigrationMode.MANUAL) {\n this.logger.info(\n 'Migration mode is MANUAL; skipping auto-migrate. Run `portqueue migrate` to apply.',\n );\n return;\n }\n const current = await this.driver.getSchemaVersion();\n if (mode === MigrationMode.VALIDATE_ONLY) {\n if ((current ?? 0) !== this.targetVersion) {\n throw new SchemaVersionMismatchError(current, this.targetVersion);\n }\n return;\n }\n await this.migrateAuto(current);\n }\n\n /** Force-apply (the programmatic `pq.migrate()` / CLI path). */\n async migrate(): Promise<void> {\n await this.migrateAuto(await this.driver.getSchemaVersion());\n }\n\n private async migrateAuto(current: number | null): Promise<void> {\n const ordered = [...this.driver.migrations].sort((a, b) => a.version - b.version);\n const pending = ordered.filter((m) => m.version > (current ?? 0));\n if (pending.length === 0) return;\n\n const useLock =\n this.driver.capabilities[DriverCapability.ADVISORY_LOCK] && this.driver.tryAdvisoryLock;\n const lockKey = `${this.context.tableNames.prefix}migrate`;\n let locked = false;\n if (useLock) {\n locked = await this.driver.tryAdvisoryLock!({ key: lockKey });\n if (!locked) {\n this.logger.debug('Another instance is migrating; waiting.');\n // Another instance is applying; poll until the version catches up.\n await this.waitForVersion(this.targetVersion);\n return;\n }\n } else {\n // No named lock on this engine. Every instance applies, which each engine's DDL is written to\n // survive; the confirmation below is what keeps a partial apply from reading as a complete one.\n this.logger.debug(\n 'This engine offers no advisory lock; applying migrations without one. Concurrent first ' +\n 'boots rely on the DDL being idempotent — run `portqueue migrate` first to avoid the race.',\n );\n }\n try {\n const from = current;\n for (const migration of pending) {\n try {\n await this.driver.applyMigration({ migration });\n } catch (err) {\n throw new MigrationFailedError(`Migration v${migration.version} failed.`, err);\n }\n // Read it back before moving on. On Postgres, SQLite and PGLite the statements and the\n // version insert share a transaction, so this only ever confirms what is already true. On\n // MySQL and Oracle it cannot: DDL commits implicitly there, so `applyMigration` runs the\n // statements and *then* records the version, and a crash between the two would otherwise\n // leave a schema that reads as one version behind — the next start re-running (idempotent)\n // DDL, and any future non-idempotent step failing on it. Stopping here says so plainly.\n const recorded = await this.driver.getSchemaVersion();\n if ((recorded ?? 0) < migration.version) {\n throw new MigrationFailedError(\n `Migration v${migration.version} ran but was not recorded (the schema still reads as ` +\n `v${recorded ?? 0}). On an engine where DDL commits implicitly this can only mean the ` +\n `process was interrupted between the two; re-run the migration to finish it.`,\n );\n }\n this.logger.info(`Applied migration v${migration.version}.`);\n }\n this.events.emit(PortQueueEvent.MIGRATION_APPLIED, { from, to: this.targetVersion });\n } finally {\n if (locked && this.driver.releaseAdvisoryLock) {\n await this.driver.releaseAdvisoryLock({ key: lockKey }).catch(() => undefined);\n }\n }\n }\n\n /**\n * Poll until another instance's migration lands. Timed against the injected clock, like every\n * other deadline in the codebase, so a test with a fake clock controls this wait rather than\n * spending real seconds inside it.\n */\n private async waitForVersion(\n target: number,\n timeoutSeconds = MIGRATION_WAIT_TIMEOUT_SECONDS,\n ): Promise<void> {\n const timeoutMs = secondsToMs(timeoutSeconds, 'migration wait timeout');\n const pollMs = secondsToMs(MIGRATION_WAIT_POLL_SECONDS, 'migration wait poll');\n const deadline = this.clock.now() + timeoutMs;\n for (;;) {\n const v = await this.driver.getSchemaVersion();\n if ((v ?? 0) >= target) return;\n if (this.clock.now() >= deadline) break;\n await new Promise((resolve) => {\n const timer = setTimeout(resolve, pollMs);\n timer.unref?.();\n });\n }\n throw new MigrationFailedError(\n 'Timed out waiting for another instance to complete migrations.',\n );\n }\n}\n","import { MigrationMode } from '../options/enums';\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { SubscriberService } from '../pubsub/subscriber.service';\nimport { SchedulerService } from '../scheduling/scheduler.service';\nimport { RetentionService } from '../retention/retention.service';\nimport { SystemMonitorService, type SystemMetrics } from '../monitoring/system-monitor.service';\nimport { InstanceService } from './instance.service';\nimport { MigrationRunner } from '../drivers/shared/migration-runner.service';\nimport { ShutdownTimeoutError } from '../errors/errors';\nimport { secondsToMs } from '../util/seconds';\nimport {\n DEFAULT_HEARTBEAT_INTERVAL_SECONDS,\n DEFAULT_TICK_INTERVAL_SECONDS,\n MIN_SUBSCRIBER_POLL_SECONDS,\n} from '../constants';\nimport type { Runtime } from './runtime';\nimport type { ClientRegistryService } from './client-registry.service';\n\ninterface Mutable {\n running: boolean;\n}\n\n/**\n * Owns the strict ordered startup and reverse-ordered shutdown.\n */\nexport class ClientLifecycleService {\n private subscriber: SubscriberService | null = null;\n private scheduler: SchedulerService | null = null;\n private retention: RetentionService | null = null;\n private monitor: SystemMonitorService | null = null;\n private tickTimer: NodeJS.Timeout | null = null;\n private ticking = false;\n private initialized = false;\n\n constructor(\n private readonly runtime: Runtime,\n private readonly registry: ClientRegistryService,\n private readonly state: Mutable,\n ) {}\n\n get systemPressureHigh(): boolean {\n return this.monitor?.pressureHigh ?? false;\n }\n\n /** This process's latest health sample, for the instance heartbeat to persist. */\n get systemMetrics(): SystemMetrics | null {\n return this.monitor?.metrics ?? null;\n }\n\n async init(): Promise<void> {\n if (this.initialized) return;\n this.initialized = true;\n const { driver, context, options, events, logger, clock } = this.runtime;\n\n // 1. Connect the driver.\n await driver.connect();\n // 2. Migrate. A headless (admin) client defaults to MANUAL: pointing a dashboard at a database\n // must never migrate it as a side effect. The CLI's `migrate` command applies them itself.\n const defaultMode = this.runtime.headless ? MigrationMode.MANUAL : MigrationMode.AUTO;\n const migrationRunner = new MigrationRunner(driver, context, logger, events, clock);\n await migrationRunner.run(options.migration ?? defaultMode);\n\n // A headless client stops here: it reads and administers, but joins nothing. No pub/sub, no\n // maintenance tick, no health monitor, no instance row, no workers.\n if (this.runtime.headless) {\n this.state.running = true;\n events.emit(PortQueueEvent.CLIENT_STARTED, { instanceKey: null });\n return;\n }\n\n // 3. Pub/sub.\n const tickIntervalSeconds = options.tickIntervalSeconds ?? DEFAULT_TICK_INTERVAL_SECONDS;\n this.subscriber = new SubscriberService(\n driver,\n logger,\n this.runtime.wakeup,\n secondsToMs(\n Math.max(tickIntervalSeconds, MIN_SUBSCRIBER_POLL_SECONDS),\n 'tickIntervalSeconds',\n ),\n this.runtime.instanceKey ?? null,\n );\n await this.subscriber.start();\n\n // 4. Scheduler + retention + monitor, driven by one coordinated tick.\n this.scheduler = new SchedulerService(this.runtime);\n this.retention = new RetentionService(this.runtime);\n // Only sample when something consumes the numbers: the instance heartbeat persists them (so a\n // named client always monitors), and a `systemLimiter` throttles on them. With neither, nobody\n // ever reads a sample and the process was still paying a `setInterval` plus `cpuUsage()` and\n // `getHeapStatistics()` every couple of seconds.\n if (this.runtime.instanceKey || options.systemLimiter) {\n this.monitor = new SystemMonitorService(options.systemLimiter, events, logger, () =>\n this.runtime.wakeup.signalAll(),\n );\n this.monitor.start();\n }\n this.tickTimer = setInterval(\n () => this.runtime.background.run(() => this.tick()),\n secondsToMs(tickIntervalSeconds, 'tickIntervalSeconds'),\n );\n this.tickTimer.unref?.();\n\n // 5. Multi-instance liveness: register + start heartbeating before workers claim.\n if (this.runtime.instanceKey) {\n const instances = new InstanceService(\n this.runtime,\n this.runtime.instanceKey,\n options.instance?.heartbeatIntervalSeconds ?? DEFAULT_HEARTBEAT_INTERVAL_SECONDS,\n () => this.systemMetrics,\n );\n this.runtime.instances = instances;\n await instances.start();\n }\n\n // 6. Mark running and start workers.\n this.state.running = true;\n for (const worker of this.registry.allWorkers()) await worker.start();\n\n events.emit(PortQueueEvent.CLIENT_STARTED, { instanceKey: this.runtime.instanceKey });\n // Run an immediate maintenance tick so due schedules/expiry aren't delayed a full interval.\n this.runtime.background.run(() => this.tick());\n }\n\n /**\n * One maintenance pass: refresh the cached queue pause flags, fire due schedules, expire and\n * reclaim, then sweep retention.\n *\n * The pause refresh lives here rather than in the claim loop. A worker used to read its queue row\n * on every pump — per poll, and again on every freed concurrency slot — which on an idle queue was\n * more queue reads than job claims. One read per declared queue per tick observes a pause made by\n * another instance within the same interval, at a fraction of the cost.\n */\n private async tick(): Promise<void> {\n if (this.ticking || !this.state.running) return;\n this.ticking = true;\n try {\n await this.runtime.registry.refreshStale();\n await this.scheduler?.tick();\n await this.retention?.sweep();\n } catch (err) {\n this.runtime.events.emit(PortQueueEvent.ERROR, { error: err, source: 'scheduler' });\n } finally {\n this.ticking = false;\n }\n }\n\n async migrate(): Promise<void> {\n const runner = new MigrationRunner(\n this.runtime.driver,\n this.runtime.context,\n this.runtime.logger,\n this.runtime.events,\n this.runtime.clock,\n );\n await runner.migrate();\n }\n\n /**\n * Stop everything in reverse order.\n *\n * Throws {@link ShutdownTimeoutError} when the graceful window elapsed with work still in flight —\n * but only after the shutdown has otherwise completed, so the caller always ends up disconnected. A\n * SIGTERM handler that ignores the rejection still shuts down cleanly; one that logs it learns that\n * handlers were aborted mid-run, which is the thing actually worth knowing.\n */\n async shutdown(options: { graceful: boolean; timeoutSeconds: number }): Promise<void> {\n if (!this.state.running) return;\n const { events } = this.runtime;\n events.emit(PortQueueEvent.CLIENT_STOPPING, { instanceKey: this.runtime.instanceKey });\n\n // Reverse order.\n if (this.tickTimer) clearInterval(this.tickTimer);\n await this.runtime.instances?.stop();\n await this.subscriber?.stop();\n this.state.running = false; // stop new claims\n\n // Drain workers.\n for (const worker of this.registry.allWorkers()) {\n await worker.stop({ graceful: options.graceful, timeoutSeconds: options.timeoutSeconds });\n }\n\n this.monitor?.stop();\n // A tick, pump, heartbeat or NOTIFY fired without an await may still be mid-query. Let it\n // settle before the driver goes away — PGLite frees its WASM heap on disconnect and faults\n // if a query is still running in it.\n const drained = await this.runtime.background.drain(options.timeoutSeconds);\n if (!drained) {\n this.runtime.logger.warn(\n 'Background work did not finish within the shutdown timeout; disconnecting anyway.',\n );\n }\n await this.runtime.driver.disconnect();\n events.emit(PortQueueEvent.CLIENT_STOPPED, { instanceKey: this.runtime.instanceKey });\n if (!drained) throw new ShutdownTimeoutError(options.timeoutSeconds);\n }\n}\n","import { secondsToMs } from '../util/seconds';\n\n/**\n * Tracks the work this client starts without awaiting it — the maintenance tick, a worker's\n * claim pump, an instance heartbeat, a NOTIFY — so shutdown can wait for it to settle before\n * the driver disconnects. Without this, `disconnect()` can land while one of those queries is\n * still in flight: an engine that runs inside this process (PGLite tears down its WASM heap)\n * faults, and a pooled engine logs a query against a closed connection.\n *\n * Failures are not this class's business: every registered task already reports its own errors,\n * so a rejection is swallowed here rather than surfacing as an unhandled rejection (which is\n * what `void task()` did).\n */\nexport class BackgroundWork {\n private readonly pending = new Set<Promise<void>>();\n\n /** Start `task` now, without waiting for it, and remember it until it settles. */\n run(task: () => Promise<unknown>): void {\n const tracked = task().then(\n () => undefined,\n () => undefined,\n );\n this.pending.add(tracked);\n void tracked.then(() => this.pending.delete(tracked));\n }\n\n /**\n * Wait for everything in flight — and anything those tasks start in turn — to settle.\n * Resolves `true` when the set emptied, `false` when `timeoutSeconds` elapsed first, so the\n * caller can carry on with a shutdown it must not abandon.\n */\n async drain(timeoutSeconds: number): Promise<boolean> {\n const expired = expiresIn(secondsToMs(timeoutSeconds, 'shutdown timeoutSeconds'));\n while (this.pending.size > 0) {\n const settled = await Promise.race([\n Promise.all([...this.pending]).then(() => true),\n expired,\n ]);\n if (!settled) return false;\n }\n return true;\n }\n}\n\n/** A promise that resolves `false` once `ms` has passed, on a timer that never holds the loop. */\nfunction expiresIn(ms: number): Promise<false> {\n return new Promise<false>((resolve) => {\n const timer = setTimeout(() => resolve(false), Math.max(ms, 0));\n timer.unref?.();\n });\n}\n","import { MAX_BATCH_IDS } from '../constants';\nimport { InvalidOptionsError } from '../errors/errors';\n\n/**\n * Refuse a by-id batch larger than one statement can carry.\n *\n * Every batch is a single statement over the whole set (see the batch invariant in CLAUDE.md), and\n * every engine caps the expressions an `IN (...)` list may hold — Oracle at 1000, the lowest of the\n * engines here. Rather than let the limit surface as an engine error on one deployment and work on\n * another, the tool takes the tightest ceiling as everyone's and says so up front.\n *\n * A caller with more than {@link MAX_BATCH_IDS} ids splits them: each slice is one round trip, and\n * partial progress is visible between them, which is what an operator wants from a large removal\n * anyway.\n */\nexport function assertBatchIds(ids: readonly unknown[], option: string): void {\n if (ids.length > MAX_BATCH_IDS) {\n throw new InvalidOptionsError(\n `'${option}' carries ${ids.length} ids, more than the ${MAX_BATCH_IDS} one batch may take. ` +\n `A batch is a single statement, and ${MAX_BATCH_IDS} is the smallest limit any supported ` +\n `engine puts on an IN list — split the ids and call again.`,\n { count: ids.length, limit: MAX_BATCH_IDS },\n );\n }\n}\n","/**\n * Result and query shapes for the `pq._dashboard` facade. These are **not** part of the public\n * developer API — they exist so `@portqueue/dashboard` can ask for exactly what it renders\n * without widening `PortQueue`. See the facade invariant in CLAUDE.md.\n */\nimport type { JobStatus } from '../jobs/job-state.enum';\nimport type { Page } from '../options/common';\nimport type { GetSchedulesQuery, InstanceInfo, QueueInfo, ScheduleInfo } from '../producer/results';\n\nexport type { Page };\n\n/** The paging window every dashboard list read accepts. */\nexport interface DashboardPageQuery {\n /** Rows to return. Clamped to `DASHBOARD_MAX_PAGE_LIMIT`. */\n limit?: number;\n offset?: number;\n}\n\n/** Pause-state narrowing shared by the queue and instance lists. */\nexport interface PausedFilter {\n /** `true` → only paused rows, `false` → only running ones, absent → both. */\n processingPaused?: boolean;\n}\n\n/**\n * The dashboard's queue query. Named for the facade, but the same shape as the public\n * `GetQueuesQuery` — the search and pause-state narrowings started here and were promoted, since a\n * developer looking for paused queues needed them just as much. The facade keeps the name (and the\n * tighter page ceiling); it no longer keeps a second implementation.\n *\n * There is deliberately no `inUse` filter. `inUse` means \"declared in the process that produced this\n * info\", and the dashboard runs on its own headless client (`createDashboard({ driver })`) rather\n * than riding on the application's — so it has no way to know which queues the workers declare, and a\n * filter that always answered \"none\" would be worse than no filter.\n */\nexport interface DashboardQueuesQuery extends DashboardPageQuery, PausedFilter {\n /** Case-insensitive substring of the queue name. */\n search?: string;\n}\n\n/** The dashboard's instance query — the public `GetInstancesQuery` under the facade's own name. */\nexport interface DashboardInstancesQuery extends DashboardPageQuery, PausedFilter {\n /** Case-insensitive substring of the instance key. */\n search?: string;\n /** `true` → only instances inside the liveness window, `false` → only stale ones. */\n alive?: boolean;\n}\n\n/**\n * The dashboard's schedule query: the public {@link GetSchedulesQuery} (paging, `queue`, `enabled`)\n * plus the free-text filter only the dashboard's table offers.\n */\nexport interface DashboardSchedulesQuery extends GetSchedulesQuery {\n /** Case-insensitive substring matched against the schedule id, queue name and cron pattern. */\n search?: string;\n}\n\n/**\n * Counts only. The dashboard renders per-status activity cards and nothing else, so this\n * deliberately carries no derived rate metrics.\n */\nexport interface DashboardStats {\n queue?: string;\n counts: Record<JobStatus, number>;\n}\n\n/** The free-text filter the dashboard's jobs table offers. */\nexport interface JobSearchQuery {\n /**\n * Free-text term matched against the job id, status, idempotency key, failure message and the\n * serialized payload. Case-insensitive substring, matched **in SQL** — so a search is a paged\n * query like any other read, not a scan of the table through this process.\n */\n search?: string;\n}\n\n/**\n * Narrow a job read to the instance that claimed the rows (`processed_on_instance_key`). Lives on\n * the facade rather than the public `GetJobsQuery`: it backs the instance detail page's \"jobs\n * processed here\" table, which is a dashboard view, not something the public read surface promises.\n */\nexport interface JobInstanceFilter {\n instanceKey?: string;\n}\n\n/** What a bulk row action does to each selected job. */\nexport enum JobBatchAction {\n RETRY = 'RETRY',\n CANCEL = 'CANCEL',\n REMOVE = 'REMOVE',\n}\n\n/**\n * The outcome of a batch. `affected` counts the rows the action actually changed — a job that\n * was already gone, or one the action refused (retrying or removing an ACTIVE row), is simply not\n * counted.\n */\nexport interface BatchResult {\n affected: number;\n /** How many ids were submitted, so a caller can report \"3 of 5 removed\". */\n requested: number;\n /**\n * Jobs a cancel could only *ask* to stop: they are running in this process, so their handler's\n * `AbortSignal` was fired and their row will settle to whatever the handler does next. Counted\n * apart from `affected` because nothing has been cancelled yet — reporting them as cancelled is\n * how the dashboard used to claim \"Cancelled 3 jobs\" for three jobs that then completed normally.\n */\n signalled?: number;\n}\n\nexport type { InstanceInfo, QueueInfo, ScheduleInfo };\n","/**\n * The `pq._dashboard` facade — everything `@portqueue/dashboard` needs that the public API\n * deliberately does not offer. Nothing here is a documented developer API (the `_` prefix on the\n * property says so); it exists so a dashboard requirement never forces a change to `PortQueue`.\n *\n * Three things this class is careful about, each a bug the dashboard used to have:\n *\n * - **Every filter runs in the database.** A free-text job search is a `LIKE` in SQL, not a chunked\n * scan of the table through this process; a list page is `LIMIT`/`OFFSET`, never a whole-table read\n * sliced in memory.\n * - **A batch is one statement.** `retry`, `cancel` and `remove` each hand the whole id set to one\n * driver call, so the cost is constant in the number of ids and a single stale id cannot roll back\n * the rest of the batch.\n * - **It never declares a queue.** Reads and writes address a queue by name; the client this runs on\n * is headless (see `PortQueueOptions._headless`), so it registers nothing and owns nothing.\n */\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { InvalidOptionsError } from '../errors/errors';\nimport { assertBatchIds } from '../util/batch-ids';\nimport { pageWindow } from '../monitoring/stats.service';\nimport { DASHBOARD_MAX_PAGE_LIMIT, DEFAULT_PAGE_LIMIT } from '../constants';\nimport {\n JobBatchAction,\n type BatchResult,\n type DashboardStats,\n type DashboardInstancesQuery,\n type DashboardQueuesQuery,\n type DashboardSchedulesQuery,\n type JobInstanceFilter,\n type JobSearchQuery,\n type Page,\n} from './dashboard-results';\nimport type { Runtime } from '../client/runtime';\nimport type { Driver, JobRef } from '../drivers/driver.interface';\nimport type {\n GetJobsQuery,\n InstanceInfo,\n JobSnapshot,\n QueueInfo,\n ScheduleInfo,\n} from '../producer/results';\nimport type { JobRecord } from '../jobs/job-record';\nimport type { ReadService } from '../monitoring/stats.service';\nimport type { ProducerService } from '../producer/producer.service';\nimport type { TransactionHandle } from '../tx/transaction-handle';\n\nexport class DashboardService {\n constructor(\n private readonly runtime: Runtime,\n private readonly reads: ReadService,\n private readonly producer: ProducerService,\n ) {}\n\n /**\n * The live driver, for the rare case the dashboard needs to compose its own transaction (see\n * {@link runInTransaction}). Exposed here rather than on `PortQueue` so the driver never becomes\n * part of the developer-facing surface.\n */\n get driver(): Driver {\n return this.runtime.driver;\n }\n\n /**\n * Run `fn` inside one driver transaction. Left on the facade for a caller that needs to compose\n * several driver calls atomically; the batch actions below no longer need it, because each is a\n * single statement.\n */\n runInTransaction<T>(options: { fn: (tx: TransactionHandle) => Promise<T> }): Promise<T> {\n return this.runtime.driver.runInTransaction(options);\n }\n\n // --- Paged lists -------------------------------------------------------------------------\n\n /**\n * A page of queues with their per-status counts.\n *\n * The public read already narrows by name and pause state in SQL and counts the whole page in one\n * grouped query, so this only tightens the page ceiling: a dashboard table never shows more than\n * {@link DASHBOARD_MAX_PAGE_LIMIT} rows, and a crafted `limit` must not be able to ask for the\n * table. Reusing the public read is what the facade rule allows and what keeps the two from\n * drifting — they were byte-identical bodies over the same driver calls.\n */\n getQueues(query: DashboardQueuesQuery = {}): Promise<Page<QueueInfo>> {\n return this.reads.getQueues({ ...query, ...pageWindow(query, DASHBOARD_MAX_PAGE_LIMIT) });\n }\n\n /** A page of instances with liveness and per-instance job attribution. Clamped like the queues. */\n getInstances(query: DashboardInstancesQuery = {}): Promise<Page<InstanceInfo>> {\n return this.reads.getInstances({ ...query, ...pageWindow(query, DASHBOARD_MAX_PAGE_LIMIT) });\n }\n\n /**\n * One instance by key, with the same liveness, health and attribution the list carries — for the\n * instance detail page. `PortQueue.getInstance` covers this, but the facade keeps its own entry\n * point so the dashboard's routes read uniformly.\n */\n getInstance(options: { instanceKey: string }): Promise<InstanceInfo | null> {\n return this.reads.getInstance(options.instanceKey);\n }\n\n /**\n * A page of schedules across every queue, in one query. Delegates to the same producer read\n * `pq.getSchedules` uses, plus the free-text filter only this table offers.\n */\n async getSchedules(query: DashboardSchedulesQuery = {}): Promise<Page<ScheduleInfo>> {\n const { limit, offset } = pageWindow(query, DASHBOARD_MAX_PAGE_LIMIT);\n if (!query.search) {\n return this.producer.getSchedules({\n ...(query.queue ? { queue: query.queue } : {}),\n ...(query.enabled !== undefined ? { enabled: query.enabled } : {}),\n limit,\n offset,\n });\n }\n const filter = {\n ...(query.queue ? { queueName: query.queue } : {}),\n ...(query.enabled !== undefined ? { enabled: query.enabled } : {}),\n search: query.search,\n };\n const [rows, total] = await Promise.all([\n this.runtime.driver.listSchedules({ ...filter, limit, offset }),\n this.runtime.driver.countSchedules(filter),\n ]);\n return {\n items: rows.map((s) => ({\n scheduleId: s.id,\n queue: s.queueName,\n cron: s.cron,\n everySeconds: s.everySeconds,\n timezone: s.timezone,\n nextRunAt: s.nextRunAt != null ? new Date(s.nextRunAt) : null,\n lastRunAt: s.lastRunAt != null ? new Date(s.lastRunAt) : null,\n enabled: s.enabled,\n idempotencyKey: s.idempotencyKey,\n })),\n total,\n };\n }\n\n /** One schedule by id, with its queue — backs the schedule detail page. */\n getSchedule(options: { scheduleId: string }): Promise<ScheduleInfo | null> {\n return this.producer.getSchedule(options.scheduleId);\n }\n\n /** Counts only — the activity cards. No throughput or failure-rate derivation. */\n async getStats(options: { queue?: string } = {}): Promise<DashboardStats> {\n const counts = await this.runtime.driver.countJobsByStatus(\n options.queue ? { queueName: options.queue } : {},\n );\n return { ...(options.queue ? { queue: options.queue } : {}), counts };\n }\n\n // --- Jobs --------------------------------------------------------------------------------\n\n /**\n * A page of jobs, optionally narrowed by a free-text search.\n *\n * The search is a SQL `LIKE` across the five fields an operator triages by — id, status,\n * idempotency key, failure message and the serialized payload — so it pages in the database and\n * `total` is a `COUNT`. The previous implementation read the whole matching set through this\n * process in 1000-row chunks and filtered in JS: bounded in memory, but O(rows / 1000) queries and\n * a `JSON.parse` of every payload in the table for one keystroke.\n */\n getJobs<TData = unknown>(\n query: GetJobsQuery & JobSearchQuery & JobInstanceFilter = {},\n ): Promise<Page<JobSnapshot<TData>>> {\n const term = query.search?.trim();\n const { search: _search, ...base } = query;\n return this.reads.getJobs<TData>({\n ...base,\n ...(term ? { search: term } : {}),\n limit: Math.min(\n Math.max(Math.trunc(base.limit ?? DEFAULT_PAGE_LIMIT), 1),\n DASHBOARD_MAX_PAGE_LIMIT,\n ),\n });\n }\n\n // --- Batch actions -----------------------------------------------------------------------\n\n /**\n * Apply one action to many jobs in a **single** driver call.\n *\n * Each action maps to one guarded statement over the whole id set, so the cost is constant in the\n * number of ids and the guard is uniform: an id that didn't match (already gone, or an `ACTIVE` row\n * that a retry or a remove refuses) is simply absent from the result rather than failing the batch.\n * The previous implementation looped `requeueJob` per id inside one transaction, where the first\n * stale id threw and rolled back every retry beside it.\n *\n * Cancellation keeps its one non-transactional side effect: a job running *in this process* is\n * cancelled by firing its handler's `AbortSignal`, which no statement can undo, so those fire only\n * after the write has landed.\n */\n async runJobBatch(options: { jobIds: string[]; action: JobBatchAction }): Promise<BatchResult> {\n const { jobIds, action } = options;\n if (!jobIds.length) return { affected: 0, requested: 0 };\n assertBatchIds(jobIds, 'runJobBatch({ jobIds })');\n\n const now = this.runtime.clock.now();\n const driver = this.runtime.driver;\n\n switch (action) {\n case JobBatchAction.REMOVE: {\n const removed = await driver.removeJobs({ jobIds });\n this.emitPerJob(PortQueueEvent.JOB_REMOVED, removed);\n return { affected: removed.length, requested: jobIds.length };\n }\n case JobBatchAction.RETRY: {\n const requeued = await driver.requeueJobs({ jobIds, now });\n // One wakeup per distinct queue, not per job.\n for (const q of new Set(requeued.map((r) => r.queueName))) this.runtime.wakeup.signal(q);\n for (const ref of requeued) {\n this.runtime.events.emit(PortQueueEvent.JOB_ADDED, {\n jobId: ref.jobId,\n queue: ref.queueName,\n deduplicated: false,\n });\n }\n return { affected: requeued.length, requested: jobIds.length };\n }\n case JobBatchAction.CANCEL: {\n // Jobs running here can only be *asked* to stop — their handler owns the row's outcome — so\n // they are signalled and counted apart. Everything else is cancelled in one statement.\n //\n // No `JOB_CANCELLED` is emitted for a signalled job: cancellation is cooperative, and a\n // handler that ignores `job.signal` completes normally. Emitting it here told every listener\n // (and the dashboard's own toast) that three jobs had been cancelled when none had.\n const running = new Set(jobIds.filter((id) => this.isRunningHere(id)));\n const remaining = jobIds.filter((id) => !running.has(id));\n const cancelled = remaining.length\n ? await driver.cancelJobs({ jobIds: remaining, now })\n : [];\n for (const jobId of running) this.runtime.cancelRunning?.(jobId);\n this.emitPerJob(PortQueueEvent.JOB_CANCELLED, cancelled);\n return {\n affected: cancelled.length,\n requested: jobIds.length,\n ...(running.size ? { signalled: running.size } : {}),\n };\n }\n default:\n throw new InvalidOptionsError(`Unknown job batch action '${String(action)}'.`);\n }\n }\n\n /**\n * Emit one event per affected job, naming the queue the row actually belongs to.\n *\n * The ref comes from the statement that changed the row, so the queue is the row's own — which is\n * why a batch needs no `queue` argument, and why one request can carry a selection that spans\n * queues without any event naming the wrong one.\n */\n private emitPerJob(\n event: PortQueueEvent.JOB_REMOVED | PortQueueEvent.JOB_CANCELLED,\n refs: JobRef[],\n ): void {\n for (const ref of refs) {\n this.runtime.events.emit(event, { jobId: ref.jobId, queue: ref.queueName });\n }\n }\n\n /**\n * Remove many schedules in **one** statement, which also returns each removed row's queue — so the\n * `SCHEDULE_REMOVED` events cost nothing beyond the delete. This used to read every schedule\n * individually just to learn its queue name, then delete them one at a time: 2N queries for N ids.\n */\n async removeSchedules(options: { scheduleIds: string[] }): Promise<BatchResult> {\n const { scheduleIds } = options;\n if (!scheduleIds.length) return { affected: 0, requested: 0 };\n assertBatchIds(scheduleIds, 'removeSchedules({ scheduleIds })');\n const removed = await this.runtime.driver.deleteSchedules({ scheduleIds });\n for (const ref of removed) {\n this.runtime.events.emit(PortQueueEvent.SCHEDULE_REMOVED, {\n scheduleId: ref.scheduleId,\n queue: ref.queueName,\n });\n }\n return { affected: removed.length, requested: scheduleIds.length };\n }\n\n /** Arm or disarm a schedule. Core exposes the flag as read-only; the dashboard can toggle it. */\n async setScheduleEnabled(options: { scheduleId: string; enabled: boolean }): Promise<boolean> {\n // One statement: the driver returns the affected row's ref, so the event needs no extra read.\n const updated = await this.runtime.driver.setScheduleEnabled({\n scheduleId: options.scheduleId,\n enabled: options.enabled,\n now: this.runtime.clock.now(),\n });\n if (!updated) return false;\n this.runtime.events.emit(PortQueueEvent.SCHEDULE_UPDATED, {\n scheduleId: updated.scheduleId,\n queue: updated.queueName,\n });\n return true;\n }\n\n /** Whether this process is currently running the job (so a cancel fires its signal). */\n private isRunningHere(jobId: string): boolean {\n // `cancelRunning` both tests and acts, so it can't be used as a probe here without\n // cancelling. `isJobRunningHere` is the read-only half.\n return this.runtime.isJobRunningHere?.(jobId) ?? false;\n }\n}\n\nexport type { JobRecord };\n","/**\n * The `pq._cli` facade — everything `@portqueue/cli` needs that the public API deliberately does\n * not offer. Nothing here is a documented developer API (the `_` prefix on the property says so);\n * it exists so a CLI requirement never forces a change to `PortQueue`. See CLAUDE.md.\n *\n * The CLI's distinguishing constraint is that it is an **admin process that never owns the app's\n * queues**: it runs on a headless client (see `PortQueueOptions._headless`), so it declares nothing,\n * registers no instance row, and addresses every queue by name against the driver.\n */\nimport { JobStatus } from '../jobs/job-state.enum';\nimport { InvalidOptionsError } from '../errors/errors';\nimport { pageWindow } from '../monitoring/stats.service';\nimport { latestVersion } from '../drivers/shared/migration';\nimport type { Runtime } from '../client/runtime';\nimport type { Driver } from '../drivers/driver.interface';\nimport type { Page, ScheduleInfo } from '../producer/results';\nimport type { ProducerService } from '../producer/producer.service';\nimport type { TransactionHandle } from '../tx/transaction-handle';\n\n/** What `portqueue doctor` reports about the connection it just made. */\nexport interface DoctorReport {\n engine: string;\n serverVersion: string;\n /** Capabilities the driver verified against the live server, not just the ones it declares. */\n verifiedCapabilities: string[];\n /** The applied schema version, or null when the schema has never been migrated. */\n schemaVersion: number | null;\n /** The highest version this driver ships; equal to `schemaVersion` when fully migrated. */\n latestVersion: number;\n queueCount: number;\n instanceCount: number;\n}\n\nexport class CliService {\n constructor(\n private readonly runtime: Runtime,\n private readonly producer: ProducerService,\n ) {}\n\n /** The live driver, for CLI paths that need engine detail the public API doesn't expose. */\n get driver(): Driver {\n return this.runtime.driver;\n }\n\n runInTransaction<T>(options: { fn: (tx: TransactionHandle) => Promise<T> }): Promise<T> {\n return this.runtime.driver.runInTransaction(options);\n }\n\n /**\n * A **page** of schedules — one queue's, or across every queue when `queue` is omitted.\n *\n * Paged like every other list path. This used to call `listSchedules` with no window at all, so\n * `portqueue schedules` loaded every schedule row in the database into the terminal.\n */\n getSchedules(\n options: { queue?: string; limit?: number; offset?: number } = {},\n ): Promise<Page<ScheduleInfo>> {\n const { limit, offset } = pageWindow(options);\n return this.producer.getSchedules({\n ...(options.queue ? { queue: options.queue } : {}),\n limit,\n offset,\n });\n }\n\n /**\n * Delete every job on a queue in the given states (`portqueue purge`). Addresses the queue by\n * name, so purging never declares it. ACTIVE is refused for the same reason the public path\n * refuses it: the row belongs to a running handler.\n */\n async purge(options: { queue: string; statuses: JobStatus[] }): Promise<number> {\n if (options.statuses.includes(JobStatus.ACTIVE)) {\n throw new InvalidOptionsError(\n `Cannot purge ACTIVE jobs on queue '${options.queue}': an ACTIVE job is running. ` +\n `Cancel it first, then purge once it has settled.`,\n { queue: options.queue },\n );\n }\n return this.runtime.driver.removeJobsByStatus({\n queueName: options.queue,\n statuses: options.statuses,\n });\n }\n\n /**\n * Everything `portqueue doctor` reports: a live probe of the server plus the applied vs shipped\n * schema version. `PortQueue` exposes none of this — `migrate()` applies migrations but never\n * says what state the schema was in.\n */\n async doctor(): Promise<DoctorReport> {\n const driver = this.runtime.driver;\n const [probe, schemaVersion, queueCount, instanceCount] = await Promise.all([\n driver.probe(),\n driver.getSchemaVersion(),\n driver.countQueues(),\n driver.countInstances(),\n ]);\n return {\n engine: driver.engine,\n serverVersion: probe.serverVersion,\n verifiedCapabilities: probe.verifiedCapabilities.map(String),\n schemaVersion,\n latestVersion: latestVersion(driver.migrations),\n queueCount,\n instanceCount,\n };\n }\n}\n","/**\n * The handle `pq.createQueue({ name })` returns.\n *\n * **It has no methods.** It is a *registration*, not a control surface: the call that produced it\n * declares everything about the queue — its default job options, its retention policy, its\n * queue-scoped hooks, and (when this process consumes the queue) its `handler` and claim settings —\n * and everything you then *do* with the queue lives on `PortQueue`: `pq.addJob({ queue })`,\n * `pq.getJobs({ queue })`, `pq.pauseQueue({ queue })`, and so on.\n *\n * Two reasons that is the better surface, both learned from the version that had chained methods:\n *\n * - **Nothing silently escapes its scope.** `queue.getJob({ jobId })` forwarded to an unscoped read,\n * so asking one queue's handle for another queue's job returned it — typed as *this* queue's\n * payload. With one `pq.getJob({ jobId })` there is no scope to be wrong about, and the reads that\n * genuinely are per-queue take `queue` as a named argument that means exactly what it says.\n * - **One import, one object.** Application code that touches five queues passes five names to one\n * `pq` instead of threading five handles through its own plumbing.\n *\n * Because of that, holding on to this handle is optional: `pq.addJob({ queue: 'emails', … })` works\n * from a name alone, and a process that only enqueues need not declare the queue at all.\n */\nexport class Queue<TData = unknown> {\n constructor(readonly name: string) {}\n\n /**\n * The payload type this handle was created with. Never read at runtime — it exists so\n * `createQueue<Payload>({ name })` keeps `Payload` attached to the handle for a caller who wants\n * to pass the type around, and so `TData` is not an unused parameter.\n */\n declare readonly __data?: TData;\n}\n","import { wholeSecondsToMs } from '../util/seconds';\nimport type { Clock } from '../util/clock';\n\n/**\n * A worker-local token-bucket limiter. Exact and in-process; limits how\n * many jobs this worker starts per window. Distinct from the cluster-wide queue rate limit.\n *\n * The window arrives in seconds (`limiter.rateDurationSeconds`) and is held in ms, because the\n * refill maths runs against the clock's epoch-ms.\n */\nexport class RateLimiterService {\n private tokens: number;\n private lastRefill: number;\n private readonly max: number;\n private readonly windowMs: number;\n\n constructor(\n options: { max: number; durationSeconds: number },\n private readonly clock: Clock,\n ) {\n this.max = options.max;\n this.windowMs = wholeSecondsToMs(options.durationSeconds, 'limiter.rateDurationSeconds');\n this.tokens = options.max;\n this.lastRefill = clock.now();\n }\n\n private refill(): void {\n const now = this.clock.now();\n const elapsed = now - this.lastRefill;\n if (elapsed <= 0) return;\n const refill = (elapsed / this.windowMs) * this.max;\n this.tokens = Math.min(this.max, this.tokens + refill);\n this.lastRefill = now;\n }\n\n /** Consume up to `want` tokens; returns how many were granted. */\n take(want: number): number {\n this.refill();\n const grant = Math.max(0, Math.min(want, Math.floor(this.tokens)));\n this.tokens -= grant;\n return grant;\n }\n\n /** Milliseconds until at least one token is available (for loop backoff). */\n msUntilAvailable(): number {\n this.refill();\n if (this.tokens >= 1) return 0;\n const needed = 1 - this.tokens;\n return Math.ceil((needed / this.max) * this.windowMs);\n }\n}\n","import { PortQueueEvent } from '../events/event-name.enum';\nimport { secondsToMs } from '../util/seconds';\nimport { LOCK_HEARTBEATS_PER_WINDOW, MIN_LOCK_HEARTBEAT_SECONDS } from '../constants';\nimport type { Job, JobHandler } from '../jobs/job';\nimport type { JobRecord } from '../jobs/job-record';\nimport type { ErrorClass } from '../options/queue-options';\nimport type { FailureDetail } from '../options/enums';\nimport type { Runtime } from '../client/runtime';\nimport type { CompletionService } from './completion.service';\n\nexport interface ExecutionConfig {\n queueName: string;\n handler: JobHandler;\n dontAutoretryFor: Array<ErrorClass | string>;\n lockDurationSeconds: number;\n /** How much of a failure this queue stores on the row — passed through to the completion. */\n failureDetail: FailureDetail;\n}\n\n/** One in-flight handler: how to abort it, and which claim it is running under. */\nexport interface ActiveExecution {\n controller: AbortController;\n /** The claim's fence token, so a lock this process releases names the claim it is releasing. */\n lockToken: string | null;\n}\n\n/**\n * Runs handlers, catches every error, and routes to retry/fail. A throw never\n * propagates to the claim loop. Each job runs under a heartbeat that\n * extends the lock and an AbortSignal fired on shutdown/cooperative-cancel.\n */\nexport class ExecutionService {\n /** Active jobs on this instance → their controller and claim token (for cancel/shutdown). */\n readonly active = new Map<string, ActiveExecution>();\n\n constructor(\n private readonly runtime: Runtime,\n private readonly completion: CompletionService,\n private readonly config: ExecutionConfig,\n ) {}\n\n async run(record: JobRecord): Promise<void> {\n const startTs = this.runtime.clock.now();\n const controller = new AbortController();\n this.active.set(record.id, { controller, lockToken: record.lockToken });\n const queueName = this.config.queueName;\n\n this.runtime.events.emit(PortQueueEvent.JOB_ACTIVE, {\n jobId: record.id,\n queue: queueName,\n retryAttempt: record.retryAttempt,\n instanceKey: this.runtime.instanceKey,\n });\n\n const job = this.buildJob(record, controller.signal);\n const heartbeat = this.startHeartbeat(record, controller);\n\n try {\n await this.runtime.hooks.runBeforeProcess(queueName, job);\n const returnValue = await this.config.handler(job);\n const outcome = await this.completion.complete(record, queueName, returnValue, startTs);\n await this.runtime.hooks.runAfterProcess(queueName, job, outcome);\n } catch (err) {\n const outcome = await this.completion.failOrRetry(\n record,\n queueName,\n err,\n this.config.dontAutoretryFor,\n this.config.failureDetail,\n );\n await this.runtime.hooks.runAfterProcess(queueName, job, outcome).catch(() => undefined);\n } finally {\n clearInterval(heartbeat);\n this.active.delete(record.id);\n }\n }\n\n private buildJob(record: JobRecord, signal: AbortSignal): Job {\n const runtime = this.runtime;\n const lockDurationSeconds = this.config.lockDurationSeconds;\n return {\n id: record.id,\n queue: this.config.queueName,\n data: record.data,\n retryAttempt: record.retryAttempt,\n retryMaxAttempts: record.retryMaxAttempts,\n priority: record.priority,\n createdAt: new Date(record.createdAt),\n startAfter: new Date(record.startAfter),\n ...(record.scheduleId ? { scheduleId: record.scheduleId } : {}),\n ...(record.idempotencyKey ? { idempotencyKey: record.idempotencyKey } : {}),\n signal,\n async extendLock(options = {}) {\n await runtime.driver.extendLock({\n jobId: record.id,\n lockDurationSeconds: options.bySeconds ?? lockDurationSeconds,\n now: runtime.clock.now(),\n lockToken: record.lockToken,\n });\n },\n };\n }\n\n private startHeartbeat(record: JobRecord, controller: AbortController): NodeJS.Timeout {\n // Beat at a fraction of the lock window, never faster than the floor, so a lock is renewed\n // several times before it could lapse.\n const intervalMs = Math.max(\n secondsToMs(MIN_LOCK_HEARTBEAT_SECONDS, 'lock heartbeat floor'),\n Math.floor(\n secondsToMs(this.config.lockDurationSeconds, 'limiter.lockDurationSeconds') /\n LOCK_HEARTBEATS_PER_WINDOW,\n ),\n );\n const timer = setInterval(async () => {\n try {\n const held = await this.runtime.driver.extendLock({\n jobId: record.id,\n lockDurationSeconds: this.config.lockDurationSeconds,\n now: this.runtime.clock.now(),\n lockToken: record.lockToken,\n });\n if (!held && !controller.signal.aborted) controller.abort();\n } catch {\n /* transient DB error — next tick retries */\n }\n }, intervalMs);\n timer.unref?.();\n return timer;\n }\n}\n","import { PortQueueEvent } from '../events/event-name.enum';\nimport { RateLimiterService } from '../monitoring/rate-limiter.service';\nimport { ExecutionService, type ExecutionConfig } from './execution.service';\nimport { secondsToMs } from '../util/seconds';\nimport { ABORT_GRACE_SECONDS, DRAIN_POLL_SECONDS, LOCK_RELEASE_SECONDS } from '../constants';\nimport type { CompletionService } from './completion.service';\nimport type { JobHandler } from '../jobs/job';\nimport type { ErrorClass } from '../options/queue-options';\nimport type { FailureDetail } from '../options/enums';\nimport type { Runtime } from '../client/runtime';\n\n/** Worker wiring, resolved from the consumer half of `CreateQueueOptions`. Every duration is seconds. */\nexport interface WorkerConfig {\n queue: string;\n handler: JobHandler;\n concurrency: number;\n batchSize: number;\n lockDurationSeconds: number;\n pollIntervalSeconds: number;\n limiter?: { max: number; durationSeconds: number };\n dontAutoretryFor: Array<ErrorClass | string>;\n /** How much of a failure this queue stores on the row. */\n failureDetail: FailureDetail;\n}\n\n/**\n * The consumer for one queue. Owns its own claim loop, heartbeat, and\n * wakeup subscription — queues are independent lanes.\n *\n * **Internal.** There is no developer-facing worker: `pq.createQueue({ name, handler })` builds one\n * of these behind the queue's declaration, and it is never handed out. It begins claiming when the\n * client starts and its queue isn't paused, and stops when the client stops — so there was never a\n * lifecycle method to expose in the first place.\n */\nexport class Worker {\n private readonly execution: ExecutionService;\n private readonly limiter?: RateLimiterService;\n private activeCount = 0;\n private stopping = false;\n private started = false;\n private queueName: string | null = null;\n private pumping = false;\n private unsubscribeWakeup: (() => void) | null = null;\n private pollTimer: NodeJS.Timeout | null = null;\n /** A one-shot timer scheduled for the moment the rate limiter will have a token again. */\n private tokenTimer: NodeJS.Timeout | null = null;\n\n constructor(\n private readonly runtime: Runtime,\n completion: CompletionService,\n private readonly config: WorkerConfig,\n private readonly isPressureHigh: () => boolean,\n ) {\n const execConfig: ExecutionConfig = {\n queueName: config.queue,\n handler: config.handler,\n dontAutoretryFor: config.dontAutoretryFor,\n lockDurationSeconds: config.lockDurationSeconds,\n failureDetail: config.failureDetail,\n };\n this.execution = new ExecutionService(runtime, completion, execConfig);\n if (config.limiter) this.limiter = new RateLimiterService(config.limiter, runtime.clock);\n }\n\n /** @internal Called by the client lifecycle when the client starts. */\n async start(): Promise<void> {\n if (this.started) return;\n this.started = true;\n this.stopping = false;\n const row = await this.runtime.registry.ensure(this.config.queue);\n this.queueName = row.name;\n this.unsubscribeWakeup = this.runtime.wakeup.subscribe(this.config.queue, () =>\n this.runtime.background.run(() => this.pump()),\n );\n this.pollTimer = setInterval(\n () => this.runtime.background.run(() => this.pump()),\n secondsToMs(this.config.pollIntervalSeconds, 'limiter.pollIntervalSeconds'),\n );\n this.pollTimer.unref?.();\n this.runtime.events.emit(PortQueueEvent.WORKER_STARTED, { queue: this.config.queue });\n this.runtime.background.run(() => this.pump());\n }\n\n /** @internal Number of in-flight handlers (used for graceful drain). */\n get inFlight(): number {\n return this.activeCount;\n }\n\n /** @internal The execution service (exposes active abort controllers). */\n get executor(): ExecutionService {\n return this.execution;\n }\n\n private async pump(): Promise<void> {\n if (this.stopping || !this.runtime.isRunning() || this.pumping) return;\n this.pumping = true;\n try {\n while (!this.stopping) {\n const capacity = this.config.concurrency - this.activeCount;\n if (capacity <= 0) break;\n // Pressure is only ever high when the client was given a `systemLimiter`; without one this\n // reads false forever, which is why there is no per-worker opt-in to carry.\n if (this.isPressureHigh()) break;\n\n // Cluster-wide pause state, from the registry's cache — no query on the hot path. The\n // maintenance tick refreshes it, and a pause made in this process updates it immediately.\n if (this.runtime.registry.pauseState(this.config.queue)?.processingPaused) break;\n // This instance's own pause state (multi-instance mode).\n if (this.runtime.instances?.processingPaused) break;\n\n let want = Math.min(capacity, this.config.batchSize);\n if (this.limiter) {\n const granted = this.limiter.take(want);\n if (granted <= 0) {\n // Out of tokens. Come back when the bucket refills rather than waiting for the poll\n // timer — otherwise a rate-limited worker idles for a whole `pollIntervalSeconds` after\n // a shortfall that may clear in milliseconds.\n this.scheduleTokenWakeup(this.limiter.msUntilAvailable());\n break;\n }\n want = granted;\n }\n\n const jobs = await this.runtime.driver.claimJobs({\n queueName: this.queueName!,\n limit: want,\n lockDurationSeconds: this.config.lockDurationSeconds,\n now: this.runtime.clock.now(),\n instanceKey: this.runtime.instanceKey,\n });\n if (jobs.length === 0) break;\n\n for (const record of jobs) {\n this.activeCount += 1;\n void this.execution\n .run(record)\n .catch((err) => {\n this.runtime.events.emit(PortQueueEvent.ERROR, { error: err, source: 'execution' });\n })\n .finally(() => {\n this.activeCount -= 1;\n // A freed slot may allow another claim.\n this.runtime.background.run(() => this.pump());\n });\n }\n }\n } catch (err) {\n // A DB error mid-claim must never crash the loop.\n this.runtime.events.emit(PortQueueEvent.ERROR, { error: err, source: 'claim' });\n } finally {\n this.pumping = false;\n }\n }\n\n /** Re-pump once the rate limiter has a token. At most one such timer is ever outstanding. */\n private scheduleTokenWakeup(delayMs: number): void {\n if (this.tokenTimer || this.stopping) return;\n this.tokenTimer = setTimeout(\n () => {\n this.tokenTimer = null;\n if (!this.stopping) this.runtime.background.run(() => this.pump());\n },\n Math.max(delayMs, 0),\n );\n this.tokenTimer.unref?.();\n }\n\n /** @internal Stop claiming; drain in-flight up to timeout, then abort + release locks. */\n async stop(options: { timeoutSeconds: number; graceful: boolean }): Promise<void> {\n this.stopping = true;\n if (this.unsubscribeWakeup) this.unsubscribeWakeup();\n if (this.pollTimer) clearInterval(this.pollTimer);\n if (this.tokenTimer) clearTimeout(this.tokenTimer);\n this.tokenTimer = null;\n\n if (options.graceful && this.activeCount > 0) {\n // Raced against a real timer rather than measured with the injected clock. The drain waits on\n // wall-clock time — the handlers really are running — so a deadline taken from a clock a test\n // controls would never arrive and this would spin for as long as the handlers took.\n await Promise.race([\n this.awaitIdle(),\n elapses(secondsToMs(options.timeoutSeconds, 'shutdown timeoutSeconds')),\n ]);\n }\n await this.abortAndRelease();\n this.started = false;\n this.runtime.events.emit(PortQueueEvent.WORKER_STOPPED, { queue: this.config.queue });\n }\n\n /**\n * Abort every handler still running, then release the lock of the ones that did not stop.\n *\n * The order matters, and the release used to sit beside the abort. An abort is cooperative: a\n * handler that ignores `job.signal` — the common case for short work — keeps going and settles a\n * moment later. Releasing its lock in that moment let another instance's reclaim return the row to\n * `PENDING` and a second worker claim it, so the same job ran twice. Waiting for the abort to be\n * observed means a handler that stops promptly settles its own row and needs no release at all;\n * only a genuine straggler, which this process is about to abandon, has its lock cut short so\n * another instance can pick the job up quickly.\n *\n * A straggler's completion is refused even if it does land later: the release clears the claim's\n * fence token, and every completion is guarded on it (see `Driver.completeJob`).\n */\n private async abortAndRelease(): Promise<void> {\n const claims = [...this.execution.active.entries()].map(([jobId, active]) => {\n active.controller.abort();\n return { jobId, lockToken: active.lockToken };\n });\n if (!claims.length) return;\n\n await Promise.race([\n this.awaitIdle(),\n elapses(secondsToMs(ABORT_GRACE_SECONDS, 'abort grace')),\n ]);\n\n for (const claim of claims) {\n if (!this.execution.active.has(claim.jobId)) continue; // stopped and settled its own row\n this.runtime.background.run(() =>\n this.runtime.driver.extendLock({\n jobId: claim.jobId,\n lockDurationSeconds: LOCK_RELEASE_SECONDS,\n now: this.runtime.clock.now(),\n lockToken: claim.lockToken,\n }),\n );\n }\n }\n\n /** Resolve once the last in-flight handler has settled. */\n private async awaitIdle(): Promise<void> {\n const pollMs = secondsToMs(DRAIN_POLL_SECONDS, 'drain poll');\n while (this.activeCount > 0) await elapses(pollMs);\n }\n\n /** @internal Try to cooperatively cancel an active job on this instance. */\n cancelRunning(jobId: string): boolean {\n const active = this.execution.active.get(jobId);\n if (!active) return false;\n active.controller.abort();\n return true;\n }\n}\n\n/** A promise that resolves once `ms` has passed, on a timer that never holds the loop open. */\nfunction elapses(ms: number): Promise<void> {\n return new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, Math.max(ms, 0));\n timer.unref?.();\n });\n}\n","/**\n * An injectable clock so delay/cron/backoff/retention/visibility\n * logic is testable deterministically without real waiting.\n */\nexport interface Clock {\n now(): number;\n date(): Date;\n}\n\n/** The real system clock used in production. */\nexport class SystemClock implements Clock {\n now(): number {\n return Date.now();\n }\n date(): Date {\n return new Date();\n }\n}\n\n/** A manually-advanced clock for tests. */\nexport class FakeClock implements Clock {\n private current: number;\n\n constructor(start: number | Date = 0) {\n this.current = start instanceof Date ? start.getTime() : start;\n }\n\n now(): number {\n return this.current;\n }\n\n date(): Date {\n return new Date(this.current);\n }\n\n /** Advance the clock by `ms` and return the new time. */\n advance(ms: number): number {\n this.current += ms;\n return this.current;\n }\n\n /** Jump to an absolute time. */\n set(time: number | Date): void {\n this.current = time instanceof Date ? time.getTime() : time;\n }\n}\n","import { CancelOutcome, FailureDetail, PauseMode } from './options/enums';\nimport { PortQueueEvent } from './events/event-name.enum';\nimport { DriverCapability } from './drivers/driver-capabilities';\nimport { ConsoleLogger } from './logging/console-logger';\nimport { EventBusService } from './events/event-bus.service';\nimport { HookRunner } from './events/hook-runner';\nimport { OptionResolver } from './options/option-resolver';\nimport { Wakeup } from './pubsub/wakeup';\nimport { QueueRegistry } from './producer/queue-registry';\nimport { NotifierService } from './pubsub/notifier.service';\nimport { ProducerService } from './producer/producer.service';\nimport { ReadService } from './monitoring/stats.service';\nimport { CompletionService } from './consumer/completion.service';\nimport { ClientRegistryService } from './client/client-registry.service';\nimport { ClientLifecycleService } from './client/client-lifecycle.service';\nimport { BackgroundWork } from './client/background-work';\nimport { DashboardService } from './dashboard/dashboard.service';\nimport { CliService } from './cli/cli.service';\nimport { Queue } from './producer/queue';\nimport { Worker, type WorkerConfig } from './consumer/worker';\nimport { JobStatus } from './jobs/job-state.enum';\nimport {\n InstanceActiveError,\n InvalidOptionsError,\n JobNotFoundError,\n NotStartedError,\n QueueInUseError,\n QueueNotFoundError,\n} from './errors/errors';\nimport { SystemClock } from './util/clock';\nimport { secondsToMs } from './util/seconds';\nimport { assertBatchIds } from './util/batch-ids';\nimport {\n DEFAULT_CONCURRENCY,\n DEFAULT_FAILURE_DETAIL,\n DEFAULT_LOCK_DURATION_SECONDS,\n DEFAULT_POLL_INTERVAL_SECONDS,\n DEFAULT_SHUTDOWN_TIMEOUT_SECONDS,\n DEFAULT_TICK_INTERVAL_SECONDS,\n INSTANCE_REMOVAL_STALE_SECONDS,\n} from './constants';\nimport type { PortQueueOptions, ShutdownOptions } from './options/client-options';\nimport type { CreateQueueOptions, ErrorClass } from './options/queue-options';\nimport type { LimiterOptions } from './options/common';\nimport type { AddJobOptions } from './options/job-options';\nimport type { JobHandler } from './jobs/job';\nimport type { Logger } from './logging/logger.interface';\nimport type { Runtime } from './client/runtime';\nimport type { HookRegistration } from './events/hooks';\nimport type { TransactionHandle } from './tx/transaction-handle';\nimport type { QueueRow } from './jobs/job-record';\nimport type { EventListener, Unsubscribe } from './events/event-name.enum';\nimport type {\n AddJobResult,\n GetInstancesQuery,\n GetJobsQuery,\n GetQueuesQuery,\n GetSchedulesQuery,\n InstanceInfo,\n JobSnapshot,\n Page,\n QueueInfo,\n QueueStats,\n ScheduleInfo,\n} from './producer/results';\n\n/**\n * The top-level client, and **the whole developer-facing surface**. Owns connection, migration,\n * shared services, and the queue declarations. A thin facade — all real work lives in focused\n * services. Construction wires dependencies only; no I/O until `init()`.\n *\n * Every operation lives here rather than on the handle `createQueue` returns: that is a registration\n * with no methods (see {@link Queue}). A per-queue operation takes `queue` as a named argument, so one\n * import reaches every queue and no read can silently escape the scope its handle implied. There is\n * also no `createWorker`: one `createQueue` call declares a queue *and*, if it carries a `handler`,\n * consumes it.\n *\n * @typeParam TQueues - an optional string enum/union of this app's queue names, threaded\n * through every queue-name argument for compile-time safety (defaults to `string`).\n */\nexport class PortQueue<TQueues extends string = string> {\n private readonly runtime: Runtime;\n private readonly producer: ProducerService;\n private readonly reads: ReadService;\n private readonly completion: CompletionService;\n private readonly clientRegistry: ClientRegistryService;\n private readonly lifecycle: ClientLifecycleService;\n private readonly events: EventBusService;\n private readonly hooks: HookRunner;\n private readonly state = { running: false };\n private readonly headless: boolean;\n\n /**\n * Internal facade for `@portqueue/dashboard`. **Not a developer API** — it is undocumented,\n * unsupported for application code, and free to change in any release. Its purpose is to keep\n * the dashboard's needs off the public surface: when the dashboard wants something this class\n * doesn't already document, the method goes here rather than on `PortQueue`.\n */\n readonly _dashboard: DashboardService;\n\n /**\n * Internal facade for `@portqueue/cli`, with the same contract as {@link _dashboard}.\n */\n readonly _cli: CliService;\n\n constructor(options: PortQueueOptions) {\n if (!options.driver) {\n throw new InvalidOptionsError(\n 'PortQueue requires a `driver`. Pass a driver instance, e.g. `new SqliteDriver(...)`.',\n );\n }\n this.headless = options._headless === true;\n if (this.headless && options.instance?.instanceKey) {\n throw new InvalidOptionsError(\n 'A headless PortQueue (the dashboard or CLI) cannot take an `instance.instanceKey`. An ' +\n 'admin client is anonymous: it registers no instance row, so naming it would put a ' +\n 'heartbeat in the instances list for a process that never claims a job.',\n );\n }\n const logger = resolveLogger(options.logger);\n const clock = options.clock ?? new SystemClock();\n const context = options.driver.context;\n this.events = new EventBusService(logger);\n this.hooks = new HookRunner(logger, this.events);\n const resolver = new OptionResolver();\n const wakeup = new Wakeup();\n const registry = new QueueRegistry(options.driver, clock, {\n tickIntervalSeconds: options.tickIntervalSeconds ?? DEFAULT_TICK_INTERVAL_SECONDS,\n headless: this.headless,\n });\n this.clientRegistry = new ClientRegistryService();\n\n this.runtime = {\n driver: options.driver,\n context,\n logger,\n clock,\n events: this.events,\n hooks: this.hooks,\n resolver,\n options,\n registry,\n wakeup,\n background: new BackgroundWork(),\n // A headless client is anonymous by construction — no instance row, no affinity, no pause.\n instanceKey: this.headless ? null : (options.instance?.instanceKey ?? null),\n instances: null,\n headless: this.headless,\n isRunning: () => this.state.running,\n cancelRunning: (jobId: string) => this.clientRegistry.cancelRunning(jobId),\n isJobRunningHere: (jobId: string) => this.clientRegistry.isRunning(jobId),\n };\n\n const notifier = new NotifierService(\n options.driver,\n logger,\n options.driver.capabilities[DriverCapability.LISTEN_NOTIFY],\n );\n this.producer = new ProducerService(this.runtime, notifier);\n this.reads = new ReadService(this.runtime);\n this.completion = new CompletionService(this.runtime);\n this.lifecycle = new ClientLifecycleService(this.runtime, this.clientRegistry, this.state);\n this._dashboard = new DashboardService(this.runtime, this.reads, this.producer);\n this._cli = new CliService(this.runtime, this.producer);\n }\n\n // --- Lifecycle ---\n async init(): Promise<void> {\n await this.lifecycle.init();\n }\n\n async shutdown(options: ShutdownOptions = {}): Promise<void> {\n await this.lifecycle.shutdown({\n graceful: options.graceful ?? true,\n timeoutSeconds: options.timeoutSeconds ?? DEFAULT_SHUTDOWN_TIMEOUT_SECONDS,\n });\n }\n\n get isRunning(): boolean {\n return this.state.running;\n }\n\n /** Force-apply migrations (the programmatic MANUAL path). */\n migrate(): Promise<void> {\n return this.lifecycle.migrate();\n }\n\n // --- Registrations ---\n /**\n * Declare a queue in this process — **everything about it, in one call**: the `handler` that\n * processes its jobs, the `limiter` / `dontAutoretryFor` settings that shape how it claims them, and\n * the `defaultJobOptions`, `retention` and `hooks` its jobs inherit.\n *\n * The handler is required: declaring a queue *is* declaring that this process consumes it. A process\n * that only enqueues declares nothing — {@link addJob} addresses a queue by name and creates its row\n * on first use, so an API tier can produce onto a queue its worker tier consumes.\n *\n * The returned {@link Queue} carries the name and the payload type and nothing else — every\n * operation is a method on this class.\n *\n * A queue is declared **once per process**: a second call for the same name throws, because two\n * handlers would run two claim loops over the same rows. This is also the only thing that records\n * queue options, and nothing internal calls it — `pauseQueue`, `getJobs`, the dashboard and the CLI\n * all address a queue by name — so an admin action can never blank the defaults a declaration set.\n *\n * On a headless client (the dashboard or CLI) this declares nothing, writes nothing and consumes\n * nothing; it only hands back a typed name.\n */\n createQueue<TData = unknown, TResult = unknown>(\n options: CreateQueueOptions<TData, TResult, TQueues>,\n ): Queue<TData> {\n const { name, handler, limiter, dontAutoretryFor, ...queueOptions } = options;\n // Every rule about the *call* is checked before anything is recorded: a rejected declaration\n // must not have replaced the queue's options or its hooks on its way to throwing.\n if (typeof handler !== 'function') {\n throw new InvalidOptionsError(\n `createQueue for queue '${name}' requires 'handler' to be a function — a queue is declared ` +\n `by the process that processes it. To only enqueue, skip createQueue and call ` +\n `pq.addJob({ queue: '${name}', data }), which creates the queue's row on first use.`,\n { queue: name },\n );\n }\n if (this.clientRegistry.hasWorker(name)) {\n throw new InvalidOptionsError(\n `Queue '${name}' already has a handler in this process. A queue is consumed by at most ` +\n `one handler per process — two claim loops over the same rows only compete for them. ` +\n `Raise 'limiter.concurrency' to process more jobs at once, or run another instance.`,\n { queue: name },\n );\n }\n if ((limiter?.rateMax == null) !== (limiter?.rateDurationSeconds == null)) {\n throw new InvalidOptionsError(\n `createQueue for queue '${name}' set only one half of the rate cap. ` +\n `'limiter.rateMax' and 'limiter.rateDurationSeconds' define one setting — how many jobs ` +\n `may start per window — so either both are given or neither is.`,\n { queue: name },\n );\n }\n this.runtime.registry.declare(name, queueOptions);\n if (!this.headless) {\n // Reached at most once per queue: the handler check above rejects a second declaration, so\n // these hooks can never stack duplicates onto every add.\n for (const hook of queueOptions.hooks ?? []) {\n this.hooks.register(hook.queue ? hook : { ...hook, queue: name });\n }\n this.startConsuming(\n name,\n handler as JobHandler,\n limiter,\n dontAutoretryFor,\n queueOptions.failureDetail,\n );\n }\n const existing = this.clientRegistry.getQueue(name) as Queue<TData> | undefined;\n if (existing) return existing;\n const queue = new Queue<TData>(name);\n this.clientRegistry.addQueue(name, queue as Queue<unknown>);\n return queue;\n }\n\n /**\n * Build the claim loop behind a queue that declared a `handler`, and start it if the client is\n * already running. Internal: there is no worker on the public surface, so nothing is handed back.\n */\n private startConsuming(\n queue: string,\n handler: JobHandler,\n limiterOptions: LimiterOptions = {},\n dontAutoretryFor: Array<ErrorClass | string> = [],\n failureDetail: FailureDetail = DEFAULT_FAILURE_DETAIL,\n ): void {\n const limiter = limiterOptions;\n const concurrency = limiter.concurrency ?? DEFAULT_CONCURRENCY;\n const rate =\n limiter.rateMax != null && limiter.rateDurationSeconds != null\n ? { max: limiter.rateMax, durationSeconds: limiter.rateDurationSeconds }\n : null;\n const config: WorkerConfig = {\n queue,\n handler,\n concurrency,\n batchSize: limiter.batchSize ?? concurrency,\n lockDurationSeconds: limiter.lockDurationSeconds ?? DEFAULT_LOCK_DURATION_SECONDS,\n // LISTEN/NOTIFY-capable engines wake instantly on new jobs and only fall back to polling as a\n // safety net; non-notify engines poll on this cadence. Lower it via\n // `limiter.pollIntervalSeconds` for snappier pickup.\n pollIntervalSeconds: limiter.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS,\n ...(rate ? { limiter: rate } : {}),\n dontAutoretryFor,\n failureDetail,\n };\n const worker = new Worker(\n this.runtime,\n this.completion,\n config,\n () => this.lifecycle.systemPressureHigh,\n );\n this.clientRegistry.addWorker(queue, worker);\n if (this.state.running) void worker.start();\n }\n\n // --- Producing ---\n /** Add one job to a queue (or create a recurring schedule, with `schedule.cron`/`startEverySeconds`). */\n addJob<TData = unknown>(\n options: AddJobOptions<TData> & { queue: TQueues | string },\n ): Promise<AddJobResult> {\n this.requireStarted('addJob');\n const { queue, ...jobOptions } = options;\n return this.producer.addJob<TData>(queue, jobOptions as AddJobOptions<TData>);\n }\n\n /**\n * Add many one-off jobs to one queue in a **single** insert — one round trip for the whole batch\n * rather than two per job. Results come back in the order the jobs were given. Recurring entries\n * are rejected: each recurrence needs its own {@link addJob} so its result can carry a `scheduleId`.\n */\n addJobs<TData = unknown>(options: {\n queue: TQueues | string;\n jobs: Array<AddJobOptions<TData>>;\n }): Promise<AddJobResult[]> {\n this.requireStarted('addJobs');\n return this.producer.addJobs<TData>(options.queue, options.jobs);\n }\n\n // --- Reads ---\n /** A page of queues with their per-status counts, plus the total across every page. */\n getQueues(options: GetQueuesQuery = {}): Promise<Page<QueueInfo>> {\n this.requireStarted('getQueues');\n return this.reads.getQueues(options);\n }\n\n /** One queue by name, with the same counts and `inUse` flag the list carries. */\n getQueue(options: { name: TQueues | string }): Promise<QueueInfo | null> {\n this.requireStarted('getQueue');\n return this.reads.getQueue(options.name);\n }\n\n getQueueStats(options: { queue?: TQueues } = {}): Promise<QueueStats> {\n this.requireStarted('getQueueStats');\n return this.reads.getQueueStats(options.queue);\n }\n\n /** Client-wide stats across every queue — the same shape `getQueueStats` returns for one. */\n getQueuesStats(): Promise<QueueStats> {\n this.requireStarted('getQueuesStats');\n return this.reads.getQueueStats();\n }\n\n /** One job by id, from any queue. */\n getJob<TData = unknown>(options: { jobId: string }): Promise<JobSnapshot<TData> | null> {\n this.requireStarted('getJob');\n return this.reads.getJob<TData>(options.jobId);\n }\n\n /** A page of jobs, newest first. Narrow with `queue`, `statuses` or `scheduleId`. */\n getJobs<TData = unknown>(\n options: GetJobsQuery & { queue?: TQueues | string } = {},\n ): Promise<Page<JobSnapshot<TData>>> {\n this.requireStarted('getJobs');\n return this.reads.getJobs<TData>(options);\n }\n\n /** A page of recurring schedules — one queue's with `queue`, every queue's without it. */\n getSchedules(\n options: GetSchedulesQuery & { queue?: TQueues | string } = {},\n ): Promise<Page<ScheduleInfo>> {\n this.requireStarted('getSchedules');\n return this.producer.getSchedules(options);\n }\n\n /** One schedule by id, with the queue it produces onto. Null if unknown. */\n getSchedule(options: { scheduleId: string }): Promise<ScheduleInfo | null> {\n this.requireStarted('getSchedule');\n return this.producer.getSchedule(options.scheduleId);\n }\n\n // --- Job control ---\n /**\n * Requeue a **settled** job to run again — its own row is re-armed with its persisted data (status\n * back to `PENDING`, retry counters, lock, return value and timestamps reset). To start a fresh\n * run instead, add a new job with {@link addJob}.\n *\n * A **running** job is never re-armed: clearing its lock would let a second worker claim it while\n * the first handler is still going, so an `ACTIVE` job — like an unknown id — returns `null`.\n * Cancel it first with {@link cancelJob} and retry once it has settled.\n */\n async retryJob(options: { jobId: string; tx?: TransactionHandle }): Promise<AddJobResult | null> {\n this.requireStarted('retryJob');\n const requeued = await this.runtime.driver.requeueJob({\n jobId: options.jobId,\n now: this.runtime.clock.now(),\n ...(options.tx ? { tx: options.tx } : {}),\n });\n if (!requeued) return null;\n this.runtime.wakeup.signal(requeued.queueName);\n this.events.emit(PortQueueEvent.JOB_ADDED, {\n jobId: requeued.jobId,\n queue: requeued.queueName,\n deduplicated: false,\n });\n return {\n jobId: requeued.jobId,\n queue: requeued.queueName,\n status: requeued.status,\n startAfter: new Date(requeued.startAfter),\n deduplicated: false,\n };\n }\n\n /**\n * Cancel a job, and report **what actually happened** — see {@link CancelOutcome}.\n *\n * A job running in this process cannot be cancelled from outside its handler, only asked to stop:\n * its `AbortSignal` fires and the outcome is `SIGNALLED`, because a handler that ignores\n * `job.signal` runs to completion and the row ends `COMPLETED`. A pending or delayed job is marked\n * `CANCELLED` so it never runs, and that is the only case that reports `CANCELLED`.\n *\n * Throws {@link JobNotFoundError} for an id that names no row: there is no honest outcome for\n * cancelling a job that does not exist.\n */\n async cancelJob(options: { jobId: string; tx?: TransactionHandle }): Promise<CancelOutcome> {\n this.requireStarted('cancelJob');\n // A locally-running handler owns its row's outcome — fire its signal and let it settle,\n // rather than racing a DB write against its completion.\n if (this.runtime.cancelRunning?.(options.jobId)) return CancelOutcome.SIGNALLED;\n const cancelled = await this.runtime.driver.cancelJob({\n jobId: options.jobId,\n now: this.runtime.clock.now(),\n ...(options.tx ? { tx: options.tx } : {}),\n });\n if (cancelled) {\n this.events.emit(PortQueueEvent.JOB_CANCELLED, {\n jobId: cancelled.jobId,\n queue: cancelled.queueName,\n });\n return CancelOutcome.CANCELLED;\n }\n // Nothing was cancellable, and the two reasons read very differently to an operator. One read\n // separates them — on the refusal path only, never on a cancel that worked.\n const row = await this.runtime.driver.getJob({\n jobId: options.jobId,\n ...(options.tx ? { tx: options.tx } : {}),\n });\n if (!row) throw new JobNotFoundError(options.jobId);\n return CancelOutcome.NOT_CANCELLABLE;\n }\n\n /**\n * Remove a single job's row. Never removes a **running** job: an `ACTIVE` row is skipped and this\n * returns `false` without touching it — cancel it first with {@link cancelJob}, then remove it once\n * it has settled.\n */\n async removeJob(options: { jobId: string; tx?: TransactionHandle }): Promise<boolean> {\n this.requireStarted('removeJob');\n const removed = await this.runtime.driver.removeJob({\n jobId: options.jobId,\n ...(options.tx ? { tx: options.tx } : {}),\n });\n if (!removed) return false;\n this.events.emit(PortQueueEvent.JOB_REMOVED, {\n jobId: removed.jobId,\n queue: removed.queueName,\n });\n return true;\n }\n\n /**\n * Remove many jobs — either a set of ids (from any queue) or every job on one queue in the given\n * statuses. Returns how many rows went away.\n *\n * `ACTIVE` is refused both ways: by id an active row is skipped, and by status it throws, because\n * deleting a running job's row would yank it out from under its handler.\n */\n async removeJobs(\n options: ({ jobIds: string[] } | { queue: TQueues | string; statuses: JobStatus[] }) & {\n tx?: TransactionHandle;\n },\n ): Promise<number> {\n this.requireStarted('removeJobs');\n if ('jobIds' in options) {\n assertBatchIds(options.jobIds, 'removeJobs({ jobIds })');\n const removed = await this.runtime.driver.removeJobs({\n jobIds: options.jobIds,\n ...(options.tx ? { tx: options.tx } : {}),\n });\n for (const ref of removed) {\n this.events.emit(PortQueueEvent.JOB_REMOVED, {\n jobId: ref.jobId,\n queue: ref.queueName,\n });\n }\n return removed.length;\n }\n if (options.statuses.includes(JobStatus.ACTIVE)) {\n throw new InvalidOptionsError(\n `Cannot remove jobs by status ACTIVE on queue '${options.queue}': an ACTIVE job is ` +\n `running. Cancel it first with cancelJob({ jobId }), then remove it once it has settled.`,\n { queue: options.queue },\n );\n }\n return this.runtime.driver.removeJobsByStatus({\n queueName: options.queue,\n statuses: options.statuses,\n ...(options.tx ? { tx: options.tx } : {}),\n });\n }\n\n /** Remove a recurring schedule by id. Returns true when a schedule went away. */\n async removeSchedule(options: { scheduleId: string; tx?: TransactionHandle }): Promise<boolean> {\n this.requireStarted('removeSchedule');\n const removed = await this.runtime.driver.deleteSchedule({\n scheduleId: options.scheduleId,\n ...(options.tx ? { tx: options.tx } : {}),\n });\n if (!removed) return false;\n this.events.emit(PortQueueEvent.SCHEDULE_REMOVED, {\n scheduleId: removed.scheduleId,\n queue: removed.queueName,\n });\n return true;\n }\n\n // --- Events & hooks ---\n on<E extends PortQueueEvent>(\n event: E,\n listener: EventListener<E>,\n filter?: { queue?: TQueues },\n ): Unsubscribe {\n return this.events.on(event, listener, filter);\n }\n once<E extends PortQueueEvent>(\n event: E,\n listener: EventListener<E>,\n filter?: { queue?: TQueues },\n ): Unsubscribe {\n return this.events.once(event, listener, filter);\n }\n off<E extends PortQueueEvent>(event: E, listener: EventListener<E>): void {\n this.events.off(event, listener);\n }\n useHook(hook: HookRegistration): Unsubscribe {\n return this.hooks.register(hook);\n }\n\n // --- Queue control (persisted, cluster-wide) ---\n /**\n * Stop workers everywhere from claiming this queue's jobs. With `mode: PauseMode.ALL` the queue\n * also refuses new jobs.\n *\n * This flips the queue row's two flags and touches nothing else — in particular it does **not**\n * re-declare the queue, so it can never overwrite the default job options or retention policy a\n * `createQueue` registered. A queue this process declared is created first if it has not produced\n * anything yet (its row is written lazily); a name nothing has ever used throws\n * {@link QueueNotFoundError} rather than conjuring a paused queue no code consumes.\n */\n async pauseQueue(options: { queue: TQueues | string; mode?: PauseMode }): Promise<void> {\n this.requireStarted('pauseQueue');\n const mode = options.mode ?? PauseMode.PROCESSING;\n // `setPaused` throws when no row matched, so everything after it describes a write that\n // happened: the cache is refreshed and the event is emitted only on success. The `if (row)` that\n // used to guard the cache update was dead code reading as though null were tolerated.\n const row = await this.setPaused(options.queue, true, mode === PauseMode.ALL);\n this.runtime.registry.update(row);\n this.events.emit(PortQueueEvent.QUEUE_PAUSED, { queue: options.queue, mode });\n }\n\n /** Resume claiming (and accepting) on this queue. See {@link pauseQueue} for what it touches. */\n async resumeQueue(options: { queue: TQueues | string }): Promise<void> {\n this.requireStarted('resumeQueue');\n const row = await this.setPaused(options.queue, false, false);\n this.runtime.registry.update(row);\n this.runtime.wakeup.signal(options.queue);\n this.events.emit(PortQueueEvent.QUEUE_RESUMED, { queue: options.queue });\n }\n\n /**\n * Write both pause flags and return the updated row, so the cached flags this process's workers\n * read are refreshed without a second query. Throws {@link QueueNotFoundError} when the name\n * matched nothing — there is no \"paused nothing\" outcome to report.\n */\n private async setPaused(\n queue: string,\n processingPaused: boolean,\n acceptingPaused: boolean,\n ): Promise<QueueRow> {\n // A queue declared here may not have written its row yet (it is created on first use), so\n // ensure it before pausing. `ensure` only creates the row; it never writes queue options.\n if (this.runtime.registry.isRegistered(queue)) await this.runtime.registry.ensure(queue);\n const row = await this.runtime.driver.setQueuePaused({\n queueName: queue,\n processingPaused,\n acceptingPaused,\n now: this.runtime.clock.now(),\n });\n if (!row) throw new QueueNotFoundError(queue);\n return row;\n }\n\n /**\n * Manually remove a queue's row from the database. Refuses if the queue is still declared in\n * *this* process (via `createQueue`) — a running process must not have its queue deleted from\n * under it. The tool never removes queues automatically; this is an admin action\n * for queues no longer used by any running code. Job rows link by name (no FK) and are untouched.\n */\n async removeQueue(options: { name: TQueues | string }): Promise<boolean> {\n this.requireStarted('removeQueue');\n if (this.runtime.registry.isRegistered(options.name)) {\n throw new QueueInUseError(options.name);\n }\n const ok = await this.runtime.driver.deleteQueue({ name: options.name });\n if (ok) this.events.emit(PortQueueEvent.QUEUE_REMOVED, { queue: options.name });\n return ok;\n }\n\n // --- Instances (multi-instance mode) ---\n /** A page of known instances with liveness + per-instance job attribution, plus the total. */\n getInstances(options: GetInstancesQuery = {}): Promise<Page<InstanceInfo>> {\n this.requireStarted('getInstances');\n return this.reads.getInstances(options);\n }\n\n /** One instance by key, with the same liveness, health and attribution the list carries. */\n getInstance(options: { instanceKey: string }): Promise<InstanceInfo | null> {\n this.requireStarted('getInstance');\n return this.reads.getInstance(options.instanceKey);\n }\n\n /** Stop the named instance from claiming jobs (persisted; the target picks it up on heartbeat). */\n async pauseInstance(options: { instanceKey: string }): Promise<void> {\n this.requireStarted('pauseInstance');\n await this.runtime.driver.setInstancePaused({\n instanceKey: options.instanceKey,\n processingPaused: true,\n now: this.runtime.clock.now(),\n });\n // If pausing ourselves, reflect it immediately rather than waiting for the next beat.\n if (this.runtime.instances?.instanceKey === options.instanceKey) {\n await this.runtime.instances.beat();\n }\n this.events.emit(PortQueueEvent.INSTANCE_PAUSED, { instanceKey: options.instanceKey });\n }\n\n /** Resume the named instance's job claiming. */\n async resumeInstance(options: { instanceKey: string }): Promise<void> {\n this.requireStarted('resumeInstance');\n await this.runtime.driver.setInstancePaused({\n instanceKey: options.instanceKey,\n processingPaused: false,\n now: this.runtime.clock.now(),\n });\n if (this.runtime.instances?.instanceKey === options.instanceKey) {\n await this.runtime.instances.beat();\n }\n this.runtime.wakeup.signalAll();\n this.events.emit(PortQueueEvent.INSTANCE_RESUMED, { instanceKey: options.instanceKey });\n }\n\n /**\n * Manually remove a long-inactive instance's monitoring row. Refuses unless the instance has not\n * heartbeat for at least 30 minutes (a live or recently-seen instance would just re-register on\n * its next beat). Jobs record the processing instance key as a plain string (no FK), so removal\n * never touches job rows — it only tidies the instances list. The tool never does this itself.\n */\n async removeInstance(options: { instanceKey: string }): Promise<boolean> {\n this.requireStarted('removeInstance');\n const row = await this.runtime.driver.getInstance({ instanceKey: options.instanceKey });\n if (!row) return false;\n const now = this.runtime.clock.now();\n const staleAfterMs = secondsToMs(\n INSTANCE_REMOVAL_STALE_SECONDS,\n 'instance removal staleness window',\n );\n if (row.lastSeenAt >= now - staleAfterMs) {\n throw new InstanceActiveError(options.instanceKey);\n }\n const ok = await this.runtime.driver.deleteInstance({ instanceKey: options.instanceKey });\n if (ok) this.events.emit(PortQueueEvent.INSTANCE_REMOVED, { instanceKey: options.instanceKey });\n return ok;\n }\n\n /**\n * Every method that touches the database goes through this first. Before `init()` the driver is\n * not connected, and the failure the caller used to get was whatever the driver said about its own\n * connection — which named neither the mistake nor the fix.\n */\n private requireStarted(method: string): void {\n if (!this.state.running) throw new NotStartedError(method);\n }\n}\n\nfunction resolveLogger(logger: PortQueueOptions['logger']): Logger {\n if (logger && typeof (logger as Logger).info === 'function') return logger as Logger;\n return new ConsoleLogger((logger as ConstructorParameters<typeof ConsoleLogger>[0]) ?? {});\n}\n"],"names":["FailureDetail","PortQueueEvent","LogLevel","HookPhase","wholeSecondsToMs","wholeSeconds","BackoffStrategy","secondsToMs","QueueNotFoundError","PubSubChannel","InvalidOptionsError","CronExpressionParser","result","QueuePausedError","JobStatus","DeduplicationReason","emptyStatusCounts","msToSeconds","LockLostError","DriverCapability","matchesInstance","cpuUsage","performance","availableParallelism","monitorEventLoopDelay","getHeapStatistics","latestVersion","MigrationMode","SchemaVersionMismatchError","migration","MigrationFailedError","ShutdownTimeoutError","MAX_BATCH_IDS","JobBatchAction","CancelOutcome","JobNotFoundError","PauseMode","QueueInUseError","InstanceActiveError","NotStartedError"],"mappings":";;;;;;;;;AASO,MAAM,gCAAgC;AAGtC,MAAM,8BAA8B;AAGpC,MAAM,qCAAqC;AAM3C,MAAM,wBAAwB;AAG9B,MAAM,iCAAiC,KAAK;AAG5C,MAAM,mCAAmC;AAGzC,MAAM,kCAAkC;AAGxC,MAAM,iCAAiC;AAOvC,MAAM,gBAAgB;AAGtB,MAAM,8BAA8B;ACxCpC,MAAM,sBAAsB;AAM5B,MAAM,gCAAgC;AAGtC,MAAM,gC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AM,eAAe9B,UAAAA;AAAAA,MACnB;AAAA,MACA;AAAA,IAAA;AAEF,QAAI,IAAI,cAAc,MAAM,cAAc;AACxC,YAAM,IAAI+B,UAAAA,oBAAoB,QAAQ,WAAW;AAAA,IACnD;AACA,UAAM,KAAK,MAAM,KAAK,QAAQ,OAAO,eAAe,EAAE,aAAa,QAAQ,aAAa;AACxF,QAAI,GAAI,MAAK,OAAO,KAAK,eAAe,kBAAkB,EAAE,aAAa,QAAQ,aAAa;AAC9F,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOQ,eAAe,QAAsB;AAC3C,QAAI,CAAC,KAAK,MAAM,QAAS,OAAM,IAAIC,UAAAA,gBAAgB,MAAM;AAAA,EAC3D;AACF;AAEA,SAAS,cAAc,QAA4C;AACjE,MAAI,UAAU,OAAQ,OAAkB,SAAS,WAAY,QAAO;AACpE,SAAO,IAAI,cAAe,UAA6D,EAAE;AAC3F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs","sources":["../src/constants/time.constants.ts","../src/constants/worker.constants.ts","../src/constants/paging.constants.ts","../src/constants/maintenance.constants.ts","../src/constants/job.constants.ts","../src/events/event-name.enum.ts","../src/logging/log-level.enum.ts","../src/logging/console-logger.ts","../src/events/event-bus.service.ts","../src/events/hooks.ts","../src/events/hook-runner.ts","../src/options/option-resolver.ts","../src/pubsub/wakeup.ts","../src/producer/queue-registry.ts","../src/pubsub/channels.ts","../src/pubsub/notifier.service.ts","../src/scheduling/cron.ts","../src/producer/producer.service.ts","../src/jobs/snapshot.ts","../src/monitoring/stats.service.ts","../src/util/backoff.ts","../src/consumer/completion.service.ts","../src/client/client-registry.service.ts","../src/pubsub/subscriber.service.ts","../src/scheduling/scheduler.service.ts","../src/retention/retention.service.ts","../src/monitoring/system-monitor.service.ts","../src/client/instance.service.ts","../src/drivers/shared/migration-runner.service.ts","../src/client/client-lifecycle.service.ts","../src/client/background-work.ts","../src/util/batch-ids.ts","../src/dashboard/dashboard-results.ts","../src/dashboard/dashboard.service.ts","../src/cli/cli.service.ts","../src/producer/queue.ts","../src/monitoring/rate-limiter.service.ts","../src/consumer/execution.service.ts","../src/consumer/worker.ts","../src/util/clock.ts","../src/port-queue.ts"],"sourcesContent":["/**\n * Default cadences and time windows, all **in seconds** (the only unit the API speaks).\n *\n * Every default lives in `constants/` rather than inline at its use site so there is exactly one\n * place to change a policy — the heartbeat window in particular was previously copied into four\n * files that could drift apart.\n */\n\n/** Maintenance tick (scheduler + retention + expiry) cadence. `PortQueueOptions.tickIntervalSeconds`. */\nexport const DEFAULT_TICK_INTERVAL_SECONDS = 5;\n\n/** The floor the pub/sub poller falls back to when the tick interval is shorter. */\nexport const MIN_SUBSCRIBER_POLL_SECONDS = 5;\n\n/** Instance heartbeat cadence. `InstanceOptions.heartbeatIntervalSeconds`. */\nexport const DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 15;\n\n/**\n * How many missed heartbeats an instance may accumulate before it reads as stale. Three, so a\n * single slow beat (a long query, a GC pause) never flips a healthy instance to \"stale\".\n */\nexport const HEARTBEAT_STALE_BEATS = 3;\n\n/** How long an instance must have been unheard-from before it can be manually removed. */\nexport const INSTANCE_REMOVAL_STALE_SECONDS = 30 * 60;\n\n/** Graceful-shutdown budget for in-flight handlers and background work. `ShutdownOptions.timeoutSeconds`. */\nexport const DEFAULT_SHUTDOWN_TIMEOUT_SECONDS = 30;\n\n/** Health sampling cadence. `SystemLimiterOptions.sampleIntervalSeconds`. */\nexport const DEFAULT_SAMPLE_INTERVAL_SECONDS = 2;\n\n/** How long a migration runner waits for another instance to finish migrating. */\nexport const MIGRATION_WAIT_TIMEOUT_SECONDS = 30;\n\n/**\n * Milliseconds → microseconds, for the one reading that is measured in microseconds: `cpuUsage()`.\n * Deliberately *not* in `util/seconds` — that module owns the seconds↔milliseconds boundary the API\n * invariant is about, and this is a different pair of units.\n */\nexport const MICROS_PER_MS = 1000;\n\n/** How often that wait re-reads the applied schema version. */\nexport const MIGRATION_WAIT_POLL_SECONDS = 0.2;\n","/** Worker throughput and claim defaults. Durations are **in seconds**. */\n\n/** Handlers a worker runs at once. `LimiterOptions.concurrency`. */\nexport const DEFAULT_CONCURRENCY = 1;\n\n/**\n * Poll cadence when nothing wakes the worker. LISTEN/NOTIFY engines wake instantly and only fall\n * back to this as a safety net; non-notify engines poll on it. `LimiterOptions.pollIntervalSeconds`.\n */\nexport const DEFAULT_POLL_INTERVAL_SECONDS = 5;\n\n/** Visibility timeout / heartbeat window for a claimed job. `LimiterOptions.lockDurationSeconds`. */\nexport const DEFAULT_LOCK_DURATION_SECONDS = 30;\n\n/** Beats per lock window — a job's lock is extended this many times before it would lapse. */\nexport const LOCK_HEARTBEATS_PER_WINDOW = 3;\n\n/** The fastest a lock heartbeat ever beats, whatever the lock window. */\nexport const MIN_LOCK_HEARTBEAT_SECONDS = 1;\n\n/** How often a graceful drain re-checks whether the last handler has finished. */\nexport const DRAIN_POLL_SECONDS = 0.025;\n\n/**\n * How long shutdown waits after aborting a handler before deciding it is not going to stop.\n *\n * A handler that observes `job.signal` settles its own row within a tick or two of the abort, and\n * needs no lock released. Only what is still running after this window has its lock cut short so\n * another instance can reclaim the job quickly.\n */\nexport const ABORT_GRACE_SECONDS = 0.25;\n\n/**\n * The lock duration that *releases* a lock: a deadline in the past, so a reclaim sees the row as\n * stalled immediately. `secondsToMs` accepts the negative value for exactly this reason.\n */\nexport const LOCK_RELEASE_SECONDS = -1;\n","/** Paging defaults. One window shape (`limit`/`offset`) for every list read. */\n\n/** Rows a list read returns when the caller names no `limit`. */\nexport const DEFAULT_PAGE_LIMIT = 50;\n\n/** The ceiling a caller-supplied `limit` is clamped to on the public API. */\nexport const MAX_PAGE_LIMIT = 500;\n\n/** The ceiling the dashboard facade clamps its own pages to (its tables never show more). */\nexport const DASHBOARD_MAX_PAGE_LIMIT = 200;\n","/**\n * Batch sizes for the maintenance work the tick drives. Every sweep is bounded per statement and\n * loops until a short batch, so a backlog is drained across round trips instead of in one\n * table-wide transaction.\n */\n\n/** Rows one retention delete removes. */\nexport const RETENTION_BATCH_SIZE = 500;\n\n/** How many retention batches one tick will run before leaving the rest to the next tick. */\nexport const RETENTION_MAX_BATCHES = 20;\n\n/** Due schedules fired per batch. */\nexport const SCHEDULE_BATCH_SIZE = 100;\n\n/** How many schedule batches one tick will fire before leaving the rest to the next tick. */\nexport const SCHEDULE_MAX_BATCHES = 20;\n\n/** Rows one `expireDueJobs` / `reclaimStalledJobs` statement touches. */\nexport const MAINTENANCE_BATCH_SIZE = 500;\n\n/** How many expire/reclaim batches one tick will run. */\nexport const MAINTENANCE_MAX_BATCHES = 20;\n","import { FailureDetail } from '../options/enums';\n\n/** Per-job resolution defaults — what a job gets when neither it nor its queue says otherwise. */\n\n/** Higher runs first. `JobOptions.priority`. */\nexport const DEFAULT_PRIORITY = 0;\n\n/** Attempts including the first, so the default is \"run once, never retry\". `retry.maxAttempts`. */\nexport const DEFAULT_RETRY_MAX_ATTEMPTS = 1;\n\n/** Delay before a retry, **in seconds**. `retry.delaySeconds`. */\nexport const DEFAULT_RETRY_DELAY_SECONDS = 0;\n\n/** Growth factor an EXPONENTIAL backoff uses when none is given. `retry.backoff.factor`. */\nexport const DEFAULT_BACKOFF_FACTOR = 2;\n\n/**\n * What a queue stores on a failed row when it names no `failureDetail`: the stack, because a\n * developer reading a failure wants the throw site, and the cost is bounded by the cap below.\n */\nexport const DEFAULT_FAILURE_DETAIL = FailureDetail.STACK;\n\n/**\n * How much of a failure's stack is kept in `failure_message`. A stack is unbounded and every\n * failed row stores one, so it is truncated to a size that still shows the throw site and the\n * frames around it.\n */\nexport const FAILURE_MESSAGE_MAX_CHARS = 4000;\n\n/** Marker appended to a truncated failure message so a reader knows frames were dropped. */\nexport const FAILURE_MESSAGE_TRUNCATION_SUFFIX = '… [truncated]';\n","import type { JobStatus } from '../jobs/job-state.enum';\n\n/**\n * All observable lifecycle events. Emitted on the PortQueue instance.\n * Every listener receives one typed payload object.\n */\nexport enum PortQueueEvent {\n CLIENT_STARTED = 'CLIENT_STARTED',\n CLIENT_STOPPING = 'CLIENT_STOPPING',\n CLIENT_STOPPED = 'CLIENT_STOPPED',\n MIGRATION_APPLIED = 'MIGRATION_APPLIED',\n ERROR = 'ERROR',\n\n JOB_ADDED = 'JOB_ADDED',\n JOB_ACTIVE = 'JOB_ACTIVE',\n JOB_COMPLETED = 'JOB_COMPLETED',\n JOB_FAILED = 'JOB_FAILED',\n JOB_RETRYING = 'JOB_RETRYING',\n JOB_STALLED = 'JOB_STALLED',\n JOB_EXPIRED = 'JOB_EXPIRED',\n JOB_CANCELLED = 'JOB_CANCELLED',\n JOB_REMOVED = 'JOB_REMOVED',\n\n SCHEDULE_CREATED = 'SCHEDULE_CREATED',\n SCHEDULE_UPDATED = 'SCHEDULE_UPDATED',\n SCHEDULE_REMOVED = 'SCHEDULE_REMOVED',\n SCHEDULE_FIRED = 'SCHEDULE_FIRED',\n\n QUEUE_PAUSED = 'QUEUE_PAUSED',\n QUEUE_RESUMED = 'QUEUE_RESUMED',\n QUEUE_REMOVED = 'QUEUE_REMOVED',\n INSTANCE_PAUSED = 'INSTANCE_PAUSED',\n INSTANCE_RESUMED = 'INSTANCE_RESUMED',\n INSTANCE_REMOVED = 'INSTANCE_REMOVED',\n WORKER_STARTED = 'WORKER_STARTED',\n WORKER_STOPPED = 'WORKER_STOPPED',\n SYSTEM_PRESSURE_HIGH = 'SYSTEM_PRESSURE_HIGH',\n SYSTEM_PRESSURE_NORMAL = 'SYSTEM_PRESSURE_NORMAL',\n}\n\n/** Source of an internal error surfaced via {@link PortQueueEvent.ERROR}. */\nexport type ErrorSource =\n | 'claim'\n | 'execution'\n | 'completion'\n | 'scheduler'\n | 'retention'\n | 'subscriber'\n | 'notifier'\n | 'listener'\n | 'hook'\n | 'monitor'\n | 'migration';\n\n/** The typed payload for every event. */\nexport interface PortQueueEventPayloads {\n [PortQueueEvent.CLIENT_STARTED]: { instanceKey: string | null };\n [PortQueueEvent.CLIENT_STOPPING]: { instanceKey: string | null };\n [PortQueueEvent.CLIENT_STOPPED]: { instanceKey: string | null };\n [PortQueueEvent.MIGRATION_APPLIED]: { from: number | null; to: number };\n [PortQueueEvent.ERROR]: { error: unknown; source: ErrorSource };\n\n [PortQueueEvent.JOB_ADDED]: { jobId: string; queue: string; deduplicated: boolean };\n [PortQueueEvent.JOB_ACTIVE]: {\n jobId: string;\n queue: string;\n retryAttempt: number;\n instanceKey: string | null;\n };\n [PortQueueEvent.JOB_COMPLETED]: {\n jobId: string;\n queue: string;\n returnValue: unknown;\n durationSeconds: number;\n };\n [PortQueueEvent.JOB_FAILED]: {\n jobId: string;\n queue: string;\n error: unknown;\n retryAttempt: number;\n };\n [PortQueueEvent.JOB_RETRYING]: {\n jobId: string;\n queue: string;\n retryAttempt: number;\n nextRunAt: Date;\n };\n [PortQueueEvent.JOB_STALLED]: {\n jobId: string;\n queue: string;\n previousInstanceKey: string | null;\n };\n [PortQueueEvent.JOB_EXPIRED]: { jobId: string; queue: string };\n [PortQueueEvent.JOB_CANCELLED]: { jobId: string; queue: string };\n [PortQueueEvent.JOB_REMOVED]: { jobId: string; queue: string };\n\n [PortQueueEvent.SCHEDULE_CREATED]: { scheduleId: string; queue: string };\n [PortQueueEvent.SCHEDULE_UPDATED]: { scheduleId: string; queue: string };\n [PortQueueEvent.SCHEDULE_REMOVED]: { scheduleId: string; queue: string };\n [PortQueueEvent.SCHEDULE_FIRED]: { scheduleId: string; jobId: string; queue: string };\n\n [PortQueueEvent.QUEUE_PAUSED]: { queue: string; mode: string };\n [PortQueueEvent.QUEUE_RESUMED]: { queue: string };\n [PortQueueEvent.QUEUE_REMOVED]: { queue: string };\n [PortQueueEvent.INSTANCE_PAUSED]: { instanceKey: string };\n [PortQueueEvent.INSTANCE_RESUMED]: { instanceKey: string };\n [PortQueueEvent.INSTANCE_REMOVED]: { instanceKey: string };\n [PortQueueEvent.WORKER_STARTED]: { queue: string };\n [PortQueueEvent.WORKER_STOPPED]: { queue: string };\n [PortQueueEvent.SYSTEM_PRESSURE_HIGH]: { metric: string; value: number; threshold: number };\n [PortQueueEvent.SYSTEM_PRESSURE_NORMAL]: Record<string, never>;\n}\n\n/** Job status re-export helper used in event/payload typing contexts. */\nexport type { JobStatus };\n\nexport type EventListener<E extends PortQueueEvent> = (payload: PortQueueEventPayloads[E]) => void;\nexport type Unsubscribe = () => void;\n","/** Log levels. Ordered lowest → highest severity. */\nexport enum LogLevel {\n TRACE = 'TRACE',\n DEBUG = 'DEBUG',\n INFO = 'INFO',\n WARN = 'WARN',\n ERROR = 'ERROR',\n FATAL = 'FATAL',\n}\n\n/** Numeric severity for gating, lower = more verbose. */\nexport const LOG_LEVEL_SEVERITY: Record<LogLevel, number> = {\n [LogLevel.TRACE]: 10,\n [LogLevel.DEBUG]: 20,\n [LogLevel.INFO]: 30,\n [LogLevel.WARN]: 40,\n [LogLevel.ERROR]: 50,\n [LogLevel.FATAL]: 60,\n};\n","import { LOG_LEVEL_SEVERITY, LogLevel } from './log-level.enum';\nimport type { Logger, LogContext, LoggerOptions } from './logger.interface';\n\n/**\n * Zero-dependency default logger. Writes structured lines to\n * stdout/stderr honoring the configured level.\n */\nexport class ConsoleLogger implements Logger {\n private readonly minSeverity: number;\n private readonly pretty: boolean;\n\n constructor(options: LoggerOptions = {}) {\n const level = options.level ?? LogLevel.INFO;\n this.minSeverity = LOG_LEVEL_SEVERITY[level];\n this.pretty = options.pretty ?? Boolean(process.stdout.isTTY);\n }\n\n trace(message: string, context?: LogContext): void {\n this.write(LogLevel.TRACE, message, context);\n }\n debug(message: string, context?: LogContext): void {\n this.write(LogLevel.DEBUG, message, context);\n }\n info(message: string, context?: LogContext): void {\n this.write(LogLevel.INFO, message, context);\n }\n warn(message: string, context?: LogContext): void {\n this.write(LogLevel.WARN, message, context);\n }\n error(message: string, context?: LogContext): void {\n this.write(LogLevel.ERROR, message, context);\n }\n fatal(message: string, context?: LogContext): void {\n this.write(LogLevel.FATAL, message, context);\n }\n\n private write(level: LogLevel, message: string, context?: LogContext): void {\n if (LOG_LEVEL_SEVERITY[level] < this.minSeverity) return;\n const stream =\n LOG_LEVEL_SEVERITY[level] >= LOG_LEVEL_SEVERITY[LogLevel.ERROR]\n ? process.stderr\n : process.stdout;\n const normalized = context ? normalizeContext(context) : undefined;\n if (this.pretty) {\n const suffix =\n normalized && Object.keys(normalized).length ? ` ${JSON.stringify(normalized)}` : '';\n stream.write(`[portqueue] ${level} ${message}${suffix}\\n`);\n } else {\n stream.write(\n `${JSON.stringify({ ts: new Date().toISOString(), level, msg: message, ...normalized })}\\n`,\n );\n }\n }\n}\n\n/** Serialize an Error in `err` to a plain object so it survives JSON logging. */\nfunction normalizeContext(context: LogContext): Record<string, unknown> {\n const out: Record<string, unknown> = { ...context };\n if (out.err instanceof Error) {\n out.err = { name: out.err.name, message: out.err.message, stack: out.err.stack };\n }\n return out;\n}\n\n/** A logger that discards everything — handy for tests. */\nexport class NoopLogger implements Logger {\n trace(): void {}\n debug(): void {}\n info(): void {}\n warn(): void {}\n error(): void {}\n fatal(): void {}\n}\n","import {\n PortQueueEvent,\n type EventListener,\n type PortQueueEventPayloads,\n type Unsubscribe,\n} from './event-name.enum';\nimport type { Logger } from '../logging/logger.interface';\n\ninterface Registration {\n listener: (payload: unknown) => void;\n queue?: string;\n once: boolean;\n}\n\n/** One event's listeners, plus how many of them are `once` registrations. */\ninterface Bucket {\n registrations: Set<Registration>;\n /** Kept in step with the set, so `emit` knows whether removal during iteration is possible. */\n onceCount: number;\n}\n\n/**\n * Typed event bus. Synchronous fan-out; listeners may be async but the\n * bus never awaits them (observation must not block the hot path). A throwing listener is\n * caught, logged, and re-surfaced as {@link PortQueueEvent.ERROR} — never breaks emission.\n *\n * Four to six events fire per job, so `emit` is a hot path. It iterates the registration set\n * **directly** and only snapshots it when the set actually holds a `once` listener — the one case\n * where emission mutates what it is iterating. Tracking that with a counter turns the common case\n * (plain `on` listeners, or none) from an allocation per event into none at all.\n */\nexport class EventBusService {\n private readonly buckets = new Map<PortQueueEvent, Bucket>();\n\n constructor(private readonly logger: Logger) {}\n\n on<E extends PortQueueEvent>(\n event: E,\n listener: EventListener<E>,\n filter?: { queue?: string },\n ): Unsubscribe {\n return this.add(event, listener as (p: unknown) => void, filter?.queue, false);\n }\n\n once<E extends PortQueueEvent>(\n event: E,\n listener: EventListener<E>,\n filter?: { queue?: string },\n ): Unsubscribe {\n return this.add(event, listener as (p: unknown) => void, filter?.queue, true);\n }\n\n off<E extends PortQueueEvent>(event: E, listener: EventListener<E>): void {\n const bucket = this.buckets.get(event);\n if (!bucket) return;\n // Snapshot, then delete. Mutating a Set mid-iteration is legal, but doing it here while `emit`\n // copies the set for exactly that reason would leave the two reading as inconsistent about the\n // same hazard.\n const matches = [...bucket.registrations].filter(\n (reg) => reg.listener === (listener as (p: unknown) => void),\n );\n for (const reg of matches) this.remove(bucket, reg);\n }\n\n private add(\n event: PortQueueEvent,\n listener: (p: unknown) => void,\n queue: string | undefined,\n once: boolean,\n ): Unsubscribe {\n let bucket = this.buckets.get(event);\n if (!bucket) {\n bucket = { registrations: new Set(), onceCount: 0 };\n this.buckets.set(event, bucket);\n }\n const reg: Registration = { listener, once, ...(queue !== undefined ? { queue } : {}) };\n bucket.registrations.add(reg);\n if (once) bucket.onceCount += 1;\n const target = bucket;\n return () => this.remove(target, reg);\n }\n\n private remove(bucket: Bucket, reg: Registration): void {\n if (!bucket.registrations.delete(reg)) return;\n if (reg.once) bucket.onceCount -= 1;\n }\n\n emit<E extends PortQueueEvent>(event: E, payload: PortQueueEventPayloads[E]): void {\n const bucket = this.buckets.get(event);\n if (!bucket || bucket.registrations.size === 0) return;\n const queue = (payload as { queue?: string }).queue;\n // Only a `once` listener is removed while we iterate, so only then is a snapshot needed.\n const targets: Iterable<Registration> =\n bucket.onceCount > 0 ? [...bucket.registrations] : bucket.registrations;\n for (const reg of targets) {\n if (reg.queue !== undefined && reg.queue !== queue) continue;\n if (reg.once) this.remove(bucket, reg);\n try {\n reg.listener(payload);\n } catch (err) {\n // Isolate listener errors and re-surface (avoid infinite loop on ERROR itself).\n this.logger.error('Event listener threw; isolated.', { err, event });\n if (event !== PortQueueEvent.ERROR) {\n this.emit(PortQueueEvent.ERROR, { error: err, source: 'listener' });\n }\n }\n }\n }\n}\n","import type { AddJobOptions, JobOptions } from '../options/job-options';\nimport type { Job } from '../jobs/job';\nimport type { AddJobResult } from '../producer/results';\n\n/** Hook lifecycle phases. */\nexport enum HookPhase {\n BEFORE_ADD = 'BEFORE_ADD',\n AFTER_ADD = 'AFTER_ADD',\n BEFORE_PROCESS = 'BEFORE_PROCESS',\n AFTER_PROCESS = 'AFTER_PROCESS',\n}\n\n/** Outcome descriptor passed to AFTER_PROCESS hooks. */\nexport type ProcessOutcome =\n | { kind: 'completed'; returnValue: unknown }\n | { kind: 'failed'; error: unknown }\n | { kind: 'retry'; error: unknown; nextRunAt: Date };\n\n/** A modified add — a BEFORE_ADD hook may return this to mutate the outgoing job. */\nexport interface BeforeAddResult<TData = unknown> {\n options?: Partial<AddJobOptions<TData>>;\n}\n\n/**\n * Participation-hook registration. Hooks are awaited, run in\n * registration order, and can mutate BEFORE_ADD/BEFORE_PROCESS or veto by throwing.\n */\nexport interface HookRegistration {\n phase: HookPhase;\n /** Optional queue scope. */\n queue?: string;\n handler: HookHandler;\n}\n\nexport type HookHandler =\n | ((ctx: {\n queue: string;\n options: AddJobOptions<unknown>;\n }) => Promise<BeforeAddResult | void> | BeforeAddResult | void)\n | ((ctx: { result: AddJobResult }) => Promise<void> | void)\n | ((ctx: { job: Job }) => Promise<void> | void)\n | ((ctx: { job: Job; outcome: ProcessOutcome }) => Promise<void> | void);\n\n/** Convenience typed registration builders (all optional to use). */\nexport interface BeforeAddHook<TData = unknown> {\n phase: HookPhase.BEFORE_ADD;\n queue?: string;\n handler: (ctx: {\n queue: string;\n options: AddJobOptions<TData>;\n }) => Promise<BeforeAddResult<TData> | void> | BeforeAddResult<TData> | void;\n}\n\nexport type { JobOptions };\n","import {\n HookPhase,\n type BeforeAddResult,\n type HookRegistration,\n type ProcessOutcome,\n} from './hooks';\nimport type { AddJobOptions } from '../options/job-options';\nimport type { Job } from '../jobs/job';\nimport type { AddJobResult } from '../producer/results';\nimport type { Logger } from '../logging/logger.interface';\nimport type { EventBusService } from './event-bus.service';\nimport { PortQueueEvent } from './event-name.enum';\n\n/** The shared empty result for a phase nothing registered against — never allocated per call. */\nconst EMPTY: readonly HookRegistration[] = [];\n\n/**\n * Runs participation hooks. Hooks are awaited, in registration order.\n * A BEFORE_* throw aborts the operation; an AFTER_* throw is logged and surfaced via ERROR\n * but does not undo the completed operation.\n *\n * Hooks are **indexed by phase at registration time**. `forPhase` runs four times per job, and\n * filtering the whole array each time meant an allocation and a full scan per job even for an\n * application with no hooks at all; now the no-hook case is a `Map` miss and an early return.\n */\nexport class HookRunner {\n private readonly byPhase = new Map<HookPhase, HookRegistration[]>();\n\n constructor(\n private readonly logger: Logger,\n private readonly events: EventBusService,\n ) {}\n\n register(hook: HookRegistration): () => void {\n const bucket = this.byPhase.get(hook.phase);\n if (bucket) bucket.push(hook);\n else this.byPhase.set(hook.phase, [hook]);\n return () => {\n const current = this.byPhase.get(hook.phase);\n if (!current) return;\n const i = current.indexOf(hook);\n if (i >= 0) current.splice(i, 1);\n if (current.length === 0) this.byPhase.delete(hook.phase);\n };\n }\n\n /**\n * The hooks for one phase that apply to `queue`, in registration order. Returns the phase's own\n * array untouched when every hook in it is unscoped — the common case — so no array is built.\n */\n private forPhase(phase: HookPhase, queue: string): readonly HookRegistration[] {\n const bucket = this.byPhase.get(phase);\n if (!bucket || bucket.length === 0) return EMPTY;\n if (bucket.every((h) => h.queue === undefined)) return bucket;\n return bucket.filter((h) => h.queue === undefined || h.queue === queue);\n }\n\n /** Run BEFORE_ADD hooks; may mutate options or veto by throwing. Returns merged options. */\n async runBeforeAdd<TData>(\n queue: string,\n options: AddJobOptions<TData>,\n ): Promise<AddJobOptions<TData>> {\n let current = options;\n for (const hook of this.forPhase(HookPhase.BEFORE_ADD, queue)) {\n const result = (await (hook.handler as (ctx: unknown) => Promise<BeforeAddResult | void>)({\n queue,\n options: current,\n })) as BeforeAddResult<TData> | void;\n if (result?.options) current = { ...current, ...result.options };\n }\n return current;\n }\n\n async runAfterAdd(queue: string, result: AddJobResult): Promise<void> {\n for (const hook of this.forPhase(HookPhase.AFTER_ADD, queue)) {\n await this.safeAfter(hook, { result });\n }\n }\n\n /** Run BEFORE_PROCESS hooks; a throw skips/fails the job before the handler runs. */\n async runBeforeProcess(queue: string, job: Job): Promise<void> {\n for (const hook of this.forPhase(HookPhase.BEFORE_PROCESS, queue)) {\n await (hook.handler as (ctx: unknown) => Promise<void>)({ job });\n }\n }\n\n async runAfterProcess(queue: string, job: Job, outcome: ProcessOutcome): Promise<void> {\n for (const hook of this.forPhase(HookPhase.AFTER_PROCESS, queue)) {\n await this.safeAfter(hook, { job, outcome });\n }\n }\n\n private async safeAfter(hook: HookRegistration, ctx: unknown): Promise<void> {\n try {\n await (hook.handler as (c: unknown) => Promise<void>)(ctx);\n } catch (err) {\n this.logger.error('AFTER hook threw; isolated.', { err, phase: hook.phase });\n this.events.emit(PortQueueEvent.ERROR, { error: err, source: 'hook' });\n }\n }\n}\n","import { BackoffStrategy } from './enums';\nimport type { JobOptions } from './job-options';\nimport type { RetentionOptions } from './common';\nimport type { JobStatus } from '../jobs/job-state.enum';\nimport { wholeSeconds, wholeSecondsToMs } from '../util/seconds';\nimport {\n DEFAULT_PRIORITY,\n DEFAULT_RETRY_DELAY_SECONDS,\n DEFAULT_RETRY_MAX_ATTEMPTS,\n} from '../constants';\n\n/**\n * The fully-resolved per-job settings frozen onto a `job` row. Instants (`startAfter`, `expireAt`)\n * are epoch ms; every duration is a whole number of seconds, exactly as the\n * caller gave it.\n */\nexport interface ResolvedJobOptions {\n priority: number;\n startAfter: number;\n expireAt: number | null;\n retryMaxAttempts: number;\n retryDelaySeconds: number;\n retryBackoff: BackoffStrategy;\n retryBackoffFactor: number | null;\n retryMaxDelaySeconds: number | null;\n retryJitter: boolean;\n /** The TTL after finishing before this job is deleted, or null to keep it forever. */\n retentionTtlSeconds: number | null;\n /** The finished statuses retention may delete this job in, or null for every finished status. */\n retentionStatuses: JobStatus[] | null;\n idempotencyKey: string | null;\n singletonKey: string | null;\n}\n\n/**\n * Merges queue → job options (job wins) and freezes resolved values.\n * Resolution happens once, at insert time. There is no client-level default layer — job\n * defaults and retention are set per queue so nothing is silently inherited client-wide.\n */\nexport class OptionResolver {\n resolve(options: {\n job: JobOptions;\n queueDefaults?: JobOptions;\n queueRetention?: RetentionOptions;\n /** One-off start delay in seconds from the job's `schedule` group (not a mergeable default). */\n startAfterSeconds?: number;\n now: number;\n }): ResolvedJobOptions {\n const { job, queueDefaults, queueRetention, now } = options;\n const merged: JobOptions = { ...queueDefaults, ...job };\n\n const startAfter = this.resolveStartAfter(options.startAfterSeconds, now);\n const expireAt =\n merged.expireInSeconds != null\n ? startAfter + wholeSecondsToMs(merged.expireInSeconds, 'expireInSeconds')\n : null;\n\n const backoff = merged.retry?.backoff;\n // Retention is chosen whole, never merged field by field: a per-job policy replaces the\n // queue's rather than inheriting half of it.\n const retention = merged.retention ?? queueRetention;\n\n return {\n priority: merged.priority ?? DEFAULT_PRIORITY,\n startAfter,\n expireAt,\n retryMaxAttempts: merged.retry?.maxAttempts ?? DEFAULT_RETRY_MAX_ATTEMPTS,\n retryDelaySeconds:\n merged.retry?.delaySeconds != null\n ? wholeSeconds(merged.retry.delaySeconds, 'retry.delaySeconds')\n : DEFAULT_RETRY_DELAY_SECONDS,\n retryBackoff: backoff?.strategy ?? BackoffStrategy.FIXED,\n retryBackoffFactor: backoff?.factor ?? null,\n retryMaxDelaySeconds:\n backoff?.maxDelaySeconds != null\n ? wholeSeconds(backoff.maxDelaySeconds, 'retry.backoff.maxDelaySeconds')\n : null,\n retryJitter: backoff?.jitter ?? false,\n retentionTtlSeconds:\n retention != null ? wholeSeconds(retention.ttlSeconds, 'retention.ttlSeconds') : null,\n // Null, not a defaulted list: \"the caller didn't scope this\" is a distinct state from \"the\n // caller asked for exactly these\", and the column stores null for the common case.\n retentionStatuses: retention?.statuses?.length ? [...retention.statuses] : null,\n idempotencyKey: merged.idempotencyKey ?? null,\n singletonKey: merged.singletonKey ?? null,\n };\n }\n\n private resolveStartAfter(startAfterSeconds: number | undefined, now: number): number {\n if (startAfterSeconds == null) return now;\n return now + wholeSecondsToMs(startAfterSeconds, 'schedule.startAfterSeconds');\n }\n}\n","/**\n * A debounced \"there is work\" signal that wakes claim loops.\n * Per-queue subscribers are notified when a job is added or a NOTIFY/poll fires.\n */\nexport class Wakeup {\n private readonly subscribers = new Map<string, Set<() => void>>();\n\n subscribe(queue: string, callback: () => void): () => void {\n let set = this.subscribers.get(queue);\n if (!set) {\n set = new Set();\n this.subscribers.set(queue, set);\n }\n const subscribers = set;\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n // Drop the queue's entry once its last subscriber goes, and only if it is still *this* set: a\n // resubscribe between the two would have installed a new one, and deleting that would strand\n // a live listener. An emptied set left in the map is small, but `signalAll` then walks it\n // forever in a process that declares and tears down queues.\n if (subscribers.size === 0 && this.subscribers.get(queue) === subscribers) {\n this.subscribers.delete(queue);\n }\n };\n }\n\n /** Wake all loops for one queue. */\n signal(queue: string): void {\n const set = this.subscribers.get(queue);\n if (set) for (const cb of set) cb();\n }\n\n /** Wake every loop (e.g. on system-pressure-normal). */\n signalAll(): void {\n for (const set of this.subscribers.values()) {\n for (const cb of set) cb();\n }\n }\n\n /**\n * How many queues currently have a subscriber. `@internal` — it exists so a test can assert the\n * map does not grow with every queue a process declares and tears down.\n */\n get queueCount(): number {\n return this.subscribers.size;\n }\n}\n","import { secondsToMs } from '../util/seconds';\nimport { DEFAULT_TICK_INTERVAL_SECONDS } from '../constants';\nimport { QueueNotFoundError } from '../errors/errors';\nimport type { Driver } from '../drivers/driver.interface';\nimport type { QueueRow } from '../jobs/job-record';\nimport type { QueueOptions } from '../options/queue-options';\nimport type { Clock } from '../util/clock';\n\ninterface QueueEntry {\n row: QueueRow;\n options: QueueOptions;\n /** When the cached pause flags were last read from the database. */\n refreshedAt: number;\n}\n\n/**\n * Caches queue name → row + in-memory options, and owns the cached pause flags the claim loop reads.\n *\n * Three things this class is deliberate about:\n *\n * - **`declare` is only ever reached from the developer's own `createQueue`.** Declared options are\n * *replaced*, because `createQueue` is a declaration: the caller states what the queue is, and the\n * last declaration wins. That is only safe because nothing internal calls it — no admin action, no\n * pause, no read path — so a `pauseQueue` can never blank the defaults a `createQueue` set.\n * - **The pause flags are cached with a TTL, not re-read per claim.** The claim loop used to issue a\n * `getQueueByName` on every pump — per worker, per poll, and again on every freed concurrency slot\n * — which on an idle queue meant more queue reads than job claims. They are refreshed on the\n * maintenance tick (and immediately by a pause/resume made here), and {@link pauseState} answers\n * from cache with no I/O at all.\n * - **A headless registry never writes.** For the dashboard and CLI (see `PortQueueOptions._headless`)\n * `declare` is a no-op, `ensure` reads the row instead of creating it, and `isRegistered` is always\n * false — an admin tool must not create queue rows or claim ownership of a queue it merely inspects.\n */\nexport class QueueRegistry {\n private readonly entries = new Map<string, QueueEntry>();\n private readonly ensuring = new Map<string, Promise<QueueRow>>();\n private readonly pendingOptions = new Map<string, QueueOptions>();\n /** How stale a cached pause flag may get before the tick refreshes it. */\n private readonly staleAfterMs: number;\n\n constructor(\n private readonly driver: Driver,\n private readonly clock: Clock,\n options: { tickIntervalSeconds?: number; headless?: boolean } = {},\n ) {\n this.staleAfterMs = secondsToMs(\n options.tickIntervalSeconds ?? DEFAULT_TICK_INTERVAL_SECONDS,\n 'tickIntervalSeconds',\n );\n this.headless = options.headless ?? false;\n }\n\n private readonly headless: boolean;\n\n /**\n * Record a queue's declared options (no I/O). **Only `PortQueue.createQueue` calls this** — see the\n * class comment. Options replace any previous declaration for the same name. A no-op on a headless\n * client, which declares nothing.\n */\n declare(name: string, options: QueueOptions): void {\n if (this.headless) return;\n const existing = this.entries.get(name);\n if (existing) {\n existing.options = options;\n return;\n }\n this.pendingOptions.set(name, options);\n }\n\n getOptions(name: string): QueueOptions {\n return this.entries.get(name)?.options ?? this.pendingOptions.get(name) ?? {};\n }\n\n /**\n * Resolve (and cache) the queue row. Idempotent under concurrency.\n *\n * Creates the row when absent — except on a headless client, where it reads and throws\n * {@link QueueNotFoundError} if the queue was never declared by an application.\n */\n async ensure(name: string): Promise<QueueRow> {\n const cached = this.entries.get(name);\n if (cached) return cached.row;\n const inflight = this.ensuring.get(name);\n if (inflight) return inflight;\n const options = this.pendingOptions.get(name);\n const promise = this.resolveRow(name, options)\n .then((row) => {\n this.entries.set(name, {\n row,\n options: options ?? {},\n refreshedAt: this.clock.now(),\n });\n this.pendingOptions.delete(name);\n this.ensuring.delete(name);\n return row;\n })\n .catch((err: unknown) => {\n // Don't strand a rejected promise in the map — the next caller must be able to retry.\n this.ensuring.delete(name);\n throw err;\n });\n this.ensuring.set(name, promise);\n return promise;\n }\n\n private async resolveRow(name: string, options: QueueOptions | undefined): Promise<QueueRow> {\n if (this.headless) {\n const row = await this.driver.getQueueByName({ name });\n if (!row) throw new QueueNotFoundError(name);\n return row;\n }\n return this.driver.ensureQueue({\n name,\n ...(options ? { options } : {}),\n now: this.clock.now(),\n });\n }\n\n /**\n * The cached pause flags for a queue, with **no I/O**. Read on the hot path by every worker pump.\n * `null` when the queue has not been ensured in this process yet, which a worker never sees — it\n * awaits `ensure()` before its first pump.\n */\n pauseState(name: string): { processingPaused: boolean; acceptingPaused: boolean } | null {\n const entry = this.entries.get(name);\n if (!entry) return null;\n return {\n processingPaused: entry.row.processingPaused,\n acceptingPaused: entry.row.acceptingPaused,\n };\n }\n\n /** Overwrite the cached row from one a driver just returned (a pause/resume this process made). */\n update(row: QueueRow): void {\n const entry = this.entries.get(row.name);\n if (entry) {\n entry.row = row;\n entry.refreshedAt = this.clock.now();\n }\n }\n\n /** Re-read one queue's flags from the database. */\n async refresh(name: string): Promise<QueueRow | null> {\n const row = await this.driver.getQueueByName({ name });\n if (row) this.update(row);\n return row;\n }\n\n /**\n * Refresh every declared queue whose cached flags have gone stale. Driven by the maintenance tick,\n * so a pause made by another instance is observed within one tick interval.\n *\n * **One query for the whole set**, not one per queue: a process declaring 50 queues was issuing 50\n * `getQueueByName` calls every tick to read two booleans each. `listQueues` returns every row, and\n * the names this process cares about are already known here — so the tick costs one round trip\n * whatever the declaration count. A name whose row has since been removed simply keeps its cached\n * flags, exactly as the per-queue refresh did when it answered `null`.\n */\n async refreshStale(): Promise<void> {\n const now = this.clock.now();\n const stale = new Set(\n [...this.entries.entries()]\n .filter(([, entry]) => now - entry.refreshedAt >= this.staleAfterMs)\n .map(([name]) => name),\n );\n if (!stale.size) return;\n try {\n const rows = await this.driver.listQueues();\n for (const row of rows) if (stale.has(row.name)) this.update(row);\n } catch {\n // A transient read failure leaves the cached flags in place; the next tick tries again.\n }\n }\n\n /**\n * Whether this queue was declared in *this* process (via `createQueue`), whether or not its row\n * has been ensured yet. Used to block manual queue removal of an in-use queue: a running process\n * that still references the queue must not have it deleted from under it. Always false on a\n * headless client — an admin tool never owns a queue.\n */\n isRegistered(name: string): boolean {\n if (this.headless) return false;\n return this.entries.has(name) || this.pendingOptions.has(name) || this.ensuring.has(name);\n }\n}\n","/** Logical pub/sub channels. Never a string literal at a notify/subscribe site. */\nexport enum PubSubChannel {\n /** New/changed jobs — carries a lightweight `{ queue }` signal, never the payload. */\n JOBS = 'jobs',\n}\n","import type { Driver } from '../drivers/driver.interface';\nimport type { Logger } from '../logging/logger.interface';\nimport { PubSubChannel } from './channels';\n\n/**\n * Emits DB notifications on new/changed jobs. Notifications carry only\n * a lightweight signal (`{ queue, pattern? }`), never the payload. The optional preferred-instance\n * pattern lets subscribers skip waking for jobs they can't claim.\n */\nexport class NotifierService {\n constructor(\n private readonly driver: Driver,\n private readonly logger: Logger,\n private readonly capable: boolean,\n ) {}\n\n async notifyJobAdded(queue: string, preferredInstanceKeyPattern?: string | null): Promise<void> {\n if (!this.capable) return;\n try {\n const signal =\n preferredInstanceKeyPattern != null\n ? { queue, pattern: preferredInstanceKeyPattern }\n : { queue };\n await this.driver.notify({ channel: PubSubChannel.JOBS, payload: JSON.stringify(signal) });\n } catch (err) {\n this.logger.debug('notify failed (non-fatal; poll backstops).', { err, queue });\n }\n }\n}\n","import { CronExpressionParser } from 'cron-parser';\nimport { InvalidOptionsError } from '../errors/errors';\n\n/**\n * A thin wrapper over the `cron-parser` package — the parsing and the calendar walk are its job,\n * not ours. What this class adds is the two things core depends on:\n * - **eager validation** with a PortQueue-shaped `InvalidOptionsError`, so a bad expression fails\n * at `addJob` rather than silently at the first tick;\n * - a **plain epoch-ms `next()`**, so the scheduler never handles a library date type.\n *\n * Supported syntax is whatever `cron-parser` supports: 5-field\n * (minute hour day-of-month month day-of-week), an optional leading seconds field (6-field), plus\n * ranges, lists, steps, names (`MON`, `JAN`), and the specials `L`, `#`, `W`, `?`.\n *\n * `next-run` is computed in the schedule's IANA timezone (default UTC) and is DST-correct.\n *\n * Catch-up on restart: recurrences are **fire-once, no backfill**. If the process was down across\n * one or more due slots, on restart the schedule fires a single time and then advances to the next\n * future slot — every intermediate missed occurrence is skipped, not replayed. (See\n * `SchedulerService.fire`.)\n */\nexport class CronExpression {\n constructor(\n readonly expression: string,\n readonly timezone: string = 'UTC',\n ) {\n // Validate the timezone before the expression so an unknown zone gets its own clear message.\n try {\n new Intl.DateTimeFormat('en-US', { timeZone: timezone });\n } catch {\n throw new InvalidOptionsError(\n `Invalid timezone '${timezone}' for cron expression '${expression}'.`,\n );\n }\n // Parse once up front so a malformed expression is rejected at add time.\n this.parse(0);\n }\n\n /** The next fire time strictly after `fromMs` (epoch ms). */\n next(fromMs: number): number {\n try {\n return this.parse(fromMs).next().getTime();\n } catch (err) {\n throw new InvalidOptionsError(\n `Cron expression '${this.expression}' has no upcoming run (possibly an impossible date): ${messageOf(err)}`,\n );\n }\n }\n\n private parse(fromMs: number): ReturnType<typeof CronExpressionParser.parse> {\n try {\n return CronExpressionParser.parse(this.expression, {\n currentDate: new Date(fromMs),\n tz: this.timezone,\n });\n } catch (err) {\n throw new InvalidOptionsError(\n `Invalid cron expression '${this.expression}': ${messageOf(err)}. ` +\n `Expected 5 fields (minute hour day-of-month month day-of-week), ` +\n `or 6 with a leading seconds field.`,\n );\n }\n }\n}\n\nfunction messageOf(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import { JobStatus } from '../jobs/job-state.enum';\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { DeduplicationReason } from '../options/enums';\nimport { InvalidOptionsError, QueuePausedError } from '../errors/errors';\nimport { wholeSeconds, wholeSecondsToMs } from '../util/seconds';\nimport { DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT } from '../constants';\nimport { CronExpression } from '../scheduling/cron';\nimport type { AddJobOptions, CronSpec, ScheduleOptions } from '../options/job-options';\nimport type { AddJobResult, GetSchedulesQuery, Page, ScheduleInfo } from './results';\nimport type { NewJobRecord, NewScheduleRow, ScheduledJobOptions } from '../jobs/job-record';\nimport type { Runtime } from '../client/runtime';\nimport type { NotifierService } from '../pubsub/notifier.service';\n\n/**\n * Insert/dedup/schedule logic behind the producing half of `PortQueue`.\n *\n * Nothing here has a side effect a caller would not expect from its name: in particular the schedule\n * *reads* do not ensure a queue row, so listing the schedules of a name that was never used no\n * longer creates that queue.\n */\nexport class ProducerService {\n constructor(\n private readonly runtime: Runtime,\n private readonly notifier: NotifierService,\n ) {}\n\n async addJob<TData>(queue: string, options: AddJobOptions<TData>): Promise<AddJobResult> {\n const { registry, clock, driver, events, hooks } = this.runtime;\n const merged = await hooks.runBeforeAdd(queue, options as AddJobOptions<unknown>);\n const opts = merged as AddJobOptions<TData>;\n\n if (opts.schedule) this.rejectUnknownScheduleKeys(queue, opts.schedule);\n\n const isRecurring = opts.schedule?.startEverySeconds != null || opts.schedule?.cron != null;\n if (isRecurring && opts.schedule?.startAfterSeconds != null) {\n throw new InvalidOptionsError(\n `Cannot combine 'schedule.startAfterSeconds' with a recurring ` +\n `'schedule.startEverySeconds'/'schedule.cron' on queue '${queue}'. ` +\n `A start delay applies to a one-off job; recurring modes schedule repeated runs.`,\n { queue },\n );\n }\n\n const queueOptions = registry.getOptions(queue);\n\n // Idempotency dedup is queue-scoped and per-entity: a one-off add (no recurring options)\n // dedups against the jobs table; a recurring add dedups against the schedule table. Each key is\n // unique only within its own entity's table, so a one-off job and a schedule may share a key\n // without colliding. First writer wins within that table — a later add with the same key\n // returns the existing entity instead of creating a new one. (Jobs a schedule produces are\n // never stamped with the key, so a recurring schedule keeps producing every run.)\n if (opts.idempotencyKey != null) {\n const dup = await this.findIdempotencyDuplicate(\n queue,\n opts.idempotencyKey,\n isRecurring,\n opts.tx,\n );\n if (dup) {\n // Only a job match carries a jobId the JOB_ADDED event needs; a schedule match is silent.\n if (dup.jobId != null) {\n events.emit(PortQueueEvent.JOB_ADDED, { jobId: dup.jobId, queue, deduplicated: true });\n }\n await hooks.runAfterAdd(queue, dup);\n return dup;\n }\n }\n\n // Scheduling mode: create a recurring definition instead of a one-off insert.\n if (isRecurring) {\n const result = await this.createSchedule(queue, opts);\n await hooks.runAfterAdd(queue, result);\n return result;\n }\n\n const row = await registry.ensure(queue);\n if (row.acceptingPaused) throw new QueuePausedError(queue);\n\n const now = clock.now();\n const job = this.buildJob(queue, opts, queueOptions, now);\n const inserted = await driver.insertJob({ job, ...(opts.tx ? { tx: opts.tx } : {}) });\n\n const result: AddJobResult = {\n jobId: inserted.id,\n queue,\n status: inserted.status,\n startAfter: new Date(inserted.startAfter),\n deduplicated: inserted.deduplicated,\n ...(inserted.deduplicationReason\n ? { deduplicationReason: inserted.deduplicationReason }\n : {}),\n };\n\n if (!inserted.deduplicated) {\n this.announce(queue, [job.preferredInstanceKeyPattern], opts.tx);\n }\n events.emit(PortQueueEvent.JOB_ADDED, {\n jobId: inserted.id,\n queue,\n deduplicated: inserted.deduplicated,\n });\n\n await hooks.runAfterAdd(queue, result);\n return result;\n }\n\n /**\n * Add many one-off jobs to one queue in a **single** insert.\n *\n * This is the batch path `Driver.insertJobs` exists for: one dedup lookup and one multi-row insert\n * for the whole set, rather than the two round trips per job a loop over {@link addJob} costs.\n *\n * Recurring options are rejected here rather than silently ignored — a batch of schedules is a\n * different operation, and each recurrence needs its own `addJob` so its result carries a\n * `scheduleId`. BEFORE_ADD/AFTER_ADD hooks still run per job, in order, exactly as they do for a\n * single add.\n *\n * **The batch is validated before any hook runs.** A hook is allowed to have a side effect (the\n * documented use is enriching options, but nothing enforces purity), and the checks below reject\n * the whole call — so running hooks first fired them for jobs that were never going to be\n * inserted.\n */\n async addJobs<TData>(queue: string, jobs: Array<AddJobOptions<TData>>): Promise<AddJobResult[]> {\n const { registry, clock, driver, events, hooks } = this.runtime;\n if (!jobs.length) return [];\n\n this.validateBatch(queue, jobs);\n // One transaction has to be shared by every entry, so a batch cannot mix caller transactions.\n const tx = jobs.find((opts) => opts.tx)?.tx;\n\n const prepared: Array<AddJobOptions<TData>> = [];\n for (const options of jobs) {\n const opts = (await hooks.runBeforeAdd(\n queue,\n options as AddJobOptions<unknown>,\n )) as AddJobOptions<TData>;\n // A hook may have introduced a recurrence, so the shape is checked again on what it returned.\n this.rejectRecurring(queue, opts);\n prepared.push(opts);\n }\n\n const row = await registry.ensure(queue);\n if (row.acceptingPaused) throw new QueuePausedError(queue);\n\n const now = clock.now();\n const queueOptions = registry.getOptions(queue);\n const records = prepared.map((opts) => this.buildJob(queue, opts, queueOptions, now));\n const inserted = await driver.insertJobs({ jobs: records, ...(tx ? { tx } : {}) });\n\n const results: AddJobResult[] = inserted.map((entry) => ({\n jobId: entry.id,\n queue,\n status: entry.status,\n startAfter: new Date(entry.startAfter),\n deduplicated: entry.deduplicated,\n ...(entry.deduplicationReason ? { deduplicationReason: entry.deduplicationReason } : {}),\n }));\n\n const freshPatterns = records\n .filter((_, index) => !inserted[index]!.deduplicated)\n .map((record) => record.preferredInstanceKeyPattern);\n if (freshPatterns.length) this.announce(queue, freshPatterns, tx);\n\n // Event then hook, per job — the same order `addJob` uses. Two sequential loops emitted every\n // event before any hook ran, so a caller listening to both saw a different ordering from a batch\n // than from a single add.\n for (const result of results) {\n events.emit(PortQueueEvent.JOB_ADDED, {\n jobId: result.jobId!,\n queue,\n deduplicated: result.deduplicated,\n });\n await hooks.runAfterAdd(queue, result);\n }\n return results;\n }\n\n /**\n * Reject a batch whose shape is wrong, before a single hook has run: an entry asking for a\n * recurrence, or entries carrying different transactions.\n */\n private validateBatch<TData>(queue: string, jobs: Array<AddJobOptions<TData>>): void {\n for (const opts of jobs) this.rejectRecurring(queue, opts);\n const tx = jobs.find((opts) => opts.tx)?.tx;\n if (tx && jobs.some((opts) => opts.tx && opts.tx !== tx)) {\n throw new InvalidOptionsError(\n `addJobs on queue '${queue}' received more than one distinct 'tx'. A batch is one insert, ` +\n `so every entry must share the same transaction (or none of them set one).`,\n { queue },\n );\n }\n }\n\n /** One entry's schedule keys: known, and not a recurrence (which `addJobs` cannot express). */\n private rejectRecurring<TData>(queue: string, opts: AddJobOptions<TData>): void {\n if (!opts.schedule) return;\n this.rejectUnknownScheduleKeys(queue, opts.schedule);\n if (opts.schedule.startEverySeconds != null || opts.schedule.cron != null) {\n throw new InvalidOptionsError(\n `addJobs on queue '${queue}' cannot create recurring jobs: one of the entries sets ` +\n `'schedule.cron'/'schedule.startEverySeconds'. Add each recurrence with addJob, whose ` +\n `result carries the scheduleId a batch insert has no place to return.`,\n { queue },\n );\n }\n }\n\n /** Resolve one job's options into the row to insert. */\n private buildJob<TData>(\n queue: string,\n opts: AddJobOptions<TData>,\n queueOptions: ReturnType<Runtime['registry']['getOptions']>,\n now: number,\n ): NewJobRecord {\n const affinity = this.resolveAffinity(queue, opts as AddJobOptions<unknown>);\n const resolved = this.runtime.resolver.resolve({\n job: opts,\n ...(queueOptions.defaultJobOptions ? { queueDefaults: queueOptions.defaultJobOptions } : {}),\n ...(queueOptions.retention ? { queueRetention: queueOptions.retention } : {}),\n ...(opts.schedule?.startAfterSeconds != null\n ? { startAfterSeconds: opts.schedule.startAfterSeconds }\n : {}),\n now,\n });\n return {\n queueName: queue,\n status: JobStatus.PENDING,\n priority: resolved.priority,\n data: opts.data,\n startAfter: resolved.startAfter,\n expireAt: resolved.expireAt,\n retryAttempt: 0,\n retryMaxAttempts: resolved.retryMaxAttempts,\n retryDelaySeconds: resolved.retryDelaySeconds,\n retryBackoff: resolved.retryBackoff,\n retryBackoffFactor: resolved.retryBackoffFactor,\n retryMaxDelaySeconds: resolved.retryMaxDelaySeconds,\n retryJitter: resolved.retryJitter,\n retentionTtlSeconds: resolved.retentionTtlSeconds,\n retentionStatuses: resolved.retentionStatuses,\n idempotencyKey: resolved.idempotencyKey,\n scheduleId: null,\n singletonKey: resolved.singletonKey,\n preferredInstanceKeyPattern: affinity.preferredInstanceKeyPattern,\n createdAt: now,\n };\n }\n\n /**\n * Wake local workers and NOTIFY the cluster that new work landed. With a caller transaction the\n * announcement is deferred to commit, so a rolled-back insert never wakes anyone.\n */\n private announce(\n queue: string,\n patterns: Array<string | null>,\n tx: AddJobOptions<unknown>['tx'],\n ): void {\n const fire = (): void => {\n this.runtime.wakeup.signal(queue);\n // One NOTIFY per distinct affinity pattern: a listener filters on it, so collapsing them\n // would tell the wrong instances to wake.\n for (const pattern of new Set(patterns)) {\n this.runtime.background.run(() => this.notifier.notifyJobAdded(queue, pattern));\n }\n };\n if (tx?.onCommit) tx.onCommit(fire);\n else if (!tx) fire();\n }\n\n /**\n * Validate and normalize the multi-instance affinity option. Affinity is only meaningful when\n * this PortQueue declared an `instanceKey`; a job targets instances by a single regex pattern.\n */\n private resolveAffinity(\n queue: string,\n opts: AddJobOptions<unknown>,\n ): {\n preferredInstanceKeyPattern: string | null;\n } {\n const { preferredInstanceKeyPattern } = opts;\n if (preferredInstanceKeyPattern != null && !this.runtime.instanceKey) {\n throw new InvalidOptionsError(\n `Job on queue '${queue}' sets 'preferredInstanceKeyPattern', but this process has no ` +\n `instance key. Pass \\`instance: { instanceKey }\\` to the PortQueue constructor to name it.`,\n { queue },\n );\n }\n if (preferredInstanceKeyPattern != null) {\n try {\n new RegExp(preferredInstanceKeyPattern);\n } catch (err) {\n throw new InvalidOptionsError(\n `Job on queue '${queue}' has an invalid 'preferredInstanceKeyPattern' regular expression: ${String(err)}`,\n { queue },\n );\n }\n }\n return { preferredInstanceKeyPattern: preferredInstanceKeyPattern ?? null };\n }\n\n /**\n * The idempotency lookup behind {@link addJob}. A one-off add checks the jobs table; a recurring\n * add checks the schedule table — a key is unique only within its own entity's table. Returns a\n * deduplicated result shaped for the matched entity, or null when the key is free in that table.\n */\n private async findIdempotencyDuplicate(\n queue: string,\n idempotencyKey: string,\n isRecurring: boolean,\n tx?: AddJobOptions<unknown>['tx'],\n ): Promise<AddJobResult | null> {\n const { driver } = this.runtime;\n if (isRecurring) {\n const schedule = await driver.findScheduleByIdempotencyKey({\n queueName: queue,\n idempotencyKey,\n ...(tx ? { tx } : {}),\n });\n if (!schedule) return null;\n return {\n queue,\n scheduleId: schedule.id,\n nextRunAt: schedule.nextRunAt != null ? new Date(schedule.nextRunAt) : null,\n deduplicated: true,\n deduplicationReason: DeduplicationReason.IDEMPOTENCY,\n };\n }\n const job = await driver.findJobByIdempotencyKey({\n queueName: queue,\n idempotencyKey,\n ...(tx ? { tx } : {}),\n });\n if (!job) return null;\n return {\n jobId: job.id,\n queue,\n status: job.status,\n startAfter: new Date(job.startAfter),\n deduplicated: true,\n deduplicationReason: DeduplicationReason.IDEMPOTENCY,\n };\n }\n\n private async createSchedule<TData>(\n queue: string,\n opts: AddJobOptions<TData>,\n ): Promise<AddJobResult> {\n this.validateSchedule(queue, opts);\n const { registry, driver, clock, resolver, events } = this.runtime;\n await registry.ensure(queue);\n const queueOptions = registry.getOptions(queue);\n const affinity = this.resolveAffinity(queue, opts);\n const now = clock.now();\n const resolved = resolver.resolve({\n job: opts,\n ...(queueOptions.defaultJobOptions ? { queueDefaults: queueOptions.defaultJobOptions } : {}),\n ...(queueOptions.retention ? { queueRetention: queueOptions.retention } : {}),\n now,\n });\n const cron = opts.schedule?.cron != null ? normalizeCron(opts.schedule.cron) : null;\n const everySeconds =\n opts.schedule?.startEverySeconds != null\n ? wholeSeconds(opts.schedule.startEverySeconds, 'schedule.startEverySeconds')\n : null;\n // No pattern-based dedup: identical recurrences on a queue are allowed to coexist. When the\n // caller wants exactly one, they pass an idempotencyKey — that dedup ran in addJob() above, so\n // reaching here means the key was free (or absent) and we always insert a fresh schedule.\n const nextRunAt = this.computeNextRun(opts.schedule!, now);\n\n // Every option that shapes the *produced* jobs (beyond the columns below) rides along with the\n // schedule and is stamped onto each run — the schedule row itself is never expired/retained by\n // these; they govern the spawned jobs. `expireInSeconds` is stored as a duration and re-applied\n // relative to each run's fire time. See {@link ScheduledJobOptions}.\n const jobOptions: ScheduledJobOptions = {\n expireInSeconds:\n opts.expireInSeconds != null ? wholeSeconds(opts.expireInSeconds, 'expireInSeconds') : null,\n retryBackoff: resolved.retryBackoff,\n retryBackoffFactor: resolved.retryBackoffFactor,\n retryMaxDelaySeconds: resolved.retryMaxDelaySeconds,\n retryJitter: resolved.retryJitter,\n retentionTtlSeconds: resolved.retentionTtlSeconds,\n retentionStatuses: resolved.retentionStatuses,\n singletonKey: resolved.singletonKey,\n preferredInstanceKeyPattern: affinity.preferredInstanceKeyPattern,\n };\n\n const newSchedule: NewScheduleRow = {\n queueName: queue,\n cron: cron?.pattern ?? null,\n everySeconds,\n timezone: cron?.tz ?? null,\n data: opts.data,\n priority: resolved.priority,\n retryMaxAttempts: resolved.retryMaxAttempts,\n retryDelaySeconds: resolved.retryDelaySeconds,\n nextRunAt,\n enabled: true,\n idempotencyKey: resolved.idempotencyKey,\n jobOptions,\n };\n const saved = await driver.insertSchedule({\n schedule: newSchedule,\n ...(opts.tx ? { tx: opts.tx } : {}),\n });\n events.emit(PortQueueEvent.SCHEDULE_CREATED, {\n scheduleId: saved.id,\n queue,\n });\n return {\n queue,\n scheduleId: saved.id,\n nextRunAt: saved.nextRunAt != null ? new Date(saved.nextRunAt) : null,\n deduplicated: false,\n };\n }\n\n /**\n * Reject any key the `schedule` group doesn't define. Without this an unknown key — a typo, or an\n * option that no longer exists like the old absolute-`Date` `startAfter` — is silently dropped and\n * the job runs immediately, which looks like the scheduler losing it. TypeScript already catches\n * this; the check is for JavaScript callers and hand-built payloads.\n */\n private rejectUnknownScheduleKeys(queue: string, schedule: ScheduleOptions): void {\n const allowed: ReadonlySet<string> = new Set<keyof ScheduleOptions>([\n 'startAfterSeconds',\n 'startEverySeconds',\n 'cron',\n ]);\n const unknown = Object.keys(schedule).filter((key) => !allowed.has(key));\n if (unknown.length > 0) {\n throw new InvalidOptionsError(\n `Unknown 'schedule' option${unknown.length > 1 ? 's' : ''} on queue '${queue}': ` +\n `${unknown.map((k) => `'${k}'`).join(', ')}. Valid keys are 'startAfterSeconds' (a ` +\n `one-off delay in seconds), 'startEverySeconds' (a recurring interval in seconds) and ` +\n `'cron'. Every duration is a whole number of seconds; there is no absolute-Date form.`,\n { queue },\n );\n }\n }\n\n private validateSchedule(queue: string, opts: AddJobOptions<unknown>): void {\n if (opts.schedule?.cron != null && opts.schedule?.startEverySeconds != null) {\n throw new InvalidOptionsError(\n `A recurring job on queue '${queue}' must set exactly one of 'schedule.cron' or 'schedule.startEverySeconds' — not both.`,\n { queue },\n );\n }\n }\n\n computeNextRun(schedule: ScheduleOptions, now: number): number {\n if (schedule.cron != null) {\n const { pattern, tz } = normalizeCron(schedule.cron);\n return new CronExpression(pattern, tz).next(now);\n }\n return now + wholeSecondsToMs(schedule.startEverySeconds!, 'schedule.startEverySeconds');\n }\n\n /**\n * A page of schedules — one queue's when `queue` is given, every queue's otherwise. Filtering and\n * paging both happen in the database; the count is a second query rather than a JOIN or a\n * whole-table read. **This is a read and behaves like one:** it does not ensure the queue row, so\n * listing the schedules of a name that was never used does not create it.\n */\n async getSchedules(query: GetSchedulesQuery = {}): Promise<Page<ScheduleInfo>> {\n const limit = Math.min(\n Math.max(Math.trunc(query.limit ?? DEFAULT_PAGE_LIMIT), 1),\n MAX_PAGE_LIMIT,\n );\n const offset = Math.max(Math.trunc(query.offset ?? 0), 0);\n const filter = {\n ...(query.queue ? { queueName: query.queue } : {}),\n ...(query.enabled !== undefined ? { enabled: query.enabled } : {}),\n };\n const [rows, total] = await Promise.all([\n this.runtime.driver.listSchedules({ ...filter, limit, offset }),\n this.runtime.driver.countSchedules(filter),\n ]);\n return { items: rows.map((s) => toScheduleInfo(s)), total };\n }\n\n /** One schedule by id, or null when no schedule has that id. */\n async getSchedule(scheduleId: string): Promise<ScheduleInfo | null> {\n const row = await this.runtime.driver.getSchedule({ scheduleId });\n return row ? toScheduleInfo(row) : null;\n }\n}\n\n/** Map a schedule row to the public {@link ScheduleInfo}. */\nfunction toScheduleInfo(s: {\n id: string;\n queueName: string;\n cron: string | null;\n everySeconds: number | null;\n timezone: string | null;\n nextRunAt: number | null;\n lastRunAt: number | null;\n enabled: boolean;\n idempotencyKey: string | null;\n}): ScheduleInfo {\n return {\n scheduleId: s.id,\n queue: s.queueName,\n cron: s.cron,\n everySeconds: s.everySeconds,\n timezone: s.timezone,\n nextRunAt: s.nextRunAt != null ? new Date(s.nextRunAt) : null,\n lastRunAt: s.lastRunAt != null ? new Date(s.lastRunAt) : null,\n enabled: s.enabled,\n idempotencyKey: s.idempotencyKey,\n };\n}\n\n/** Normalize a {@link CronSpec} (string or `{ pattern, tz }`) to a pattern + IANA tz. */\nfunction normalizeCron(cron: CronSpec): { pattern: string; tz: string } {\n if (typeof cron === 'string') return { pattern: cron, tz: 'UTC' };\n return { pattern: cron.pattern, tz: cron.tz ?? 'UTC' };\n}\n","import type { JobRecord } from './job-record';\nimport type { JobSnapshot } from '../producer/results';\nimport { JobStatus } from './job-state.enum';\n\nconst d = (ms: number | null | undefined): Date | null => (ms == null ? null : new Date(ms));\n\n/** Map an internal {@link JobRecord} to a public {@link JobSnapshot}. */\nexport function toSnapshot<TData = unknown>(\n record: JobRecord,\n queueName: string,\n now: number,\n): JobSnapshot<TData> {\n const stalled =\n record.status === JobStatus.ACTIVE && record.lockedUntil != null && record.lockedUntil < now;\n return {\n id: record.id,\n queue: queueName,\n status: record.status,\n data: record.data as TData,\n returnValue: record.returnValue,\n priority: record.priority,\n retryAttempt: record.retryAttempt,\n retryMaxAttempts: record.retryMaxAttempts,\n createdAt: new Date(record.createdAt),\n updatedAt: new Date(record.updatedAt),\n startAfter: new Date(record.startAfter),\n startedAt: d(record.startedAt),\n completedAt: d(record.completedAt),\n failedAt: d(record.failedAt),\n cancelledAt: d(record.cancelledAt),\n expiredAt: d(record.expiredAt),\n retriedAt: d(record.retriedAt),\n stalledAt: d(record.stalledAt),\n lockedUntil: d(record.lockedUntil),\n preferredInstanceKeyPattern: record.preferredInstanceKeyPattern,\n processedOnInstanceKey: record.processedOnInstanceKey,\n failureMessage: record.failureMessage,\n idempotencyKey: record.idempotencyKey,\n scheduleId: record.scheduleId,\n stalled,\n };\n}\n","import { emptyStatusCounts, JobStatus } from '../jobs/job-state.enum';\nimport { toSnapshot } from '../jobs/snapshot';\nimport { secondsToMs } from '../util/seconds';\nimport {\n DEFAULT_HEARTBEAT_INTERVAL_SECONDS,\n DEFAULT_PAGE_LIMIT,\n HEARTBEAT_STALE_BEATS,\n MAX_PAGE_LIMIT,\n} from '../constants';\nimport type { Runtime } from '../client/runtime';\nimport type { InstanceRow, QueueRow } from '../jobs/job-record';\nimport type { JobListFilter } from '../drivers/driver.interface';\nimport type { PortQueueOptions } from '../options/client-options';\nimport type {\n GetInstancesQuery,\n GetJobsQuery,\n GetQueuesQuery,\n InstanceInfo,\n JobSnapshot,\n Page,\n QueueInfo,\n QueueStats,\n} from '../producer/results';\n\n/**\n * How long an instance may go unheard-from before it counts as stale: {@link HEARTBEAT_STALE_BEATS}\n * heartbeats, so a single missed beat (a slow query, a GC pause) doesn't flip a healthy instance.\n *\n * Exported because the dashboard facade needs the identical window to build the same `alive` flag —\n * this policy used to live as a literal `15` and a literal `× 3` in four separate files.\n */\nexport function instanceStaleAfterMs(options: PortQueueOptions): number {\n const beatSeconds =\n options.instance?.heartbeatIntervalSeconds ?? DEFAULT_HEARTBEAT_INTERVAL_SECONDS;\n return secondsToMs(beatSeconds * HEARTBEAT_STALE_BEATS, 'instance.heartbeatIntervalSeconds');\n}\n\n/**\n * Map an `instance` row to the public {@link InstanceInfo}. One mapper, used by both the public read\n * and the dashboard facade — the two used to build byte-identical objects from their own copies of\n * the same liveness arithmetic.\n */\nexport function toInstanceInfo(\n row: InstanceRow,\n counts: Record<JobStatus, number> | undefined,\n seenSince: number,\n): InstanceInfo {\n return {\n instanceKey: row.instanceKey,\n processingPaused: row.processingPaused,\n alive: row.lastSeenAt >= seenSince,\n createdAt: new Date(row.createdAt),\n updatedAt: new Date(row.updatedAt),\n lastSeenAt: new Date(row.lastSeenAt),\n cpuPercent: row.cpuPercent,\n memoryPercent: row.memoryPercent,\n counts: counts ?? emptyStatusCounts(),\n };\n}\n\n/** Map a `queue` row to the public {@link QueueInfo}. */\nexport function toQueueInfo(\n row: QueueRow,\n counts: Record<JobStatus, number> | undefined,\n inUse: boolean,\n): QueueInfo {\n return {\n name: row.name,\n processingPaused: row.processingPaused,\n acceptingPaused: row.acceptingPaused,\n counts: counts ?? emptyStatusCounts(),\n inUse,\n };\n}\n\n/** Clamp a caller-supplied page window to something the database is happy to serve. */\nexport function pageWindow(\n query: { limit?: number; offset?: number },\n maxLimit = MAX_PAGE_LIMIT,\n): { limit: number; offset: number } {\n return {\n limit: Math.min(Math.max(Math.trunc(query.limit ?? DEFAULT_PAGE_LIMIT), 1), maxLimit),\n offset: Math.max(Math.trunc(query.offset ?? 0), 0),\n };\n}\n\n/**\n * Read-side aggregations for the API, dashboard, and CLI. A job carries its\n * `queueName` directly, so there is no id→name lookup and never a JOIN.\n */\nexport class ReadService {\n constructor(private readonly runtime: Runtime) {}\n\n async getJob<TData = unknown>(jobId: string): Promise<JobSnapshot<TData> | null> {\n const record = await this.runtime.driver.getJob({ jobId });\n if (!record) return null;\n return toSnapshot<TData>(record, record.queueName, this.runtime.clock.now());\n }\n\n /**\n * A page of jobs, newest first.\n *\n * `instanceKey` and `search` are not part of the public `GetJobsQuery` — they are here for the\n * dashboard facade, whose instance detail view reads jobs by the instance that claimed them and\n * whose table offers a free-text filter. Both are pushed into SQL, so a search pages in the\n * database rather than streaming the table into this process.\n */\n async getJobs<TData = unknown>(\n query: GetJobsQuery & { instanceKey?: string; search?: string },\n ): Promise<Page<JobSnapshot<TData>>> {\n const { limit, offset } = pageWindow(query);\n const filter: JobListFilter = {\n ...(query.queue ? { queueName: query.queue } : {}),\n ...(query.statuses ? { statuses: query.statuses } : {}),\n ...(query.scheduleId ? { scheduleId: query.scheduleId } : {}),\n ...(query.instanceKey ? { processedOnInstanceKey: query.instanceKey } : {}),\n ...(query.search ? { search: query.search } : {}),\n };\n // `total` is a real `COUNT` over the same predicate as the page, always. It used to be inferred\n // from the page when nothing followed it — `offset + page.length` — which is only the count of\n // anything on a forward walk: jumping straight to `offset: 1000` on a 20-row table reported\n // `total: 1000`. Both the dashboard's pagination and the CLI's \"… more\" hint read this number.\n const [records, total] = await Promise.all([\n this.runtime.driver.getJobs({ ...filter, limit, offset }),\n this.runtime.driver.countJobs(filter),\n ]);\n const now = this.runtime.clock.now();\n return { items: records.map((r) => toSnapshot<TData>(r, r.queueName, now)), total };\n }\n\n async getQueueStats(queue?: string): Promise<QueueStats> {\n const counts = await this.runtime.driver.countJobsByStatus(queue ? { queueName: queue } : {});\n return { ...(queue ? { queue } : {}), counts };\n }\n\n /**\n * A page of queues with their per-status counts, plus the total across every page. Same\n * `limit`/`offset` window as the job, schedule and instance reads.\n */\n async getQueues(query: GetQueuesQuery = {}): Promise<Page<QueueInfo>> {\n const { limit, offset } = pageWindow(query);\n // The filter goes to both calls, so the page and its total can never disagree about what they\n // are describing — and a caller looking for paused queues narrows in SQL instead of paging the\n // whole table and filtering here.\n const filter = {\n ...(query.search ? { search: query.search } : {}),\n ...(query.processingPaused !== undefined ? { processingPaused: query.processingPaused } : {}),\n };\n const [rows, total] = await Promise.all([\n this.runtime.driver.listQueues({ ...filter, limit, offset }),\n this.runtime.driver.countQueues(filter),\n ]);\n if (!rows.length) return { items: [], total };\n // One grouped count for the whole page rather than a query per queue.\n const counts = await this.runtime.driver.countJobsByStatusPerQueue({\n queueNames: rows.map((r) => r.name),\n });\n return {\n items: rows.map((row) =>\n toQueueInfo(row, counts[row.name], this.runtime.registry.isRegistered(row.name)),\n ),\n total,\n };\n }\n\n /** One queue by name, with the same counts and `inUse` flag the list carries. Null if unknown. */\n async getQueue(name: string): Promise<QueueInfo | null> {\n const row = await this.runtime.driver.getQueueByName({ name });\n if (!row) return null;\n const counts = await this.runtime.driver.countJobsByStatusPerQueue({ queueNames: [row.name] });\n return toQueueInfo(row, counts[row.name], this.runtime.registry.isRegistered(row.name));\n }\n\n /**\n * A page of instances with liveness and per-instance job attribution, plus the total across\n * every page. Same `limit`/`offset` window as the job and schedule reads.\n */\n async getInstances(query: GetInstancesQuery = {}): Promise<Page<InstanceInfo>> {\n const { limit, offset } = pageWindow(query);\n const filter = {\n ...(query.search ? { search: query.search } : {}),\n ...(query.processingPaused !== undefined ? { processingPaused: query.processingPaused } : {}),\n ...(query.alive !== undefined\n ? {\n alive: query.alive,\n seenSince: this.runtime.clock.now() - instanceStaleAfterMs(this.runtime.options),\n }\n : {}),\n };\n const [rows, total] = await Promise.all([\n this.runtime.driver.listInstances({ ...filter, limit, offset }),\n this.runtime.driver.countInstances(filter),\n ]);\n if (!rows.length) return { items: [], total };\n const seenSince = this.runtime.clock.now() - instanceStaleAfterMs(this.runtime.options);\n // One grouped count for the whole page rather than a query per instance.\n const counts = await this.runtime.driver.countJobsByStatusPerInstance({\n instanceKeys: rows.map((r) => r.instanceKey),\n });\n return {\n items: rows.map((row) => toInstanceInfo(row, counts[row.instanceKey], seenSince)),\n total,\n };\n }\n\n /** One instance by key, with the same liveness, health and attribution the list carries. */\n async getInstance(instanceKey: string): Promise<InstanceInfo | null> {\n const row = await this.runtime.driver.getInstance({ instanceKey });\n if (!row) return null;\n const seenSince = this.runtime.clock.now() - instanceStaleAfterMs(this.runtime.options);\n const counts = await this.runtime.driver.countJobsByStatusPerInstance({\n instanceKeys: [row.instanceKey],\n });\n return toInstanceInfo(row, counts[row.instanceKey], seenSince);\n }\n}\n\nexport { JobStatus };\n","import { BackoffStrategy } from '../options/enums';\nimport { DEFAULT_BACKOFF_FACTOR } from '../constants';\n\nexport interface BackoffInput {\n strategy: BackoffStrategy;\n /** The attempt number that just failed (1-based). */\n attempt: number;\n /** Base delay in seconds. */\n baseDelaySeconds: number;\n /** Growth factor for EXPONENTIAL (ignored for FIXED). */\n factor?: number | null;\n /** Cap on the computed delay, in seconds. */\n maxDelaySeconds?: number | null;\n /** Whether to apply jitter. */\n jitter?: boolean;\n /** Random source in [0,1) — injectable for deterministic tests. */\n random?: () => number;\n}\n\n/**\n * Compute the delay in **seconds** before the next retry. Fractions are preserved — the caller\n * converts to the epoch-ms instant, so rounding here would quantise sub-second retries away.\n * - FIXED: `baseDelaySeconds` each time.\n * - EXPONENTIAL: `baseDelaySeconds * factor^(attempt-1)`, capped at `maxDelaySeconds`.\n * Optional full jitter multiplies the result by a random factor in [0,1].\n */\nexport function computeBackoffSeconds(input: BackoffInput): number {\n const { strategy, attempt, baseDelaySeconds } = input;\n const factor = input.factor ?? DEFAULT_BACKOFF_FACTOR;\n let delay: number;\n if (strategy === BackoffStrategy.EXPONENTIAL) {\n delay = baseDelaySeconds * Math.pow(factor, Math.max(0, attempt - 1));\n } else {\n delay = baseDelaySeconds;\n }\n if (input.maxDelaySeconds != null) {\n delay = Math.min(delay, input.maxDelaySeconds);\n }\n if (input.jitter) {\n const rand = input.random ?? Math.random;\n // Full jitter: uniform in [0, delay].\n delay = delay * rand();\n }\n return Math.max(0, delay);\n}\n","import { JobStatus } from '../jobs/job-state.enum';\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { computeBackoffSeconds } from '../util/backoff';\nimport { msToSeconds, secondsToMs } from '../util/seconds';\nimport { LockLostError } from '../errors/errors';\nimport {\n DEFAULT_FAILURE_DETAIL,\n FAILURE_MESSAGE_MAX_CHARS,\n FAILURE_MESSAGE_TRUNCATION_SUFFIX,\n} from '../constants';\nimport { FailureDetail } from '../options/enums';\nimport type { ErrorClass } from '../options/queue-options';\nimport type { JobRecord } from '../jobs/job-record';\nimport type { Runtime } from '../client/runtime';\nimport type { ProcessOutcome } from '../events/hooks';\n\n/**\n * Marks complete/failed/retry atomically and emits the matching event.\n *\n * Every write is fenced on the claim the run was made under (`record.lockToken`), and the driver\n * reports whether the row was actually settled. When it was not — the lock lapsed, another worker\n * reclaimed the row and is running the job now — this run's outcome is **not** the job's outcome, so\n * no lifecycle event is emitted for it and the `ERROR` event carries a {@link LockLostError}\n * instead. Emitting `JOB_COMPLETED` there would tell every listener a job had finished while its\n * second run was still going.\n */\nexport class CompletionService {\n constructor(private readonly runtime: Runtime) {}\n\n async complete(\n record: JobRecord,\n queueName: string,\n returnValue: unknown,\n startTs: number,\n ): Promise<ProcessOutcome> {\n const now = this.runtime.clock.now();\n const settled = await this.runtime.driver.completeJob({\n jobId: record.id,\n returnValue,\n now,\n lockToken: record.lockToken,\n });\n if (!settled) return this.claimLost(record, queueName, { kind: 'completed', returnValue });\n this.runtime.events.emit(PortQueueEvent.JOB_COMPLETED, {\n jobId: record.id,\n queue: queueName,\n returnValue,\n durationSeconds: msToSeconds(now - startTs),\n });\n return { kind: 'completed', returnValue };\n }\n\n /** Decide retry-vs-fail after a handler throw. */\n async failOrRetry(\n record: JobRecord,\n queueName: string,\n error: unknown,\n dontAutoretryFor: Array<ErrorClass | string>,\n failureDetail: FailureDetail = DEFAULT_FAILURE_DETAIL,\n ): Promise<ProcessOutcome> {\n const now = this.runtime.clock.now();\n const message = errorToMessage(error, failureDetail);\n const attemptsMade = record.retryAttempt + 1;\n const nonRetryable = matchesNonRetryable(error, dontAutoretryFor);\n const canRetry = !nonRetryable && attemptsMade < record.retryMaxAttempts;\n\n if (canRetry) {\n const delaySeconds = computeBackoffSeconds({\n strategy: record.retryBackoff,\n attempt: attemptsMade,\n baseDelaySeconds: record.retryDelaySeconds,\n factor: record.retryBackoffFactor,\n maxDelaySeconds: record.retryMaxDelaySeconds,\n jitter: record.retryJitter,\n });\n const nextRunAt = now + Math.round(secondsToMs(delaySeconds, 'retry delay'));\n const outcome: ProcessOutcome = { kind: 'retry', error, nextRunAt: new Date(nextRunAt) };\n const armed = await this.runtime.driver.retryJob({\n jobId: record.id,\n nextRunAt,\n retryAttempt: attemptsMade,\n lastError: message,\n now,\n lockToken: record.lockToken,\n });\n if (!armed) return this.claimLost(record, queueName, outcome);\n this.runtime.events.emit(PortQueueEvent.JOB_RETRYING, {\n jobId: record.id,\n queue: queueName,\n retryAttempt: attemptsMade,\n nextRunAt: new Date(nextRunAt),\n });\n // Wake the loop; the claim query still gates on start_after so a delayed retry waits.\n this.runtime.wakeup.signal(queueName);\n return outcome;\n }\n\n const failed = await this.runtime.driver.failJob({\n jobId: record.id,\n lastError: message,\n now,\n lockToken: record.lockToken,\n });\n if (!failed) return this.claimLost(record, queueName, { kind: 'failed', error });\n this.runtime.events.emit(PortQueueEvent.JOB_FAILED, {\n jobId: record.id,\n queue: queueName,\n error,\n retryAttempt: record.retryAttempt,\n });\n return { kind: 'failed', error };\n }\n\n /**\n * Report a settle the row refused, and hand back the outcome unchanged.\n *\n * The outcome still describes what *this handler* did, which is what an `AFTER_PROCESS` hook is\n * asking about; what it no longer describes is the row, so nothing is emitted for the job.\n */\n private claimLost(record: JobRecord, queueName: string, outcome: ProcessOutcome): ProcessOutcome {\n this.runtime.events.emit(PortQueueEvent.ERROR, {\n error: new LockLostError(record.id, queueName),\n source: 'completion',\n });\n return outcome;\n }\n}\n\n/**\n * Normalize any thrown value to the message stored on the row, **truncated**.\n *\n * Includes the stack by default, because that is what anyone diagnosing a failure opens the job to\n * read. A stack from a deep async chain runs to tens of kilobytes, so it is capped — and a queue that\n * fails often and predictably can drop the frames altogether with\n * `createQueue({ failureDetail: FailureDetail.MESSAGE })`, since even the capped form is ~4 KB on\n * every failed row.\n */\nexport function errorToMessage(\n error: unknown,\n detail: FailureDetail = DEFAULT_FAILURE_DETAIL,\n): string {\n return truncate(rawErrorMessage(error, detail));\n}\n\nfunction rawErrorMessage(error: unknown, detail: FailureDetail): string {\n if (error instanceof Error) {\n const named = `${error.name}: ${error.message}`;\n // `MESSAGE` is the choice a queue makes when its handler fails often: the frames are noise, and\n // ~4 KB per failed row is not.\n if (detail === FailureDetail.MESSAGE) return named;\n return error.stack ?? named;\n }\n if (typeof error === 'string') return error;\n try {\n return JSON.stringify(error) ?? String(error);\n } catch {\n return String(error);\n }\n}\n\n/**\n * Cut a message to the cap **on a code-point boundary**.\n *\n * `slice` counts UTF-16 code units, so cutting mid-surrogate-pair stores a lone surrogate — which is\n * not valid text, and which some engines (Oracle in particular) refuse on write. An emoji or a\n * non-BMP character landing exactly on the boundary is enough to hit it. Dropping the trailing high\n * surrogate keeps the message one character shorter and always writable.\n */\nfunction truncate(message: string): string {\n if (message.length <= FAILURE_MESSAGE_MAX_CHARS) return message;\n let end = FAILURE_MESSAGE_MAX_CHARS;\n const last = message.charCodeAt(end - 1);\n const isHighSurrogate = last >= 0xd800 && last <= 0xdbff;\n if (isHighSurrogate) end -= 1;\n return message.slice(0, end) + FAILURE_MESSAGE_TRUNCATION_SUFFIX;\n}\n\nfunction matchesNonRetryable(error: unknown, list: Array<ErrorClass | string>): boolean {\n if (!list.length) return false;\n const name = error instanceof Error ? error.name : undefined;\n for (const entry of list) {\n if (typeof entry === 'string') {\n if (name === entry) return true;\n } else if (typeof entry === 'function' && error instanceof entry) {\n return true;\n }\n }\n return false;\n}\n\nexport { JobStatus };\n","import type { Worker } from '../consumer/worker';\nimport type { Queue } from '../producer/queue';\n\n/**\n * Tracks this process's queue declarations and their consumers, for graceful shutdown, stats and\n * cooperative cancellation.\n *\n * A queue has **at most one** consumer per process, so the consumers are keyed by queue name.\n * `PortQueue.createQueue` builds one when a declaration carries a `handler`, and {@link hasWorker} is\n * how it refuses a second one before it gets here — replacing a live consumer would strand its claim\n * loop outside {@link allWorkers}, where nothing would ever drain it.\n */\nexport class ClientRegistryService {\n private readonly workers = new Map<string, Worker>();\n private readonly queues = new Map<string, Queue<unknown>>();\n\n addWorker(queueName: string, worker: Worker): void {\n this.workers.set(queueName, worker);\n }\n\n hasWorker(queueName: string): boolean {\n return this.workers.has(queueName);\n }\n\n addQueue(name: string, queue: Queue<unknown>): void {\n this.queues.set(name, queue);\n }\n\n getQueue(name: string): Queue<unknown> | undefined {\n return this.queues.get(name);\n }\n\n allWorkers(): IterableIterator<Worker> {\n return this.workers.values();\n }\n\n /** Try to cooperatively cancel an active job across every queue consumed on this instance. */\n cancelRunning(jobId: string): boolean {\n for (const worker of this.workers.values()) {\n if (worker.cancelRunning(jobId)) return true;\n }\n return false;\n }\n\n /**\n * Whether a job is currently running *in this process*. The read-only half of\n * {@link cancelRunning}, which both tests and acts and so can't be used as a probe.\n */\n isRunning(jobId: string): boolean {\n for (const worker of this.workers.values()) {\n if (worker.executor.active.has(jobId)) return true;\n }\n return false;\n }\n}\n","import type { Driver, Subscription } from '../drivers/driver.interface';\nimport { DriverCapability } from '../drivers/driver-capabilities';\nimport { matchesInstance } from '../jobs/instance-affinity';\nimport type { Logger } from '../logging/logger.interface';\nimport type { Wakeup } from './wakeup';\nimport { PubSubChannel } from './channels';\n\n/**\n * Listens for DB notifications and wakes claim loops. When LISTEN/NOTIFY\n * is unavailable it relies on each worker's interval poller; a \"safety poll\" also runs even\n * when LISTEN is available to catch missed notifications (delayed jobs, stalled reclaims).\n */\nexport class SubscriberService {\n private subscription: Subscription | null = null;\n private safetyTimer: NodeJS.Timeout | null = null;\n\n constructor(\n private readonly driver: Driver,\n private readonly logger: Logger,\n private readonly wakeup: Wakeup,\n private readonly safetyPollMs: number,\n private readonly instanceKey: string | null,\n ) {}\n\n async start(): Promise<void> {\n if (this.driver.capabilities[DriverCapability.LISTEN_NOTIFY]) {\n try {\n this.subscription = await this.driver.subscribe({\n channel: PubSubChannel.JOBS,\n onNotification: (payload) => {\n try {\n const { queue, pattern } = JSON.parse(payload) as {\n queue?: string;\n pattern?: string | null;\n };\n if (!queue) {\n this.wakeup.signalAll();\n return;\n }\n // Skip the wakeup when the added job targets a pattern this instance can't match —\n // claiming it would find nothing. Jobs meant for us fire their own notify, and the\n // safety poll backstops anything missed. Null pattern (or single-instance) → wake.\n if (pattern != null && this.instanceKey != null) {\n if (!matchesInstance(pattern, this.instanceKey)) return;\n }\n this.wakeup.signal(queue);\n } catch {\n this.wakeup.signalAll();\n }\n },\n });\n } catch (err) {\n this.logger.warn('LISTEN/NOTIFY subscribe failed; relying on polling.', { err });\n }\n } else {\n this.logger.debug('Driver has no LISTEN/NOTIFY; using interval polling.');\n }\n // Safety poll backstops missed notifications and delayed/stalled jobs on every driver.\n this.safetyTimer = setInterval(() => this.wakeup.signalAll(), this.safetyPollMs);\n this.safetyTimer.unref?.();\n }\n\n async stop(): Promise<void> {\n if (this.safetyTimer) {\n clearInterval(this.safetyTimer);\n this.safetyTimer = null;\n }\n if (this.subscription) {\n await this.subscription.unsubscribe().catch(() => undefined);\n this.subscription = null;\n }\n }\n}\n","import { JobStatus } from '../jobs/job-state.enum';\nimport { BackoffStrategy } from '../options/enums';\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { CronExpression } from './cron';\nimport { secondsToMs } from '../util/seconds';\nimport {\n MAINTENANCE_BATCH_SIZE,\n MAINTENANCE_MAX_BATCHES,\n SCHEDULE_BATCH_SIZE,\n SCHEDULE_MAX_BATCHES,\n} from '../constants';\nimport type { NewJobRecord, ScheduleRow } from '../jobs/job-record';\nimport type { Runtime } from '../client/runtime';\n\n/**\n * Turns due schedules into concrete jobs. Production is exactly-once per\n * tick across the cluster (guarded `advanceSchedule`). A missed schedule fires once and\n * advances to the next future slot — it never backfills every missed occurrence.\n * The tick also owns expiring due-but-unstarted jobs and reclaiming stalled jobs.\n *\n * **Every sweep here is batched and looped.** Each pass takes a bounded number of rows and repeats\n * until a batch comes back short, so a backlog drains across round trips rather than either waiting\n * for the next tick (which one capped batch did to the 101st due schedule) or arriving as a single\n * unbounded transfer (which an uncapped `expireDueJobs` did to a 100k-row backlog).\n */\nexport class SchedulerService {\n constructor(private readonly runtime: Runtime) {}\n\n async tick(): Promise<void> {\n await this.produceDue();\n await this.expireDue();\n await this.reclaimStalled();\n }\n\n /**\n * Fire every schedule that is due, in batches. The loop matters: with more than one batch worth of\n * due schedules, the remainder used to wait a full tick interval — so a hundred hourly crons all\n * set for the same minute drifted apart from one another.\n */\n private async produceDue(): Promise<void> {\n for (let batch = 0; batch < SCHEDULE_MAX_BATCHES; batch += 1) {\n const now = this.runtime.clock.now();\n const due = await this.runtime.driver.getDueSchedules({ now, limit: SCHEDULE_BATCH_SIZE });\n for (const schedule of due) {\n try {\n await this.fire(schedule, now);\n } catch (err) {\n this.runtime.events.emit(PortQueueEvent.ERROR, { error: err, source: 'scheduler' });\n }\n }\n if (due.length < SCHEDULE_BATCH_SIZE) return;\n }\n this.runtime.logger.debug(\n `Scheduler stopped after ${SCHEDULE_MAX_BATCHES} batches; the rest fire on the next tick.`,\n );\n }\n\n private async fire(schedule: ScheduleRow, now: number): Promise<void> {\n const previous = schedule.nextRunAt;\n if (previous == null) return;\n\n // Compute the next future slot (fire-once semantics; no backfill). A null disarms the schedule:\n // it fires this once and never again.\n const nextRunAt = this.computeNext(schedule, now);\n\n // Claim this tick — only one instance wins the guarded advance.\n const won = await this.runtime.driver.advanceSchedule({\n scheduleId: schedule.id,\n nextRunAt,\n lastRunAt: now,\n fromNextRunAt: previous,\n });\n if (!won) return;\n\n // Stamp every option the recurring add carried (see ScheduledJobOptions) onto this run. These\n // shape the produced job, never the schedule itself; `expireInSeconds` becomes an absolute\n // deadline relative to *this* run. Produced jobs are never given the schedule's idempotencyKey,\n // so the recurrence keeps firing.\n const t = schedule.jobOptions;\n const queueName = schedule.queueName;\n const job: NewJobRecord = {\n queueName: schedule.queueName,\n status: JobStatus.PENDING,\n priority: schedule.priority ?? 0,\n data: schedule.data,\n startAfter: now,\n expireAt:\n t?.expireInSeconds != null ? now + secondsToMs(t.expireInSeconds, 'expireInSeconds') : null,\n retryAttempt: 0,\n retryMaxAttempts: schedule.retryMaxAttempts ?? 1,\n retryDelaySeconds: schedule.retryDelaySeconds ?? 0,\n retryBackoff: t?.retryBackoff ?? BackoffStrategy.FIXED,\n retryBackoffFactor: t?.retryBackoffFactor ?? null,\n retryMaxDelaySeconds: t?.retryMaxDelaySeconds ?? null,\n retryJitter: t?.retryJitter ?? false,\n retentionTtlSeconds: t?.retentionTtlSeconds ?? null,\n retentionStatuses: t?.retentionStatuses ?? null,\n idempotencyKey: null,\n scheduleId: schedule.id,\n singletonKey: t?.singletonKey ?? null,\n preferredInstanceKeyPattern: t?.preferredInstanceKeyPattern ?? null,\n createdAt: now,\n };\n const inserted = await this.runtime.driver.insertJob({ job });\n this.runtime.events.emit(PortQueueEvent.SCHEDULE_FIRED, {\n scheduleId: schedule.id,\n jobId: inserted.id,\n queue: queueName,\n });\n this.runtime.wakeup.signal(queueName);\n }\n\n private computeNext(schedule: ScheduleRow, now: number): number | null {\n if (schedule.cron) {\n return new CronExpression(schedule.cron, schedule.timezone ?? 'UTC').next(now);\n }\n if (schedule.everySeconds != null) {\n return now + secondsToMs(schedule.everySeconds, 'schedule.startEverySeconds');\n }\n return null;\n }\n\n /**\n * Expire due-but-unstarted jobs past their deadline, in batches. The driver returns ids and queue\n * names rather than whole rows: those two are all that is used, and a backlog of a hundred\n * thousand expired jobs would otherwise transfer every column of every one of them.\n */\n private async expireDue(): Promise<void> {\n for (let batch = 0; batch < MAINTENANCE_MAX_BATCHES; batch += 1) {\n const expired = await this.runtime.driver.expireDueJobs({\n now: this.runtime.clock.now(),\n limit: MAINTENANCE_BATCH_SIZE,\n });\n for (const job of expired) {\n this.runtime.events.emit(PortQueueEvent.JOB_EXPIRED, {\n jobId: job.jobId,\n queue: job.queueName,\n });\n }\n if (expired.length < MAINTENANCE_BATCH_SIZE) return;\n }\n this.runtime.logger.debug(\n `Expiry stopped after ${MAINTENANCE_MAX_BATCHES} batches; the rest expire on the next tick.`,\n );\n }\n\n /** Return stalled jobs to PENDING, in batches, and wake the queues that gained work. */\n private async reclaimStalled(): Promise<void> {\n for (let batch = 0; batch < MAINTENANCE_MAX_BATCHES; batch += 1) {\n const reclaimed = await this.runtime.driver.reclaimStalledJobs({\n now: this.runtime.clock.now(),\n limit: MAINTENANCE_BATCH_SIZE,\n });\n const queues = new Set<string>();\n for (const job of reclaimed) {\n this.runtime.events.emit(PortQueueEvent.JOB_STALLED, {\n jobId: job.jobId,\n queue: job.queueName,\n previousInstanceKey: job.previousInstanceKey,\n });\n queues.add(job.queueName);\n }\n // One wakeup per queue rather than per row: a batch of stalled jobs on one queue only needs to\n // tell that queue's workers once.\n for (const queue of queues) this.runtime.wakeup.signal(queue);\n if (reclaimed.length < MAINTENANCE_BATCH_SIZE) return;\n }\n this.runtime.logger.debug(\n `Reclaim stopped after ${MAINTENANCE_MAX_BATCHES} batches; the rest reclaim on the next tick.`,\n );\n }\n}\n","import { RETENTION_BATCH_SIZE, RETENTION_MAX_BATCHES } from '../constants';\nimport type { Runtime } from '../client/runtime';\n\n/**\n * Hard-deletes finished jobs per retention policy, in bounded batches. A job with no retention\n * policy is kept forever; only jobs that carry a TTL, and whose TTL has elapsed, are removed.\n * Cluster-coordinated by running on the same interval tick.\n *\n * **Which statuses a job may be deleted in is the job's own setting**, not this sweeper's. The\n * caller's `retention.statuses` is resolved per job and frozen onto its row, so this passes no status\n * list at all — which is what makes `statuses: [COMPLETED]` really leave the failed jobs alone, where\n * a sweeper that always passed every finished status deleted them too.\n */\nexport class RetentionService {\n constructor(private readonly runtime: Runtime) {}\n\n async sweep(): Promise<number> {\n const now = this.runtime.clock.now();\n let total = 0;\n // Bounded batches so the table is never long-locked.\n for (let batch = 0; batch < RETENTION_MAX_BATCHES; batch += 1) {\n const removed = await this.runtime.driver.deleteFinishedJobs({\n olderThan: now,\n limit: RETENTION_BATCH_SIZE,\n });\n total += removed;\n if (removed < RETENTION_BATCH_SIZE) break;\n }\n if (total > 0) this.runtime.logger.debug(`Retention removed ${total} finished jobs.`);\n return total;\n }\n}\n","import { availableParallelism } from 'node:os';\nimport { monitorEventLoopDelay, performance } from 'node:perf_hooks';\nimport { cpuUsage } from 'node:process';\nimport { getHeapStatistics } from 'node:v8';\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { secondsToMs } from '../util/seconds';\nimport { DEFAULT_SAMPLE_INTERVAL_SECONDS, MICROS_PER_MS } from '../constants';\nimport type { SystemLimiterOptions } from '../options/common';\nimport type { EventBusService } from '../events/event-bus.service';\nimport type { Logger } from '../logging/logger.interface';\n\ntype EventLoopDelayMonitor = ReturnType<typeof monitorEventLoopDelay>;\n\n/**\n * One sample of **this Node process's** health, not the machine's.\n *\n * Per-process is the only reading that means anything here. A host figure says \"the box is at 92%\"\n * on a machine where the OS has merely *allocated* nearly all of RAM to page cache and other\n * processes — which is what Linux and macOS both do, so `os.freemem()` sits above 90% used on an\n * idle laptop and a memory threshold fires forever. It also says nothing about the process that is\n * actually running the jobs: a container with a 512 MB cap on a 64 GB host reads as healthy right\n * up to the moment it is killed.\n */\nexport interface SystemMetrics {\n /**\n * CPU this process burned since the previous sample as a share of **every core available to\n * it**, 0-100: core-seconds used over cores × wall time.\n *\n * `top`'s per-core figure was the obvious alternative and is the wrong one here — it reads past\n * 100 whenever work spreads across libuv or worker threads, so it can't be compared between a\n * 2-core container and a 64-core box or shown beside a memory percentage.\n */\n cpuPercent: number;\n /**\n * Heap this process is holding as a share of the heap V8 will let it grow to\n * (`v8.getHeapStatistics().heap_size_limit`, which `--max-old-space-size` sets), 0-100.\n * 100 is the OOM abort, so this is the memory number worth throttling on — unlike a share of\n * machine RAM, which a process is never allowed to reach.\n */\n memoryPercent: number;\n /** Mean event-loop delay in seconds, or null when it isn't being watched. */\n eventLoopDelaySeconds: number | null;\n}\n\n/** A configured threshold and the reading taken against it. */\ninterface Reading {\n metric: string;\n value: number;\n threshold: number;\n}\n\n/**\n * Samples **this process's** health, and optionally throttles on it.\n *\n * **Monitoring is unconditional.** Process CPU and heap are sampled for as long as the client runs,\n * because the instance heartbeat persists them — that is what makes the dashboard's per-instance\n * metrics possible, so there is no option to turn it off. Both numbers belong to the process that\n * took them, so two PortQueue processes on one box report their own figures and the instance row\n * says whose reading it was.\n *\n * **Limiting is opt-in.** Only when the caller passes `systemLimiter` does a breached threshold\n * raise the backpressure flag that stops workers claiming, and clearing every threshold lower it\n * again. Event-loop delay is the one metric that isn't sampled unless asked for: reading it means\n * keeping a `perf_hooks` histogram enabled for the process's lifetime, so it is enabled only when\n * `maxEventLoopDelaySeconds` gives it a purpose.\n *\n * Uses only Node built-ins. Pressure transitions are observed via the event bus, never a callback.\n */\nexport class SystemMonitorService {\n private timer: NodeJS.Timeout | null = null;\n private histogram: EventLoopDelayMonitor | null = null;\n private lastCpu = cpuUsage();\n // `performance.now()` rather than the clock: a monotonic origin, so a system clock that steps\n // backwards mid-sample can't produce a negative window and a CPU percentage to match.\n private lastSampleAt = performance.now();\n // Cores this process may actually run on — `availableParallelism()` honours CPU affinity and\n // container limits, where `cpus().length` reports the whole host. Read once: it can't change\n // for a running process, and `|| 1` keeps a hostile value from producing a division by zero.\n private readonly cores = availableParallelism() || 1;\n private _pressureHigh = false;\n private _metrics: SystemMetrics = {\n cpuPercent: 0,\n memoryPercent: 0,\n eventLoopDelaySeconds: null,\n };\n\n constructor(\n /** Thresholds that make workers pause. Undefined means monitor only, never throttle. */\n private readonly limiter: SystemLimiterOptions | undefined,\n private readonly events: EventBusService,\n private readonly logger: Logger,\n private readonly onResume: () => void,\n ) {}\n\n /** The most recent sample. Zeroed until the first one lands. */\n get metrics(): SystemMetrics {\n return this._metrics;\n }\n\n get pressureHigh(): boolean {\n return this._pressureHigh;\n }\n\n start(): void {\n if (this.limiter?.maxEventLoopDelaySeconds != null) {\n this.histogram = monitorEventLoopDelay({ resolution: 20 });\n this.histogram.enable();\n }\n this.timer = setInterval(\n () => this.sample(),\n secondsToMs(\n this.limiter?.sampleIntervalSeconds ?? DEFAULT_SAMPLE_INTERVAL_SECONDS,\n 'systemLimiter.sampleIntervalSeconds',\n ),\n );\n this.timer.unref?.();\n // Take one sample immediately so the first heartbeat has real numbers to persist.\n this.sample();\n }\n\n stop(): void {\n if (this.timer) clearInterval(this.timer);\n this.timer = null;\n this.histogram?.disable();\n this.histogram = null;\n }\n\n private sample(): void {\n this._metrics = this.measure();\n if (!this.limiter) return; // monitoring only\n\n const readings = this.readings(this._metrics);\n const breached = readings.find((r) => r.value > r.threshold);\n\n if (breached) {\n if (!this._pressureHigh) {\n this._pressureHigh = true;\n this.logger.warn('System pressure high; workers pause claiming until it clears.', {\n metric: breached.metric,\n value: breached.value,\n threshold: breached.threshold,\n });\n this.events.emit(PortQueueEvent.SYSTEM_PRESSURE_HIGH, breached);\n }\n return;\n }\n\n // Nothing breached: every watched metric is back at or under its own threshold, so claiming\n // resumes on the very next sample that clears.\n if (this._pressureHigh) {\n this._pressureHigh = false;\n this.logger.info('System pressure normal; workers resume claiming.');\n this.events.emit(PortQueueEvent.SYSTEM_PRESSURE_NORMAL, {});\n this.onResume();\n }\n }\n\n /** Read every metric, whether or not a threshold watches it. */\n private measure(): SystemMetrics {\n // `cpuUsage()` is cumulative microseconds of CPU time (user + system) since the process\n // started. Over the wall time of the window that is \"cores busy\"; divided again by the cores\n // available it is a 0-100 share of this process's whole CPU budget. Read the absolute value\n // once and subtract, rather than taking `cpuUsage(previous)` and re-reading: two reads would\n // leave the microseconds between them out of the next window.\n const now = performance.now();\n const current = cpuUsage();\n // Milliseconds to *microseconds*, to match what `cpuUsage()` reports — not the seconds↔ms\n // conversion the seconds invariant is about, so `MICROS_PER_MS` rather than `secondsToMs`.\n const elapsedMicros = (now - this.lastSampleAt) * MICROS_PER_MS;\n const usedMicros = current.user - this.lastCpu.user + (current.system - this.lastCpu.system);\n this.lastCpu = current;\n this.lastSampleAt = now;\n // Two samples inside one timer resolution leave no wall time to divide by; keeping the previous\n // reading is honest, where reporting 0% would claim an idle process. The clamp covers CPU\n // accounting and the monotonic clock being sampled separately, which can put a window a\n // fraction over its own core-time budget.\n const cpuPercent =\n elapsedMicros > 0\n ? Math.min(100, (usedMicros / (elapsedMicros * this.cores)) * 100)\n : this._metrics.cpuPercent;\n\n // The heap limit, not machine RAM: it is the ceiling this process actually dies at, and the one\n // `--max-old-space-size` moves. `used_heap_size` is what V8 reports as live after its last GC.\n const heap = getHeapStatistics();\n\n let eventLoopDelaySeconds: number | null = null;\n if (this.histogram) {\n // The histogram reports nanoseconds and is reset each sample, so this is the mean since the\n // previous one rather than since the process started.\n eventLoopDelaySeconds = this.histogram.mean / 1e9;\n this.histogram.reset();\n }\n return {\n cpuPercent,\n memoryPercent: (heap.used_heap_size / heap.heap_size_limit) * 100,\n eventLoopDelaySeconds,\n };\n }\n\n /**\n * The configured thresholds paired with this sample's values. Only thresholds the caller set are\n * included — an unset one is never a reason to throttle, and never blocks a recovery either.\n */\n private readings(metrics: SystemMetrics): Reading[] {\n const limiter = this.limiter;\n if (!limiter) return [];\n const readings: Reading[] = [];\n if (limiter.maxEventLoopDelaySeconds != null && metrics.eventLoopDelaySeconds != null) {\n readings.push({\n metric: 'eventLoopDelaySeconds',\n value: metrics.eventLoopDelaySeconds,\n threshold: limiter.maxEventLoopDelaySeconds,\n });\n }\n if (limiter.maxCpuPercent != null) {\n readings.push({\n metric: 'cpuPercent',\n value: metrics.cpuPercent,\n threshold: limiter.maxCpuPercent,\n });\n }\n if (limiter.maxMemoryPercent != null) {\n readings.push({\n metric: 'memoryPercent',\n value: metrics.memoryPercent,\n threshold: limiter.maxMemoryPercent,\n });\n }\n return readings;\n }\n}\n","import { secondsToMs } from '../util/seconds';\nimport type { Runtime } from './runtime';\nimport type { SystemMetrics } from '../monitoring/system-monitor.service';\n\n/**\n * Multi-instance liveness, health reporting + per-instance pause. Active only when the\n * PortQueue was given an `instanceKey`. Registers this process's `instance` row, then\n * heartbeats on a timer: each beat bumps `last_seen_at`, records the latest CPU / memory sample for\n * **this Node process** alongside it, and refreshes this instance's cached\n * `processingPaused` flag, which the worker's claim loop reads on the hot path. The dashboard can\n * pause an instance by flipping its row; the next heartbeat picks it up.\n *\n * The metrics ride along with the heartbeat rather than on their own timer: they are only useful as\n * \"how was this instance doing when we last heard from it\", which is exactly what a beat means.\n */\nexport class InstanceService {\n private timer: NodeJS.Timeout | null = null;\n private _processingPaused = false;\n\n constructor(\n private readonly runtime: Runtime,\n readonly instanceKey: string,\n private readonly intervalSeconds: number,\n /** This process's latest health sample; null before the first one lands. */\n private readonly readMetrics: () => SystemMetrics | null,\n ) {}\n\n /** This instance's cached pause flag (refreshed each heartbeat). */\n get processingPaused(): boolean {\n return this._processingPaused;\n }\n\n /** Register the row and begin heartbeating. */\n async start(): Promise<void> {\n await this.beat();\n this.timer = setInterval(\n () => this.runtime.background.run(() => this.beat()),\n secondsToMs(this.intervalSeconds, 'instance.heartbeatIntervalSeconds'),\n );\n this.timer.unref?.();\n }\n\n async stop(): Promise<void> {\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n /**\n * One heartbeat: bump last_seen_at + metrics and refresh the cached pause flag. Never throws.\n *\n * **One round trip.** `upsertInstance` returns the resulting row, so the flag comes from the write\n * itself; the follow-up `getInstance` this used to issue read back exactly what had just been\n * returned, doubling the query count of a beat that runs every 15 s per instance.\n */\n async beat(): Promise<void> {\n try {\n const now = this.runtime.clock.now();\n const metrics = this.readMetrics();\n const row = await this.runtime.driver.upsertInstance({\n instanceKey: this.instanceKey,\n now,\n ...(metrics\n ? {\n metrics: {\n cpuPercent: metrics.cpuPercent,\n memoryPercent: metrics.memoryPercent,\n },\n }\n : {}),\n });\n this._processingPaused = row.processingPaused;\n } catch (err) {\n this.runtime.logger.debug('Instance heartbeat failed; keeping cached pause state.', { err });\n }\n }\n}\n","import { MigrationMode } from '../../options/enums';\nimport { PortQueueEvent } from '../../events/event-name.enum';\nimport { MigrationFailedError, SchemaVersionMismatchError } from '../../errors/errors';\nimport { DriverCapability } from '../driver-capabilities';\nimport { latestVersion } from './migration';\nimport { MIGRATION_WAIT_POLL_SECONDS, MIGRATION_WAIT_TIMEOUT_SECONDS } from '../../constants';\nimport { secondsToMs } from '../../util/seconds';\nimport type { Driver } from '../driver.interface';\nimport type { DriverContext } from '../driver-context';\nimport type { Logger } from '../../logging/logger.interface';\nimport type { EventBusService } from '../../events/event-bus.service';\nimport type { Clock } from '../../util/clock';\n\n/**\n * Applies a driver's ordered migrations. The steps come from the driver itself\n * (`driver.migrations`) — each engine authors its own DDL alongside its driver; this is the single\n * shared mechanism that runs them. A migration is identified by its version and nothing else.\n * Supports AUTO / MANUAL / VALIDATE_ONLY.\n *\n * **Two rules make `MAX(version)` a truthful answer**, which matters because that is what\n * `getSchemaVersion` reads and what decides what is still pending:\n *\n * - Versions are applied in ascending order, and\n * - each one is **confirmed recorded** before the next is attempted. So the applied set is always a\n * contiguous prefix, and there is no way to reach \"v1 and v3 applied, v2 not\" — the state in which\n * a maximum would read as complete while a version was missing.\n *\n * **Concurrency.** Where the engine has a named lock (PostgreSQL' `pg_try_advisory_lock`, MySQL's\n * `GET_LOCK`) one instance migrates and the rest wait for the version to land. Where it does not\n * (Oracle, SQLite, PGLite) every instance proceeds, which is safe only because each engine's DDL is\n * written to be idempotent — `IF NOT EXISTS`, `MERGE`, PL/SQL-guarded `CREATE INDEX` — and because\n * the confirmation above turns a half-applied step into an error rather than a silent skip. For a\n * multi-instance Oracle deployment, running `portqueue migrate` once before starting workers is\n * still the recommendation; see the production docs.\n */\nexport class MigrationRunner {\n constructor(\n private readonly driver: Driver,\n private readonly context: DriverContext,\n private readonly logger: Logger,\n private readonly events: EventBusService,\n private readonly clock: Clock,\n ) {}\n\n /** The schema version this driver's migration set ships (its latest step). */\n private get targetVersion(): number {\n return latestVersion(this.driver.migrations);\n }\n\n async run(mode: MigrationMode): Promise<void> {\n if (mode === MigrationMode.MANUAL) {\n this.logger.info(\n 'Migration mode is MANUAL; skipping auto-migrate. Run `portqueue migrate` to apply.',\n );\n return;\n }\n const current = await this.driver.getSchemaVersion();\n if (mode === MigrationMode.VALIDATE_ONLY) {\n if ((current ?? 0) !== this.targetVersion) {\n throw new SchemaVersionMismatchError(current, this.targetVersion);\n }\n return;\n }\n await this.migrateAuto(current);\n }\n\n /** Force-apply (the programmatic `pq.migrate()` / CLI path). */\n async migrate(): Promise<void> {\n await this.migrateAuto(await this.driver.getSchemaVersion());\n }\n\n private async migrateAuto(current: number | null): Promise<void> {\n const ordered = [...this.driver.migrations].sort((a, b) => a.version - b.version);\n const pending = ordered.filter((m) => m.version > (current ?? 0));\n if (pending.length === 0) return;\n\n const useLock =\n this.driver.capabilities[DriverCapability.ADVISORY_LOCK] && this.driver.tryAdvisoryLock;\n const lockKey = `${this.context.tableNames.prefix}migrate`;\n let locked = false;\n if (useLock) {\n locked = await this.driver.tryAdvisoryLock!({ key: lockKey });\n if (!locked) {\n this.logger.debug('Another instance is migrating; waiting.');\n // Another instance is applying; poll until the version catches up.\n await this.waitForVersion(this.targetVersion);\n return;\n }\n } else {\n // No named lock on this engine. Every instance applies, which each engine's DDL is written to\n // survive; the confirmation below is what keeps a partial apply from reading as a complete one.\n this.logger.debug(\n 'This engine offers no advisory lock; applying migrations without one. Concurrent first ' +\n 'boots rely on the DDL being idempotent — run `portqueue migrate` first to avoid the race.',\n );\n }\n try {\n const from = current;\n for (const migration of pending) {\n try {\n await this.driver.applyMigration({ migration });\n } catch (err) {\n throw new MigrationFailedError(`Migration v${migration.version} failed.`, err);\n }\n // Read it back before moving on. On PostgreSQL, SQLite and PGLite the statements and the\n // version insert share a transaction, so this only ever confirms what is already true. On\n // MySQL and Oracle it cannot: DDL commits implicitly there, so `applyMigration` runs the\n // statements and *then* records the version, and a crash between the two would otherwise\n // leave a schema that reads as one version behind — the next start re-running (idempotent)\n // DDL, and any future non-idempotent step failing on it. Stopping here says so plainly.\n const recorded = await this.driver.getSchemaVersion();\n if ((recorded ?? 0) < migration.version) {\n throw new MigrationFailedError(\n `Migration v${migration.version} ran but was not recorded (the schema still reads as ` +\n `v${recorded ?? 0}). On an engine where DDL commits implicitly this can only mean the ` +\n `process was interrupted between the two; re-run the migration to finish it.`,\n );\n }\n this.logger.info(`Applied migration v${migration.version}.`);\n }\n this.events.emit(PortQueueEvent.MIGRATION_APPLIED, { from, to: this.targetVersion });\n } finally {\n if (locked && this.driver.releaseAdvisoryLock) {\n await this.driver.releaseAdvisoryLock({ key: lockKey }).catch(() => undefined);\n }\n }\n }\n\n /**\n * Poll until another instance's migration lands. Timed against the injected clock, like every\n * other deadline in the codebase, so a test with a fake clock controls this wait rather than\n * spending real seconds inside it.\n */\n private async waitForVersion(\n target: number,\n timeoutSeconds = MIGRATION_WAIT_TIMEOUT_SECONDS,\n ): Promise<void> {\n const timeoutMs = secondsToMs(timeoutSeconds, 'migration wait timeout');\n const pollMs = secondsToMs(MIGRATION_WAIT_POLL_SECONDS, 'migration wait poll');\n const deadline = this.clock.now() + timeoutMs;\n for (;;) {\n const v = await this.driver.getSchemaVersion();\n if ((v ?? 0) >= target) return;\n if (this.clock.now() >= deadline) break;\n await new Promise((resolve) => {\n const timer = setTimeout(resolve, pollMs);\n timer.unref?.();\n });\n }\n throw new MigrationFailedError(\n 'Timed out waiting for another instance to complete migrations.',\n );\n }\n}\n","import { MigrationMode } from '../options/enums';\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { SubscriberService } from '../pubsub/subscriber.service';\nimport { SchedulerService } from '../scheduling/scheduler.service';\nimport { RetentionService } from '../retention/retention.service';\nimport { SystemMonitorService, type SystemMetrics } from '../monitoring/system-monitor.service';\nimport { InstanceService } from './instance.service';\nimport { MigrationRunner } from '../drivers/shared/migration-runner.service';\nimport { ShutdownTimeoutError } from '../errors/errors';\nimport { secondsToMs } from '../util/seconds';\nimport {\n DEFAULT_HEARTBEAT_INTERVAL_SECONDS,\n DEFAULT_TICK_INTERVAL_SECONDS,\n MIN_SUBSCRIBER_POLL_SECONDS,\n} from '../constants';\nimport type { Runtime } from './runtime';\nimport type { ClientRegistryService } from './client-registry.service';\n\ninterface Mutable {\n running: boolean;\n}\n\n/**\n * Owns the strict ordered startup and reverse-ordered shutdown.\n */\nexport class ClientLifecycleService {\n private subscriber: SubscriberService | null = null;\n private scheduler: SchedulerService | null = null;\n private retention: RetentionService | null = null;\n private monitor: SystemMonitorService | null = null;\n private tickTimer: NodeJS.Timeout | null = null;\n private ticking = false;\n private initialized = false;\n\n constructor(\n private readonly runtime: Runtime,\n private readonly registry: ClientRegistryService,\n private readonly state: Mutable,\n ) {}\n\n get systemPressureHigh(): boolean {\n return this.monitor?.pressureHigh ?? false;\n }\n\n /** This process's latest health sample, for the instance heartbeat to persist. */\n get systemMetrics(): SystemMetrics | null {\n return this.monitor?.metrics ?? null;\n }\n\n async init(): Promise<void> {\n if (this.initialized) return;\n this.initialized = true;\n const { driver, context, options, events, logger, clock } = this.runtime;\n\n // 1. Connect the driver.\n await driver.connect();\n // 2. Migrate. A headless (admin) client defaults to MANUAL: pointing a dashboard at a database\n // must never migrate it as a side effect. The CLI's `migrate` command applies them itself.\n const defaultMode = this.runtime.headless ? MigrationMode.MANUAL : MigrationMode.AUTO;\n const migrationRunner = new MigrationRunner(driver, context, logger, events, clock);\n await migrationRunner.run(options.migration ?? defaultMode);\n\n // A headless client stops here: it reads and administers, but joins nothing. No pub/sub, no\n // maintenance tick, no health monitor, no instance row, no workers.\n if (this.runtime.headless) {\n this.state.running = true;\n events.emit(PortQueueEvent.CLIENT_STARTED, { instanceKey: null });\n return;\n }\n\n // 3. Pub/sub.\n const tickIntervalSeconds = options.tickIntervalSeconds ?? DEFAULT_TICK_INTERVAL_SECONDS;\n this.subscriber = new SubscriberService(\n driver,\n logger,\n this.runtime.wakeup,\n secondsToMs(\n Math.max(tickIntervalSeconds, MIN_SUBSCRIBER_POLL_SECONDS),\n 'tickIntervalSeconds',\n ),\n this.runtime.instanceKey ?? null,\n );\n await this.subscriber.start();\n\n // 4. Scheduler + retention + monitor, driven by one coordinated tick.\n this.scheduler = new SchedulerService(this.runtime);\n this.retention = new RetentionService(this.runtime);\n // Only sample when something consumes the numbers: the instance heartbeat persists them (so a\n // named client always monitors), and a `systemLimiter` throttles on them. With neither, nobody\n // ever reads a sample and the process was still paying a `setInterval` plus `cpuUsage()` and\n // `getHeapStatistics()` every couple of seconds.\n if (this.runtime.instanceKey || options.systemLimiter) {\n this.monitor = new SystemMonitorService(options.systemLimiter, events, logger, () =>\n this.runtime.wakeup.signalAll(),\n );\n this.monitor.start();\n }\n this.tickTimer = setInterval(\n () => this.runtime.background.run(() => this.tick()),\n secondsToMs(tickIntervalSeconds, 'tickIntervalSeconds'),\n );\n this.tickTimer.unref?.();\n\n // 5. Multi-instance liveness: register + start heartbeating before workers claim.\n if (this.runtime.instanceKey) {\n const instances = new InstanceService(\n this.runtime,\n this.runtime.instanceKey,\n options.instance?.heartbeatIntervalSeconds ?? DEFAULT_HEARTBEAT_INTERVAL_SECONDS,\n () => this.systemMetrics,\n );\n this.runtime.instances = instances;\n await instances.start();\n }\n\n // 6. Mark running and start workers.\n this.state.running = true;\n for (const worker of this.registry.allWorkers()) await worker.start();\n\n events.emit(PortQueueEvent.CLIENT_STARTED, { instanceKey: this.runtime.instanceKey });\n // Run an immediate maintenance tick so due schedules/expiry aren't delayed a full interval.\n this.runtime.background.run(() => this.tick());\n }\n\n /**\n * One maintenance pass: refresh the cached queue pause flags, fire due schedules, expire and\n * reclaim, then sweep retention.\n *\n * The pause refresh lives here rather than in the claim loop. A worker used to read its queue row\n * on every pump — per poll, and again on every freed concurrency slot — which on an idle queue was\n * more queue reads than job claims. One read per declared queue per tick observes a pause made by\n * another instance within the same interval, at a fraction of the cost.\n */\n private async tick(): Promise<void> {\n if (this.ticking || !this.state.running) return;\n this.ticking = true;\n try {\n await this.runtime.registry.refreshStale();\n await this.scheduler?.tick();\n await this.retention?.sweep();\n } catch (err) {\n this.runtime.events.emit(PortQueueEvent.ERROR, { error: err, source: 'scheduler' });\n } finally {\n this.ticking = false;\n }\n }\n\n async migrate(): Promise<void> {\n const runner = new MigrationRunner(\n this.runtime.driver,\n this.runtime.context,\n this.runtime.logger,\n this.runtime.events,\n this.runtime.clock,\n );\n await runner.migrate();\n }\n\n /**\n * Stop everything in reverse order.\n *\n * Throws {@link ShutdownTimeoutError} when the graceful window elapsed with work still in flight —\n * but only after the shutdown has otherwise completed, so the caller always ends up disconnected. A\n * SIGTERM handler that ignores the rejection still shuts down cleanly; one that logs it learns that\n * handlers were aborted mid-run, which is the thing actually worth knowing.\n */\n async shutdown(options: { graceful: boolean; timeoutSeconds: number }): Promise<void> {\n if (!this.state.running) return;\n const { events } = this.runtime;\n events.emit(PortQueueEvent.CLIENT_STOPPING, { instanceKey: this.runtime.instanceKey });\n\n // Reverse order.\n if (this.tickTimer) clearInterval(this.tickTimer);\n await this.runtime.instances?.stop();\n await this.subscriber?.stop();\n this.state.running = false; // stop new claims\n\n // Drain workers.\n for (const worker of this.registry.allWorkers()) {\n await worker.stop({ graceful: options.graceful, timeoutSeconds: options.timeoutSeconds });\n }\n\n this.monitor?.stop();\n // A tick, pump, heartbeat or NOTIFY fired without an await may still be mid-query. Let it\n // settle before the driver goes away — PGLite frees its WASM heap on disconnect and faults\n // if a query is still running in it.\n const drained = await this.runtime.background.drain(options.timeoutSeconds);\n if (!drained) {\n this.runtime.logger.warn(\n 'Background work did not finish within the shutdown timeout; disconnecting anyway.',\n );\n }\n await this.runtime.driver.disconnect();\n events.emit(PortQueueEvent.CLIENT_STOPPED, { instanceKey: this.runtime.instanceKey });\n if (!drained) throw new ShutdownTimeoutError(options.timeoutSeconds);\n }\n}\n","import { secondsToMs } from '../util/seconds';\n\n/**\n * Tracks the work this client starts without awaiting it — the maintenance tick, a worker's\n * claim pump, an instance heartbeat, a NOTIFY — so shutdown can wait for it to settle before\n * the driver disconnects. Without this, `disconnect()` can land while one of those queries is\n * still in flight: an engine that runs inside this process (PGLite tears down its WASM heap)\n * faults, and a pooled engine logs a query against a closed connection.\n *\n * Failures are not this class's business: every registered task already reports its own errors,\n * so a rejection is swallowed here rather than surfacing as an unhandled rejection (which is\n * what `void task()` did).\n */\nexport class BackgroundWork {\n private readonly pending = new Set<Promise<void>>();\n\n /** Start `task` now, without waiting for it, and remember it until it settles. */\n run(task: () => Promise<unknown>): void {\n const tracked = task().then(\n () => undefined,\n () => undefined,\n );\n this.pending.add(tracked);\n void tracked.then(() => this.pending.delete(tracked));\n }\n\n /**\n * Wait for everything in flight — and anything those tasks start in turn — to settle.\n * Resolves `true` when the set emptied, `false` when `timeoutSeconds` elapsed first, so the\n * caller can carry on with a shutdown it must not abandon.\n */\n async drain(timeoutSeconds: number): Promise<boolean> {\n const expired = expiresIn(secondsToMs(timeoutSeconds, 'shutdown timeoutSeconds'));\n while (this.pending.size > 0) {\n const settled = await Promise.race([\n Promise.all([...this.pending]).then(() => true),\n expired,\n ]);\n if (!settled) return false;\n }\n return true;\n }\n}\n\n/** A promise that resolves `false` once `ms` has passed, on a timer that never holds the loop. */\nfunction expiresIn(ms: number): Promise<false> {\n return new Promise<false>((resolve) => {\n const timer = setTimeout(() => resolve(false), Math.max(ms, 0));\n timer.unref?.();\n });\n}\n","import { MAX_BATCH_IDS } from '../constants';\nimport { InvalidOptionsError } from '../errors/errors';\n\n/**\n * Refuse a by-id batch larger than one statement can carry.\n *\n * Every batch is a single statement over the whole set (see the batch invariant in CLAUDE.md), and\n * every engine caps the expressions an `IN (...)` list may hold — Oracle at 1000, the lowest of the\n * engines here. Rather than let the limit surface as an engine error on one deployment and work on\n * another, the tool takes the tightest ceiling as everyone's and says so up front.\n *\n * A caller with more than {@link MAX_BATCH_IDS} ids splits them: each slice is one round trip, and\n * partial progress is visible between them, which is what an operator wants from a large removal\n * anyway.\n */\nexport function assertBatchIds(ids: readonly unknown[], option: string): void {\n if (ids.length > MAX_BATCH_IDS) {\n throw new InvalidOptionsError(\n `'${option}' carries ${ids.length} ids, more than the ${MAX_BATCH_IDS} one batch may take. ` +\n `A batch is a single statement, and ${MAX_BATCH_IDS} is the smallest limit any supported ` +\n `engine puts on an IN list — split the ids and call again.`,\n { count: ids.length, limit: MAX_BATCH_IDS },\n );\n }\n}\n","/**\n * Result and query shapes for the `pq._dashboard` facade. These are **not** part of the public\n * developer API — they exist so `@portqueue/dashboard` can ask for exactly what it renders\n * without widening `PortQueue`. See the facade invariant in CLAUDE.md.\n */\nimport type { JobStatus } from '../jobs/job-state.enum';\nimport type { Page } from '../options/common';\nimport type { GetSchedulesQuery, InstanceInfo, QueueInfo, ScheduleInfo } from '../producer/results';\n\nexport type { Page };\n\n/** The paging window every dashboard list read accepts. */\nexport interface DashboardPageQuery {\n /** Rows to return. Clamped to `DASHBOARD_MAX_PAGE_LIMIT`. */\n limit?: number;\n offset?: number;\n}\n\n/** Pause-state narrowing shared by the queue and instance lists. */\nexport interface PausedFilter {\n /** `true` → only paused rows, `false` → only running ones, absent → both. */\n processingPaused?: boolean;\n}\n\n/**\n * The dashboard's queue query. Named for the facade, but the same shape as the public\n * `GetQueuesQuery` — the search and pause-state narrowings started here and were promoted, since a\n * developer looking for paused queues needed them just as much. The facade keeps the name (and the\n * tighter page ceiling); it no longer keeps a second implementation.\n *\n * There is deliberately no `inUse` filter. `inUse` means \"declared in the process that produced this\n * info\", and the dashboard runs on its own headless client (`createDashboard({ driver })`) rather\n * than riding on the application's — so it has no way to know which queues the workers declare, and a\n * filter that always answered \"none\" would be worse than no filter.\n */\nexport interface DashboardQueuesQuery extends DashboardPageQuery, PausedFilter {\n /** Case-insensitive substring of the queue name. */\n search?: string;\n}\n\n/** The dashboard's instance query — the public `GetInstancesQuery` under the facade's own name. */\nexport interface DashboardInstancesQuery extends DashboardPageQuery, PausedFilter {\n /** Case-insensitive substring of the instance key. */\n search?: string;\n /** `true` → only instances inside the liveness window, `false` → only stale ones. */\n alive?: boolean;\n}\n\n/**\n * The dashboard's schedule query: the public {@link GetSchedulesQuery} (paging, `queue`, `enabled`)\n * plus the free-text filter only the dashboard's table offers.\n */\nexport interface DashboardSchedulesQuery extends GetSchedulesQuery {\n /** Case-insensitive substring matched against the schedule id, queue name and cron pattern. */\n search?: string;\n}\n\n/**\n * Counts only. The dashboard renders per-status activity cards and nothing else, so this\n * deliberately carries no derived rate metrics.\n */\nexport interface DashboardStats {\n queue?: string;\n counts: Record<JobStatus, number>;\n}\n\n/** The free-text filter the dashboard's jobs table offers. */\nexport interface JobSearchQuery {\n /**\n * Free-text term matched against the job id, status, idempotency key, failure message and the\n * serialized payload. Case-insensitive substring, matched **in SQL** — so a search is a paged\n * query like any other read, not a scan of the table through this process.\n */\n search?: string;\n}\n\n/**\n * Narrow a job read to the instance that claimed the rows (`processed_on_instance_key`). Lives on\n * the facade rather than the public `GetJobsQuery`: it backs the instance detail page's \"jobs\n * processed here\" table, which is a dashboard view, not something the public read surface promises.\n */\nexport interface JobInstanceFilter {\n instanceKey?: string;\n}\n\n/** What a bulk row action does to each selected job. */\nexport enum JobBatchAction {\n RETRY = 'RETRY',\n CANCEL = 'CANCEL',\n REMOVE = 'REMOVE',\n}\n\n/**\n * The outcome of a batch. `affected` counts the rows the action actually changed — a job that\n * was already gone, or one the action refused (retrying or removing an ACTIVE row), is simply not\n * counted.\n */\nexport interface BatchResult {\n affected: number;\n /** How many ids were submitted, so a caller can report \"3 of 5 removed\". */\n requested: number;\n /**\n * Jobs a cancel could only *ask* to stop: they are running in this process, so their handler's\n * `AbortSignal` was fired and their row will settle to whatever the handler does next. Counted\n * apart from `affected` because nothing has been cancelled yet — reporting them as cancelled is\n * how the dashboard used to claim \"Cancelled 3 jobs\" for three jobs that then completed normally.\n */\n signalled?: number;\n}\n\nexport type { InstanceInfo, QueueInfo, ScheduleInfo };\n","/**\n * The `pq._dashboard` facade — everything `@portqueue/dashboard` needs that the public API\n * deliberately does not offer. Nothing here is a documented developer API (the `_` prefix on the\n * property says so); it exists so a dashboard requirement never forces a change to `PortQueue`.\n *\n * Three things this class is careful about, each a bug the dashboard used to have:\n *\n * - **Every filter runs in the database.** A free-text job search is a `LIKE` in SQL, not a chunked\n * scan of the table through this process; a list page is `LIMIT`/`OFFSET`, never a whole-table read\n * sliced in memory.\n * - **A batch is one statement.** `retry`, `cancel` and `remove` each hand the whole id set to one\n * driver call, so the cost is constant in the number of ids and a single stale id cannot roll back\n * the rest of the batch.\n * - **It never declares a queue.** Reads and writes address a queue by name; the client this runs on\n * is headless (see `PortQueueOptions._headless`), so it registers nothing and owns nothing.\n */\nimport { PortQueueEvent } from '../events/event-name.enum';\nimport { InvalidOptionsError } from '../errors/errors';\nimport { assertBatchIds } from '../util/batch-ids';\nimport { pageWindow } from '../monitoring/stats.service';\nimport { DASHBOARD_MAX_PAGE_LIMIT, DEFAULT_PAGE_LIMIT } from '../constants';\nimport {\n JobBatchAction,\n type BatchResult,\n type DashboardStats,\n type DashboardInstancesQuery,\n type DashboardQueuesQuery,\n type DashboardSchedulesQuery,\n type JobInstanceFilter,\n type JobSearchQuery,\n type Page,\n} from './dashboard-results';\nimport type { Runtime } from '../client/runtime';\nimport type { Driver, JobRef } from '../drivers/driver.interface';\nimport type {\n GetJobsQuery,\n InstanceInfo,\n JobSnapshot,\n QueueInfo,\n ScheduleInfo,\n} from '../producer/results';\nimport type { JobRecord } from '../jobs/job-record';\nimport type { ReadService } from '../monitoring/stats.service';\nimport type { ProducerService } from '../producer/producer.service';\nimport type { TransactionHandle } from '../tx/transaction-handle';\n\nexport class DashboardService {\n constructor(\n private readonly runtime: Runtime,\n private readonly reads: ReadService,\n private readonly producer: ProducerService,\n ) {}\n\n /**\n * The live driver, for the rare case the dashboard needs to compose its own transaction (see\n * {@link runInTransaction}). Exposed here rather than on `PortQueue` so the driver never becomes\n * part of the developer-facing surface.\n */\n get driver(): Driver {\n return this.runtime.driver;\n }\n\n /**\n * Run `fn` inside one driver transaction. Left on the facade for a caller that needs to compose\n * several driver calls atomically; the batch actions below no longer need it, because each is a\n * single statement.\n */\n runInTransaction<T>(options: { fn: (tx: TransactionHandle) => Promise<T> }): Promise<T> {\n return this.runtime.driver.runInTransaction(options);\n }\n\n // --- Paged lists -------------------------------------------------------------------------\n\n /**\n * A page of queues with their per-status counts.\n *\n * The public read already narrows by name and pause state in SQL and counts the whole page in one\n * grouped query, so this only tightens the page ceiling: a dashboard table never shows more than\n * {@link DASHBOARD_MAX_PAGE_LIMIT} rows, and a crafted `limit` must not be able to ask for the\n * table. Reusing the public read is what the facade rule allows and what keeps the two from\n * drifting — they were byte-identical bodies over the same driver calls.\n */\n getQueues(query: DashboardQueuesQuery = {}): Promise<Page<QueueInfo>> {\n return this.reads.getQueues({ ...query, ...pageWindow(query, DASHBOARD_MAX_PAGE_LIMIT) });\n }\n\n /** A page of instances with liveness and per-instance job attribution. Clamped like the queues. */\n getInstances(query: DashboardInstancesQuery = {}): Promise<Page<InstanceInfo>> {\n return this.reads.getInstances({ ...query, ...pageWindow(query, DASHBOARD_MAX_PAGE_LIMIT) });\n }\n\n /**\n * One instance by key, with the same liveness, health and attribution the list carries — for the\n * instance detail page. `PortQueue.getInstance` covers this, but the facade keeps its own entry\n * point so the dashboard's routes read uniformly.\n */\n getInstance(options: { instanceKey: string }): Promise<InstanceInfo | null> {\n return this.reads.getInstance(options.instanceKey);\n }\n\n /**\n * A page of schedules across every queue, in one query. Delegates to the same producer read\n * `pq.getSchedules` uses, plus the free-text filter only this table offers.\n */\n async getSchedules(query: DashboardSchedulesQuery = {}): Promise<Page<ScheduleInfo>> {\n const { limit, offset } = pageWindow(query, DASHBOARD_MAX_PAGE_LIMIT);\n if (!query.search) {\n return this.producer.getSchedules({\n ...(query.queue ? { queue: query.queue } : {}),\n ...(query.enabled !== undefined ? { enabled: query.enabled } : {}),\n limit,\n offset,\n });\n }\n const filter = {\n ...(query.queue ? { queueName: query.queue } : {}),\n ...(query.enabled !== undefined ? { enabled: query.enabled } : {}),\n search: query.search,\n };\n const [rows, total] = await Promise.all([\n this.runtime.driver.listSchedules({ ...filter, limit, offset }),\n this.runtime.driver.countSchedules(filter),\n ]);\n return {\n items: rows.map((s) => ({\n scheduleId: s.id,\n queue: s.queueName,\n cron: s.cron,\n everySeconds: s.everySeconds,\n timezone: s.timezone,\n nextRunAt: s.nextRunAt != null ? new Date(s.nextRunAt) : null,\n lastRunAt: s.lastRunAt != null ? new Date(s.lastRunAt) : null,\n enabled: s.enabled,\n idempotencyKey: s.idempotencyKey,\n })),\n total,\n };\n }\n\n /** One schedule by id, with its queue — backs the schedule detail page. */\n getSchedule(options: { scheduleId: string }): Promise<ScheduleInfo | null> {\n return this.producer.getSchedule(options.scheduleId);\n }\n\n /** Counts only — the activity cards. No throughput or failure-rate derivation. */\n async getStats(options: { queue?: string } = {}): Promise<DashboardStats> {\n const counts = await this.runtime.driver.countJobsByStatus(\n options.queue ? { queueName: options.queue } : {},\n );\n return { ...(options.queue ? { queue: options.queue } : {}), counts };\n }\n\n // --- Jobs --------------------------------------------------------------------------------\n\n /**\n * A page of jobs, optionally narrowed by a free-text search.\n *\n * The search is a SQL `LIKE` across the five fields an operator triages by — id, status,\n * idempotency key, failure message and the serialized payload — so it pages in the database and\n * `total` is a `COUNT`. The previous implementation read the whole matching set through this\n * process in 1000-row chunks and filtered in JS: bounded in memory, but O(rows / 1000) queries and\n * a `JSON.parse` of every payload in the table for one keystroke.\n */\n getJobs<TData = unknown>(\n query: GetJobsQuery & JobSearchQuery & JobInstanceFilter = {},\n ): Promise<Page<JobSnapshot<TData>>> {\n const term = query.search?.trim();\n const { search: _search, ...base } = query;\n return this.reads.getJobs<TData>({\n ...base,\n ...(term ? { search: term } : {}),\n limit: Math.min(\n Math.max(Math.trunc(base.limit ?? DEFAULT_PAGE_LIMIT), 1),\n DASHBOARD_MAX_PAGE_LIMIT,\n ),\n });\n }\n\n // --- Batch actions -----------------------------------------------------------------------\n\n /**\n * Apply one action to many jobs in a **single** driver call.\n *\n * Each action maps to one guarded statement over the whole id set, so the cost is constant in the\n * number of ids and the guard is uniform: an id that didn't match (already gone, or an `ACTIVE` row\n * that a retry or a remove refuses) is simply absent from the result rather than failing the batch.\n * The previous implementation looped `requeueJob` per id inside one transaction, where the first\n * stale id threw and rolled back every retry beside it.\n *\n * Cancellation keeps its one non-transactional side effect: a job running *in this process* is\n * cancelled by firing its handler's `AbortSignal`, which no statement can undo, so those fire only\n * after the write has landed.\n */\n async runJobBatch(options: { jobIds: string[]; action: JobBatchAction }): Promise<BatchResult> {\n const { jobIds, action } = options;\n if (!jobIds.length) return { affected: 0, requested: 0 };\n assertBatchIds(jobIds, 'runJobBatch({ jobIds })');\n\n const now = this.runtime.clock.now();\n const driver = this.runtime.driver;\n\n switch (action) {\n case JobBatchAction.REMOVE: {\n const removed = await driver.removeJobs({ jobIds });\n this.emitPerJob(PortQueueEvent.JOB_REMOVED, removed);\n return { affected: removed.length, requested: jobIds.length };\n }\n case JobBatchAction.RETRY: {\n const requeued = await driver.requeueJobs({ jobIds, now });\n // One wakeup per distinct queue, not per job.\n for (const q of new Set(requeued.map((r) => r.queueName))) this.runtime.wakeup.signal(q);\n for (const ref of requeued) {\n this.runtime.events.emit(PortQueueEvent.JOB_ADDED, {\n jobId: ref.jobId,\n queue: ref.queueName,\n deduplicated: false,\n });\n }\n return { affected: requeued.length, requested: jobIds.length };\n }\n case JobBatchAction.CANCEL: {\n // Jobs running here can only be *asked* to stop — their handler owns the row's outcome — so\n // they are signalled and counted apart. Everything else is cancelled in one statement.\n //\n // No `JOB_CANCELLED` is emitted for a signalled job: cancellation is cooperative, and a\n // handler that ignores `job.signal` completes normally. Emitting it here told every listener\n // (and the dashboard's own toast) that three jobs had been cancelled when none had.\n const running = new Set(jobIds.filter((id) => this.isRunningHere(id)));\n const remaining = jobIds.filter((id) => !running.has(id));\n const cancelled = remaining.length\n ? await driver.cancelJobs({ jobIds: remaining, now })\n : [];\n for (const jobId of running) this.runtime.cancelRunning?.(jobId);\n this.emitPerJob(PortQueueEvent.JOB_CANCELLED, cancelled);\n return {\n affected: cancelled.length,\n requested: jobIds.length,\n ...(running.size ? { signalled: running.size } : {}),\n };\n }\n default:\n throw new InvalidOptionsError(`Unknown job batch action '${String(action)}'.`);\n }\n }\n\n /**\n * Emit one event per affected job, naming the queue the row actually belongs to.\n *\n * The ref comes from the statement that changed the row, so the queue is the row's own — which is\n * why a batch needs no `queue` argument, and why one request can carry a selection that spans\n * queues without any event naming the wrong one.\n */\n private emitPerJob(\n event: PortQueueEvent.JOB_REMOVED | PortQueueEvent.JOB_CANCELLED,\n refs: JobRef[],\n ): void {\n for (const ref of refs) {\n this.runtime.events.emit(event, { jobId: ref.jobId, queue: ref.queueName });\n }\n }\n\n /**\n * Remove many schedules in **one** statement, which also returns each removed row's queue — so the\n * `SCHEDULE_REMOVED` events cost nothing beyond the delete. This used to read every schedule\n * individually just to learn its queue name, then delete them one at a time: 2N queries for N ids.\n */\n async removeSchedules(options: { scheduleIds: string[] }): Promise<BatchResult> {\n const { scheduleIds } = options;\n if (!scheduleIds.length) return { affected: 0, requested: 0 };\n assertBatchIds(scheduleIds, 'removeSchedules({ scheduleIds })');\n const removed = await this.runtime.driver.deleteSchedules({ scheduleIds });\n for (const ref of removed) {\n this.runtime.events.emit(PortQueueEvent.SCHEDULE_REMOVED, {\n scheduleId: ref.scheduleId,\n queue: ref.queueName,\n });\n }\n return { affected: removed.length, requested: scheduleIds.length };\n }\n\n /** Arm or disarm a schedule. Core exposes the flag as read-only; the dashboard can toggle it. */\n async setScheduleEnabled(options: { scheduleId: string; enabled: boolean }): Promise<boolean> {\n // One statement: the driver returns the affected row's ref, so the event needs no extra read.\n const updated = await this.runtime.driver.setScheduleEnabled({\n scheduleId: options.scheduleId,\n enabled: options.enabled,\n now: this.runtime.clock.now(),\n });\n if (!updated) return false;\n this.runtime.events.emit(PortQueueEvent.SCHEDULE_UPDATED, {\n scheduleId: updated.scheduleId,\n queue: updated.queueName,\n });\n return true;\n }\n\n /** Whether this process is currently running the job (so a cancel fires its signal). */\n private isRunningHere(jobId: string): boolean {\n // `cancelRunning` both tests and acts, so it can't be used as a probe here without\n // cancelling. `isJobRunningHere` is the read-only half.\n return this.runtime.isJobRunningHere?.(jobId) ?? false;\n }\n}\n\nexport type { JobRecord };\n","/**\n * The `pq._cli` facade — everything `@portqueue/cli` needs that the public API deliberately does\n * not offer. Nothing here is a documented developer API (the `_` prefix on the property says so);\n * it exists so a CLI requirement never forces a change to `PortQueue`. See CLAUDE.md.\n *\n * The CLI's distinguishing constraint is that it is an **admin process that never owns the app's\n * queues**: it runs on a headless client (see `PortQueueOptions._headless`), so it declares nothing,\n * registers no instance row, and addresses every queue by name against the driver.\n */\nimport { JobStatus } from '../jobs/job-state.enum';\nimport { InvalidOptionsError } from '../errors/errors';\nimport { pageWindow } from '../monitoring/stats.service';\nimport { latestVersion } from '../drivers/shared/migration';\nimport type { Runtime } from '../client/runtime';\nimport type { Driver } from '../drivers/driver.interface';\nimport type { Page, ScheduleInfo } from '../producer/results';\nimport type { ProducerService } from '../producer/producer.service';\nimport type { TransactionHandle } from '../tx/transaction-handle';\n\n/** What `portqueue doctor` reports about the connection it just made. */\nexport interface DoctorReport {\n engine: string;\n serverVersion: string;\n /** Capabilities the driver verified against the live server, not just the ones it declares. */\n verifiedCapabilities: string[];\n /** The applied schema version, or null when the schema has never been migrated. */\n schemaVersion: number | null;\n /** The highest version this driver ships; equal to `schemaVersion` when fully migrated. */\n latestVersion: number;\n queueCount: number;\n instanceCount: number;\n}\n\nexport class CliService {\n constructor(\n private readonly runtime: Runtime,\n private readonly producer: ProducerService,\n ) {}\n\n /** The live driver, for CLI paths that need engine detail the public API doesn't expose. */\n get driver(): Driver {\n return this.runtime.driver;\n }\n\n runInTransaction<T>(options: { fn: (tx: TransactionHandle) => Promise<T> }): Promise<T> {\n return this.runtime.driver.runInTransaction(options);\n }\n\n /**\n * A **page** of schedules — one queue's, or across every queue when `queue` is omitted.\n *\n * Paged like every other list path. This used to call `listSchedules` with no window at all, so\n * `portqueue schedules` loaded every schedule row in the database into the terminal.\n */\n getSchedules(\n options: { queue?: string; limit?: number; offset?: number } = {},\n ): Promise<Page<ScheduleInfo>> {\n const { limit, offset } = pageWindow(options);\n return this.producer.getSchedules({\n ...(options.queue ? { queue: options.queue } : {}),\n limit,\n offset,\n });\n }\n\n /**\n * Delete every job on a queue in the given states (`portqueue purge`). Addresses the queue by\n * name, so purging never declares it. ACTIVE is refused for the same reason the public path\n * refuses it: the row belongs to a running handler.\n */\n async purge(options: { queue: string; statuses: JobStatus[] }): Promise<number> {\n if (options.statuses.includes(JobStatus.ACTIVE)) {\n throw new InvalidOptionsError(\n `Cannot purge ACTIVE jobs on queue '${options.queue}': an ACTIVE job is running. ` +\n `Cancel it first, then purge once it has settled.`,\n { queue: options.queue },\n );\n }\n return this.runtime.driver.removeJobsByStatus({\n queueName: options.queue,\n statuses: options.statuses,\n });\n }\n\n /**\n * Everything `portqueue doctor` reports: a live probe of the server plus the applied vs shipped\n * schema version. `PortQueue` exposes none of this — `migrate()` applies migrations but never\n * says what state the schema was in.\n */\n async doctor(): Promise<DoctorReport> {\n const driver = this.runtime.driver;\n const [probe, schemaVersion, queueCount, instanceCount] = await Promise.all([\n driver.probe(),\n driver.getSchemaVersion(),\n driver.countQueues(),\n driver.countInstances(),\n ]);\n return {\n engine: driver.engine,\n serverVersion: probe.serverVersion,\n verifiedCapabilities: probe.verifiedCapabilities.map(String),\n schemaVersion,\n latestVersion: latestVersion(driver.migrations),\n queueCount,\n instanceCount,\n };\n }\n}\n","/**\n * The handle `pq.createQueue({ name })` returns.\n *\n * **It has no methods.** It is a *registration*, not a control surface: the call that produced it\n * declares everything about the queue — its default job options, its retention policy, its\n * queue-scoped hooks, and (when this process consumes the queue) its `handler` and claim settings —\n * and everything you then *do* with the queue lives on `PortQueue`: `pq.addJob({ queue })`,\n * `pq.getJobs({ queue })`, `pq.pauseQueue({ queue })`, and so on.\n *\n * Two reasons that is the better surface, both learned from the version that had chained methods:\n *\n * - **Nothing silently escapes its scope.** `queue.getJob({ jobId })` forwarded to an unscoped read,\n * so asking one queue's handle for another queue's job returned it — typed as *this* queue's\n * payload. With one `pq.getJob({ jobId })` there is no scope to be wrong about, and the reads that\n * genuinely are per-queue take `queue` as a named argument that means exactly what it says.\n * - **One import, one object.** Application code that touches five queues passes five names to one\n * `pq` instead of threading five handles through its own plumbing.\n *\n * Because of that, holding on to this handle is optional: `pq.addJob({ queue: 'emails', … })` works\n * from a name alone, and a process that only enqueues need not declare the queue at all.\n */\nexport class Queue<TData = unknown> {\n constructor(readonly name: string) {}\n\n /**\n * The payload type this handle was created with. Never read at runtime — it exists so\n * `createQueue<Payload>({ name })` keeps `Payload` attached to the handle for a caller who wants\n * to pass the type around, and so `TData` is not an unused parameter.\n */\n declare readonly __data?: TData;\n}\n","import { wholeSecondsToMs } from '../util/seconds';\nimport type { Clock } from '../util/clock';\n\n/**\n * A worker-local token-bucket limiter. Exact and in-process; limits how\n * many jobs this worker starts per window. Distinct from the cluster-wide queue rate limit.\n *\n * The window arrives in seconds (`limiter.rateDurationSeconds`) and is held in ms, because the\n * refill maths runs against the clock's epoch-ms.\n */\nexport class RateLimiterService {\n private tokens: number;\n private lastRefill: number;\n private readonly max: number;\n private readonly windowMs: number;\n\n constructor(\n options: { max: number; durationSeconds: number },\n private readonly clock: Clock,\n ) {\n this.max = options.max;\n this.windowMs = wholeSecondsToMs(options.durationSeconds, 'limiter.rateDurationSeconds');\n this.tokens = options.max;\n this.lastRefill = clock.now();\n }\n\n private refill(): void {\n const now = this.clock.now();\n const elapsed = now - this.lastRefill;\n if (elapsed <= 0) return;\n const refill = (elapsed / this.windowMs) * this.max;\n this.tokens = Math.min(this.max, this.tokens + refill);\n this.lastRefill = now;\n }\n\n /** Consume up to `want` tokens; returns how many were granted. */\n take(want: number): number {\n this.refill();\n const grant = Math.max(0, Math.min(want, Math.floor(this.tokens)));\n this.tokens -= grant;\n return grant;\n }\n\n /** Milliseconds until at least one token is available (for loop backoff). */\n msUntilAvailable(): number {\n this.refill();\n if (this.tokens >= 1) return 0;\n const needed = 1 - this.tokens;\n return Math.ceil((needed / this.max) * this.windowMs);\n }\n}\n","import { PortQueueEvent } from '../events/event-name.enum';\nimport { secondsToMs } from '../util/seconds';\nimport { LOCK_HEARTBEATS_PER_WINDOW, MIN_LOCK_HEARTBEAT_SECONDS } from '../constants';\nimport type { Job, JobHandler } from '../jobs/job';\nimport type { JobRecord } from '../jobs/job-record';\nimport type { ErrorClass } from '../options/queue-options';\nimport type { FailureDetail } from '../options/enums';\nimport type { Runtime } from '../client/runtime';\nimport type { CompletionService } from './completion.service';\n\nexport interface ExecutionConfig {\n queueName: string;\n handler: JobHandler;\n dontAutoretryFor: Array<ErrorClass | string>;\n lockDurationSeconds: number;\n /** How much of a failure this queue stores on the row — passed through to the completion. */\n failureDetail: FailureDetail;\n}\n\n/** One in-flight handler: how to abort it, and which claim it is running under. */\nexport interface ActiveExecution {\n controller: AbortController;\n /** The claim's fence token, so a lock this process releases names the claim it is releasing. */\n lockToken: string | null;\n}\n\n/**\n * Runs handlers, catches every error, and routes to retry/fail. A throw never\n * propagates to the claim loop. Each job runs under a heartbeat that\n * extends the lock and an AbortSignal fired on shutdown/cooperative-cancel.\n */\nexport class ExecutionService {\n /** Active jobs on this instance → their controller and claim token (for cancel/shutdown). */\n readonly active = new Map<string, ActiveExecution>();\n\n constructor(\n private readonly runtime: Runtime,\n private readonly completion: CompletionService,\n private readonly config: ExecutionConfig,\n ) {}\n\n async run(record: JobRecord): Promise<void> {\n const startTs = this.runtime.clock.now();\n const controller = new AbortController();\n this.active.set(record.id, { controller, lockToken: record.lockToken });\n const queueName = this.config.queueName;\n\n this.runtime.events.emit(PortQueueEvent.JOB_ACTIVE, {\n jobId: record.id,\n queue: queueName,\n retryAttempt: record.retryAttempt,\n instanceKey: this.runtime.instanceKey,\n });\n\n const job = this.buildJob(record, controller.signal);\n const heartbeat = this.startHeartbeat(record, controller);\n\n try {\n await this.runtime.hooks.runBeforeProcess(queueName, job);\n const returnValue = await this.config.handler(job);\n const outcome = await this.completion.complete(record, queueName, returnValue, startTs);\n await this.runtime.hooks.runAfterProcess(queueName, job, outcome);\n } catch (err) {\n const outcome = await this.completion.failOrRetry(\n record,\n queueName,\n err,\n this.config.dontAutoretryFor,\n this.config.failureDetail,\n );\n await this.runtime.hooks.runAfterProcess(queueName, job, outcome).catch(() => undefined);\n } finally {\n clearInterval(heartbeat);\n this.active.delete(record.id);\n }\n }\n\n private buildJob(record: JobRecord, signal: AbortSignal): Job {\n const runtime = this.runtime;\n const lockDurationSeconds = this.config.lockDurationSeconds;\n return {\n id: record.id,\n queue: this.config.queueName,\n data: record.data,\n retryAttempt: record.retryAttempt,\n retryMaxAttempts: record.retryMaxAttempts,\n priority: record.priority,\n createdAt: new Date(record.createdAt),\n startAfter: new Date(record.startAfter),\n ...(record.scheduleId ? { scheduleId: record.scheduleId } : {}),\n ...(record.idempotencyKey ? { idempotencyKey: record.idempotencyKey } : {}),\n signal,\n async extendLock(options = {}) {\n await runtime.driver.extendLock({\n jobId: record.id,\n lockDurationSeconds: options.bySeconds ?? lockDurationSeconds,\n now: runtime.clock.now(),\n lockToken: record.lockToken,\n });\n },\n };\n }\n\n private startHeartbeat(record: JobRecord, controller: AbortController): NodeJS.Timeout {\n // Beat at a fraction of the lock window, never faster than the floor, so a lock is renewed\n // several times before it could lapse.\n const intervalMs = Math.max(\n secondsToMs(MIN_LOCK_HEARTBEAT_SECONDS, 'lock heartbeat floor'),\n Math.floor(\n secondsToMs(this.config.lockDurationSeconds, 'limiter.lockDurationSeconds') /\n LOCK_HEARTBEATS_PER_WINDOW,\n ),\n );\n const timer = setInterval(async () => {\n try {\n const held = await this.runtime.driver.extendLock({\n jobId: record.id,\n lockDurationSeconds: this.config.lockDurationSeconds,\n now: this.runtime.clock.now(),\n lockToken: record.lockToken,\n });\n if (!held && !controller.signal.aborted) controller.abort();\n } catch {\n /* transient DB error — next tick retries */\n }\n }, intervalMs);\n timer.unref?.();\n return timer;\n }\n}\n","import { PortQueueEvent } from '../events/event-name.enum';\nimport { RateLimiterService } from '../monitoring/rate-limiter.service';\nimport { ExecutionService, type ExecutionConfig } from './execution.service';\nimport { secondsToMs } from '../util/seconds';\nimport { ABORT_GRACE_SECONDS, DRAIN_POLL_SECONDS, LOCK_RELEASE_SECONDS } from '../constants';\nimport type { CompletionService } from './completion.service';\nimport type { JobHandler } from '../jobs/job';\nimport type { ErrorClass } from '../options/queue-options';\nimport type { FailureDetail } from '../options/enums';\nimport type { Runtime } from '../client/runtime';\n\n/** Worker wiring, resolved from the consumer half of `CreateQueueOptions`. Every duration is seconds. */\nexport interface WorkerConfig {\n queue: string;\n handler: JobHandler;\n concurrency: number;\n batchSize: number;\n lockDurationSeconds: number;\n pollIntervalSeconds: number;\n limiter?: { max: number; durationSeconds: number };\n dontAutoretryFor: Array<ErrorClass | string>;\n /** How much of a failure this queue stores on the row. */\n failureDetail: FailureDetail;\n}\n\n/**\n * The consumer for one queue. Owns its own claim loop, heartbeat, and\n * wakeup subscription — queues are independent lanes.\n *\n * **Internal.** There is no developer-facing worker: `pq.createQueue({ name, handler })` builds one\n * of these behind the queue's declaration, and it is never handed out. It begins claiming when the\n * client starts and its queue isn't paused, and stops when the client stops — so there was never a\n * lifecycle method to expose in the first place.\n */\nexport class Worker {\n private readonly execution: ExecutionService;\n private readonly limiter?: RateLimiterService;\n private activeCount = 0;\n private stopping = false;\n private started = false;\n private queueName: string | null = null;\n private pumping = false;\n private unsubscribeWakeup: (() => void) | null = null;\n private pollTimer: NodeJS.Timeout | null = null;\n /** A one-shot timer scheduled for the moment the rate limiter will have a token again. */\n private tokenTimer: NodeJS.Timeout | null = null;\n\n constructor(\n private readonly runtime: Runtime,\n completion: CompletionService,\n private readonly config: WorkerConfig,\n private readonly isPressureHigh: () => boolean,\n ) {\n const execConfig: ExecutionConfig = {\n queueName: config.queue,\n handler: config.handler,\n dontAutoretryFor: config.dontAutoretryFor,\n lockDurationSeconds: config.lockDurationSeconds,\n failureDetail: config.failureDetail,\n };\n this.execution = new ExecutionService(runtime, completion, execConfig);\n if (config.limiter) this.limiter = new RateLimiterService(config.limiter, runtime.clock);\n }\n\n /** @internal Called by the client lifecycle when the client starts. */\n async start(): Promise<void> {\n if (this.started) return;\n this.started = true;\n this.stopping = false;\n const row = await this.runtime.registry.ensure(this.config.queue);\n this.queueName = row.name;\n this.unsubscribeWakeup = this.runtime.wakeup.subscribe(this.config.queue, () =>\n this.runtime.background.run(() => this.pump()),\n );\n this.pollTimer = setInterval(\n () => this.runtime.background.run(() => this.pump()),\n secondsToMs(this.config.pollIntervalSeconds, 'limiter.pollIntervalSeconds'),\n );\n this.pollTimer.unref?.();\n this.runtime.events.emit(PortQueueEvent.WORKER_STARTED, { queue: this.config.queue });\n this.runtime.background.run(() => this.pump());\n }\n\n /** @internal Number of in-flight handlers (used for graceful drain). */\n get inFlight(): number {\n return this.activeCount;\n }\n\n /** @internal The execution service (exposes active abort controllers). */\n get executor(): ExecutionService {\n return this.execution;\n }\n\n private async pump(): Promise<void> {\n if (this.stopping || !this.runtime.isRunning() || this.pumping) return;\n this.pumping = true;\n try {\n while (!this.stopping) {\n const capacity = this.config.concurrency - this.activeCount;\n if (capacity <= 0) break;\n // Pressure is only ever high when the client was given a `systemLimiter`; without one this\n // reads false forever, which is why there is no per-worker opt-in to carry.\n if (this.isPressureHigh()) break;\n\n // Cluster-wide pause state, from the registry's cache — no query on the hot path. The\n // maintenance tick refreshes it, and a pause made in this process updates it immediately.\n if (this.runtime.registry.pauseState(this.config.queue)?.processingPaused) break;\n // This instance's own pause state (multi-instance mode).\n if (this.runtime.instances?.processingPaused) break;\n\n let want = Math.min(capacity, this.config.batchSize);\n if (this.limiter) {\n const granted = this.limiter.take(want);\n if (granted <= 0) {\n // Out of tokens. Come back when the bucket refills rather than waiting for the poll\n // timer — otherwise a rate-limited worker idles for a whole `pollIntervalSeconds` after\n // a shortfall that may clear in milliseconds.\n this.scheduleTokenWakeup(this.limiter.msUntilAvailable());\n break;\n }\n want = granted;\n }\n\n const jobs = await this.runtime.driver.claimJobs({\n queueName: this.queueName!,\n limit: want,\n lockDurationSeconds: this.config.lockDurationSeconds,\n now: this.runtime.clock.now(),\n instanceKey: this.runtime.instanceKey,\n });\n if (jobs.length === 0) break;\n\n for (const record of jobs) {\n this.activeCount += 1;\n void this.execution\n .run(record)\n .catch((err) => {\n this.runtime.events.emit(PortQueueEvent.ERROR, { error: err, source: 'execution' });\n })\n .finally(() => {\n this.activeCount -= 1;\n // A freed slot may allow another claim.\n this.runtime.background.run(() => this.pump());\n });\n }\n }\n } catch (err) {\n // A DB error mid-claim must never crash the loop.\n this.runtime.events.emit(PortQueueEvent.ERROR, { error: err, source: 'claim' });\n } finally {\n this.pumping = false;\n }\n }\n\n /** Re-pump once the rate limiter has a token. At most one such timer is ever outstanding. */\n private scheduleTokenWakeup(delayMs: number): void {\n if (this.tokenTimer || this.stopping) return;\n this.tokenTimer = setTimeout(\n () => {\n this.tokenTimer = null;\n if (!this.stopping) this.runtime.background.run(() => this.pump());\n },\n Math.max(delayMs, 0),\n );\n this.tokenTimer.unref?.();\n }\n\n /** @internal Stop claiming; drain in-flight up to timeout, then abort + release locks. */\n async stop(options: { timeoutSeconds: number; graceful: boolean }): Promise<void> {\n this.stopping = true;\n if (this.unsubscribeWakeup) this.unsubscribeWakeup();\n if (this.pollTimer) clearInterval(this.pollTimer);\n if (this.tokenTimer) clearTimeout(this.tokenTimer);\n this.tokenTimer = null;\n\n if (options.graceful && this.activeCount > 0) {\n // Raced against a real timer rather than measured with the injected clock. The drain waits on\n // wall-clock time — the handlers really are running — so a deadline taken from a clock a test\n // controls would never arrive and this would spin for as long as the handlers took.\n await Promise.race([\n this.awaitIdle(),\n elapses(secondsToMs(options.timeoutSeconds, 'shutdown timeoutSeconds')),\n ]);\n }\n await this.abortAndRelease();\n this.started = false;\n this.runtime.events.emit(PortQueueEvent.WORKER_STOPPED, { queue: this.config.queue });\n }\n\n /**\n * Abort every handler still running, then release the lock of the ones that did not stop.\n *\n * The order matters, and the release used to sit beside the abort. An abort is cooperative: a\n * handler that ignores `job.signal` — the common case for short work — keeps going and settles a\n * moment later. Releasing its lock in that moment let another instance's reclaim return the row to\n * `PENDING` and a second worker claim it, so the same job ran twice. Waiting for the abort to be\n * observed means a handler that stops promptly settles its own row and needs no release at all;\n * only a genuine straggler, which this process is about to abandon, has its lock cut short so\n * another instance can pick the job up quickly.\n *\n * A straggler's completion is refused even if it does land later: the release clears the claim's\n * fence token, and every completion is guarded on it (see `Driver.completeJob`).\n */\n private async abortAndRelease(): Promise<void> {\n const claims = [...this.execution.active.entries()].map(([jobId, active]) => {\n active.controller.abort();\n return { jobId, lockToken: active.lockToken };\n });\n if (!claims.length) return;\n\n await Promise.race([\n this.awaitIdle(),\n elapses(secondsToMs(ABORT_GRACE_SECONDS, 'abort grace')),\n ]);\n\n for (const claim of claims) {\n if (!this.execution.active.has(claim.jobId)) continue; // stopped and settled its own row\n this.runtime.background.run(() =>\n this.runtime.driver.extendLock({\n jobId: claim.jobId,\n lockDurationSeconds: LOCK_RELEASE_SECONDS,\n now: this.runtime.clock.now(),\n lockToken: claim.lockToken,\n }),\n );\n }\n }\n\n /** Resolve once the last in-flight handler has settled. */\n private async awaitIdle(): Promise<void> {\n const pollMs = secondsToMs(DRAIN_POLL_SECONDS, 'drain poll');\n while (this.activeCount > 0) await elapses(pollMs);\n }\n\n /** @internal Try to cooperatively cancel an active job on this instance. */\n cancelRunning(jobId: string): boolean {\n const active = this.execution.active.get(jobId);\n if (!active) return false;\n active.controller.abort();\n return true;\n }\n}\n\n/** A promise that resolves once `ms` has passed, on a timer that never holds the loop open. */\nfunction elapses(ms: number): Promise<void> {\n return new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, Math.max(ms, 0));\n timer.unref?.();\n });\n}\n","/**\n * An injectable clock so delay/cron/backoff/retention/visibility\n * logic is testable deterministically without real waiting.\n */\nexport interface Clock {\n now(): number;\n date(): Date;\n}\n\n/** The real system clock used in production. */\nexport class SystemClock implements Clock {\n now(): number {\n return Date.now();\n }\n date(): Date {\n return new Date();\n }\n}\n\n/** A manually-advanced clock for tests. */\nexport class FakeClock implements Clock {\n private current: number;\n\n constructor(start: number | Date = 0) {\n this.current = start instanceof Date ? start.getTime() : start;\n }\n\n now(): number {\n return this.current;\n }\n\n date(): Date {\n return new Date(this.current);\n }\n\n /** Advance the clock by `ms` and return the new time. */\n advance(ms: number): number {\n this.current += ms;\n return this.current;\n }\n\n /** Jump to an absolute time. */\n set(time: number | Date): void {\n this.current = time instanceof Date ? time.getTime() : time;\n }\n}\n","import { CancelOutcome, FailureDetail, PauseMode } from './options/enums';\nimport { PortQueueEvent } from './events/event-name.enum';\nimport { DriverCapability } from './drivers/driver-capabilities';\nimport { ConsoleLogger } from './logging/console-logger';\nimport { EventBusService } from './events/event-bus.service';\nimport { HookRunner } from './events/hook-runner';\nimport { OptionResolver } from './options/option-resolver';\nimport { Wakeup } from './pubsub/wakeup';\nimport { QueueRegistry } from './producer/queue-registry';\nimport { NotifierService } from './pubsub/notifier.service';\nimport { ProducerService } from './producer/producer.service';\nimport { ReadService } from './monitoring/stats.service';\nimport { CompletionService } from './consumer/completion.service';\nimport { ClientRegistryService } from './client/client-registry.service';\nimport { ClientLifecycleService } from './client/client-lifecycle.service';\nimport { BackgroundWork } from './client/background-work';\nimport { DashboardService } from './dashboard/dashboard.service';\nimport { CliService } from './cli/cli.service';\nimport { Queue } from './producer/queue';\nimport { Worker, type WorkerConfig } from './consumer/worker';\nimport { JobStatus } from './jobs/job-state.enum';\nimport {\n InstanceActiveError,\n InvalidOptionsError,\n JobNotFoundError,\n NotStartedError,\n QueueInUseError,\n QueueNotFoundError,\n} from './errors/errors';\nimport { SystemClock } from './util/clock';\nimport { secondsToMs } from './util/seconds';\nimport { assertBatchIds } from './util/batch-ids';\nimport {\n DEFAULT_CONCURRENCY,\n DEFAULT_FAILURE_DETAIL,\n DEFAULT_LOCK_DURATION_SECONDS,\n DEFAULT_POLL_INTERVAL_SECONDS,\n DEFAULT_SHUTDOWN_TIMEOUT_SECONDS,\n DEFAULT_TICK_INTERVAL_SECONDS,\n INSTANCE_REMOVAL_STALE_SECONDS,\n} from './constants';\nimport type { PortQueueOptions, ShutdownOptions } from './options/client-options';\nimport type { CreateQueueOptions, ErrorClass } from './options/queue-options';\nimport type { LimiterOptions } from './options/common';\nimport type { AddJobOptions } from './options/job-options';\nimport type { JobHandler } from './jobs/job';\nimport type { Logger } from './logging/logger.interface';\nimport type { Runtime } from './client/runtime';\nimport type { HookRegistration } from './events/hooks';\nimport type { TransactionHandle } from './tx/transaction-handle';\nimport type { QueueRow } from './jobs/job-record';\nimport type { EventListener, Unsubscribe } from './events/event-name.enum';\nimport type {\n AddJobResult,\n GetInstancesQuery,\n GetJobsQuery,\n GetQueuesQuery,\n GetSchedulesQuery,\n InstanceInfo,\n JobSnapshot,\n Page,\n QueueInfo,\n QueueStats,\n ScheduleInfo,\n} from './producer/results';\n\n/**\n * The top-level client, and **the whole developer-facing surface**. Owns connection, migration,\n * shared services, and the queue declarations. A thin facade — all real work lives in focused\n * services. Construction wires dependencies only; no I/O until `init()`.\n *\n * Every operation lives here rather than on the handle `createQueue` returns: that is a registration\n * with no methods (see {@link Queue}). A per-queue operation takes `queue` as a named argument, so one\n * import reaches every queue and no read can silently escape the scope its handle implied. There is\n * also no `createWorker`: one `createQueue` call declares a queue *and*, if it carries a `handler`,\n * consumes it.\n *\n * @typeParam TQueues - an optional string enum/union of this app's queue names, threaded\n * through every queue-name argument for compile-time safety (defaults to `string`).\n */\nexport class PortQueue<TQueues extends string = string> {\n private readonly runtime: Runtime;\n private readonly producer: ProducerService;\n private readonly reads: ReadService;\n private readonly completion: CompletionService;\n private readonly clientRegistry: ClientRegistryService;\n private readonly lifecycle: ClientLifecycleService;\n private readonly events: EventBusService;\n private readonly hooks: HookRunner;\n private readonly state = { running: false };\n private readonly headless: boolean;\n\n /**\n * Internal facade for `@portqueue/dashboard`. **Not a developer API** — it is undocumented,\n * unsupported for application code, and free to change in any release. Its purpose is to keep\n * the dashboard's needs off the public surface: when the dashboard wants something this class\n * doesn't already document, the method goes here rather than on `PortQueue`.\n */\n readonly _dashboard: DashboardService;\n\n /**\n * Internal facade for `@portqueue/cli`, with the same contract as {@link _dashboard}.\n */\n readonly _cli: CliService;\n\n constructor(options: PortQueueOptions) {\n if (!options.driver) {\n throw new InvalidOptionsError(\n 'PortQueue requires a `driver`. Pass a driver instance, e.g. `new SqliteDriver(...)`.',\n );\n }\n this.headless = options._headless === true;\n if (this.headless && options.instance?.instanceKey) {\n throw new InvalidOptionsError(\n 'A headless PortQueue (the dashboard or CLI) cannot take an `instance.instanceKey`. An ' +\n 'admin client is anonymous: it registers no instance row, so naming it would put a ' +\n 'heartbeat in the instances list for a process that never claims a job.',\n );\n }\n const logger = resolveLogger(options.logger);\n const clock = options.clock ?? new SystemClock();\n const context = options.driver.context;\n this.events = new EventBusService(logger);\n this.hooks = new HookRunner(logger, this.events);\n const resolver = new OptionResolver();\n const wakeup = new Wakeup();\n const registry = new QueueRegistry(options.driver, clock, {\n tickIntervalSeconds: options.tickIntervalSeconds ?? DEFAULT_TICK_INTERVAL_SECONDS,\n headless: this.headless,\n });\n this.clientRegistry = new ClientRegistryService();\n\n this.runtime = {\n driver: options.driver,\n context,\n logger,\n clock,\n events: this.events,\n hooks: this.hooks,\n resolver,\n options,\n registry,\n wakeup,\n background: new BackgroundWork(),\n // A headless client is anonymous by construction — no instance row, no affinity, no pause.\n instanceKey: this.headless ? null : (options.instance?.instanceKey ?? null),\n instances: null,\n headless: this.headless,\n isRunning: () => this.state.running,\n cancelRunning: (jobId: string) => this.clientRegistry.cancelRunning(jobId),\n isJobRunningHere: (jobId: string) => this.clientRegistry.isRunning(jobId),\n };\n\n const notifier = new NotifierService(\n options.driver,\n logger,\n options.driver.capabilities[DriverCapability.LISTEN_NOTIFY],\n );\n this.producer = new ProducerService(this.runtime, notifier);\n this.reads = new ReadService(this.runtime);\n this.completion = new CompletionService(this.runtime);\n this.lifecycle = new ClientLifecycleService(this.runtime, this.clientRegistry, this.state);\n this._dashboard = new DashboardService(this.runtime, this.reads, this.producer);\n this._cli = new CliService(this.runtime, this.producer);\n }\n\n // --- Lifecycle ---\n async init(): Promise<void> {\n await this.lifecycle.init();\n }\n\n async shutdown(options: ShutdownOptions = {}): Promise<void> {\n await this.lifecycle.shutdown({\n graceful: options.graceful ?? true,\n timeoutSeconds: options.timeoutSeconds ?? DEFAULT_SHUTDOWN_TIMEOUT_SECONDS,\n });\n }\n\n get isRunning(): boolean {\n return this.state.running;\n }\n\n /** Force-apply migrations (the programmatic MANUAL path). */\n migrate(): Promise<void> {\n return this.lifecycle.migrate();\n }\n\n // --- Registrations ---\n /**\n * Declare a queue in this process — **everything about it, in one call**: the `handler` that\n * processes its jobs, the `limiter` / `dontAutoretryFor` settings that shape how it claims them, and\n * the `defaultJobOptions`, `retention` and `hooks` its jobs inherit.\n *\n * The handler is required: declaring a queue *is* declaring that this process consumes it. A process\n * that only enqueues declares nothing — {@link addJob} addresses a queue by name and creates its row\n * on first use, so an API tier can produce onto a queue its worker tier consumes.\n *\n * The returned {@link Queue} carries the name and the payload type and nothing else — every\n * operation is a method on this class.\n *\n * A queue is declared **once per process**: a second call for the same name throws, because two\n * handlers would run two claim loops over the same rows. This is also the only thing that records\n * queue options, and nothing internal calls it — `pauseQueue`, `getJobs`, the dashboard and the CLI\n * all address a queue by name — so an admin action can never blank the defaults a declaration set.\n *\n * On a headless client (the dashboard or CLI) this declares nothing, writes nothing and consumes\n * nothing; it only hands back a typed name.\n */\n createQueue<TData = unknown, TResult = unknown>(\n options: CreateQueueOptions<TData, TResult, TQueues>,\n ): Queue<TData> {\n const { name, handler, limiter, dontAutoretryFor, ...queueOptions } = options;\n // Every rule about the *call* is checked before anything is recorded: a rejected declaration\n // must not have replaced the queue's options or its hooks on its way to throwing.\n if (typeof handler !== 'function') {\n throw new InvalidOptionsError(\n `createQueue for queue '${name}' requires 'handler' to be a function — a queue is declared ` +\n `by the process that processes it. To only enqueue, skip createQueue and call ` +\n `pq.addJob({ queue: '${name}', data }), which creates the queue's row on first use.`,\n { queue: name },\n );\n }\n if (this.clientRegistry.hasWorker(name)) {\n throw new InvalidOptionsError(\n `Queue '${name}' already has a handler in this process. A queue is consumed by at most ` +\n `one handler per process — two claim loops over the same rows only compete for them. ` +\n `Raise 'limiter.concurrency' to process more jobs at once, or run another instance.`,\n { queue: name },\n );\n }\n if ((limiter?.rateMax == null) !== (limiter?.rateDurationSeconds == null)) {\n throw new InvalidOptionsError(\n `createQueue for queue '${name}' set only one half of the rate cap. ` +\n `'limiter.rateMax' and 'limiter.rateDurationSeconds' define one setting — how many jobs ` +\n `may start per window — so either both are given or neither is.`,\n { queue: name },\n );\n }\n this.runtime.registry.declare(name, queueOptions);\n if (!this.headless) {\n // Reached at most once per queue: the handler check above rejects a second declaration, so\n // these hooks can never stack duplicates onto every add.\n for (const hook of queueOptions.hooks ?? []) {\n this.hooks.register(hook.queue ? hook : { ...hook, queue: name });\n }\n this.startConsuming(\n name,\n handler as JobHandler,\n limiter,\n dontAutoretryFor,\n queueOptions.failureDetail,\n );\n }\n const existing = this.clientRegistry.getQueue(name) as Queue<TData> | undefined;\n if (existing) return existing;\n const queue = new Queue<TData>(name);\n this.clientRegistry.addQueue(name, queue as Queue<unknown>);\n return queue;\n }\n\n /**\n * Build the claim loop behind a queue that declared a `handler`, and start it if the client is\n * already running. Internal: there is no worker on the public surface, so nothing is handed back.\n */\n private startConsuming(\n queue: string,\n handler: JobHandler,\n limiterOptions: LimiterOptions = {},\n dontAutoretryFor: Array<ErrorClass | string> = [],\n failureDetail: FailureDetail = DEFAULT_FAILURE_DETAIL,\n ): void {\n const limiter = limiterOptions;\n const concurrency = limiter.concurrency ?? DEFAULT_CONCURRENCY;\n const rate =\n limiter.rateMax != null && limiter.rateDurationSeconds != null\n ? { max: limiter.rateMax, durationSeconds: limiter.rateDurationSeconds }\n : null;\n const config: WorkerConfig = {\n queue,\n handler,\n concurrency,\n batchSize: limiter.batchSize ?? concurrency,\n lockDurationSeconds: limiter.lockDurationSeconds ?? DEFAULT_LOCK_DURATION_SECONDS,\n // LISTEN/NOTIFY-capable engines wake instantly on new jobs and only fall back to polling as a\n // safety net; non-notify engines poll on this cadence. Lower it via\n // `limiter.pollIntervalSeconds` for snappier pickup.\n pollIntervalSeconds: limiter.pollIntervalSeconds ?? DEFAULT_POLL_INTERVAL_SECONDS,\n ...(rate ? { limiter: rate } : {}),\n dontAutoretryFor,\n failureDetail,\n };\n const worker = new Worker(\n this.runtime,\n this.completion,\n config,\n () => this.lifecycle.systemPressureHigh,\n );\n this.clientRegistry.addWorker(queue, worker);\n if (this.state.running) void worker.start();\n }\n\n // --- Producing ---\n /** Add one job to a queue (or create a recurring schedule, with `schedule.cron`/`startEverySeconds`). */\n addJob<TData = unknown>(\n options: AddJobOptions<TData> & { queue: TQueues | string },\n ): Promise<AddJobResult> {\n this.requireStarted('addJob');\n const { queue, ...jobOptions } = options;\n return this.producer.addJob<TData>(queue, jobOptions as AddJobOptions<TData>);\n }\n\n /**\n * Add many one-off jobs to one queue in a **single** insert — one round trip for the whole batch\n * rather than two per job. Results come back in the order the jobs were given. Recurring entries\n * are rejected: each recurrence needs its own {@link addJob} so its result can carry a `scheduleId`.\n */\n addJobs<TData = unknown>(options: {\n queue: TQueues | string;\n jobs: Array<AddJobOptions<TData>>;\n }): Promise<AddJobResult[]> {\n this.requireStarted('addJobs');\n return this.producer.addJobs<TData>(options.queue, options.jobs);\n }\n\n // --- Reads ---\n /** A page of queues with their per-status counts, plus the total across every page. */\n getQueues(options: GetQueuesQuery = {}): Promise<Page<QueueInfo>> {\n this.requireStarted('getQueues');\n return this.reads.getQueues(options);\n }\n\n /** One queue by name, with the same counts and `inUse` flag the list carries. */\n getQueue(options: { name: TQueues | string }): Promise<QueueInfo | null> {\n this.requireStarted('getQueue');\n return this.reads.getQueue(options.name);\n }\n\n getQueueStats(options: { queue?: TQueues } = {}): Promise<QueueStats> {\n this.requireStarted('getQueueStats');\n return this.reads.getQueueStats(options.queue);\n }\n\n /** Client-wide stats across every queue — the same shape `getQueueStats` returns for one. */\n getQueuesStats(): Promise<QueueStats> {\n this.requireStarted('getQueuesStats');\n return this.reads.getQueueStats();\n }\n\n /** One job by id, from any queue. */\n getJob<TData = unknown>(options: { jobId: string }): Promise<JobSnapshot<TData> | null> {\n this.requireStarted('getJob');\n return this.reads.getJob<TData>(options.jobId);\n }\n\n /** A page of jobs, newest first. Narrow with `queue`, `statuses` or `scheduleId`. */\n getJobs<TData = unknown>(\n options: GetJobsQuery & { queue?: TQueues | string } = {},\n ): Promise<Page<JobSnapshot<TData>>> {\n this.requireStarted('getJobs');\n return this.reads.getJobs<TData>(options);\n }\n\n /** A page of recurring schedules — one queue's with `queue`, every queue's without it. */\n getSchedules(\n options: GetSchedulesQuery & { queue?: TQueues | string } = {},\n ): Promise<Page<ScheduleInfo>> {\n this.requireStarted('getSchedules');\n return this.producer.getSchedules(options);\n }\n\n /** One schedule by id, with the queue it produces onto. Null if unknown. */\n getSchedule(options: { scheduleId: string }): Promise<ScheduleInfo | null> {\n this.requireStarted('getSchedule');\n return this.producer.getSchedule(options.scheduleId);\n }\n\n // --- Job control ---\n /**\n * Requeue a **settled** job to run again — its own row is re-armed with its persisted data (status\n * back to `PENDING`, retry counters, lock, return value and timestamps reset). To start a fresh\n * run instead, add a new job with {@link addJob}.\n *\n * A **running** job is never re-armed: clearing its lock would let a second worker claim it while\n * the first handler is still going, so an `ACTIVE` job — like an unknown id — returns `null`.\n * Cancel it first with {@link cancelJob} and retry once it has settled.\n */\n async retryJob(options: { jobId: string; tx?: TransactionHandle }): Promise<AddJobResult | null> {\n this.requireStarted('retryJob');\n const requeued = await this.runtime.driver.requeueJob({\n jobId: options.jobId,\n now: this.runtime.clock.now(),\n ...(options.tx ? { tx: options.tx } : {}),\n });\n if (!requeued) return null;\n this.runtime.wakeup.signal(requeued.queueName);\n this.events.emit(PortQueueEvent.JOB_ADDED, {\n jobId: requeued.jobId,\n queue: requeued.queueName,\n deduplicated: false,\n });\n return {\n jobId: requeued.jobId,\n queue: requeued.queueName,\n status: requeued.status,\n startAfter: new Date(requeued.startAfter),\n deduplicated: false,\n };\n }\n\n /**\n * Cancel a job, and report **what actually happened** — see {@link CancelOutcome}.\n *\n * A job running in this process cannot be cancelled from outside its handler, only asked to stop:\n * its `AbortSignal` fires and the outcome is `SIGNALLED`, because a handler that ignores\n * `job.signal` runs to completion and the row ends `COMPLETED`. A pending or delayed job is marked\n * `CANCELLED` so it never runs, and that is the only case that reports `CANCELLED`.\n *\n * Throws {@link JobNotFoundError} for an id that names no row: there is no honest outcome for\n * cancelling a job that does not exist.\n */\n async cancelJob(options: { jobId: string; tx?: TransactionHandle }): Promise<CancelOutcome> {\n this.requireStarted('cancelJob');\n // A locally-running handler owns its row's outcome — fire its signal and let it settle,\n // rather than racing a DB write against its completion.\n if (this.runtime.cancelRunning?.(options.jobId)) return CancelOutcome.SIGNALLED;\n const cancelled = await this.runtime.driver.cancelJob({\n jobId: options.jobId,\n now: this.runtime.clock.now(),\n ...(options.tx ? { tx: options.tx } : {}),\n });\n if (cancelled) {\n this.events.emit(PortQueueEvent.JOB_CANCELLED, {\n jobId: cancelled.jobId,\n queue: cancelled.queueName,\n });\n return CancelOutcome.CANCELLED;\n }\n // Nothing was cancellable, and the two reasons read very differently to an operator. One read\n // separates them — on the refusal path only, never on a cancel that worked.\n const row = await this.runtime.driver.getJob({\n jobId: options.jobId,\n ...(options.tx ? { tx: options.tx } : {}),\n });\n if (!row) throw new JobNotFoundError(options.jobId);\n return CancelOutcome.NOT_CANCELLABLE;\n }\n\n /**\n * Remove a single job's row. Never removes a **running** job: an `ACTIVE` row is skipped and this\n * returns `false` without touching it — cancel it first with {@link cancelJob}, then remove it once\n * it has settled.\n */\n async removeJob(options: { jobId: string; tx?: TransactionHandle }): Promise<boolean> {\n this.requireStarted('removeJob');\n const removed = await this.runtime.driver.removeJob({\n jobId: options.jobId,\n ...(options.tx ? { tx: options.tx } : {}),\n });\n if (!removed) return false;\n this.events.emit(PortQueueEvent.JOB_REMOVED, {\n jobId: removed.jobId,\n queue: removed.queueName,\n });\n return true;\n }\n\n /**\n * Remove many jobs — either a set of ids (from any queue) or every job on one queue in the given\n * statuses. Returns how many rows went away.\n *\n * `ACTIVE` is refused both ways: by id an active row is skipped, and by status it throws, because\n * deleting a running job's row would yank it out from under its handler.\n */\n async removeJobs(\n options: ({ jobIds: string[] } | { queue: TQueues | string; statuses: JobStatus[] }) & {\n tx?: TransactionHandle;\n },\n ): Promise<number> {\n this.requireStarted('removeJobs');\n if ('jobIds' in options) {\n assertBatchIds(options.jobIds, 'removeJobs({ jobIds })');\n const removed = await this.runtime.driver.removeJobs({\n jobIds: options.jobIds,\n ...(options.tx ? { tx: options.tx } : {}),\n });\n for (const ref of removed) {\n this.events.emit(PortQueueEvent.JOB_REMOVED, {\n jobId: ref.jobId,\n queue: ref.queueName,\n });\n }\n return removed.length;\n }\n if (options.statuses.includes(JobStatus.ACTIVE)) {\n throw new InvalidOptionsError(\n `Cannot remove jobs by status ACTIVE on queue '${options.queue}': an ACTIVE job is ` +\n `running. Cancel it first with cancelJob({ jobId }), then remove it once it has settled.`,\n { queue: options.queue },\n );\n }\n return this.runtime.driver.removeJobsByStatus({\n queueName: options.queue,\n statuses: options.statuses,\n ...(options.tx ? { tx: options.tx } : {}),\n });\n }\n\n /** Remove a recurring schedule by id. Returns true when a schedule went away. */\n async removeSchedule(options: { scheduleId: string; tx?: TransactionHandle }): Promise<boolean> {\n this.requireStarted('removeSchedule');\n const removed = await this.runtime.driver.deleteSchedule({\n scheduleId: options.scheduleId,\n ...(options.tx ? { tx: options.tx } : {}),\n });\n if (!removed) return false;\n this.events.emit(PortQueueEvent.SCHEDULE_REMOVED, {\n scheduleId: removed.scheduleId,\n queue: removed.queueName,\n });\n return true;\n }\n\n // --- Events & hooks ---\n on<E extends PortQueueEvent>(\n event: E,\n listener: EventListener<E>,\n filter?: { queue?: TQueues },\n ): Unsubscribe {\n return this.events.on(event, listener, filter);\n }\n once<E extends PortQueueEvent>(\n event: E,\n listener: EventListener<E>,\n filter?: { queue?: TQueues },\n ): Unsubscribe {\n return this.events.once(event, listener, filter);\n }\n off<E extends PortQueueEvent>(event: E, listener: EventListener<E>): void {\n this.events.off(event, listener);\n }\n useHook(hook: HookRegistration): Unsubscribe {\n return this.hooks.register(hook);\n }\n\n // --- Queue control (persisted, cluster-wide) ---\n /**\n * Stop workers everywhere from claiming this queue's jobs. With `mode: PauseMode.ALL` the queue\n * also refuses new jobs.\n *\n * This flips the queue row's two flags and touches nothing else — in particular it does **not**\n * re-declare the queue, so it can never overwrite the default job options or retention policy a\n * `createQueue` registered. A queue this process declared is created first if it has not produced\n * anything yet (its row is written lazily); a name nothing has ever used throws\n * {@link QueueNotFoundError} rather than conjuring a paused queue no code consumes.\n */\n async pauseQueue(options: { queue: TQueues | string; mode?: PauseMode }): Promise<void> {\n this.requireStarted('pauseQueue');\n const mode = options.mode ?? PauseMode.PROCESSING;\n // `setPaused` throws when no row matched, so everything after it describes a write that\n // happened: the cache is refreshed and the event is emitted only on success. The `if (row)` that\n // used to guard the cache update was dead code reading as though null were tolerated.\n const row = await this.setPaused(options.queue, true, mode === PauseMode.ALL);\n this.runtime.registry.update(row);\n this.events.emit(PortQueueEvent.QUEUE_PAUSED, { queue: options.queue, mode });\n }\n\n /** Resume claiming (and accepting) on this queue. See {@link pauseQueue} for what it touches. */\n async resumeQueue(options: { queue: TQueues | string }): Promise<void> {\n this.requireStarted('resumeQueue');\n const row = await this.setPaused(options.queue, false, false);\n this.runtime.registry.update(row);\n this.runtime.wakeup.signal(options.queue);\n this.events.emit(PortQueueEvent.QUEUE_RESUMED, { queue: options.queue });\n }\n\n /**\n * Write both pause flags and return the updated row, so the cached flags this process's workers\n * read are refreshed without a second query. Throws {@link QueueNotFoundError} when the name\n * matched nothing — there is no \"paused nothing\" outcome to report.\n */\n private async setPaused(\n queue: string,\n processingPaused: boolean,\n acceptingPaused: boolean,\n ): Promise<QueueRow> {\n // A queue declared here may not have written its row yet (it is created on first use), so\n // ensure it before pausing. `ensure` only creates the row; it never writes queue options.\n if (this.runtime.registry.isRegistered(queue)) await this.runtime.registry.ensure(queue);\n const row = await this.runtime.driver.setQueuePaused({\n queueName: queue,\n processingPaused,\n acceptingPaused,\n now: this.runtime.clock.now(),\n });\n if (!row) throw new QueueNotFoundError(queue);\n return row;\n }\n\n /**\n * Manually remove a queue's row from the database. Refuses if the queue is still declared in\n * *this* process (via `createQueue`) — a running process must not have its queue deleted from\n * under it. The tool never removes queues automatically; this is an admin action\n * for queues no longer used by any running code. Job rows link by name (no FK) and are untouched.\n */\n async removeQueue(options: { name: TQueues | string }): Promise<boolean> {\n this.requireStarted('removeQueue');\n if (this.runtime.registry.isRegistered(options.name)) {\n throw new QueueInUseError(options.name);\n }\n const ok = await this.runtime.driver.deleteQueue({ name: options.name });\n if (ok) this.events.emit(PortQueueEvent.QUEUE_REMOVED, { queue: options.name });\n return ok;\n }\n\n // --- Instances (multi-instance mode) ---\n /** A page of known instances with liveness + per-instance job attribution, plus the total. */\n getInstances(options: GetInstancesQuery = {}): Promise<Page<InstanceInfo>> {\n this.requireStarted('getInstances');\n return this.reads.getInstances(options);\n }\n\n /** One instance by key, with the same liveness, health and attribution the list carries. */\n getInstance(options: { instanceKey: string }): Promise<InstanceInfo | null> {\n this.requireStarted('getInstance');\n return this.reads.getInstance(options.instanceKey);\n }\n\n /** Stop the named instance from claiming jobs (persisted; the target picks it up on heartbeat). */\n async pauseInstance(options: { instanceKey: string }): Promise<void> {\n this.requireStarted('pauseInstance');\n await this.runtime.driver.setInstancePaused({\n instanceKey: options.instanceKey,\n processingPaused: true,\n now: this.runtime.clock.now(),\n });\n // If pausing ourselves, reflect it immediately rather than waiting for the next beat.\n if (this.runtime.instances?.instanceKey === options.instanceKey) {\n await this.runtime.instances.beat();\n }\n this.events.emit(PortQueueEvent.INSTANCE_PAUSED, { instanceKey: options.instanceKey });\n }\n\n /** Resume the named instance's job claiming. */\n async resumeInstance(options: { instanceKey: string }): Promise<void> {\n this.requireStarted('resumeInstance');\n await this.runtime.driver.setInstancePaused({\n instanceKey: options.instanceKey,\n processingPaused: false,\n now: this.runtime.clock.now(),\n });\n if (this.runtime.instances?.instanceKey === options.instanceKey) {\n await this.runtime.instances.beat();\n }\n this.runtime.wakeup.signalAll();\n this.events.emit(PortQueueEvent.INSTANCE_RESUMED, { instanceKey: options.instanceKey });\n }\n\n /**\n * Manually remove a long-inactive instance's monitoring row. Refuses unless the instance has not\n * heartbeat for at least 30 minutes (a live or recently-seen instance would just re-register on\n * its next beat). Jobs record the processing instance key as a plain string (no FK), so removal\n * never touches job rows — it only tidies the instances list. The tool never does this itself.\n */\n async removeInstance(options: { instanceKey: string }): Promise<boolean> {\n this.requireStarted('removeInstance');\n const row = await this.runtime.driver.getInstance({ instanceKey: options.instanceKey });\n if (!row) return false;\n const now = this.runtime.clock.now();\n const staleAfterMs = secondsToMs(\n INSTANCE_REMOVAL_STALE_SECONDS,\n 'instance removal staleness window',\n );\n if (row.lastSeenAt >= now - staleAfterMs) {\n throw new InstanceActiveError(options.instanceKey);\n }\n const ok = await this.runtime.driver.deleteInstance({ instanceKey: options.instanceKey });\n if (ok) this.events.emit(PortQueueEvent.INSTANCE_REMOVED, { instanceKey: options.instanceKey });\n return ok;\n }\n\n /**\n * Every method that touches the database goes through this first. Before `init()` the driver is\n * not connected, and the failure the caller used to get was whatever the driver said about its own\n * connection — which named neither the mistake nor the fix.\n */\n private requireStarted(method: string): void {\n if (!this.state.running) throw new NotStartedError(method);\n }\n}\n\nfunction resolveLogger(logger: PortQueueOptions['logger']): Logger {\n if (logger && typeof (logger as Logger).info === 'function') return logger as Logger;\n return new ConsoleLogger((logger as ConstructorParameters<typeof ConsoleLogger>[0]) ?? {});\n}\n"],"names":["FailureDetail","PortQueueEvent","LogLevel","HookPhase","wholeSecondsToMs","wholeSeconds","BackoffStrategy","secondsToMs","QueueNotFoundError","PubSubChannel","InvalidOptionsError","CronExpressionParser","result","QueuePausedError","JobStatus","DeduplicationReason","emptyStatusCounts","msToSeconds","LockLostError","DriverCapability","matchesInstance","cpuUsage","performance","availableParallelism","monitorEventLoopDelay","getHeapStatistics","latestVersion","MigrationMode","SchemaVersionMismatchError","migration","MigrationFailedError","ShutdownTimeoutError","MAX_BATCH_IDS","JobBatchAction","CancelOutcome","JobNotFoundError","PauseMode","QueueInUseError","InstanceActiveError","NotStartedError"],"mappings":";;;;;;;;;AASO,MAAM,gCAAgC;AAGtC,MAAM,8BAA8B;AAGpC,MAAM,qCAAqC;AAM3C,MAAM,wBAAwB;AAG9B,MAAM,iCAAiC,KAAK;AAG5C,MAAM,mCAAmC;AAGzC,MAAM,kCAAkC;AAGxC,MAAM,iCAAiC;AAOvC,MAAM,gBAAgB;AAGtB,MAAM,8BAA8B;ACxCpC,MAAM,sBAAsB;AAM5B,MAAM,gCAAgC;AAGtC,MAAM,gCAAgC;AAGtC,MAAM,6BAA6B;AAGnC,MAAM,6BAA6B;AAGnC,MAAM,qBAAqB;AAS3B,MAAM,sBAAsB;AAM5B,MAAM,uBAAuB;ACjC7B,MAAM,qBAAqB;AAG3B,MAAM,iBAAiB;AAGvB,MAAM,2BAA2B;ACFjC,MAAM,uBAAuB;AAG7B,MAAM,wBAAwB;AAG9B,MAAM,sBAAsB;AAG5B,MAAM,uBAAuB;AAG7B,MAAM,yBAAyB;AAG/B,MAAM,0BAA0B;ACjBhC,MAAM,mBAAmB;AAGzB,MAAM,6BAA6B;AAGnC,MAAM,8BAA8B;AAGpC,MAAM,yBAAyB;AAM/B,MAAM,yBAAyBA,kBAAAA,cAAc;AAO7C,MAAM,4BAA4B;AAGlC,MAAM,oCAAoC;ACxB1C,IAAK,m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