gemi 0.222.1 → 0.223.0
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/dist/ai/index.js +1 -1
- package/dist/{chunk-ejvjn9tq.js → chunk-fn166jp3.js} +1 -1
- package/dist/{chunk-nqjchwdj.js → chunk-ke1q6hfm.js} +1 -1
- package/dist/chunk-p1ern8r4.js +577 -0
- package/dist/chunk-p1ern8r4.js.map +27 -0
- package/dist/{chunk-y8dpexn0.js → chunk-qtczhd81.js} +2 -2
- package/dist/{chunk-y8dpexn0.js.map → chunk-qtczhd81.js.map} +1 -1
- package/dist/{chunk-t7ppe7gt.js → chunk-qvxs1vjh.js} +1 -1
- package/dist/{chunk-dy01vy29.js → chunk-rw45xz3f.js} +3 -3
- package/dist/{chunk-dy01vy29.js.map → chunk-rw45xz3f.js.map} +3 -3
- package/dist/{chunk-qvspq5tm.js → chunk-sqyf0gey.js} +1 -1
- package/dist/console/run.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.d.ts +2 -1
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/queue/DatabaseQueueDriver.d.ts +16 -0
- package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
- package/dist/services/queue/DatabaseSlots.d.ts +100 -0
- package/dist/services/queue/DatabaseSlots.d.ts.map +1 -0
- package/dist/services/queue/Job.d.ts +20 -3
- package/dist/services/queue/Job.d.ts.map +1 -1
- package/dist/services/queue/MemoryQueueDriver.d.ts +11 -1
- package/dist/services/queue/MemoryQueueDriver.d.ts.map +1 -1
- package/dist/services/queue/QueueDriver.d.ts +24 -0
- package/dist/services/queue/QueueDriver.d.ts.map +1 -1
- package/dist/services/queue/QueueManager.d.ts +28 -8
- package/dist/services/queue/QueueManager.d.ts.map +1 -1
- package/dist/services/queue/slots.d.ts +111 -0
- package/dist/services/queue/slots.d.ts.map +1 -0
- package/dist/services/queue/work.js +1 -1
- package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts +2 -0
- package/dist/services/queue/workflow/MemoryWorkflowStore.d.ts.map +1 -1
- package/dist/services/queue/workflow/Workflow.d.ts +16 -0
- package/dist/services/queue/workflow/Workflow.d.ts.map +1 -1
- package/dist/services/queue/workflow/WorkflowRuntime.d.ts +10 -0
- package/dist/services/queue/workflow/WorkflowRuntime.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-9kdqdjdf.js +0 -521
- package/dist/chunk-9kdqdjdf.js.map +0 -25
- /package/dist/{chunk-ejvjn9tq.js.map → chunk-fn166jp3.js.map} +0 -0
- /package/dist/{chunk-nqjchwdj.js.map → chunk-ke1q6hfm.js.map} +0 -0
- /package/dist/{chunk-t7ppe7gt.js.map → chunk-qvxs1vjh.js.map} +0 -0
- /package/dist/{chunk-qvspq5tm.js.map → chunk-sqyf0gey.js.map} +0 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../services/lock/DatabaseLockStore.ts", "../services/lock/MemoryLockStore.ts", "../services/queue/workflow/WorkflowStore.ts", "../services/queue/workflow/DatabaseWorkflowStore.ts", "../services/queue/batch.ts", "../services/queue/DatabaseSlots.ts", "../services/queue/DatabaseQueueDriver.ts", "../services/queue/config.ts", "../services/queue/workflow/MemoryWorkflowStore.ts", "../services/queue/slots.ts", "../services/queue/MemoryQueueDriver.ts", "../services/queue/QueueManager.ts", "../services/queue/Job.ts", "../services/queue/backoff.ts", "../services/queue/workflow/Step.ts", "../services/queue/workflow/wire.ts", "../services/queue/workflow/WorkflowRuntime.ts", "../services/queue/workflow/ItemSource.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"import type { SQL } from \"bun\";\n\nimport type { DatabaseConnection } from \"../../database/Connection\";\nimport type { Dialect } from \"../../database/dialect\";\nimport { runOnConnection, withTransaction } from \"../../orm/context\";\nimport { LockLostError, type LockStore } from \"./LockStore\";\n\nexport type DatabaseLockStoreOptions = {\n /**\n * The locks table. Default `gemi_locks`. A plain identifier, because it is\n * spliced into every statement.\n */\n table?: string;\n /**\n * SQLite only: the busy timeout given to a connection still at SQLite's `0`,\n * as `DatabaseQueueDriver` does. Default `1000`; `0` leaves the connection\n * alone.\n */\n busyTimeout?: number;\n};\n\n/**\n * Locks in a table of the application's database, so every process sharing\n * the database sees the same holder. One row per lock name, kept after\n * release so the name's fencing token keeps growing.\n *\n * Every statement is a single atomic row update, guarded by the holder's\n * owner, token and lease: `acquire` is \"take the row if its lease ran out\",\n * `extend` and `release` are \"change the row if it is still mine\". Leases are\n * measured on the database's clock, as the queue's are, so skewed replicas\n * agree on when one ran out. No Redis is involved.\n *\n * `fence` opens a transaction that locks the row first (`SELECT … FOR UPDATE`\n * on Postgres and MySQL, a write on SQLite, which takes the file's write\n * lock), so a new holder's `acquire` waits until the fenced work commits.\n *\n * Written for SQLite, Postgres and MySQL 8 / MariaDB 10.6+, like the queue's\n * driver.\n */\nexport class DatabaseLockStore implements LockStore {\n readonly table: string;\n private readonly sql: SQL;\n private readonly dialect: Dialect;\n private readonly connection: string | undefined;\n private readonly busyTimeout: number;\n private configured: Promise<void> | undefined;\n\n constructor(\n connection: Pick<DatabaseConnection, \"sql\" | \"dialect\"> &\n Partial<Pick<DatabaseConnection, \"name\">>,\n options: DatabaseLockStoreOptions = {},\n ) {\n const table = options.table ?? \"gemi_locks\";\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {\n throw new Error(\n `The lock table name \"${table}\" is not a plain identifier. Use ` +\n `letters, digits and underscores.`,\n );\n }\n this.table = table;\n this.sql = connection.sql;\n this.dialect = connection.dialect;\n this.connection = connection.name;\n this.busyTimeout = options.busyTimeout ?? 1000;\n }\n\n /** Creates the table if it does not exist; the DDL Prisma makes for the model in the docs. */\n async createTable(): Promise<void> {\n await this.configure();\n for (const statement of createLockTableStatements(this.dialect, this.table)) {\n await this.sql.unsafe(statement);\n }\n }\n\n async acquire(name: string, owner: string, ttlMs: number): Promise<number | null> {\n await this.configure();\n const q = this.sql;\n const now = this.now(q);\n await this.seed(q, name);\n\n if (this.mysql) {\n const result = await q`\n UPDATE ${this.name(q)}\n SET owner = ${owner}, token = token + 1, expires_at = ${now} + ${this.ms(q, ttlMs)},\n updated_at = ${now}\n WHERE name = ${name} AND expires_at <= ${now}\n `;\n if (affected(result) === 0) return null;\n // The owner is unique to this acquisition, so this reads our own row\n // unless the lease already ran out and was taken again.\n const [row] = (await q`\n SELECT token FROM ${this.name(q)} WHERE name = ${name} AND owner = ${owner}\n `) as Array<{ token: unknown }>;\n return row ? Number(row.token) : null;\n }\n\n const rows = (await q`\n UPDATE ${this.name(q)}\n SET owner = ${owner}, token = token + 1, expires_at = ${now} + ${this.ms(q, ttlMs)},\n updated_at = ${now}\n WHERE name = ${name} AND expires_at <= ${now}\n RETURNING token\n `) as Array<{ token: unknown }>;\n return rows[0] ? Number(rows[0].token) : null;\n }\n\n async extend(name: string, owner: string, token: number, ttlMs: number): Promise<boolean> {\n await this.configure();\n const q = this.sql;\n const now = this.now(q);\n const result = await q`\n UPDATE ${this.name(q)}\n SET expires_at = ${now} + ${this.ms(q, ttlMs)}, updated_at = ${now}\n WHERE name = ${name} AND owner = ${owner} AND token = ${token} AND expires_at > ${now}\n `;\n if (affected(result) > 0) return true;\n // MySQL counts changed rows, not matched ones, so a renewal that lands in\n // the same millisecond as the last one reports nothing changed.\n return this.mysql ? this.held(name, owner, token) : false;\n }\n\n async release(name: string, owner: string, token?: number): Promise<boolean> {\n await this.configure();\n const q = this.sql;\n const now = this.now(q);\n const byToken = token === undefined ? q`1 = 1` : q`token = ${token}`;\n const result = await q`\n UPDATE ${this.name(q)}\n SET owner = '', expires_at = 0, updated_at = ${now}\n WHERE name = ${name} AND owner = ${owner} AND ${byToken} AND expires_at > ${now}\n `;\n return affected(result) > 0;\n }\n\n async holder(name: string): Promise<{ owner: string; token: number } | null> {\n await this.configure();\n const q = this.sql;\n const [row] = (await q`\n SELECT owner, token FROM ${this.name(q)}\n WHERE name = ${name} AND expires_at > ${this.now(q)}\n `) as Array<{ owner: unknown; token: unknown }>;\n return row ? { owner: String(row.owner), token: Number(row.token) } : null;\n }\n\n async held(name: string, owner: string, token: number): Promise<boolean> {\n await this.configure();\n const q = this.sql;\n const rows = (await q`\n SELECT 1 AS held FROM ${this.name(q)}\n WHERE name = ${name} AND owner = ${owner} AND token = ${token} AND expires_at > ${this.now(q)}\n `) as unknown[];\n return rows.length > 0;\n }\n\n async advance(name: string, value: number): Promise<boolean> {\n await this.configure();\n const q = this.sql;\n await this.seed(q, name);\n const result = await q`\n UPDATE ${this.name(q)}\n SET token = ${this.int(q, value)}, updated_at = ${this.now(q)}\n WHERE name = ${name} AND token < ${this.int(q, value)}\n `;\n return affected(result) > 0;\n }\n\n async fence<T>(name: string, owner: string, token: number, fn: () => Promise<T>): Promise<T> {\n await this.configure();\n const body = async (tx: SQL) => {\n const now = this.now(tx);\n let ok: boolean;\n if (this.dialect === \"sqlite\") {\n // SQLite has no row locks; a write takes the file's write lock until\n // the commit, which is what keeps another holder out.\n const result = await tx`\n UPDATE ${this.name(tx)} SET updated_at = ${now}\n WHERE name = ${name} AND owner = ${owner} AND token = ${token} AND expires_at > ${now}\n `;\n ok = affected(result) > 0;\n } else {\n const rows = (await tx`\n SELECT 1 AS held FROM ${this.name(tx)}\n WHERE name = ${name} AND owner = ${owner} AND token = ${token} AND expires_at > ${now}\n FOR UPDATE\n `) as unknown[];\n ok = rows.length > 0;\n }\n if (!ok) throw new LockLostError(name, token);\n return fn();\n };\n\n const connection = this.connection;\n if (connection === undefined) {\n return (await this.sql.begin((tx) => body(tx))) as T;\n }\n // An ORM transaction on the store's own connection, so model writes in\n // `fn` join it and commit only while the hold is current.\n return withTransaction(this.sql, (tx) => runOnConnection(connection, () => body(tx)), {\n connection,\n });\n }\n\n /**\n * A fixed window in the lock's row: `token` is the count and `expires_at`\n * the window's end. One guarded `UPDATE` either starts a new window, counts\n * a hit in the current one, or matches nothing because it is full.\n */\n async hit(name: string, limit: number, windowMs: number) {\n await this.configure();\n const q = this.sql;\n const now = this.now(q);\n await this.seed(q, name);\n const window = this.ms(q, Math.max(1, windowMs));\n const result = await q`\n UPDATE ${this.name(q)}\n SET token = CASE WHEN expires_at <= ${now} THEN 1 ELSE token + 1 END,\n expires_at = CASE WHEN expires_at <= ${now} THEN ${now} + ${window} ELSE expires_at END,\n updated_at = ${now}\n WHERE name = ${name} AND (expires_at <= ${now} OR token < ${this.int(q, limit)})\n `;\n const allowed = affected(result) > 0;\n const [row] = (await q`\n SELECT expires_at - ${now} AS reset FROM ${this.name(q)} WHERE name = ${name}\n `) as Array<{ reset: unknown }>;\n return { allowed, resetInMs: Math.max(0, Number(row?.reset ?? 0)) };\n }\n\n async refund(name: string) {\n await this.configure();\n const q = this.sql;\n const now = this.now(q);\n await q`\n UPDATE ${this.name(q)} SET token = token - 1, updated_at = ${now}\n WHERE name = ${name} AND token > 0 AND expires_at > ${now}\n `;\n }\n\n /**\n * Deletes locks that are free and were last touched more than `olderThanMs`\n * ago, and resolves to how many. Tokens start again from 1 for a pruned\n * name, so keep `olderThanMs` far above any lease.\n */\n async prune(olderThanMs: number): Promise<number> {\n await this.configure();\n const q = this.sql;\n const now = this.now(q);\n const result = await q`\n DELETE FROM ${this.name(q)}\n WHERE expires_at <= ${now} AND updated_at <= ${now} - ${this.ms(q, olderThanMs)}\n `;\n return affected(result);\n }\n\n /** Makes sure the name has a row, free, so the guarded `UPDATE`s have something to match. */\n private async seed(q: SQL, name: string) {\n const now = this.now(q);\n if (this.mysql) {\n await q`\n INSERT IGNORE INTO ${this.name(q)} (name, owner, token, expires_at, updated_at)\n VALUES (${name}, '', 0, 0, ${now})\n `;\n return;\n }\n await q`\n INSERT INTO ${this.name(q)} (name, owner, token, expires_at, updated_at)\n VALUES (${name}, '', 0, 0, ${now})\n ON CONFLICT (name) DO NOTHING\n `;\n }\n\n private get mysql() {\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n }\n\n /** See `DatabaseQueueDriver.configure`. */\n private configure(): Promise<void> {\n if (this.dialect !== \"sqlite\" || this.busyTimeout === 0) return Promise.resolve();\n this.configured ??= (async () => {\n const [current] = (await this.sql.unsafe(\"PRAGMA busy_timeout\")) as Array<{\n timeout: number | string;\n }>;\n if (Number(current?.timeout ?? 0) !== 0) return;\n await this.sql.unsafe(`PRAGMA busy_timeout = ${this.busyTimeout}`);\n })().catch((error) => {\n this.configured = undefined;\n throw error;\n });\n return this.configured;\n }\n\n private name(q: SQL) {\n return q.unsafe(this.mysql ? `\\`${this.table}\\`` : `\"${this.table}\"`);\n }\n\n /** The database's clock in epoch milliseconds, as the queue driver reads it. */\n private now(q: SQL) {\n switch (this.dialect) {\n case \"postgres\":\n return q`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;\n case \"mysql\":\n case \"mariadb\":\n return q`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;\n case \"sqlite\":\n return q`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`;\n }\n }\n\n private ms(q: SQL, value: number) {\n return this.int(q, Math.max(0, Math.round(value)));\n }\n\n private int(q: SQL, value: number) {\n const n = Math.round(value);\n return this.mysql ? q`CAST(${n} AS SIGNED)` : q`CAST(${n} AS BIGINT)`;\n }\n}\n\nfunction affected(result: unknown): number {\n const counts = result as { count?: number | null; affectedRows?: number | null };\n return Math.max(Number(counts.count ?? 0), Number(counts.affectedRows ?? 0));\n}\n\n/** The locks table, as Prisma generates it for the model in the docs, with `IF NOT EXISTS`. */\nexport function createLockTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`name\\` VARCHAR(191) NOT NULL,\n \\`owner\\` VARCHAR(191) NOT NULL,\n \\`token\\` BIGINT NOT NULL DEFAULT 0,\n \\`expires_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n\n PRIMARY KEY (\\`name\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n const key = dialect === \"sqlite\" ? `\"name\" TEXT NOT NULL PRIMARY KEY,` : `\"name\" TEXT NOT NULL,`;\n const constraint =\n dialect === \"sqlite\" ? \"\" : `,\\n\\n CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"name\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n ${key}\n \"owner\" TEXT NOT NULL,\n \"token\" BIGINT NOT NULL DEFAULT 0,\n \"expires_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL${constraint}\n)`,\n ];\n}\n",
|
|
6
|
+
"import { LockLostError, type LockStore } from \"./LockStore\";\n\ntype Entry = {\n owner: string;\n token: number;\n expiresAt: number;\n /** Running `fence` calls. A fenced lock cannot change hands, lease or not. */\n fences: number;\n};\n\n/**\n * Locks in this process's memory. Correct for one process and useless across\n * several: two servers each have their own map, so each takes every lock. It\n * is what the queue uses with the memory driver, and in tests.\n */\nexport class MemoryLockStore implements LockStore {\n private readonly entries = new Map<string, Entry>();\n private readonly counters = new Map<string, number>();\n\n async acquire(name: string, owner: string, ttlMs: number): Promise<number | null> {\n const now = Date.now();\n const entry = this.entries.get(name);\n if (entry && (entry.expiresAt > now || entry.fences > 0)) return null;\n const token = (entry?.token ?? 0) + 1;\n this.entries.set(name, { owner, token, expiresAt: now + Math.max(0, ttlMs), fences: 0 });\n return token;\n }\n\n async extend(name: string, owner: string, token: number, ttlMs: number): Promise<boolean> {\n const entry = this.current(name, owner, token);\n if (!entry) return false;\n entry.expiresAt = Date.now() + Math.max(0, ttlMs);\n return true;\n }\n\n async release(name: string, owner: string, token?: number): Promise<boolean> {\n const entry = this.current(name, owner, token);\n if (!entry) return false;\n entry.owner = \"\";\n entry.expiresAt = 0;\n return true;\n }\n\n async holder(name: string) {\n const entry = this.entries.get(name);\n if (!entry || entry.expiresAt <= Date.now()) return null;\n return { owner: entry.owner, token: entry.token };\n }\n\n async held(name: string, owner: string, token: number): Promise<boolean> {\n return this.current(name, owner, token) !== undefined;\n }\n\n async advance(name: string, value: number): Promise<boolean> {\n if ((this.counters.get(name) ?? -Infinity) >= value) return false;\n this.counters.set(name, value);\n return true;\n }\n\n async fence<T>(name: string, owner: string, token: number, fn: () => Promise<T>): Promise<T> {\n const entry = this.current(name, owner, token);\n if (!entry) throw new LockLostError(name, token);\n entry.fences++;\n try {\n return await fn();\n } finally {\n entry.fences--;\n }\n }\n\n private readonly windows = new Map<string, { count: number; endsAt: number }>();\n\n async hit(name: string, limit: number, windowMs: number) {\n const now = Date.now();\n let window = this.windows.get(name);\n if (!window || window.endsAt <= now) {\n window = { count: 0, endsAt: now + Math.max(1, windowMs) };\n this.windows.set(name, window);\n }\n if (window.count >= limit) return { allowed: false, resetInMs: window.endsAt - now };\n window.count++;\n return { allowed: true, resetInMs: window.endsAt - now };\n }\n\n async refund(name: string) {\n const window = this.windows.get(name);\n if (window && window.endsAt > Date.now() && window.count > 0) window.count--;\n }\n\n private current(name: string, owner: string, token?: number) {\n const entry = this.entries.get(name);\n if (!entry || entry.owner !== owner || entry.expiresAt <= Date.now()) return undefined;\n if (token !== undefined && entry.token !== token) return undefined;\n return entry;\n }\n}\n",
|
|
7
|
+
"/**\n * Where workflows are kept (#846), and the one atomic operation everything a\n * workflow does is built from.\n *\n * A store belongs to a queue driver (`QueueDriver.workflowStore`), because a\n * workflow's writes and the jobs they schedule must commit together: a step\n * that sleeps records the sleep and enqueues the tick that wakes it in one\n * step, and `step.batch` records the step and dispatches the batch in one\n * step, so a crash between the two can neither lose the wake-up nor fan out\n * twice. The memory driver does each change synchronously; the database driver\n * does it in a transaction that locks the workflow's row first.\n *\n * A store only keeps records. What a change means (when a step is done, when\n * a workflow sleeps) is decided by the runtime, in the `decide` callback of\n * `update`, while the store holds the workflow exclusively.\n */\nimport type { StepRunStatus, WorkflowRunStatus } from \"./wire\";\nimport type { EnqueueBatch } from \"../QueueDriver\";\n\n/** The registered name the internal tick job runs under. */\nexport const WORKFLOW_TICK_JOB = \"gemi.WorkflowTick\";\n\n/**\n * The most a step's output, a signal's payload or a workflow's result may be,\n * as JSON, in bytes. Store an id for anything larger.\n */\nexport const WORKFLOW_OUTPUT_LIMIT = 256 * 1024;\n\nexport type { StepRunStatus, WorkflowRunStatus } from \"./wire\";\n\n/** A workflow's row. Times are epoch milliseconds. */\nexport type WorkflowRecord = {\n id: string;\n /** The workflow class's `static name`. */\n name: string;\n /** The `run` arguments after `step`, as JSON. */\n args: string;\n status: WorkflowRunStatus;\n /** The key of the step it is on, or `null`. */\n currentStep: string | null;\n /** 0 to 1, as `step.progress` last set it; 1 once completed. */\n progress: number;\n /** What `run` returned, as JSON, once completed. `null` for `undefined`. */\n result: string | null;\n error: string | null;\n /** When the next tick that was scheduled for a wake-up is due, or `null`. */\n wakeAt: number | null;\n /** The tick holding the workflow, and until when (on the store's clock). */\n lockedBy: string | null;\n lockedUntil: number | null;\n /** Another tick arrived while one held the workflow; see `update`'s `unlock`. */\n retick: boolean;\n createdAt: number;\n updatedAt: number;\n};\n\n/** A step's row, unique per workflow and key. */\nexport type StepRecord = {\n workflowId: string;\n key: string;\n status: StepRunStatus;\n /** Attempts started, counting from 1. */\n attempt: number;\n /** The step's result or the signal's payload, as JSON. `null` for `undefined`. */\n output: string | null;\n error: string | null;\n /** The batch a `step.batch` dispatched. */\n batchId: string | null;\n /** When a sleep ends, a wait times out, or a retry is due. */\n wakeAt: number | null;\n startedAt: number | null;\n finishedAt: number | null;\n createdAt: number;\n updatedAt: number;\n};\n\n/**\n * Where one item of a `step.each` stands. Only items that are in flight or\n * had a problem have a row: one that succeeded is deleted, so a long list\n * keeps rows for its problems and its window, not for every item.\n *\n * - `running`: an attempt was started. Found at the start of a tick, it is an\n * attempt whose process died, and the item runs again.\n * - `retrying`: an attempt failed; the next one is due at `wakeAt`.\n * - `failed`: out of attempts. `skipped`: the step function called `ctx.skip`.\n */\nexport type ItemRunStatus = \"running\" | \"retrying\" | \"failed\" | \"skipped\";\n\n/** An item's row, unique per workflow, step key and index. */\nexport type ItemRecord = {\n workflowId: string;\n /** The key of the `step.each` it belongs to. */\n step: string;\n /** Its index in the list, from 0. */\n index: number;\n /** The item key `key(input)` gave, once known; `null` before. */\n key: string | null;\n status: ItemRunStatus;\n /** Attempts started, counting from 1. */\n attempt: number;\n /** The error's message, or the reason given to `ctx.skip`. */\n error: string | null;\n /** The `data` given to `ctx.skip`, as JSON. */\n output: string | null;\n /** When the next attempt of a `retrying` item is due. */\n wakeAt: number | null;\n startedAt: number | null;\n finishedAt: number | null;\n createdAt: number;\n updatedAt: number;\n};\n\n/** The item rows a change writes, all of one `step.each`. */\nexport type ItemChange = {\n step: string;\n /** Rows that do not exist yet. */\n insert?: ItemRecord[];\n /** Rows that exist, replaced whole. */\n update?: ItemRecord[];\n /** Indexes whose rows are deleted. */\n delete?: number[];\n};\n\n/** A workflow and its steps, in the order the steps were first recorded. */\nexport type WorkflowState = { workflow: WorkflowRecord; steps: StepRecord[] };\n\nexport type AcquireResult =\n | { kind: \"missing\" }\n /** Another tick holds it; `retick` is set, so that tick runs it again. */\n | { kind: \"busy\" }\n | ({ kind: \"acquired\" } & WorkflowState);\n\n/** What `update`'s `decide` sees, read while the workflow is held. */\nexport type WorkflowSnapshot = {\n workflow: WorkflowRecord;\n /** The step `key` names, or `null` when there is none (or no key was given). */\n step: StepRecord | null;\n /** Every step, when `allSteps` was asked for; otherwise empty. */\n steps: StepRecord[];\n /**\n * The `running` and `retrying` item rows of the step `items` names, by\n * index; otherwise empty.\n */\n items: ItemRecord[];\n /** This process's clock, for the wake-up times the runtime computes. */\n now: number;\n};\n\n/** What `decide` wants written, all in the same atomic step. */\nexport type WorkflowChange<T> = {\n /** What `update` resolves to. */\n result: T;\n workflow?: Partial<\n Pick<\n WorkflowRecord,\n \"status\" | \"currentStep\" | \"progress\" | \"result\" | \"error\" | \"wakeAt\"\n >\n >;\n /** The step's new row: inserted, or replacing the one under its key. */\n step?: StepRecord;\n /** Item rows of a `step.each` to insert, replace or delete. */\n items?: ItemChange;\n /** A batch to dispatch, as `QueueDriver.enqueueBatch` would. */\n batch?: EnqueueBatch;\n /** Batches to cancel, as `QueueDriver.cancelBatch` would. */\n cancelBatches?: string[];\n /** Enqueue a tick for this workflow, claimable after `delayMs`. */\n tick?: { delayMs: number };\n /**\n * Release the tick's hold on the workflow. When another tick arrived while\n * it was held (`retick`), a new tick is enqueued in the same step, so a\n * signal that landed mid-tick is never lost.\n */\n unlock?: boolean;\n};\n\n/**\n * Whether two holds are attempts of the same tick job. A tick holds the\n * workflow as `<tick job id>:<attempt>`, so a retry of a tick that failed or\n * died takes the workflow straight back instead of waiting out the lease,\n * and the earlier attempt's writes are refused from then on.\n */\nexport function sameTick(a: string, b: string): boolean {\n const job = (owner: string) => owner.slice(0, owner.lastIndexOf(\":\"));\n return job(a) === job(b);\n}\n\nexport class WorkflowLeaseLostError extends Error {\n constructor(id: string) {\n super(\n `The tick running workflow ${id} lost its hold on it (another tick took ` +\n `it over after its lease ran out), so its writes were refused.`,\n );\n this.name = \"WorkflowLeaseLostError\";\n }\n}\n\n/** What `update` reads and how it writes. */\nexport type UpdateOptions = {\n /** Refuse the change with a `WorkflowLeaseLostError` unless this tick holds the workflow. */\n owner?: string;\n /** The step to read. */\n key?: string;\n /** Read every step. */\n allSteps?: boolean;\n /** Read the open item rows of this `step.each`. */\n items?: string;\n /** Write on the transaction `transaction` opened, when one is open. */\n joinTransaction?: boolean;\n};\n\nexport interface WorkflowStore {\n /**\n * Records a new workflow and enqueues its first tick, in one atomic step.\n * Like `QueueDriver.enqueue`, a store that answers `joinsTransaction`\n * writes on the caller's ORM transaction.\n */\n create(workflow: { id: string; name: string; args: string }): Promise<void>;\n\n /** Whether `create` would write on the caller's open ORM transaction. */\n joinsTransaction?(): boolean;\n\n /** The workflow, and its steps unless `steps: false`, or `null`. */\n find(id: string, options?: { steps?: boolean }): Promise<WorkflowState | null>;\n\n /**\n * Takes the workflow for one tick, for `leaseMs` on the store's clock, and\n * returns its state. A workflow another tick holds under a live lease is\n * `busy`, and is marked to be ticked again when that tick lets go; one held\n * by an earlier attempt of the same tick job (see `sameTick`) is taken over.\n */\n acquire(id: string, owner: string, leaseMs: number): Promise<AcquireResult>;\n\n /** Extends the tick's lease, and resolves to whether it still held it. */\n renew(id: string, owner: string, leaseMs: number): Promise<boolean>;\n\n /**\n * Runs `fn` in an ORM transaction on the store's own connection, in which\n * an `update` with `joinTransaction` writes, so `fn`'s writes and that\n * change commit or roll back together (`step.each` with `transaction:\n * true`). A store that cannot (memory, SQLite, a bare connection) leaves\n * it out.\n */\n transaction?<T>(fn: () => Promise<T>): Promise<T>;\n\n /**\n * Reads the workflow (and the step `key`, or every step with `allSteps`)\n * while holding it exclusively, calls `decide`, and writes what it returns,\n * all in one atomic step. With `owner`, the write is refused with a\n * `WorkflowLeaseLostError` unless that tick still holds the workflow.\n * Resolves to `undefined` for an unknown workflow.\n */\n update<T>(\n id: string,\n options: UpdateOptions,\n decide: (snapshot: WorkflowSnapshot) => WorkflowChange<T>,\n ): Promise<T | undefined>;\n\n /**\n * The item rows of one `step.each` whose status is one of `statuses`, by\n * index, from just after `after`, at most `limit`. A store that has it\n * supports `step.each`: it also reads `items` in `update` and writes a\n * change's `items`.\n */\n listItems?(\n workflowId: string,\n step: string,\n options: { statuses: ItemRunStatus[]; after?: number; limit: number },\n ): Promise<ItemRecord[]>;\n\n /**\n * Adds rows to the item source `sourceId` (`ItemSource`, `step.source`),\n * owned by `workflowId` (deleted with it by `prune`) or by nobody. A store\n * that has it supports item sources, with `readSource` and `deleteSource`.\n */\n writeSource?(\n sourceId: string,\n workflowId: string | null,\n rows: Array<{ index: number; payload: string }>,\n ): Promise<void>;\n\n /** The rows of `sourceId` whose index is from `from` up to, not including, `to`, by index. */\n readSource?(\n sourceId: string,\n from: number,\n to: number,\n ): Promise<Array<{ index: number; payload: string }>>;\n\n /** Deletes the rows of `sourceId`, and resolves to how many there were. */\n deleteSource?(sourceId: string): Promise<number>;\n\n /**\n * Deletes the sources that belong to no workflow and were written more\n * than `olderThanMs` ago, and resolves to how many rows.\n */\n pruneSources?(olderThanMs: number): Promise<number>;\n\n /**\n * Deletes workflows that ended (completed, failed or cancelled) more than\n * `olderThanMs` ago, with their steps, items and item sources, and resolves\n * to how many.\n */\n prune?(olderThanMs: number): Promise<number>;\n}\n",
|
|
8
|
+
"import type { SQL, TransactionSQL } from \"bun\";\n\nimport type { Dialect } from \"../../../database/dialect\";\nimport { commitDependsOn, withTransaction } from \"../../../orm/context\";\nimport type { EnqueueBatch, EnqueueJob } from \"../QueueDriver\";\nimport {\n type AcquireResult,\n type ItemChange,\n type ItemRecord,\n type ItemRunStatus,\n type StepRecord,\n type UpdateOptions,\n type StepRunStatus,\n WORKFLOW_TICK_JOB,\n type WorkflowChange,\n WorkflowLeaseLostError,\n sameTick,\n type WorkflowRecord,\n type WorkflowRunStatus,\n type WorkflowSnapshot,\n type WorkflowState,\n type WorkflowStore,\n} from \"./WorkflowStore\";\n\n/** A SQL fragment, as the driver's helpers build them. */\ntype Fragment = ReturnType<SQL[\"unsafe\"]>;\n\n/**\n * What the database queue driver lends its workflow store: its connection,\n * its transactions and clock, and the writes a workflow's changes schedule.\n * The driver builds it from its private methods, so the two share one\n * transaction per change.\n */\nexport type DatabaseQueueInternals = {\n sql: SQL;\n dialect: Dialect;\n connection: string | undefined;\n configure(): Promise<void>;\n atomically<T>(fn: (q: SQL) => Promise<T>): Promise<T>;\n transaction(): TransactionSQL | undefined;\n now(q: SQL): Fragment;\n ms(q: SQL, value: number): Fragment;\n timeOrNull(q: SQL, value: number | null): Fragment;\n fraction(q: SQL, value: number): Fragment;\n clock(q: SQL): Promise<number>;\n insertJob(q: SQL, job: EnqueueJob): Promise<string>;\n insertBatch(q: SQL, batch: EnqueueBatch): Promise<void>;\n cancelBatch(q: SQL, id: string): Promise<boolean>;\n quoted(identifier: string): string;\n};\n\ntype Row = Record<string, unknown>;\n\nconst ENDED: WorkflowRunStatus[] = [\"completed\", \"failed\", \"cancelled\"];\n\n/**\n * Workflows in two tables of the queue's database: one row per workflow, and\n * one per step, keyed by the workflow and the step's key.\n *\n * Every change runs in a transaction that locks the workflow's row first\n * (`SELECT … FOR UPDATE` on Postgres and MySQL; a no-op write on SQLite, which\n * takes the file's write lock), reads what the change depends on, and writes\n * it together with any tick job or batch it schedules. The queue's batch\n * transactions lock a batch row and then job rows and never a workflow row,\n * so the two kinds cannot deadlock on each other.\n */\nexport class DatabaseWorkflowStore implements WorkflowStore {\n readonly table: string;\n readonly stepTable: string;\n /** The items of `step.each`; only touched by workflows that use it. */\n readonly itemTable: string;\n /** Item sources (`ItemSource`, `step.source`); only touched by what uses them. */\n readonly sourceTable: string;\n\n constructor(\n private readonly db: DatabaseQueueInternals,\n options: { table: string; stepTable: string; itemTable: string; sourceTable: string },\n ) {\n this.table = options.table;\n this.stepTable = options.stepTable;\n this.itemTable = options.itemTable;\n this.sourceTable = options.sourceTable;\n // As `joinsTransaction`: only a named connection the ORM can recognise\n // its transaction on, and never SQLite (see `DatabaseQueueDriver.transaction`).\n const connection = db.connection;\n if (db.dialect !== \"sqlite\" && connection !== undefined) {\n this.transaction = (fn) => withTransaction(db.sql, () => fn(), { connection });\n }\n }\n\n /** See `WorkflowStore.transaction`: Postgres and MySQL on a named connection. */\n transaction?: <T>(fn: () => Promise<T>) => Promise<T>;\n\n joinsTransaction(): boolean {\n return this.db.transaction() !== undefined;\n }\n\n create(workflow: { id: string; name: string; args: string }): Promise<void> {\n // On the caller's transaction when the driver would join it, as a\n // dispatch does; otherwise in a transaction of its own.\n const tx = this.db.transaction();\n const written = tx\n ? this.insertWorkflow(tx, workflow)\n : this.db.atomically((q) => this.insertWorkflow(q, workflow));\n if (tx) commitDependsOn(written);\n return written;\n }\n\n private async insertWorkflow(\n q: SQL,\n workflow: { id: string; name: string; args: string },\n ): Promise<void> {\n await this.db.configure();\n const now = this.db.now(q);\n await explainMissingSchema(\n q`\n INSERT INTO ${this.workflows(q)}\n (id, name, args, status, progress, retick, created_at, updated_at)\n VALUES\n (${workflow.id}, ${workflow.name}, ${workflow.args}, 'running',\n ${this.db.fraction(q, 0)}, 0, ${now}, ${now})\n `,\n this.table,\n );\n await this.db.insertJob(q, { name: WORKFLOW_TICK_JOB, args: JSON.stringify([workflow.id]) });\n }\n\n async find(id: string, options: { steps?: boolean } = {}): Promise<WorkflowState | null> {\n await this.db.configure();\n const q = this.db.sql;\n const [row] = (await explainMissingSchema(\n q`SELECT * FROM ${this.workflows(q)} WHERE id = ${id}`,\n this.table,\n )) as Row[];\n if (!row) return null;\n return {\n workflow: workflowRecord(row),\n steps: options.steps === false ? [] : await this.stepsOf(q, id),\n };\n }\n\n acquire(id: string, owner: string, leaseMs: number): Promise<AcquireResult> {\n return this.db.atomically(async (q) => {\n const workflow = await this.lock(q, id);\n if (!workflow) return { kind: \"missing\" } as const;\n const now = await this.db.clock(q);\n if (\n workflow.lockedBy !== null &&\n !sameTick(workflow.lockedBy, owner) &&\n (workflow.lockedUntil ?? 0) > now\n ) {\n await q`UPDATE ${this.workflows(q)} SET retick = 1 WHERE id = ${id}`;\n return { kind: \"busy\" } as const;\n }\n const until = now + Math.max(0, Math.round(leaseMs));\n await q`\n UPDATE ${this.workflows(q)}\n SET locked_by = ${owner}, locked_until = ${this.db.ms(q, until)}, retick = 0\n WHERE id = ${id}\n `;\n return {\n kind: \"acquired\",\n workflow: { ...workflow, lockedBy: owner, lockedUntil: until, retick: false },\n steps: await this.stepsOf(q, id),\n } as const;\n });\n }\n\n async renew(id: string, owner: string, leaseMs: number): Promise<boolean> {\n await this.db.configure();\n const q = this.db.sql;\n const result = await q`\n UPDATE ${this.workflows(q)}\n SET locked_until = ${this.db.now(q)} + ${this.db.ms(q, leaseMs)}\n WHERE id = ${id} AND locked_by = ${owner}\n `;\n return affected(result) > 0;\n }\n\n update<T>(\n id: string,\n options: UpdateOptions,\n decide: (snapshot: WorkflowSnapshot) => WorkflowChange<T>,\n ): Promise<T | undefined> {\n const body = async (q: SQL) => {\n const workflow = await this.lock(q, id);\n if (!workflow) return undefined;\n if (options.owner !== undefined && workflow.lockedBy !== options.owner) {\n throw new WorkflowLeaseLostError(id);\n }\n const step = options.key === undefined ? null : await this.stepOf(q, id, options.key);\n const steps = options.allSteps ? await this.stepsOf(q, id) : [];\n const items =\n options.items === undefined\n ? []\n : await this.itemsOf(q, id, options.items, [\"running\", \"retrying\"], -1, null);\n const change = decide({ workflow, step, steps, items, now: Date.now() });\n\n if (change.step) {\n const exists =\n change.step.key === options.key\n ? step !== null\n : (await this.stepOf(q, id, change.step.key)) !== null;\n await this.writeStep(q, change.step, exists);\n }\n if (change.items) await this.writeItems(q, id, change.items);\n if (change.batch) await this.db.insertBatch(q, change.batch);\n for (const batchId of change.cancelBatches ?? []) await this.db.cancelBatch(q, batchId);\n\n const next: WorkflowRecord = { ...workflow, ...change.workflow };\n const unlock = change.unlock === true;\n const set = q`\n status = ${next.status}, current_step = ${next.currentStep},\n progress = ${this.db.fraction(q, next.progress)}, result = ${next.result},\n error = ${next.error}, wake_at = ${this.db.timeOrNull(q, next.wakeAt)},\n updated_at = ${this.db.now(q)}\n `;\n if (unlock) {\n await q`\n UPDATE ${this.workflows(q)}\n SET ${set}, locked_by = NULL, locked_until = NULL, retick = 0\n WHERE id = ${id}\n `;\n } else {\n await q`UPDATE ${this.workflows(q)} SET ${set} WHERE id = ${id}`;\n }\n\n const tick = (delayMs: number) =>\n this.db.insertJob(q, {\n name: WORKFLOW_TICK_JOB,\n args: JSON.stringify([id]),\n delayMs: Math.max(0, Math.round(delayMs)),\n });\n if (change.tick) await tick(change.tick.delayMs);\n if (unlock && workflow.retick) await tick(0);\n return change.result;\n };\n const tx = options.joinTransaction ? this.db.transaction() : undefined;\n return tx ? body(tx) : this.db.atomically(body);\n }\n\n async listItems(\n workflowId: string,\n step: string,\n options: { statuses: ItemRunStatus[]; after?: number; limit: number },\n ): Promise<ItemRecord[]> {\n await this.db.configure();\n return this.itemsOf(\n this.db.sql,\n workflowId,\n step,\n options.statuses,\n options.after ?? -1,\n options.limit,\n );\n }\n\n async prune(olderThanMs: number): Promise<number> {\n const pruned = await this.db.atomically(async (q) => {\n const ended = this.endedClause(q);\n const cutoff = q`${this.db.now(q)} - ${this.db.ms(q, olderThanMs)}`;\n await q`\n DELETE FROM ${this.steps(q)}\n WHERE workflow_id IN (\n SELECT id FROM ${this.workflows(q)} WHERE ${ended} AND updated_at <= ${cutoff}\n )\n `;\n const result = await q`\n DELETE FROM ${this.workflows(q)} WHERE ${ended} AND updated_at <= ${cutoff}\n `;\n return affected(result);\n });\n // The items of workflows that are gone, on its own: an app that never\n // used `step.each` has no items table, and a failed statement inside the\n // transaction above would abort it on Postgres.\n try {\n const q = this.db.sql;\n await q`\n DELETE FROM ${this.items(q)}\n WHERE NOT EXISTS (\n SELECT 1 FROM ${this.workflows(q)} w WHERE w.id = ${this.items(q)}.workflow_id\n )\n `;\n } catch (error) {\n if (!isMissingSchema(error)) throw error;\n }\n try {\n const q = this.db.sql;\n await q`\n DELETE FROM ${this.sources(q)}\n WHERE workflow_id IS NOT NULL AND NOT EXISTS (\n SELECT 1 FROM ${this.workflows(q)} w WHERE w.id = ${this.sources(q)}.workflow_id\n )\n `;\n } catch (error) {\n if (!isMissingSchema(error)) throw error;\n }\n return pruned;\n }\n\n async writeSource(\n sourceId: string,\n workflowId: string | null,\n rows: Array<{ index: number; payload: string }>,\n ): Promise<void> {\n if (rows.length === 0) return;\n await this.db.configure();\n const q = this.db.sql;\n for (let i = 0; i < rows.length; i += 500) {\n const now = this.db.now(q);\n const values = rows\n .slice(i, i + 500)\n .map((row) => q`(${sourceId}, ${row.index}, ${workflowId}, ${row.payload}, ${now})`);\n await explainMissingSources(\n q`\n INSERT INTO ${this.sources(q)} (source_id, idx, workflow_id, payload, created_at)\n VALUES ${values.reduce((a, b) => q`${a}, ${b}`)}\n `,\n this.sourceTable,\n );\n }\n }\n\n async readSource(\n sourceId: string,\n from: number,\n to: number,\n ): Promise<Array<{ index: number; payload: string }>> {\n await this.db.configure();\n const q = this.db.sql;\n const rows = (await explainMissingSources(\n q`\n SELECT idx, payload FROM ${this.sources(q)}\n WHERE source_id = ${sourceId} AND idx >= ${from} AND idx < ${to}\n ORDER BY idx\n `,\n this.sourceTable,\n )) as Row[];\n return rows.map((row) => ({ index: Number(row.idx), payload: String(row.payload) }));\n }\n\n async deleteSource(sourceId: string): Promise<number> {\n await this.db.configure();\n const q = this.db.sql;\n const result = await explainMissingSources(\n q`DELETE FROM ${this.sources(q)} WHERE source_id = ${sourceId}`,\n this.sourceTable,\n );\n return affected(result);\n }\n\n async pruneSources(olderThanMs: number): Promise<number> {\n await this.db.configure();\n const q = this.db.sql;\n const result = await explainMissingSources(\n q`\n DELETE FROM ${this.sources(q)}\n WHERE workflow_id IS NULL\n AND created_at <= ${this.db.now(q)} - ${this.db.ms(q, olderThanMs)}\n `,\n this.sourceTable,\n );\n return affected(result);\n }\n\n private endedClause(q: SQL) {\n return q`status IN (${ENDED.map((s) => q`${s}`).reduce((a, b) => q`${a}, ${b}`)})`;\n }\n\n private async writeItems(q: SQL, workflowId: string, change: ItemChange) {\n const db = this.db;\n const step = change.step;\n const indexes = change.delete ?? [];\n for (let i = 0; i < indexes.length; i += 500) {\n const chunk = indexes.slice(i, i + 500).map((index) => q`${index}`);\n await explainMissingItems(\n q`\n DELETE FROM ${this.items(q)}\n WHERE workflow_id = ${workflowId} AND step_key = ${step}\n AND idx IN (${chunk.reduce((a, b) => q`${a}, ${b}`)})\n `,\n this.itemTable,\n );\n }\n const inserts = change.insert ?? [];\n for (let i = 0; i < inserts.length; i += 200) {\n const now = db.now(q);\n const values = inserts.slice(i, i + 200).map(\n (item) => q`(\n ${workflowId}, ${step}, ${item.index}, ${item.key}, ${item.status}, ${item.attempt},\n ${item.error}, ${item.output}, ${db.timeOrNull(q, item.wakeAt)},\n ${db.timeOrNull(q, item.startedAt)}, ${db.timeOrNull(q, item.finishedAt)}, ${now}, ${now}\n )`,\n );\n await explainMissingItems(\n q`\n INSERT INTO ${this.items(q)}\n (workflow_id, step_key, idx, item_key, status, attempt, error, output, wake_at,\n started_at, finished_at, created_at, updated_at)\n VALUES ${values.reduce((a, b) => q`${a}, ${b}`)}\n `,\n this.itemTable,\n );\n }\n for (const item of change.update ?? []) {\n await explainMissingItems(\n q`\n UPDATE ${this.items(q)}\n SET item_key = ${item.key}, status = ${item.status}, attempt = ${item.attempt},\n error = ${item.error}, output = ${item.output},\n wake_at = ${db.timeOrNull(q, item.wakeAt)},\n started_at = ${db.timeOrNull(q, item.startedAt)},\n finished_at = ${db.timeOrNull(q, item.finishedAt)}, updated_at = ${db.now(q)}\n WHERE workflow_id = ${workflowId} AND step_key = ${step} AND idx = ${item.index}\n `,\n this.itemTable,\n );\n }\n }\n\n private async itemsOf(\n q: SQL,\n workflowId: string,\n step: string,\n statuses: ItemRunStatus[],\n after: number,\n limit: number | null,\n ): Promise<ItemRecord[]> {\n const status = statuses.map((s) => q`${s}`).reduce((a, b) => q`${a}, ${b}`);\n const rows = (await explainMissingItems(\n limit === null\n ? q`\n SELECT * FROM ${this.items(q)}\n WHERE workflow_id = ${workflowId} AND step_key = ${step}\n AND status IN (${status}) AND idx > ${after}\n ORDER BY idx\n `\n : q`\n SELECT * FROM ${this.items(q)}\n WHERE workflow_id = ${workflowId} AND step_key = ${step}\n AND status IN (${status}) AND idx > ${after}\n ORDER BY idx LIMIT ${limit}\n `,\n this.itemTable,\n )) as Row[];\n return rows.map(itemRecord);\n }\n\n private async writeStep(q: SQL, step: StepRecord, exists: boolean) {\n const db = this.db;\n const key = this.keyColumn(q);\n if (exists) {\n await q`\n UPDATE ${this.steps(q)}\n SET status = ${step.status}, attempt = ${step.attempt}, output = ${step.output},\n error = ${step.error}, batch_id = ${step.batchId},\n wake_at = ${db.timeOrNull(q, step.wakeAt)},\n started_at = ${db.timeOrNull(q, step.startedAt)},\n finished_at = ${db.timeOrNull(q, step.finishedAt)}, updated_at = ${db.now(q)}\n WHERE workflow_id = ${step.workflowId} AND ${key} = ${step.key}\n `;\n return;\n }\n const now = db.now(q);\n await q`\n INSERT INTO ${this.steps(q)}\n (workflow_id, ${key}, status, attempt, output, error, batch_id, wake_at,\n started_at, finished_at, created_at, updated_at)\n VALUES\n (${step.workflowId}, ${step.key}, ${step.status}, ${step.attempt}, ${step.output},\n ${step.error}, ${step.batchId}, ${db.timeOrNull(q, step.wakeAt)},\n ${db.timeOrNull(q, step.startedAt)}, ${db.timeOrNull(q, step.finishedAt)}, ${now}, ${now})\n `;\n }\n\n /**\n * Reads the workflow's row and holds it until the transaction ends, as the\n * driver's `lockBatch` holds a batch's.\n */\n private async lock(q: SQL, id: string): Promise<WorkflowRecord | undefined> {\n let rows: Row[];\n if (this.db.dialect === \"sqlite\") {\n await explainMissingSchema(\n q`UPDATE ${this.workflows(q)} SET updated_at = updated_at WHERE id = ${id}`,\n this.table,\n );\n rows = await q`SELECT * FROM ${this.workflows(q)} WHERE id = ${id}`;\n } else {\n rows = await explainMissingSchema(\n q`SELECT * FROM ${this.workflows(q)} WHERE id = ${id} FOR UPDATE`,\n this.table,\n );\n }\n return rows[0] ? workflowRecord(rows[0]) : undefined;\n }\n\n private async stepOf(q: SQL, id: string, key: string): Promise<StepRecord | null> {\n const [row] = (await explainMissingSchema(\n q`SELECT * FROM ${this.steps(q)} WHERE workflow_id = ${id} AND ${this.keyColumn(q)} = ${key}`,\n this.stepTable,\n )) as Row[];\n return row ? stepRecord(row) : null;\n }\n\n private async stepsOf(q: SQL, id: string): Promise<StepRecord[]> {\n const rows = (await explainMissingSchema(\n q`\n SELECT * FROM ${this.steps(q)} WHERE workflow_id = ${id}\n ORDER BY created_at, ${this.keyColumn(q)}\n `,\n this.stepTable,\n )) as Row[];\n return rows.map(stepRecord);\n }\n\n private workflows(q: SQL) {\n return q.unsafe(this.db.quoted(this.table));\n }\n\n private steps(q: SQL) {\n return q.unsafe(this.db.quoted(this.stepTable));\n }\n\n private items(q: SQL) {\n return q.unsafe(this.db.quoted(this.itemTable));\n }\n\n private sources(q: SQL) {\n return q.unsafe(this.db.quoted(this.sourceTable));\n }\n\n /** `key` is a reserved word in MySQL. */\n private keyColumn(q: SQL) {\n return q.unsafe(this.db.quoted(\"key\"));\n }\n}\n\nfunction time(value: unknown): number | null {\n return value == null ? null : Number(value);\n}\n\nfunction text(value: unknown): string | null {\n return value == null ? null : String(value);\n}\n\nfunction workflowRecord(row: Row): WorkflowRecord {\n return {\n id: String(row.id),\n name: String(row.name),\n args: String(row.args),\n status: String(row.status) as WorkflowRunStatus,\n currentStep: text(row.current_step),\n progress: Number(row.progress ?? 0),\n result: text(row.result),\n error: text(row.error),\n wakeAt: time(row.wake_at),\n lockedBy: text(row.locked_by),\n lockedUntil: time(row.locked_until),\n retick: Number(row.retick ?? 0) !== 0,\n createdAt: Number(row.created_at),\n updatedAt: Number(row.updated_at),\n };\n}\n\nfunction stepRecord(row: Row): StepRecord {\n return {\n workflowId: String(row.workflow_id),\n key: String(row.key),\n status: String(row.status) as StepRunStatus,\n attempt: Number(row.attempt ?? 0),\n output: text(row.output),\n error: text(row.error),\n batchId: text(row.batch_id),\n wakeAt: time(row.wake_at),\n startedAt: time(row.started_at),\n finishedAt: time(row.finished_at),\n createdAt: Number(row.created_at),\n updatedAt: Number(row.updated_at),\n };\n}\n\nfunction itemRecord(row: Row): ItemRecord {\n return {\n workflowId: String(row.workflow_id),\n step: String(row.step_key),\n index: Number(row.idx),\n key: text(row.item_key),\n status: String(row.status) as ItemRunStatus,\n attempt: Number(row.attempt ?? 0),\n error: text(row.error),\n output: text(row.output),\n wakeAt: time(row.wake_at),\n startedAt: time(row.started_at),\n finishedAt: time(row.finished_at),\n createdAt: Number(row.created_at),\n updatedAt: Number(row.updated_at),\n };\n}\n\nfunction affected(result: unknown): number {\n const counts = result as { count?: number | null; affectedRows?: number | null };\n return Math.max(Number(counts.count ?? 0), Number(counts.affectedRows ?? 0));\n}\n\nfunction isMissingSchema(error: unknown): boolean {\n const message = String((error as Error)?.message ?? error);\n return /does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test(\n message,\n );\n}\n\n/**\n * Runs a statement that needs the workflow tables, and turns \"no such table\"\n * into an error that says what to do about it.\n */\nasync function explainMissingSchema<T>(statement: PromiseLike<T>, table: string): Promise<T> {\n try {\n return await statement;\n } catch (error) {\n if (!isMissingSchema(error)) throw error;\n throw new Error(\n `Workflows need the \"${table}\" table, and the database says it is missing. ` +\n `Add the GemiWorkflow and GemiWorkflowStep models from the docs ` +\n `(docs/workflows.md#the-workflow-tables) and migrate, or call the queue ` +\n `driver's createTable().`,\n { cause: error },\n );\n }\n}\n\n/** As `explainMissingSchema`, for the table only `step.each` needs. */\nasync function explainMissingItems<T>(statement: PromiseLike<T>, table: string): Promise<T> {\n try {\n return await statement;\n } catch (error) {\n if (!isMissingSchema(error)) throw error;\n throw new Error(\n `step.each needs the \"${table}\" table, and the database says it is missing. ` +\n `Add the GemiWorkflowItem model from the docs ` +\n `(docs/workflows.md#the-workflow-tables) and migrate, or call the queue ` +\n `driver's createTable().`,\n { cause: error },\n );\n }\n}\n\n/** As `explainMissingSchema`, for the table only item sources need. */\nasync function explainMissingSources<T>(statement: PromiseLike<T>, table: string): Promise<T> {\n try {\n return await statement;\n } catch (error) {\n if (!isMissingSchema(error)) throw error;\n throw new Error(\n `Item sources need the \"${table}\" table, and the database says it is missing. ` +\n `Add the GemiWorkflowSource model from the docs ` +\n `(docs/workflows.md#the-workflow-tables) and migrate, or call the queue ` +\n `driver's createTable().`,\n { cause: error },\n );\n }\n}\n\n/**\n * The two workflow tables, as Prisma generates them for the `GemiWorkflow`\n * and `GemiWorkflowStep` models in the docs (checked against `prisma migrate\n * diff` for all three providers), with `IF NOT EXISTS` added. MySQL cannot\n * say that of an index, so its index is declared inside the table, which is\n * also where Prisma puts it.\n */\nexport function createWorkflowTableStatements(\n dialect: Dialect,\n table: string,\n stepTable: string,\n): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`name\\` VARCHAR(191) NOT NULL,\n \\`args\\` LONGTEXT NOT NULL,\n \\`status\\` VARCHAR(191) NOT NULL,\n \\`current_step\\` VARCHAR(191) NULL,\n \\`progress\\` DOUBLE NOT NULL DEFAULT 0,\n \\`result\\` LONGTEXT NULL,\n \\`error\\` LONGTEXT NULL,\n \\`wake_at\\` BIGINT NULL,\n \\`locked_by\\` VARCHAR(191) NULL,\n \\`locked_until\\` BIGINT NULL,\n \\`retick\\` INTEGER NOT NULL DEFAULT 0,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n\n INDEX \\`${table}_status_idx\\`(\\`status\\`),\n PRIMARY KEY (\\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n `CREATE TABLE IF NOT EXISTS \\`${stepTable}\\` (\n \\`workflow_id\\` VARCHAR(191) NOT NULL,\n \\`key\\` VARCHAR(191) NOT NULL,\n \\`status\\` VARCHAR(191) NOT NULL,\n \\`attempt\\` INTEGER NOT NULL DEFAULT 0,\n \\`output\\` LONGTEXT NULL,\n \\`error\\` LONGTEXT NULL,\n \\`batch_id\\` VARCHAR(191) NULL,\n \\`wake_at\\` BIGINT NULL,\n \\`started_at\\` BIGINT NULL,\n \\`finished_at\\` BIGINT NULL,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n\n PRIMARY KEY (\\`workflow_id\\`, \\`key\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n\n const sqlite = dialect === \"sqlite\";\n const progress = sqlite ? \"REAL\" : \"DOUBLE PRECISION\";\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n \"id\" TEXT NOT NULL${sqlite ? \" PRIMARY KEY\" : \"\"},\n \"name\" TEXT NOT NULL,\n \"args\" TEXT NOT NULL,\n \"status\" TEXT NOT NULL,\n \"current_step\" TEXT,\n \"progress\" ${progress} NOT NULL DEFAULT 0,\n \"result\" TEXT,\n \"error\" TEXT,\n \"wake_at\" BIGINT,\n \"locked_by\" TEXT,\n \"locked_until\" BIGINT,\n \"retick\" INTEGER NOT NULL DEFAULT 0,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL${sqlite ? \"\" : `,\\n\\n CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"id\")`}\n)`,\n `CREATE TABLE IF NOT EXISTS \"${stepTable}\" (\n \"workflow_id\" TEXT NOT NULL,\n \"key\" TEXT NOT NULL,\n \"status\" TEXT NOT NULL,\n \"attempt\" INTEGER NOT NULL DEFAULT 0,\n \"output\" TEXT,\n \"error\" TEXT,\n \"batch_id\" TEXT,\n \"wake_at\" BIGINT,\n \"started_at\" BIGINT,\n \"finished_at\" BIGINT,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL,\n\n ${\n sqlite\n ? `PRIMARY KEY (\"workflow_id\", \"key\")`\n : `CONSTRAINT \"${stepTable}_pkey\" PRIMARY KEY (\"workflow_id\",\"key\")`\n }\n)`,\n `CREATE INDEX IF NOT EXISTS \"${table}_status_idx\" ON \"${table}\"(\"status\")`,\n ];\n}\n\n/**\n * The items table of `step.each`, as Prisma generates it for the\n * `GemiWorkflowItem` model in the docs (checked against `prisma migrate diff`\n * for all three providers), with `IF NOT EXISTS` added.\n */\nexport function createWorkflowItemTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`workflow_id\\` VARCHAR(191) NOT NULL,\n \\`step_key\\` VARCHAR(191) NOT NULL,\n \\`idx\\` INTEGER NOT NULL,\n \\`item_key\\` VARCHAR(191) NULL,\n \\`status\\` VARCHAR(191) NOT NULL,\n \\`attempt\\` INTEGER NOT NULL DEFAULT 0,\n \\`error\\` LONGTEXT NULL,\n \\`output\\` LONGTEXT NULL,\n \\`wake_at\\` BIGINT NULL,\n \\`started_at\\` BIGINT NULL,\n \\`finished_at\\` BIGINT NULL,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n\n PRIMARY KEY (\\`workflow_id\\`, \\`step_key\\`, \\`idx\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n const sqlite = dialect === \"sqlite\";\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n \"workflow_id\" TEXT NOT NULL,\n \"step_key\" TEXT NOT NULL,\n \"idx\" INTEGER NOT NULL,\n \"item_key\" TEXT,\n \"status\" TEXT NOT NULL,\n \"attempt\" INTEGER NOT NULL DEFAULT 0,\n \"error\" TEXT,\n \"output\" TEXT,\n \"wake_at\" BIGINT,\n \"started_at\" BIGINT,\n \"finished_at\" BIGINT,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL,\n\n ${\n sqlite\n ? `PRIMARY KEY (\"workflow_id\", \"step_key\", \"idx\")`\n : `CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"workflow_id\",\"step_key\",\"idx\")`\n }\n)`,\n ];\n}\n\n/**\n * The item sources table, as Prisma generates it for the\n * `GemiWorkflowSource` model in the docs (checked against `prisma migrate\n * diff` for all three providers), with `IF NOT EXISTS` added. MySQL cannot\n * say that of an index, so its index is declared inside the table.\n */\nexport function createWorkflowSourceTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`source_id\\` VARCHAR(191) NOT NULL,\n \\`idx\\` INTEGER NOT NULL,\n \\`workflow_id\\` VARCHAR(191) NULL,\n \\`payload\\` LONGTEXT NOT NULL,\n \\`created_at\\` BIGINT NOT NULL,\n\n INDEX \\`${table}_workflow_id_idx\\`(\\`workflow_id\\`),\n PRIMARY KEY (\\`source_id\\`, \\`idx\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n const sqlite = dialect === \"sqlite\";\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n \"source_id\" TEXT NOT NULL,\n \"idx\" INTEGER NOT NULL,\n \"workflow_id\" TEXT,\n \"payload\" TEXT NOT NULL,\n \"created_at\" BIGINT NOT NULL,\n\n ${\n sqlite\n ? `PRIMARY KEY (\"source_id\", \"idx\")`\n : `CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"source_id\",\"idx\")`\n }\n)`,\n `CREATE INDEX IF NOT EXISTS \"${table}_workflow_id_idx\" ON \"${table}\"(\"workflow_id\")`,\n ];\n}\n",
|
|
9
|
+
"/**\n * The bookkeeping of a job batch, shared by every driver so that the rules for\n * when a batch is cancelled and which callbacks run are written once.\n *\n * A driver keeps a `BatchRecord` per batch and calls these functions while it\n * holds that record exclusively: inside the transaction that also ends the job\n * (the database driver, with the batch row locked), or synchronously (the\n * memory driver). Everything here is pure; the driver writes what comes back,\n * and enqueues the callback jobs `settle` returns in the same step, which is\n * what makes each callback run exactly once.\n *\n * The rules:\n *\n * - Every job of the batch ends exactly once as `succeeded`, `failed` (it was\n * dead-lettered) or `cancelled` (it never ran to the end because the batch was\n * cancelled). `pending` counts the ones that have not ended yet.\n * - `catch` is due at the first failure or cancellation, whichever comes first.\n * - Without `allowFailures`, the first failure cancels the batch: the jobs still\n * waiting are ended as `cancelled` at once, and running ones see it through\n * `this.batch.cancelled()`.\n * - Once `pending` reaches 0 the batch is finished: `then` is due when it was\n * not cancelled and nothing failed (or `allowFailures` is set), and `finally`\n * is always due.\n */\n\n/** A job and the arguments to dispatch it with: what `Job.with(...)` returns. */\nexport type JobCall = {\n /** The job's registered name: its class's `static name`. */\n name: string;\n /** The `run` arguments, before the batch status is appended. */\n args: unknown[];\n};\n\nexport type BatchCallbacks = {\n then?: JobCall;\n catch?: JobCall;\n finally?: JobCall;\n};\n\n/** What `Job.findBatch` resolves to, and the last argument a batch callback gets. */\nexport type BatchStatus = {\n id: string;\n /** The `name` given to `dispatchBatch`, or `null`. */\n name: string | null;\n /** How many jobs the batch was dispatched with. */\n total: number;\n /** Jobs that have not ended yet: waiting, running, or waiting out a retry. */\n pending: number;\n succeeded: number;\n /** Jobs that were dead-lettered. */\n failed: number;\n /** Jobs that ended without running to the end because the batch was cancelled. */\n cancelled: number;\n /** The ids of the dead-lettered jobs, in the order they failed. */\n failedJobIds: string[];\n /**\n * 0 to 1: the ended jobs plus the share each running job reported with\n * `this.progress()`, over `total`. 1 for a batch of no jobs.\n */\n progress: number;\n /** When the batch was cancelled, in epoch milliseconds, or `null`. */\n cancelledAt: number | null;\n /** When its last job ended, in epoch milliseconds, or `null` while it runs. */\n finishedAt: number | null;\n createdAt: number;\n};\n\n/** What a driver stores per batch. */\nexport type BatchRecord = Omit<BatchStatus, \"progress\"> & {\n allowFailures: boolean;\n callbacks: BatchCallbacks;\n};\n\n/** How one job of a batch ended. */\nexport type BatchOutcome = \"succeeded\" | \"failed\" | \"cancelled\";\n\n/** The callback jobs to enqueue, their arguments already serialised. */\nexport type BatchCallbackJob = { name: string; args: string };\n\nexport function newBatchRecord(batch: {\n id: string;\n name: string | null;\n total: number;\n allowFailures: boolean;\n callbacks: BatchCallbacks;\n now: number;\n}): BatchRecord {\n return {\n id: batch.id,\n name: batch.name,\n total: batch.total,\n pending: batch.total,\n succeeded: 0,\n failed: 0,\n cancelled: 0,\n failedJobIds: [],\n cancelledAt: null,\n finishedAt: null,\n createdAt: batch.now,\n allowFailures: batch.allowFailures,\n callbacks: batch.callbacks,\n };\n}\n\n/** Counts one job's end. A batch with nothing pending is left as it is. */\nexport function countOutcome(\n record: BatchRecord,\n outcome: BatchOutcome,\n jobId: string,\n): BatchRecord {\n if (record.pending <= 0) return record;\n const next = { ...record, pending: record.pending - 1 };\n if (outcome === \"succeeded\") next.succeeded++;\n else if (outcome === \"cancelled\") next.cancelled++;\n else {\n next.failed++;\n next.failedJobIds = [...record.failedJobIds, jobId];\n }\n return next;\n}\n\n/**\n * Whether going from `prev` to `next` is the failure that cancels the batch:\n * its first, without `allowFailures`, in a batch not already cancelled.\n */\nexport function cancelsBatch(prev: BatchRecord, next: BatchRecord): boolean {\n return (\n !next.allowFailures &&\n next.cancelledAt === null &&\n next.finishedAt === null &&\n next.failed > prev.failed\n );\n}\n\n/**\n * Marks the batch cancelled, counting the `waiting` jobs the driver has just\n * ended as `cancelled`.\n */\nexport function markCancelled(record: BatchRecord, now: number, waiting: number): BatchRecord {\n const ended = Math.min(Math.max(0, waiting), record.pending);\n return {\n ...record,\n cancelledAt: record.cancelledAt ?? now,\n pending: record.pending - ended,\n cancelled: record.cancelled + ended,\n };\n}\n\n/**\n * Finishes the batch when nothing is pending, and says which callbacks became\n * due between `prev` and `next`. Each callback's arguments are its own followed\n * by the batch's status as it stands after this step.\n */\nexport function settle(\n prev: BatchRecord,\n next: BatchRecord,\n now: number,\n): { record: BatchRecord; calls: BatchCallbackJob[] } {\n let record = next;\n const due: JobCall[] = [];\n const callbacks = next.callbacks;\n\n const wasClean = prev.failed === 0 && prev.cancelledAt === null;\n const isClean = next.failed === 0 && next.cancelledAt === null;\n if (wasClean && !isClean && callbacks.catch) due.push(callbacks.catch);\n\n if (next.pending === 0 && next.finishedAt === null) {\n record = { ...next, finishedAt: now };\n const succeeded = next.cancelledAt === null && (next.failed === 0 || next.allowFailures);\n if (succeeded && callbacks.then) due.push(callbacks.then);\n if (callbacks.finally) due.push(callbacks.finally);\n }\n\n const status = statusOf(record);\n return {\n record,\n calls: due.map((call) => ({\n name: call.name,\n args: JSON.stringify([...call.args, status]),\n })),\n };\n}\n\n/**\n * The status of a batch. `running` is the sum of the progress the batch's\n * unfinished jobs have reported, each 0 to 1.\n */\nexport function statusOf(record: BatchRecord, running = 0): BatchStatus {\n const { allowFailures: _allowFailures, callbacks: _callbacks, ...status } = record;\n const ended = record.total - record.pending;\n const progress =\n record.total === 0 ? 1 : Math.min(1, Math.max(0, (ended + Math.max(0, running)) / record.total));\n return { ...status, failedJobIds: [...record.failedJobIds], progress };\n}\n\n/** A progress value as stored: a finite number clamped to 0..1. */\nexport function clampProgress(value: number): number {\n if (typeof value !== \"number\" || !Number.isFinite(value)) {\n throw new TypeError(`A job's progress is a number from 0 to 1; got ${String(value)}.`);\n }\n return Math.min(1, Math.max(0, value));\n}\n",
|
|
10
|
+
"import { SQL } from \"bun\";\n\nimport type { Dialect } from \"../../database/dialect\";\nimport type { EnqueueJob } from \"./QueueDriver\";\nimport type { SlotRequest } from \"./slots\";\nimport { WORKFLOW_TICK_JOB } from \"./workflow/WorkflowStore\";\n\n/**\n * Concurrency slots (#1319) in a table of the queue's database, so every\n * process sharing it shares one line per key. The model is in `slots.ts`.\n *\n * ### The table\n *\n * One row per key and holder, keyed by both. The empty holder is the key's\n * **gate** row: every step on a line starts by upserting it, which locks it\n * (a row lock on Postgres and MySQL, the file's write lock on SQLite), so the\n * steps on one key run one at a time across processes, and it keeps the\n * limit the line was last admitted under, for a release that has none. A\n * step on several keys locks their gates in sorted order first, so two steps\n * never wait on each other in a cycle.\n *\n * ### Indexed, all of it\n *\n * Every statement is on `(slot_key, state, queued_at, holder)`, on `(holder)`,\n * or a primary-key lookup, and the counts are `LIMIT`ed to the limit: an\n * admission costs the same with ten waiters or ten thousand, and nothing\n * counts or scans the jobs table. `DatabaseSlots.test.ts` runs `EXPLAIN` on\n * each statement on all three databases.\n *\n * On MySQL a step runs at READ COMMITTED on a connection of its own, as the\n * claim does: at REPEATABLE READ the range deletes and counts would take gap\n * locks reaching into the next key's rows, and steps on different keys would\n * wait on each other.\n *\n * ### Bun 1.3 and Postgres\n *\n * Bun 1.3's Postgres pool can send a query made on the pool (the queue's\n * claim, say) down a connection that is inside a `sql.begin` or reserved.\n * The claim then runs in the step's transaction, the step's next statement\n * never comes back, and the key's gate row stays locked, so every other step\n * on the key waits for good. Bun 1.4 does not. So under Bun 1.3, on\n * Postgres, steps run one at a time per driver on a client of their own (one\n * connection, closed when idle) that nothing else uses.\n */\nexport class DatabaseSlots {\n private readonly statements: SlotStatements;\n /** Bun 1.3 on Postgres: the steps' own client, and the step running on it. */\n private own: SQL | undefined;\n private ownTail: Promise<unknown> = Promise.resolve();\n\n constructor(\n private readonly db: {\n sql: SQL;\n dialect: Dialect;\n configure(): Promise<void>;\n atomically<T>(fn: (q: SQL) => Promise<T>): Promise<T>;\n insertJob(q: SQL, job: EnqueueJob): Promise<string>;\n },\n tables: SlotTables,\n ) {\n this.statements = slotStatements(db.dialect, tables);\n }\n\n async acquire(request: SlotRequest): Promise<boolean> {\n return this.step(async (run) => {\n const keys = [...new Set(request.slots.map((slot) => slot.key))].sort();\n for (const key of keys) {\n const { limit } = request.slots.find((slot) => slot.key === key)!;\n await run(\"lockGate\", { key, limit });\n }\n\n // A holder's place is when it first asked for any of its keys.\n const [known] = await run(\"placeOf\", { holder: request.holder });\n const queued =\n known?.queued_at == null\n ? Number((await run(\"clock\", {}))[0]!.now)\n : Number(known.queued_at);\n\n for (const { key, limit } of request.slots) {\n await this.prune(run, key);\n const [own] = await run(\"ticket\", { key, holder: request.holder });\n if (!own) {\n await run(\"insertWaiting\", {\n key,\n holder: request.holder,\n job: request.job.id,\n workflow: request.workflowId ?? null,\n queued,\n });\n } else if (String(own.job_id) !== request.job.id) {\n await run(\"pointAt\", { key, holder: request.holder, job: request.job.id });\n }\n const place = own ? Number(own.queued_at) : queued;\n\n const grantable = async () =>\n (await this.count(run, \"countHolders\", { key })) +\n (await this.count(run, \"countAhead\", {\n key,\n queued: place,\n holder: request.holder,\n cap: Math.max(1, limit),\n })) <\n limit;\n let holding = own?.state === \"holding\";\n if (!holding && (await grantable())) holding = true;\n if (!holding) {\n // Waking drops the dead waiters ahead, which may leave room.\n await this.wake(run, key, limit, request.holder);\n holding = await grantable();\n }\n if (holding && own?.state !== \"holding\") await run(\"hold\", { key, holder: request.holder });\n // A raised limit, or holders that were gone, can leave room behind this one too.\n if (holding) {\n await this.wake(run, key, limit, request.holder);\n continue;\n }\n\n const ahead = await this.count(run, \"countAhead\", {\n key,\n queued: place,\n holder: request.holder,\n cap: Math.max(1, limit),\n });\n // The first waiter re-checks soon even under a limit of 0, so a limit\n // raised while nothing else happens on the key is seen.\n const ms = ahead < Math.max(1, limit) ? request.recheckMs.near : request.recheckMs.far;\n await run(\"park\", {\n id: request.job.id,\n attempt: request.job.attempt,\n ms: Math.max(0, Math.round(ms)),\n });\n return false;\n }\n return true;\n });\n }\n\n async release(holder: string): Promise<void> {\n await this.step(async (run) => {\n const rows = await run(\"keysOf\", { holder });\n const keys = [...new Set(rows.map((row) => String(row.slot_key)))].sort();\n for (const key of keys) await run(\"touchGate\", { key });\n for (const key of keys) {\n await run(\"deleteTicket\", { key, holder });\n await this.prune(run, key);\n const [gate] = await run(\"gate\", { key });\n await this.wake(run, key, Number(gate?.slot_limit ?? 0), holder);\n }\n });\n }\n\n /** Drops holders whose job or workflow is gone. */\n private async prune(run: Runner, key: string) {\n await run(\"pruneJobHolders\", { key });\n // Only touched when a workflow holds a slot of this key, so a queue that\n // runs no workflows needs no workflow tables.\n if ((await run(\"hasWorkflowHolders\", { key })).length > 0) {\n await run(\"pruneWorkflowHolders\", { key });\n }\n }\n\n /** Makes the first waiters due, as many as `key` has free slots, dropping dead ones. */\n private async wake(run: Runner, key: string, limit: number, except: string) {\n let free = limit - (await this.count(run, \"countHolders\", { key }));\n while (free > 0) {\n const waiters = await run(\"nextWaiters\", { key, except, n: free + 8 });\n if (waiters.length === 0) return;\n let dropped = 0;\n for (const waiter of waiters) {\n if (free <= 0) return;\n const holder = String(waiter.holder);\n const jobId = waiter.job_id == null ? null : String(waiter.job_id);\n const workflowId = waiter.workflow_id == null ? null : String(waiter.workflow_id);\n\n if (workflowId !== null) {\n const [workflow] = await run(\"workflowStatus\", { id: workflowId });\n if (!workflow || INACTIVE.includes(String(workflow.status))) {\n await run(\"deleteTicket\", { key, holder });\n dropped++;\n continue;\n }\n }\n if (jobId !== null) await run(\"wakeJob\", { id: jobId });\n const [job] = jobId === null ? [] : await run(\"jobStatus\", { id: jobId });\n const alive = job !== undefined && LIVE.includes(String(job.status));\n if (!alive) {\n if (workflowId === null) {\n await run(\"deleteTicket\", { key, holder });\n dropped++;\n continue;\n }\n // A workflow whose parked tick is gone gets a new one.\n const tick = await this.db.insertJob(run.q, {\n name: WORKFLOW_TICK_JOB,\n args: JSON.stringify([workflowId]),\n });\n await run(\"pointAt\", { key, holder, job: tick });\n }\n free--;\n }\n // Only dead waiters were dropped this round; with none dropped, every\n // waiter there is was woken.\n if (dropped === 0) return;\n }\n }\n\n private async count(run: Runner, name: CountStatement, params: Params): Promise<number> {\n const [row] = await run(name, params);\n return Number(row?.n ?? 0);\n }\n\n /**\n * One step on the lines, in a transaction of its own. On MySQL at READ\n * COMMITTED on a reserved connection (see the class), and every step is\n * retried a few times on a deadlock, which MySQL can still report for two\n * first upserts of one gate row.\n */\n private async step<T>(fn: (run: Runner) => Promise<T>): Promise<T> {\n await this.db.configure();\n for (let attempt = 0; ; attempt++) {\n try {\n return await this.transaction((q) => fn(this.runner(q)));\n } catch (error) {\n if (attempt >= 4 || !isDeadlock(error))\n throw explainMissingTable(error, this.statements.table);\n await new Promise((resolve) =>\n setTimeout(resolve, 10 + Math.random() * 40 * (attempt + 1)),\n );\n }\n }\n }\n\n private async transaction<T>(fn: (q: SQL) => Promise<T>): Promise<T> {\n const own = this.ownClient();\n if (own) {\n const result = this.ownTail.then(() => own.begin((tx) => fn(tx)) as Promise<T>);\n this.ownTail = result.catch(() => {});\n return result;\n }\n if (this.db.dialect !== \"mysql\" && this.db.dialect !== \"mariadb\") {\n return this.db.atomically(fn);\n }\n const connection = await this.db.sql.reserve();\n const [isolation] = (await connection`SELECT @@transaction_isolation AS level`) as Array<{\n level: string;\n }>;\n await connection`SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED`;\n try {\n return (await connection.begin((tx) => fn(tx))) as T;\n } finally {\n const previous = isolation?.level?.replaceAll(\"-\", \" \");\n if (previous && /^[A-Z ]+$/.test(previous)) {\n await connection.unsafe(`SET SESSION TRANSACTION ISOLATION LEVEL ${previous}`);\n }\n connection.release();\n }\n }\n\n /** See \"Bun 1.3 and Postgres\" above. */\n private ownClient(): SQL | undefined {\n if (this.own) return this.own;\n if (this.db.dialect !== \"postgres\" || !bunBefore14()) return undefined;\n const options = (this.db.sql as { options?: Record<string, unknown> }).options;\n if (options?.adapter !== \"postgres\") return undefined;\n this.own = new SQL({ ...options, max: 1, idleTimeout: 5 } as ConstructorParameters<\n typeof SQL\n >[0]);\n return this.own;\n }\n\n private runner(q: SQL): Runner {\n const run = (async (name: StatementName, params: Params) => {\n const [text, values] = this.statements.compile(name, params);\n return (await q.unsafe(text, values)) as Row[];\n }) as Runner;\n run.q = q;\n return run;\n }\n}\n\ntype Row = Record<string, unknown>;\ntype Params = Record<string, string | number | null>;\ntype Runner = ((name: StatementName, params: Params) => Promise<Row[]>) & { q: SQL };\ntype CountStatement = \"countHolders\" | \"countAhead\";\n\n/** A job whose slot is still held: waiting (parked, or due) or claimed. */\nconst LIVE = [\"pending\", \"claimed\"];\n/** A workflow whose slot is no longer held. */\nconst INACTIVE = [\"completed\", \"failed\", \"cancelled\", \"paused\"];\n\nexport type SlotTables = { slots: string; jobs: string; workflows: string };\n\n/**\n * The slots table, as Prisma generates it for the `GemiJobSlot` model in the\n * docs, with `IF NOT EXISTS` added.\n */\nexport function createSlotTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`slot_key\\` VARCHAR(191) NOT NULL,\n \\`holder\\` VARCHAR(191) NOT NULL,\n \\`job_id\\` VARCHAR(191) NULL,\n \\`workflow_id\\` VARCHAR(191) NULL,\n \\`state\\` VARCHAR(191) NOT NULL,\n \\`slot_limit\\` INTEGER NOT NULL DEFAULT 0,\n \\`queued_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n\n INDEX \\`${table}_slot_key_state_queued_at_holder_idx\\`(\\`slot_key\\`, \\`state\\`, \\`queued_at\\`, \\`holder\\`),\n INDEX \\`${table}_holder_idx\\`(\\`holder\\`),\n PRIMARY KEY (\\`slot_key\\`, \\`holder\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n const constraint = `,\\n\\n CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"slot_key\", \"holder\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n \"slot_key\" TEXT NOT NULL,\n \"holder\" TEXT NOT NULL,\n \"job_id\" TEXT,\n \"workflow_id\" TEXT,\n \"state\" TEXT NOT NULL,\n \"slot_limit\" INTEGER NOT NULL DEFAULT 0,\n \"queued_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL${constraint}\n)`,\n `CREATE INDEX IF NOT EXISTS \"${table}_slot_key_state_queued_at_holder_idx\" ON \"${table}\"(\"slot_key\", \"state\", \"queued_at\", \"holder\")`,\n `CREATE INDEX IF NOT EXISTS \"${table}_holder_idx\" ON \"${table}\"(\"holder\")`,\n ];\n}\n\nexport type StatementName =\n | \"clock\"\n | \"lockGate\"\n | \"touchGate\"\n | \"gate\"\n | \"placeOf\"\n | \"ticket\"\n | \"insertWaiting\"\n | \"pointAt\"\n | \"hold\"\n | \"deleteTicket\"\n | \"keysOf\"\n | \"countHolders\"\n | \"countAhead\"\n | \"nextWaiters\"\n | \"pruneJobHolders\"\n | \"hasWorkflowHolders\"\n | \"pruneWorkflowHolders\"\n | \"wakeJob\"\n | \"jobStatus\"\n | \"workflowStatus\"\n | \"park\";\n\nexport type SlotStatements = {\n table: string;\n /** The text of every statement, with `{name}` placeholders, for `EXPLAIN`. */\n texts: Record<StatementName, string>;\n /** A statement as the dialect's text and its positional values. */\n compile(name: StatementName, params: Params): [string, unknown[]];\n};\n\n/**\n * Every statement the slots run, per dialect, as text: one place to read\n * them, and what the test hands to `EXPLAIN`. Placeholders are `{name}`, and\n * `compile` turns them into `$n` (Postgres) or `?` (MySQL, SQLite).\n */\nexport function slotStatements(dialect: Dialect, tables: SlotTables): SlotStatements {\n const mysql = dialect === \"mysql\" || dialect === \"mariadb\";\n const quote = (name: string) => (mysql ? `\\`${name}\\`` : `\"${name}\"`);\n const S = quote(tables.slots);\n const J = quote(tables.jobs);\n const W = quote(tables.workflows);\n const now =\n dialect === \"postgres\"\n ? \"floor(extract(epoch from statement_timestamp()) * 1000)::bigint\"\n : mysql\n ? \"(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)\"\n : \"CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)\";\n const int = (name: string) => (mysql ? `CAST({${name}} AS SIGNED)` : `CAST({${name}} AS BIGINT)`);\n const upsert = (set: string) =>\n mysql\n ? `ON DUPLICATE KEY UPDATE ${set.replace(/excluded\\.(\\w+)/g, \"VALUES($1)\")}`\n : `ON CONFLICT (slot_key, holder) DO UPDATE SET ${set}`;\n\n const texts: Record<StatementName, string> = {\n clock: `SELECT ${now} AS now`,\n lockGate: `INSERT INTO ${S} (slot_key, holder, state, slot_limit, queued_at, updated_at)\n VALUES ({key}, '', 'gate', ${int(\"limit\")}, ${now}, ${now})\n ${upsert(\"slot_limit = excluded.slot_limit, updated_at = excluded.updated_at\")}`,\n touchGate: `INSERT INTO ${S} (slot_key, holder, state, slot_limit, queued_at, updated_at)\n VALUES ({key}, '', 'gate', 0, ${now}, ${now})\n ${upsert(\"updated_at = excluded.updated_at\")}`,\n gate: `SELECT slot_limit FROM ${S} WHERE slot_key = {key} AND holder = ''`,\n placeOf: `SELECT MIN(queued_at) AS queued_at FROM ${S} WHERE holder = {holder}`,\n ticket: `SELECT state, queued_at, job_id FROM ${S} WHERE slot_key = {key} AND holder = {holder}`,\n insertWaiting: `INSERT INTO ${S}\n (slot_key, holder, job_id, workflow_id, state, slot_limit, queued_at, updated_at)\n VALUES ({key}, {holder}, {job}, {workflow}, 'waiting', 0, ${int(\"queued\")}, ${now})`,\n pointAt: `UPDATE ${S} SET job_id = {job}, updated_at = ${now}\n WHERE slot_key = {key} AND holder = {holder}`,\n hold: `UPDATE ${S} SET state = 'holding', updated_at = ${now}\n WHERE slot_key = {key} AND holder = {holder}`,\n deleteTicket: `DELETE FROM ${S} WHERE slot_key = {key} AND holder = {holder}`,\n keysOf: `SELECT slot_key FROM ${S} WHERE holder = {holder}`,\n countHolders: `SELECT COUNT(*) AS n FROM ${S} WHERE slot_key = {key} AND state = 'holding'`,\n countAhead: `SELECT COUNT(*) AS n FROM (\n SELECT holder FROM ${S}\n WHERE slot_key = {key} AND state = 'waiting'\n AND (queued_at < ${int(\"queued\")} OR (queued_at = ${int(\"queued\")} AND holder < {holder}))\n LIMIT {cap}\n ) ahead`,\n nextWaiters: `SELECT holder, job_id, workflow_id FROM ${S}\n WHERE slot_key = {key} AND state = 'waiting' AND holder <> {except}\n ORDER BY queued_at, holder\n LIMIT {n}`,\n pruneJobHolders: `DELETE FROM ${S}\n WHERE slot_key = {key} AND state = 'holding' AND workflow_id IS NULL\n AND NOT EXISTS (\n SELECT 1 FROM ${J} WHERE ${J}.id = ${S}.holder AND ${J}.status IN ('pending', 'claimed')\n )`,\n hasWorkflowHolders: `SELECT holder FROM ${S}\n WHERE slot_key = {key} AND state = 'holding' AND workflow_id IS NOT NULL\n LIMIT 1`,\n pruneWorkflowHolders: `DELETE FROM ${S}\n WHERE slot_key = {key} AND state = 'holding' AND workflow_id IS NOT NULL\n AND NOT EXISTS (\n SELECT 1 FROM ${W}\n WHERE ${W}.id = ${S}.workflow_id\n AND ${W}.status NOT IN ('completed', 'failed', 'cancelled', 'paused')\n )`,\n wakeJob: `UPDATE ${J} SET available_at = ${now}, updated_at = ${now}\n WHERE id = {id} AND status = 'pending' AND available_at > ${now}`,\n jobStatus: `SELECT status FROM ${J} WHERE id = {id}`,\n workflowStatus: `SELECT status FROM ${W} WHERE id = {id}`,\n park: `UPDATE ${J}\n SET status = 'pending', attempts = attempts - 1, available_at = ${now} + ${int(\"ms\")},\n lease_expires_at = NULL, updated_at = ${now}\n WHERE id = {id} AND status = 'claimed' AND attempts = ${int(\"attempt\")}`,\n };\n\n const compiled = new Map<StatementName, { text: string; names: string[] }>();\n return {\n table: tables.slots,\n texts,\n compile(name, params) {\n let entry = compiled.get(name);\n if (!entry) {\n const names: string[] = [];\n const text = texts[name].replace(/\\{([a-z]+)\\}/g, (_, param: string) => {\n if (dialect === \"postgres\") {\n let index = names.indexOf(param);\n if (index === -1) index = names.push(param) - 1;\n return `$${index + 1}`;\n }\n names.push(param);\n return \"?\";\n });\n entry = { text, names };\n compiled.set(name, entry);\n }\n return [\n entry.text,\n entry.names.map((param) => {\n if (!(param in params)) throw new Error(`The slot statement ${name} needs {${param}}.`);\n return params[param];\n }),\n ];\n },\n };\n}\n\nfunction bunBefore14(): boolean {\n const [major = 0, minor = 0] = Bun.version.split(\".\").map(Number);\n return major < 1 || (major === 1 && minor < 4);\n}\n\nfunction isDeadlock(error: unknown): boolean {\n const e = error as { errno?: unknown; code?: unknown; message?: unknown };\n return (\n e?.errno === 1213 ||\n e?.code === \"40P01\" ||\n /deadlock|try restarting transaction/i.test(String(e?.message ?? \"\"))\n );\n}\n\nfunction explainMissingTable(error: unknown, table: string): unknown {\n const message = String((error as Error)?.message ?? error);\n if (!/does not exist|doesn't exist|no such table/i.test(message) || !message.includes(table)) {\n return error;\n }\n return new Error(\n `Concurrency limits on the database driver need the \"${table}\" table, and the ` +\n `database says it is missing. Add the GemiJobSlot model from the docs ` +\n `(docs/jobs-and-queues.md#concurrency-limits--concurrency) and migrate, or call ` +\n `the driver's createTable().`,\n { cause: error },\n );\n}\n",
|
|
11
|
+
"import type { SQL, TransactionSQL } from \"bun\";\n\nimport type { DatabaseConnection } from \"../../database/Connection\";\nimport type { Dialect } from \"../../database/dialect\";\nimport { DatabaseLockStore } from \"../lock/DatabaseLockStore\";\nimport { commitDependsOn, currentConnectionName, currentTransaction } from \"../../orm/context\";\nimport {\n type BatchCallbacks,\n type BatchOutcome,\n type BatchRecord,\n type BatchStatus,\n cancelsBatch,\n clampProgress,\n countOutcome,\n markCancelled,\n newBatchRecord,\n settle,\n statusOf,\n} from \"./batch\";\nimport type {\n ClaimOptions,\n ClaimedJob,\n EnqueueBatch,\n EnqueueJob,\n JobFailure,\n JobRelease,\n QueueDriver,\n} from \"./QueueDriver\";\nimport { DatabaseSlots, createSlotTableStatements } from \"./DatabaseSlots\";\nimport type { SlotRequest } from \"./slots\";\nimport {\n DatabaseWorkflowStore,\n createWorkflowItemTableStatements,\n createWorkflowSourceTableStatements,\n createWorkflowTableStatements,\n} from \"./workflow/DatabaseWorkflowStore\";\n\nexport type DatabaseQueueDriverOptions = {\n /**\n * The jobs table. Default `gemi_jobs`. A plain identifier — letters, digits\n * and underscores — because it is spliced into every statement.\n */\n table?: string;\n /**\n * The table batches are kept in. Default `gemi_job_batches` beside\n * `gemi_jobs`, and `<table>_batches` beside a jobs table of another name.\n * A plain identifier, like `table`. Only touched by `Job.dispatchBatch` and\n * the batch methods.\n */\n batchTable?: string;\n /**\n * The tables workflows are kept in. Default `gemi_workflows` and\n * `gemi_workflow_steps` beside `gemi_jobs`, and `<table>_workflows` and\n * `<table>_workflow_steps` beside a jobs table of another name. Plain\n * identifiers, like `table`. Only touched by `Workflow`.\n */\n workflowTable?: string;\n workflowStepTable?: string;\n /**\n * The table `step.each` keeps its item rows in. Default\n * `gemi_workflow_items`, or `<table>_workflow_items` beside a jobs table of\n * another name. Only touched by workflows that use `step.each`.\n */\n workflowItemTable?: string;\n /**\n * The table item sources (`ItemSource`, `step.source`) are kept in.\n * Default `gemi_workflow_sources`, or `<table>_workflow_sources` beside a\n * jobs table of another name. Only touched by what uses them.\n */\n workflowSourceTable?: string;\n /**\n * The table concurrency slots are kept in (#1319). Default\n * `gemi_job_slots`, or `<table>_slots` beside a jobs table of another name.\n * Only touched by jobs and workflows that declare `concurrency`.\n */\n slotTable?: string;\n /**\n * SQLite only: how long, in milliseconds, a statement waits for another\n * process's write lock before failing with `SQLITE_BUSY`. Default `1000`.\n * Applied only to a connection whose busy timeout is still SQLite's `0`, so\n * one the application configured itself keeps its own; `0` here leaves the\n * connection alone. See `configure` for what the wait costs.\n */\n busyTimeout?: number;\n};\n\n/**\n * What a row's `status` can be. `pending` rows are claimable once\n * `available_at` has passed; `claimed` ones once `lease_expires_at` has. `dead`\n * is terminal and kept, with `last_error`, until `prune` removes it. A\n * completed job is deleted, so there is no status for it.\n */\nexport type DatabaseJobStatus = \"pending\" | \"claimed\" | \"dead\";\n\ntype Row = {\n id: string;\n name: string;\n payload: string;\n attempts: number | string;\n available_at: number | string | bigint;\n created_at: number | string | bigint;\n /** Absent on a table from before batches; see `claim`. */\n batch_id?: string | null;\n};\n\ntype BatchRow = {\n id: string;\n name: string | null;\n total: number | string;\n pending: number | string;\n succeeded: number | string;\n failed: number | string;\n cancelled: number | string;\n failed_job_ids: string;\n options: string;\n cancelled_at: number | string | bigint | null;\n finished_at: number | string | bigint | null;\n created_at: number | string | bigint;\n};\n\n/** How many job rows one `INSERT` of a batch carries. */\nconst BATCH_INSERT_CHUNK = 200;\n\n/** The `last_error` of a waiting job ended by its batch's cancellation. */\nconst CANCELLED_ERROR = \"Its batch was cancelled before it ran.\";\n\n/**\n * A driver that keeps jobs in a table of the application's own database, so\n * they outlive the process: a job dispatched before a deploy, a scale-in or a\n * crash is still there afterwards, and any process sharing the database claims\n * it — the one waiting at once, the one that was running once its lease runs\n * out. Nothing replays anything at boot; claiming is the recovery.\n *\n * **At least once, not exactly once.** A job whose lease lapses while it is\n * still running — its process frozen, or unable to reach the database to\n * heartbeat, for longer than the visibility timeout — can be claimed and run\n * by another process too, and a job whose process died after its work but\n * before `complete` reached the database runs again. Jobs must be idempotent.\n *\n * ### Claiming\n *\n * Postgres and MySQL lock the rows they hand out with `FOR UPDATE SKIP\n * LOCKED`, so concurrent claimers — in this process or any other — each take\n * different rows and none waits on another. Postgres does it in one statement\n * (a locking CTE feeding an `UPDATE … RETURNING`); MySQL has no `RETURNING`\n * and refuses a `LIMIT` inside `IN (…)`, so there it is a `SELECT … FOR\n * UPDATE SKIP LOCKED` and one `UPDATE` per row in a transaction, at READ\n * COMMITTED and in two passes — see `claimLocking`, where both are load\n * bearing rather than tidying. SQLite has no row locks and needs none: it\n * runs one write at a time, so a single `UPDATE … RETURNING` is atomic.\n * MariaDB needs 10.6 for `SKIP LOCKED`.\n *\n * It honours `registered`: a claim is `WHERE name IN (…)` the claimer's\n * registry, so a replica never takes a job it has no class for until that job\n * has been claimable for the grace window. Every replica claims from this one\n * table, and during a blue/green ramp half of them are running the other\n * release.\n *\n * ### Time\n *\n * Every time in the table is epoch milliseconds, read from the database's\n * clock rather than this process's, so replicas with skewed clocks still agree\n * on when a lease ran out. Integers rather than timestamp columns so the same\n * arithmetic works in all three dialects.\n *\n * ### Transactions\n *\n * On Postgres and MySQL, a dispatch inside an ORM transaction on this\n * driver's own connection is written on that transaction: the row commits\n * with the data it describes or not at all, and no claimer — each reads\n * through a pooled connection of its own — sees it before the commit. See\n * `transaction` below for why SQLite is left out, and why a driver built from\n * a bare client never joins.\n *\n * ### Batches\n *\n * A batch is a row of `batchTable`, and its jobs are rows of the jobs table\n * with `batch_id` set. Ending a job of a batch, counting it and enqueueing any\n * callback it makes due happen in one transaction that locks the batch row\n * first; see the \"Batches\" section below. A table from before batches, without\n * `batch_id` and `progress`, still runs every other job: the claim reads `*`,\n * and only the batch methods need the new columns.\n *\n * ### What it does not do\n *\n * It has no `subscribe`: another process's dispatch cannot wake this one, so\n * the queue polls every `pollInterval` (and wakes itself for its own\n * dispatches).\n */\nexport class DatabaseQueueDriver implements QueueDriver {\n readonly table: string;\n readonly batchTable: string;\n readonly workflowTable: string;\n readonly workflowStepTable: string;\n readonly workflowItemTable: string;\n readonly workflowSourceTable: string;\n readonly slotTable: string;\n private workflows: DatabaseWorkflowStore | undefined;\n private slotLines: DatabaseSlots | undefined;\n private readonly sql: SQL;\n private readonly dialect: Dialect;\n /** The connection's name, when it came with one; see `transaction`. */\n private readonly connection: string | undefined;\n private readonly busyTimeout: number;\n private configured: Promise<void> | undefined;\n /** SQLite: the transaction before the next; see `atomically`. */\n private sqliteTail: Promise<unknown> = Promise.resolve();\n\n constructor(\n connection: Pick<DatabaseConnection, \"sql\" | \"dialect\"> &\n Partial<Pick<DatabaseConnection, \"name\">>,\n options: DatabaseQueueDriverOptions = {},\n ) {\n const table = options.table ?? \"gemi_jobs\";\n const batchTable =\n options.batchTable ?? (table === \"gemi_jobs\" ? \"gemi_job_batches\" : `${table}_batches`);\n const defaults = table === \"gemi_jobs\";\n const workflowTable =\n options.workflowTable ?? (defaults ? \"gemi_workflows\" : `${table}_workflows`);\n const workflowStepTable =\n options.workflowStepTable ??\n (defaults ? \"gemi_workflow_steps\" : `${table}_workflow_steps`);\n const workflowItemTable =\n options.workflowItemTable ??\n (defaults ? \"gemi_workflow_items\" : `${table}_workflow_items`);\n const workflowSourceTable =\n options.workflowSourceTable ??\n (defaults ? \"gemi_workflow_sources\" : `${table}_workflow_sources`);\n const slotTable = options.slotTable ?? (defaults ? \"gemi_job_slots\" : `${table}_slots`);\n for (const name of [\n table,\n slotTable,\n batchTable,\n workflowTable,\n workflowStepTable,\n workflowItemTable,\n workflowSourceTable,\n ]) {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {\n throw new Error(\n `The queue table name \"${name}\" is not a plain identifier. Use ` +\n `letters, digits and underscores.`,\n );\n }\n }\n const busyTimeout = options.busyTimeout ?? 1000;\n if (!Number.isInteger(busyTimeout) || busyTimeout < 0) {\n throw new Error(\n `The queue's busyTimeout must be a whole number of milliseconds, 0 or more; got ${busyTimeout}.`,\n );\n }\n this.table = table;\n this.batchTable = batchTable;\n this.workflowTable = workflowTable;\n this.workflowStepTable = workflowStepTable;\n this.workflowItemTable = workflowItemTable;\n this.workflowSourceTable = workflowSourceTable;\n this.slotTable = slotTable;\n this.sql = connection.sql;\n this.dialect = connection.dialect;\n this.connection = connection.name;\n this.busyTimeout = busyTimeout;\n }\n\n /**\n * Gives a SQLite connection a busy timeout, once, before the driver's first\n * statement on it.\n *\n * Bun opens SQLite with `busy_timeout` 0, so a statement that finds another\n * process holding the file's write lock fails at once with `SQLITE_BUSY`.\n * Two processes on one file — `gemi dev` and a script that dispatches, or\n * the dev server and a seed — then lose writes at random: a dispatch whose\n * INSERT is refused is a job that never runs, and a `complete` that is\n * refused leaves the row claimed until its lease lapses and runs it again.\n * With a timeout SQLite retries the lock for that long instead.\n *\n * The wait is not free. Bun runs SQLite on the JavaScript thread, and the\n * busy handler sleeps there: while one statement waits out another\n * process's transaction, this process serves nothing else — measured, a\n * timer due every 10ms did not fire once across a 400ms wait. Hence a\n * second rather than the several a dedicated worker would choose; a lock\n * held longer than that still fails as it did before.\n *\n * On the connection, not on the driver's statements, because SQLite has no\n * other place for it — so it is the application's default connection's\n * setting too whenever the queue shares that connection, as `\"database\"`\n * does. That is why a connection already set to anything but 0 is left as\n * it is. Lazily rather than from the constructor, because a driver built\n * over a connection that is closed unused would otherwise leave a pragma\n * rejecting against it with nobody holding the promise. Retried after a\n * failure rather than remembered, so one lost statement does not fail every\n * later one.\n */\n private configure(): Promise<void> {\n if (this.dialect !== \"sqlite\" || this.busyTimeout === 0) return Promise.resolve();\n this.configured ??= (async () => {\n const [current] = (await this.sql.unsafe(\"PRAGMA busy_timeout\")) as Array<{\n timeout: number | string;\n }>;\n if (Number(current?.timeout ?? 0) !== 0) return;\n await this.sql.unsafe(`PRAGMA busy_timeout = ${this.busyTimeout}`);\n })().catch((error) => {\n this.configured = undefined;\n throw error;\n });\n return this.configured;\n }\n\n /**\n * Creates the jobs table, the batches table, the four workflow tables and\n * their indexes if they do not exist — the same DDL Prisma generates for\n * the models in the docs, so\n * a table made either way is the table the other expects — and adds the\n * batch columns to a jobs table from before batches. For tests and for an\n * app that does not manage its schema with Prisma; one that does should add\n * the models instead, or `prisma migrate` will see tables it does not know\n * and drop them.\n */\n async createTable(): Promise<void> {\n await this.configure();\n // The table first and its indexes after any upgrade, because one of them\n // is on `batch_id`, which a table from before batches does not have yet.\n const [table, ...indexes] = createTableStatements(this.dialect, this.table);\n await this.sql.unsafe(table!);\n if (!(await this.hasBatchColumns())) {\n for (const statement of addBatchColumnsStatements(this.dialect, this.table)) {\n await this.sql.unsafe(statement);\n }\n }\n for (const statement of indexes) await this.sql.unsafe(statement);\n for (const statement of createBatchTableStatements(this.dialect, this.batchTable)) {\n await this.sql.unsafe(statement);\n }\n for (const statement of createWorkflowTableStatements(\n this.dialect,\n this.workflowTable,\n this.workflowStepTable,\n )) {\n await this.sql.unsafe(statement);\n }\n for (const statement of createWorkflowItemTableStatements(\n this.dialect,\n this.workflowItemTable,\n )) {\n await this.sql.unsafe(statement);\n }\n for (const statement of createWorkflowSourceTableStatements(\n this.dialect,\n this.workflowSourceTable,\n )) {\n await this.sql.unsafe(statement);\n }\n for (const statement of createSlotTableStatements(this.dialect, this.slotTable)) {\n await this.sql.unsafe(statement);\n }\n }\n\n /** Whether the jobs table has `batch_id` and `progress` yet. */\n private async hasBatchColumns(): Promise<boolean> {\n try {\n await this.sql.unsafe(`SELECT batch_id, progress FROM ${this.quoted(this.table)} WHERE 1 = 0`);\n return true;\n } catch (error) {\n if (isMissingSchema(error)) return false;\n throw error;\n }\n }\n\n enqueue(job: EnqueueJob): Promise<string> {\n // Read here, at the call, and never kept: Bun's handle stays callable\n // after its transaction ends and then runs on the pool, so a stored one\n // would write outside any transaction and succeed.\n const tx = this.transaction();\n const written = this.insert(tx ?? this.sql, job);\n // A row written on the transaction is part of it, so the commit waits for\n // it and does not happen if it failed. Otherwise a dispatch nobody awaits\n // — every queued listener's — that fails on Postgres aborts the\n // transaction, and the `COMMIT` that follows is quietly a rollback that\n // `begin` reports as success: the caller's rows are gone with no error.\n // Registered synchronously, while the caller's scope is current.\n if (tx) commitDependsOn(written);\n return written;\n }\n\n private async insert(\n q: SQL,\n { name, args, delayMs = 0, id = Bun.randomUUIDv7() }: EnqueueJob,\n ): Promise<string> {\n await this.configure();\n const now = this.now(q);\n await q`\n INSERT INTO ${this.name(q)}\n (id, name, payload, status, attempts, available_at, created_at, updated_at)\n VALUES\n (${id}, ${name}, ${args}, 'pending', 0, ${now} + ${this.ms(q, delayMs)}, ${now}, ${now})\n `;\n return id;\n }\n\n /**\n * Locks in the `gemi_locks` table of the same connection, so unique jobs,\n * `withoutOverlapping` and `onOneServer` hold across every process sharing\n * this database. The table is only touched when one of those is used.\n */\n lockStore(): DatabaseLockStore {\n return new DatabaseLockStore(\n { sql: this.sql, dialect: this.dialect, name: this.connection },\n { busyTimeout: this.busyTimeout },\n );\n }\n\n joinsTransaction(): boolean {\n return this.transaction() !== undefined;\n }\n\n /**\n * The open ORM transaction, when an `enqueue` should be written on it.\n *\n * Only one on this driver's own connection, matched by name as the ORM and\n * the `DB` facade match it: the transaction's handle does not say which\n * pool it came from. A driver built from a bare `{ sql, dialect }` has no\n * name to match, so it never joins, and the manager holds its dispatches\n * until the commit instead. Guessing \"default\" there would write a job\n * into whichever database the default connection is, which need not be the\n * one this driver's table is in.\n *\n * Never on SQLite. Bun gives a SQLite client one connection, and a\n * statement on the pool while a transaction is open runs *inside* that\n * transaction — measured on Bun 1.3.14: it sees the transaction's\n * uncommitted rows. The queue claims through the pool, so a job row\n * written on the transaction would be visible to this process's own claim\n * before the commit, and run before the data it describes exists — or\n * whether or not it ever does. Held until the commit, it cannot.\n */\n private transaction(): TransactionSQL | undefined {\n if (this.dialect === \"sqlite\" || this.connection === undefined) return undefined;\n const tx = currentTransaction();\n if (tx === undefined || currentConnectionName() !== this.connection) return undefined;\n return tx;\n }\n\n async claim(limit: number, options: ClaimOptions): Promise<ClaimedJob[]> {\n const count = Math.max(0, Math.floor(limit));\n if (count === 0) return [];\n await this.configure();\n\n const rows =\n this.dialect === \"mysql\" || this.dialect === \"mariadb\"\n ? await this.claimLocking(count, options)\n : await this.claimUpdating(count, options);\n\n // `RETURNING` promises no order, and the manager expects oldest first.\n //\n // Every column is read back (`*`) rather than a list, so that `batch_id`\n // comes back where the table has it and the claim still works on a table\n // from before batches, which never has a batch job in it.\n return rows\n .map((row) => ({\n order: Number(row.available_at),\n job: {\n id: String(row.id),\n name: String(row.name),\n args: String(row.payload),\n attempt: Number(row.attempts),\n createdAt: Number(row.created_at),\n ...(row.batch_id == null ? {} : { batchId: String(row.batch_id) }),\n },\n }))\n .sort((a, b) => a.order - b.order || (a.job.id < b.job.id ? -1 : 1))\n .map(({ job }) => job);\n }\n\n async complete(job: ClaimedJob): Promise<void> {\n if (job.batchId !== undefined) return this.endBatchJob(job, \"succeeded\");\n await this.configure();\n const q = this.sql;\n await q`\n DELETE FROM ${this.name(q)}\n WHERE id = ${job.id} AND status = 'claimed' AND attempts = ${job.attempt}\n `;\n }\n\n async fail(job: ClaimedJob, failure: JobFailure): Promise<void> {\n if (job.batchId !== undefined) return this.endBatchJob(job, \"failed\", failure);\n await this.configure();\n const q = this.sql;\n const now = this.now(q);\n if (failure.retryInMs === null) {\n await q`\n UPDATE ${this.name(q)}\n SET status = 'dead', lease_expires_at = NULL, last_error = ${failure.error},\n updated_at = ${now}\n WHERE id = ${job.id} AND status = 'claimed' AND attempts = ${job.attempt}\n `;\n return;\n }\n await q`\n UPDATE ${this.name(q)}\n SET status = 'pending', available_at = ${now} + ${this.ms(q, failure.retryInMs)},\n lease_expires_at = NULL, last_error = ${failure.error}, updated_at = ${now}\n WHERE id = ${job.id} AND status = 'claimed' AND attempts = ${job.attempt}\n `;\n }\n\n /**\n * `attempts - 1`, so the attempt this claim added is taken back. Guarded by\n * the claim's attempt like every other report, so it can only undo the\n * increment it is reporting on.\n */\n async release(job: ClaimedJob, release: JobRelease): Promise<void> {\n const q = this.sql;\n const now = this.now(q);\n await q`\n UPDATE ${this.name(q)}\n SET status = 'pending', attempts = attempts - 1,\n available_at = ${now} + ${this.ms(q, release.retryInMs)},\n lease_expires_at = NULL, updated_at = ${now}\n WHERE id = ${job.id} AND status = 'claimed' AND attempts = ${job.attempt}\n `;\n }\n\n /**\n * Extends a lease that has lapsed but not been re-issued, too, as the memory\n * driver does: the job is still running here and nobody else has it.\n */\n async heartbeat(jobs: ClaimedJob[], options: ClaimOptions): Promise<void> {\n await this.configure();\n const q = this.sql;\n await Promise.all(\n jobs.map((job) => {\n const now = this.now(q);\n return q`\n UPDATE ${this.name(q)}\n SET lease_expires_at = ${now} + ${this.ms(q, options.visibilityTimeoutMs)},\n updated_at = ${now}\n WHERE id = ${job.id} AND status = 'claimed' AND attempts = ${job.attempt}\n `;\n }),\n );\n }\n\n /**\n * Puts a dead row back to waiting with its attempts reset, so the job gets\n * its whole `maxAttempts` again. `last_error` is kept until the next failure\n * replaces it, so the reason it died is still there to read while it runs.\n */\n async retryDead(id: string): Promise<boolean> {\n await this.configure();\n const q = this.sql;\n // A job of a batch has been counted as failed or cancelled already, and\n // its batch may have finished and run its callbacks. Run again, it would\n // be counted a second time.\n const [dead] = (await q`\n SELECT * FROM ${this.name(q)} WHERE id = ${id} AND status = 'dead'\n `) as Row[];\n if (!dead || dead.batch_id != null) return false;\n const now = this.now(q);\n const result = await q`\n UPDATE ${this.name(q)}\n SET status = 'pending', attempts = 0, available_at = ${now}, lease_expires_at = NULL,\n updated_at = ${now}\n WHERE id = ${id} AND status = 'dead'\n `;\n return affected(result) > 0;\n }\n\n /**\n * Deletes dead-lettered jobs last touched more than `olderThanMs` ago, and\n * resolves to how many. Dead rows are kept so a failure can be read and the\n * job brought back with `retryDead`; nothing removes them unless this is called — from\n * a scheduled job, say.\n */\n async prune(olderThanMs: number): Promise<number> {\n await this.configure();\n const q = this.sql;\n const result = await q`\n DELETE FROM ${this.name(q)}\n WHERE status = 'dead' AND updated_at <= ${this.now(q)} - ${this.ms(q, olderThanMs)}\n `;\n return affected(result);\n }\n\n // ---------------------------------------------------------------------\n // Batches\n //\n // A batch is a row in `batchTable` with its counters, and its jobs are\n // ordinary rows of the jobs table with `batch_id` set. Every change to the\n // counters happens in a transaction that first locks the batch row, so the\n // ends of two jobs of one batch are counted one after the other, and the\n // one that brings `pending` to 0 is the only one that sees it reach 0. The\n // job's own row is ended in that transaction, guarded by its attempt like\n // every other report, so a stale claim neither ends the job nor counts it;\n // and the callback jobs that become due are inserted in it, so they commit\n // with the count or not at all. That is the whole of \"exactly once\".\n //\n // Locks are always taken batch row first, then job rows, so the driver's\n // own transactions cannot deadlock on each other.\n // ---------------------------------------------------------------------\n\n enqueueBatch(batch: EnqueueBatch): Promise<void> {\n // On the caller's transaction when it is one this driver joins, as\n // `enqueue` is; otherwise in a transaction of its own, so a batch is\n // never half recorded.\n const tx = this.transaction();\n const written = tx\n ? this.insertBatch(tx, batch)\n : this.atomically((q) => this.insertBatch(q, batch));\n if (tx) commitDependsOn(written);\n return written;\n }\n\n private async insertBatch(q: SQL, batch: EnqueueBatch): Promise<void> {\n await this.configure();\n const now = await this.clock(q);\n const record = newBatchRecord({ ...batch, total: batch.args.length, now });\n // A batch of no jobs is finished as soon as it exists.\n const { record: settled, calls } = settle(record, record, now);\n await explainMissingSchema(\n q`\n INSERT INTO ${this.batches(q)}\n (id, name, total, pending, succeeded, failed, cancelled, failed_job_ids, options,\n cancelled_at, finished_at, created_at, updated_at)\n VALUES\n (${settled.id}, ${settled.name}, ${settled.total}, ${settled.pending}, 0, 0, 0,\n '[]', ${batchOptions(settled)}, NULL, ${this.timeOrNull(q, settled.finishedAt)},\n ${this.ms(q, now)}, ${this.ms(q, now)})\n `,\n this.batchTable,\n );\n\n const at = this.ms(q, now);\n for (let start = 0; start < batch.args.length; start += BATCH_INSERT_CHUNK) {\n const rows = batch.args\n .slice(start, start + BATCH_INSERT_CHUNK)\n .map(\n (args) =>\n q`(${Bun.randomUUIDv7()}, ${batch.job}, ${args}, 'pending', 0, ${at}, ${at}, ${at}, ${batch.id}, 0)`,\n )\n .reduce((list, row) => q`${list}, ${row}`);\n await explainMissingSchema(\n q`\n INSERT INTO ${this.name(q)}\n (id, name, payload, status, attempts, available_at, created_at, updated_at, batch_id, progress)\n VALUES ${rows}\n `,\n this.table,\n );\n }\n for (const call of calls) await this.insert(q, call);\n }\n\n async findBatch(id: string, options: { progress?: boolean } = {}): Promise<BatchStatus | null> {\n await this.configure();\n const q = this.sql;\n const [row] = (await explainMissingSchema(\n q`SELECT * FROM ${this.batches(q)} WHERE id = ${id}`,\n this.batchTable,\n )) as BatchRow[];\n if (!row) return null;\n const record = batchRecord(row);\n if (options.progress === false || record.pending === 0) return statusOf(record);\n const [sum] = (await q`\n SELECT COALESCE(SUM(progress), 0) AS running FROM ${this.name(q)}\n WHERE batch_id = ${id} AND status IN ('pending', 'claimed')\n `) as Array<{ running: unknown }>;\n return statusOf(record, Number(sum?.running ?? 0));\n }\n\n async cancelBatch(id: string): Promise<boolean> {\n return this.atomically((q) => this.cancelBatchOn(q, id));\n }\n\n /** `cancelBatch`, inside a transaction the caller has open. */\n private async cancelBatchOn(q: SQL, id: string): Promise<boolean> {\n const prev = await this.lockBatch(q, id);\n if (!prev || prev.finishedAt !== null || prev.cancelledAt !== null) return false;\n const now = await this.clock(q);\n const next = markCancelled(prev, now, await this.cancelWaiting(q, id));\n await this.saveBatch(q, prev, next, now);\n return true;\n }\n\n /**\n * Workflows (#846), in `workflowTable` and `workflowStepTable` of this\n * driver's database. Their writes share this driver's transactions, so a\n * step's record and the tick or batch it schedules commit together.\n */\n workflowStore(): DatabaseWorkflowStore {\n this.workflows ??= new DatabaseWorkflowStore(\n {\n sql: this.sql,\n dialect: this.dialect,\n connection: this.connection,\n configure: () => this.configure(),\n atomically: (fn) => this.atomically(fn),\n transaction: () => this.transaction(),\n now: (q) => this.now(q),\n ms: (q, value) => this.ms(q, value),\n timeOrNull: (q, value) => this.timeOrNull(q, value),\n fraction: (q, value) => this.fraction(q, value),\n clock: (q) => this.clock(q),\n insertJob: (q, job) => this.insert(q, job),\n insertBatch: (q, batch) => this.insertBatch(q, batch),\n cancelBatch: (q, id) => this.cancelBatchOn(q, id),\n quoted: (table) => this.quoted(table),\n },\n {\n table: this.workflowTable,\n stepTable: this.workflowStepTable,\n itemTable: this.workflowItemTable,\n sourceTable: this.workflowSourceTable,\n },\n );\n return this.workflows;\n }\n\n /**\n * Concurrency slots (#1319), in `slotTable`, shared by every process on\n * this database; see `DatabaseSlots`.\n */\n acquireSlots(request: SlotRequest): Promise<boolean> {\n return this.slots().acquire(request);\n }\n\n releaseSlots(holder: string): Promise<void> {\n return this.slots().release(holder);\n }\n\n private slots(): DatabaseSlots {\n this.slotLines ??= new DatabaseSlots(\n {\n sql: this.sql,\n dialect: this.dialect,\n configure: () => this.configure(),\n atomically: (fn) => this.atomically(fn),\n insertJob: (q, job) => this.insert(q, job),\n },\n { slots: this.slotTable, jobs: this.table, workflows: this.workflowTable },\n );\n return this.slotLines;\n }\n\n async reportProgress(job: ClaimedJob, progress: number): Promise<void> {\n const value = clampProgress(progress);\n await this.configure();\n const q = this.sql;\n await q`\n UPDATE ${this.name(q)} SET progress = ${this.fraction(q, value)}\n WHERE id = ${job.id} AND status = 'claimed' AND attempts = ${job.attempt}\n `;\n }\n\n /**\n * Deletes batches that finished more than `olderThanMs` ago, and resolves\n * to how many. Nothing else removes them; a finished batch is only kept so\n * `findBatch` can still answer for it.\n */\n async pruneBatches(olderThanMs: number): Promise<number> {\n await this.configure();\n const q = this.sql;\n const result = await q`\n DELETE FROM ${this.batches(q)}\n WHERE finished_at IS NOT NULL AND finished_at <= ${this.now(q)} - ${this.ms(q, olderThanMs)}\n `;\n return affected(result);\n }\n\n /**\n * `complete` and `fail` for a job of a batch: the job's row is ended and the\n * batch counts it, in one transaction.\n */\n private endBatchJob(job: ClaimedJob, kind: \"succeeded\" | \"failed\", failure?: JobFailure) {\n const batchId = job.batchId!;\n return this.atomically(async (q) => {\n const prev = await this.lockBatch(q, batchId);\n const guard = q`id = ${job.id} AND status = 'claimed' AND attempts = ${job.attempt}`;\n const now = this.now(q);\n\n if (kind === \"succeeded\") {\n const result = await q`DELETE FROM ${this.name(q)} WHERE ${guard}`;\n if (affected(result) === 0 || !prev) return;\n return this.count(q, prev, \"succeeded\", job.id);\n }\n\n const cancelled =\n failure!.cancelled === true ||\n (failure!.retryInMs !== null && prev !== undefined && prev.cancelledAt !== null);\n if (failure!.retryInMs !== null && !cancelled) {\n // A retry starts its share of the batch's progress from 0 again.\n await q`\n UPDATE ${this.name(q)}\n SET status = 'pending', available_at = ${now} + ${this.ms(q, failure!.retryInMs)},\n lease_expires_at = NULL, last_error = ${failure!.error}, progress = 0,\n updated_at = ${now}\n WHERE ${guard}\n `;\n return;\n }\n\n const result = await q`\n UPDATE ${this.name(q)}\n SET status = 'dead', lease_expires_at = NULL, last_error = ${failure!.error},\n updated_at = ${now}\n WHERE ${guard}\n `;\n if (affected(result) === 0 || !prev) return;\n return this.count(q, prev, cancelled ? \"cancelled\" : \"failed\", job.id);\n });\n }\n\n /** Counts one job's end against its locked batch row. */\n private async count(q: SQL, prev: BatchRecord, outcome: BatchOutcome, jobId: string) {\n const now = await this.clock(q);\n let next = countOutcome(prev, outcome, jobId);\n if (cancelsBatch(prev, next)) {\n next = markCancelled(next, now, await this.cancelWaiting(q, prev.id));\n }\n await this.saveBatch(q, prev, next, now);\n }\n\n /**\n * Ends the batch's waiting jobs as cancelled — kept as dead rows that say\n * why — and resolves to how many there were. Their rows are locked after\n * the batch row, the order every batch transaction takes.\n */\n private async cancelWaiting(q: SQL, batchId: string): Promise<number> {\n const now = this.now(q);\n const result = await q`\n UPDATE ${this.name(q)}\n SET status = 'dead', last_error = ${CANCELLED_ERROR}, updated_at = ${now}\n WHERE batch_id = ${batchId} AND status = 'pending'\n `;\n return affected(result);\n }\n\n /** Writes the batch's new counters and enqueues the callbacks they made due. */\n private async saveBatch(q: SQL, prev: BatchRecord, next: BatchRecord, now: number) {\n const { record, calls } = settle(prev, next, now);\n await q`\n UPDATE ${this.batches(q)}\n SET pending = ${record.pending}, succeeded = ${record.succeeded}, failed = ${record.failed},\n cancelled = ${record.cancelled}, failed_job_ids = ${JSON.stringify(record.failedJobIds)},\n cancelled_at = ${this.timeOrNull(q, record.cancelledAt)},\n finished_at = ${this.timeOrNull(q, record.finishedAt)}, updated_at = ${this.ms(q, now)}\n WHERE id = ${record.id}\n `;\n for (const call of calls) await this.insert(q, call);\n }\n\n /**\n * Reads the batch row and holds it until the transaction ends. Postgres and\n * MySQL lock the row; SQLite has no row locks, so a write to the row takes\n * the file's write lock instead, waiting out another process's for the\n * busy timeout rather than failing on the upgrade from a read lock.\n */\n private async lockBatch(q: SQL, id: string): Promise<BatchRecord | undefined> {\n let rows: BatchRow[];\n if (this.dialect === \"sqlite\") {\n await q`UPDATE ${this.batches(q)} SET updated_at = updated_at WHERE id = ${id}`;\n rows = await q`SELECT * FROM ${this.batches(q)} WHERE id = ${id}`;\n } else {\n rows = await q`SELECT * FROM ${this.batches(q)} WHERE id = ${id} FOR UPDATE`;\n }\n return rows[0] ? batchRecord(rows[0]) : undefined;\n }\n\n /**\n * Runs `fn` in a transaction of the driver's own.\n *\n * On SQLite one at a time per driver. Bun gives a SQLite client a single\n * connection, and a second `begin` on it while one is open is refused with\n * \"cannot start a transaction within a transaction\". One the application\n * has open on the same client — an ORM transaction, when the queue shares\n * the default connection — is waited out the same way, a few times.\n */\n private atomically<T>(fn: (q: SQL) => Promise<T>): Promise<T> {\n const run = async () => {\n await this.configure();\n for (let attempt = 0; ; attempt++) {\n try {\n return (await this.sql.begin((tx) => fn(tx))) as T;\n } catch (error) {\n if (\n this.dialect !== \"sqlite\" ||\n attempt >= 50 ||\n !/within a transaction/i.test(String((error as Error)?.message ?? error))\n ) {\n throw error;\n }\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n }\n };\n if (this.dialect !== \"sqlite\") return run();\n const result = this.sqliteTail.then(run, run);\n this.sqliteTail = result.catch(() => {});\n return result;\n }\n\n /** The database's clock now, as a number, for values computed here. */\n private async clock(q: SQL): Promise<number> {\n const [row] = (await q`SELECT ${this.now(q)} AS now`) as Array<{ now: unknown }>;\n return Number(row!.now);\n }\n\n /** An epoch-milliseconds value or `NULL`, typed as the BIGINT columns are. */\n private timeOrNull(q: SQL, value: number | null) {\n return value === null ? q`NULL` : this.ms(q, value);\n }\n\n /** A 0..1 progress value as a parameter Postgres can assign to its column. */\n private fraction(q: SQL, value: number) {\n return this.dialect === \"postgres\" ? q`CAST(${value} AS DOUBLE PRECISION)` : q`${value}`;\n }\n\n /**\n * Postgres and SQLite: one statement. Postgres locks the rows it picks with\n * `SKIP LOCKED` in a CTE, which it evaluates once, so a concurrent claimer\n * skips them rather than waiting and then taking them too. SQLite serialises\n * writes, so its statement needs no lock clause to be atomic.\n */\n private async claimUpdating(limit: number, options: ClaimOptions): Promise<Row[]> {\n const q = this.sql;\n const now = this.now(q);\n const lease = this.ms(q, options.visibilityTimeoutMs);\n const table = this.name(q);\n\n if (this.dialect === \"postgres\") {\n return await q`\n WITH next AS (\n SELECT id FROM ${table}\n WHERE ${this.claimable(q, options)}\n ORDER BY available_at, id\n LIMIT ${limit}\n FOR UPDATE SKIP LOCKED\n )\n UPDATE ${table} AS job\n SET status = 'claimed', attempts = job.attempts + 1, claimed_at = ${now},\n lease_expires_at = ${now} + ${lease}, updated_at = ${now}\n FROM next\n WHERE job.id = next.id\n RETURNING job.*\n `;\n }\n\n return await q`\n UPDATE ${table}\n SET status = 'claimed', attempts = attempts + 1, claimed_at = ${now},\n lease_expires_at = ${now} + ${lease}, updated_at = ${now}\n WHERE id IN (\n SELECT id FROM ${table}\n WHERE ${this.claimable(q, options)}\n ORDER BY available_at, id\n LIMIT ${limit}\n )\n RETURNING *\n `;\n }\n\n /**\n * MySQL and MariaDB: lock, then update. The rows stay locked until the\n * transaction commits, so the attempt counted here is the one written.\n *\n * Two selects rather than one, because the `OR` in `claimable` leaves MySQL\n * no index to walk: it scans the whole table and sorts it (`type: ALL`,\n * `Using filesort`), and `LIMIT` is applied only after the sort, so InnoDB\n * locks every candidate row rather than the handful being claimed. A second\n * claimer's `SKIP LOCKED` then skips the entire table and claims nothing —\n * the opposite of what `SKIP LOCKED` is here for, and enough to serialise\n * every replica onto one claimer. Fixing `status` to a single value in each\n * pass lets its index supply both the filter and the order, so only the rows\n * actually handed out are locked. The two passes cannot overlap, because a\n * row's `status` is in exactly one of them.\n */\n private async claimLocking(limit: number, options: ClaimOptions): Promise<Row[]> {\n // A connection of our own, so the isolation level below is this claim's\n // and not the pool's. MySQL will not change it inside an open\n // transaction, and `begin` opens one at once, so it is set just before.\n const connection = await this.sql.reserve();\n const [isolation] = (await connection`\n SELECT @@transaction_isolation AS level\n `) as Array<{ level: string }>;\n // REPEATABLE READ — MySQL's default — locks the gaps a range scan passes\n // over, not just the rows it returns. The two passes below read different\n // indexes, so two claimers take those gap locks in opposite orders and\n // deadlock, even when the second pass matches no row at all. READ\n // COMMITTED takes no gap locks, which is what `SKIP LOCKED` wants: each\n // claimer locks the rows it is taking and nothing else.\n await connection`SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED`;\n try {\n return await this.claimLockingOn(connection, limit, options);\n } finally {\n // The connection goes back to the pool the application shares, so it\n // goes back as it came. `@@transaction_isolation` reads back with a\n // hyphen and `SET` wants a space.\n const previous = isolation?.level?.replaceAll(\"-\", \" \");\n if (previous && /^[A-Z ]+$/.test(previous)) {\n await connection.unsafe(`SET SESSION TRANSACTION ISOLATION LEVEL ${previous}`);\n }\n connection.release();\n }\n }\n\n private async claimLockingOn(\n connection: SQL,\n limit: number,\n options: ClaimOptions,\n ): Promise<Row[]> {\n return await connection.begin(async (tx) => {\n const table = this.name(tx);\n const columns = tx.unsafe(\"*\");\n\n // Waiting and due, oldest first, along the (status, available_at) index.\n const rows: Row[] = await tx`\n SELECT ${columns} FROM ${table}\n WHERE status = 'pending' AND available_at <= ${this.now(tx)}\n AND ${this.runnable(tx, options, \"available_at\")}\n ORDER BY available_at, id\n LIMIT ${limit}\n FOR UPDATE SKIP LOCKED\n `;\n\n // Only then the leases that ran out, longest-expired first, along the\n // (status, lease_expires_at) index. `claim` sorts what both passes\n // return by `available_at` before handing it to the manager.\n if (rows.length < limit) {\n const expired: Row[] = await tx`\n SELECT ${columns} FROM ${table}\n WHERE status = 'claimed' AND lease_expires_at <= ${this.now(tx)}\n AND ${this.runnable(tx, options, \"lease_expires_at\")}\n ORDER BY lease_expires_at, id\n LIMIT ${limit - rows.length}\n FOR UPDATE SKIP LOCKED\n `;\n rows.push(...expired);\n }\n\n for (const row of rows) {\n const now = this.now(tx);\n await tx`\n UPDATE ${table}\n SET status = 'claimed', attempts = attempts + 1, claimed_at = ${now},\n lease_expires_at = ${now} + ${this.ms(tx, options.visibilityTimeoutMs)},\n updated_at = ${now}\n WHERE id = ${row.id}\n `;\n }\n return rows.map((row) => ({ ...row, attempts: Number(row.attempts) + 1 }));\n });\n }\n\n /**\n * Waiting and due, or leased and the lease has run out — and, when the\n * claimer said which names it can run, under one of them or claimable for\n * longer than the grace window. See `ClaimOptions.registered`.\n */\n private claimable(q: SQL, options: ClaimOptions) {\n const now = this.now(q);\n return q`(\n (status = 'pending' AND available_at <= ${now}\n AND ${this.runnable(q, options, \"available_at\")})\n OR (status = 'claimed' AND lease_expires_at <= ${now}\n AND ${this.runnable(q, options, \"lease_expires_at\")})\n )`;\n }\n\n /**\n * Whether a row is one the claimer may take by its name. `since` is the\n * column holding when the row became claimable, which is what the grace\n * window is measured from: a job delayed for a day and due a second ago has\n * been waiting for a second, not a day, and a replica that knows its name\n * may be about to take it.\n *\n * The list is spliced in as one parameter per name, because `name IN ()` is\n * a syntax error in all three dialects; an empty registry matches no name\n * and leaves only the grace window.\n *\n * No index covers `name`, on purpose. On MySQL 8.4 the claim keeps walking\n * `(status, available_at)` and filters names as it goes, and a\n * `(status, name, available_at)` index is not chosen even when it exists:\n * it cannot hand back rows in `available_at` order across several names. A\n * head of rows with names this replica does not know costs only the scan,\n * not locks, because `claimLocking` claims at READ COMMITTED. Measured with\n * 2,000 unknown rows ahead of the rest: 10 record locks held for a claim of\n * 5, and a second replica that knows those names took them meanwhile. At\n * REPEATABLE READ the same claim held 4,014, and the second replica skipped\n * every one of them.\n */\n private runnable(q: SQL, options: ClaimOptions, since: \"available_at\" | \"lease_expires_at\") {\n const registered = options.registered;\n if (!registered) return q`1 = 1`;\n const names = registered.names.length\n ? q`name IN (${registered.names\n .map((name) => q`${name}`)\n .reduce((list, name) => q`${list}, ${name}`)})`\n : q`1 = 0`;\n if (!Number.isFinite(registered.graceMs)) return names;\n const column = q.unsafe(since);\n return q`(${names} OR ${column} <= ${this.now(q)} - ${this.ms(q, registered.graceMs)})`;\n }\n\n /**\n * The table name, already checked to be a plain identifier, and quoted the\n * way `createTable` quotes it. Unquoted, Postgres folds `GemiJobs` to\n * `gemijobs` and misses the table `createTable` (or a Prisma model without\n * `@@map`) made, and a reserved word such as `order` is a syntax error.\n */\n private name(q: SQL) {\n return q.unsafe(this.quoted(this.table));\n }\n\n /** The batches table, quoted as `name` quotes the jobs table. */\n private batches(q: SQL) {\n return q.unsafe(this.quoted(this.batchTable));\n }\n\n private quoted(table: string) {\n const mysql = this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n return mysql ? `\\`${table}\\`` : `\"${table}\"`;\n }\n\n /** The database's clock, in epoch milliseconds. */\n private now(q: SQL) {\n switch (this.dialect) {\n case \"postgres\":\n return q`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;\n case \"mysql\":\n case \"mariadb\":\n // UTC against a naive epoch literal, so the session's time zone — and a\n // daylight-saving hour that occurs twice in it — never enters in.\n return q`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;\n case \"sqlite\":\n return q`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`;\n }\n }\n\n /**\n * A millisecond count as an integer parameter. Cast, so Postgres does not\n * have to infer the type of a bare parameter added to a `bigint`.\n */\n private ms(q: SQL, value: number) {\n const ms = Math.max(0, Math.round(value));\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\"\n ? q`CAST(${ms} AS SIGNED)`\n : q`CAST(${ms} AS BIGINT)`;\n }\n}\n\n/**\n * How many rows a `DELETE` or `UPDATE` touched. SQLite and Postgres report\n * them in `count`; MySQL may report them in `affectedRows` and zero rows\n * returned in `count`.\n */\nfunction affected(result: unknown): number {\n const counts = result as { count?: number | null; affectedRows?: number | null };\n return Math.max(Number(counts.count ?? 0), Number(counts.affectedRows ?? 0));\n}\n\n/**\n * The jobs table, as Prisma generates it for the model in the docs — checked\n * against `prisma migrate diff` for all three providers — with `IF NOT EXISTS`\n * added. MySQL cannot say that of an index, so its indexes are declared inside\n * the table, which is also where Prisma puts them.\n */\nexport function createTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`name\\` VARCHAR(191) NOT NULL,\n \\`payload\\` LONGTEXT NOT NULL,\n \\`status\\` VARCHAR(191) NOT NULL,\n \\`attempts\\` INTEGER NOT NULL DEFAULT 0,\n \\`available_at\\` BIGINT NOT NULL,\n \\`claimed_at\\` BIGINT NULL,\n \\`lease_expires_at\\` BIGINT NULL,\n \\`last_error\\` LONGTEXT NULL,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n \\`batch_id\\` VARCHAR(191) NULL,\n \\`progress\\` DOUBLE NULL,\n\n INDEX \\`${table}_status_available_at_idx\\`(\\`status\\`, \\`available_at\\`),\n INDEX \\`${table}_status_lease_expires_at_idx\\`(\\`status\\`, \\`lease_expires_at\\`),\n INDEX \\`${table}_batch_id_idx\\`(\\`batch_id\\`),\n PRIMARY KEY (\\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n\n const key = dialect === \"sqlite\" ? `\"id\" TEXT NOT NULL PRIMARY KEY,` : `\"id\" TEXT NOT NULL,`;\n const constraint =\n dialect === \"sqlite\" ? \"\" : `,\\n\\n CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"id\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n ${key}\n \"name\" TEXT NOT NULL,\n \"payload\" TEXT NOT NULL,\n \"status\" TEXT NOT NULL,\n \"attempts\" INTEGER NOT NULL DEFAULT 0,\n \"available_at\" BIGINT NOT NULL,\n \"claimed_at\" BIGINT,\n \"lease_expires_at\" BIGINT,\n \"last_error\" TEXT,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL,\n \"batch_id\" TEXT,\n \"progress\" ${dialect === \"sqlite\" ? \"REAL\" : \"DOUBLE PRECISION\"}${constraint}\n)`,\n `CREATE INDEX IF NOT EXISTS \"${table}_status_available_at_idx\" ON \"${table}\"(\"status\", \"available_at\")`,\n `CREATE INDEX IF NOT EXISTS \"${table}_status_lease_expires_at_idx\" ON \"${table}\"(\"status\", \"lease_expires_at\")`,\n `CREATE INDEX IF NOT EXISTS \"${table}_batch_id_idx\" ON \"${table}\"(\"batch_id\")`,\n ];\n}\n\n/**\n * The two columns and the index batches add to a jobs table made before them,\n * as Prisma's migration for the updated model writes them. `createTable` runs\n * these when the columns are missing; an app on Prisma gets the same from\n * `prisma migrate dev` after updating the model.\n */\nexport function addBatchColumnsStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `ALTER TABLE \\`${table}\\` ADD COLUMN \\`batch_id\\` VARCHAR(191) NULL,\n ADD COLUMN \\`progress\\` DOUBLE NULL,\n ADD INDEX \\`${table}_batch_id_idx\\`(\\`batch_id\\`)`,\n ];\n }\n const progress = dialect === \"sqlite\" ? \"REAL\" : \"DOUBLE PRECISION\";\n if (dialect === \"sqlite\") {\n return [\n `ALTER TABLE \"${table}\" ADD COLUMN \"batch_id\" TEXT`,\n `ALTER TABLE \"${table}\" ADD COLUMN \"progress\" ${progress}`,\n `CREATE INDEX IF NOT EXISTS \"${table}_batch_id_idx\" ON \"${table}\"(\"batch_id\")`,\n ];\n }\n return [\n `ALTER TABLE \"${table}\" ADD COLUMN IF NOT EXISTS \"batch_id\" TEXT,\nADD COLUMN IF NOT EXISTS \"progress\" ${progress}`,\n `CREATE INDEX IF NOT EXISTS \"${table}_batch_id_idx\" ON \"${table}\"(\"batch_id\")`,\n ];\n}\n\n/**\n * The batches table, as Prisma generates it for the `GemiJobBatch` model in\n * the docs, with `IF NOT EXISTS` added.\n */\nexport function createBatchTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`name\\` VARCHAR(191) NULL,\n \\`total\\` INTEGER NOT NULL,\n \\`pending\\` INTEGER NOT NULL,\n \\`succeeded\\` INTEGER NOT NULL DEFAULT 0,\n \\`failed\\` INTEGER NOT NULL DEFAULT 0,\n \\`cancelled\\` INTEGER NOT NULL DEFAULT 0,\n \\`failed_job_ids\\` LONGTEXT NOT NULL,\n \\`options\\` LONGTEXT NOT NULL,\n \\`cancelled_at\\` BIGINT NULL,\n \\`finished_at\\` BIGINT NULL,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n\n PRIMARY KEY (\\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n\n const key = dialect === \"sqlite\" ? `\"id\" TEXT NOT NULL PRIMARY KEY,` : `\"id\" TEXT NOT NULL,`;\n const constraint =\n dialect === \"sqlite\" ? \"\" : `,\\n\\n CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"id\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n ${key}\n \"name\" TEXT,\n \"total\" INTEGER NOT NULL,\n \"pending\" INTEGER NOT NULL,\n \"succeeded\" INTEGER NOT NULL DEFAULT 0,\n \"failed\" INTEGER NOT NULL DEFAULT 0,\n \"cancelled\" INTEGER NOT NULL DEFAULT 0,\n \"failed_job_ids\" TEXT NOT NULL,\n \"options\" TEXT NOT NULL,\n \"cancelled_at\" BIGINT,\n \"finished_at\" BIGINT,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL${constraint}\n)`,\n ];\n}\n\n/** A batch row as the record `batch.ts` works on. */\nfunction batchRecord(row: BatchRow): BatchRecord {\n const options = JSON.parse(row.options) as {\n allowFailures?: boolean;\n callbacks?: BatchCallbacks;\n };\n const time = (value: BatchRow[\"cancelled_at\"]) => (value == null ? null : Number(value));\n return {\n id: String(row.id),\n name: row.name == null ? null : String(row.name),\n total: Number(row.total),\n pending: Number(row.pending),\n succeeded: Number(row.succeeded),\n failed: Number(row.failed),\n cancelled: Number(row.cancelled),\n failedJobIds: JSON.parse(row.failed_job_ids) as string[],\n cancelledAt: time(row.cancelled_at),\n finishedAt: time(row.finished_at),\n createdAt: Number(row.created_at),\n allowFailures: options.allowFailures === true,\n callbacks: options.callbacks ?? {},\n };\n}\n\n/** What the `options` column holds: what does not change once dispatched. */\nfunction batchOptions(record: BatchRecord): string {\n return JSON.stringify({ allowFailures: record.allowFailures, callbacks: record.callbacks });\n}\n\n/**\n * Whether a database error says a table or column does not exist, in the\n * words of any of the three: Postgres' `relation … does not exist` and\n * `column … does not exist`, MySQL's `Table … doesn't exist` and `Unknown\n * column`, SQLite's `no such table` and `no such column`.\n */\nfunction isMissingSchema(error: unknown): boolean {\n const message = String((error as Error)?.message ?? error);\n return /does not exist|doesn't exist|unknown column|no such (table|column)|has no column/i.test(\n message,\n );\n}\n\n/**\n * Runs a statement that needs the batch schema, and turns \"no such table or\n * column\" into an error that says what to do about it.\n */\nasync function explainMissingSchema<T>(statement: PromiseLike<T>, table: string): Promise<T> {\n try {\n return await statement;\n } catch (error) {\n if (!isMissingSchema(error)) throw error;\n throw new Error(\n `Job batches need the \"${table}\" table and the batch_id and progress columns ` +\n `of the jobs table, and the database says one is missing. Add the ` +\n `GemiJobBatch model and the two GemiJob fields from the docs ` +\n `(docs/jobs-and-queues.md#batches) and migrate, or call the driver's ` +\n `createTable().`,\n { cause: error },\n );\n }\n}\n",
|
|
12
|
+
"import type { Application } from \"../../foundation/Application\";\nimport type { Job } from \"./Job\";\nimport type { LockStore } from \"../lock/LockStore\";\nimport type { QueueDriver } from \"./QueueDriver\";\nimport type { WorkflowClass } from \"./workflow/Workflow\";\n\n// Config key: `queue`. Derived from `QueueServiceProvider`.\nexport interface QueueConfig {\n /**\n * The `Job` subclasses this application dispatches, or nothing.\n *\n * ### Why \"or nothing\" is the point\n *\n * A dispatch that names a job the `QueueManager` has never heard of does not\n * fail — `run()` looks the name up in this list, and what is not there is\n * dropped with a line on stderr and nothing else. With the memory driver that\n * happens at once; with one other processes share (the database driver) the\n * job is first left for a replica that has the class, so the line comes only\n * after `unknownJobGrace` — an hour by default, of rows sitting pending with\n * no output at all. `Job.dispatch` has already\n * returned by then, so nothing upstream can be told. The list is therefore a\n * second spelling of `app/jobs`, kept in step by hand, and the cost of the\n * two disagreeing is paid by whatever was supposed to happen after the\n * dispatch.\n *\n * Leaving this out spells it once: the jobs are the classes under `jobsDir`.\n *\n * ### The rule, exactly\n *\n * **Declared wins, and `[]` is declared.** A `jobs` that is present is used\n * verbatim and no directory is read — that is the escape hatch for an app\n * whose jobs live somewhere this cannot walk, for one that deliberately\n * registers a subset, and for a deploy that ships no source. An empty array\n * means an app with no jobs and says so; it does not mean \"find some\".\n *\n * **Absent or `undefined` discovers.** `undefined` counts as absent for the\n * same reason `withDefaults` treats it that way everywhere else: a key spread\n * in from an optional value is an omission, not an instruction.\n */\n jobs?: Array<new () => Job>;\n\n /**\n * Where to look when `jobs` was not declared. Relative to the project root,\n * or absolute.\n *\n * Every `.ts`/`.tsx` file underneath it is imported at boot and every exported\n * class extending `Job` is registered, so this wants to be a directory of job\n * declarations rather than a directory that merely contains some. Moving the\n * jobs is what this field is for; pointing it at `app/` is not.\n */\n jobsDir?: string;\n\n /**\n * The `Workflow` subclasses this application runs, or nothing, by the same\n * rule as `jobs`: declared (including `[]`) is used as given, and absent\n * discovers the classes under `workflowsDir`.\n */\n workflows?: WorkflowClass[];\n\n /** Where to look when `workflows` was not declared. Default `app/workflows`. */\n workflowsDir?: string;\n\n concurrency?: number;\n\n /**\n * Where queued jobs are kept: `\"memory\"`, `\"database\"`, a `QueueDriver`, or\n * a function returning one.\n *\n * `\"memory\"` is the default and keeps them in this process — so **a restart,\n * a deploy or a crash loses every job that is waiting or running**, silently.\n * See `MemoryQueueDriver`.\n *\n * `\"database\"` keeps them in the `gemi_jobs` table of the default database\n * connection, which has to exist. See `DatabaseQueueDriver`.\n *\n * A function is called once per application, when the queue is first\n * resolved, with that application — so it can pick a named connection:\n * `(app) => new DatabaseQueueDriver(app.make(DatabaseManager).connection(\"jobs\"))`.\n * Prefer it to an instance: a config module is imported by more than the\n * server (tests building several applications, build tooling, a `worker`\n * job's thread), and an instance created at import is shared by every\n * application built from that config, or opened by a process that never\n * runs a job.\n */\n driver?:\n | \"memory\"\n | \"database\"\n | QueueDriver\n | ((application: Application) => QueueDriver);\n\n /**\n * How long a claimed job is leased for, in milliseconds, before a driver\n * that shares its storage between processes may hand it to another one. The\n * manager heartbeats every job it is running at a third of this, so it bounds\n * how long a dead process's jobs stay stuck, not how long a job may run. A\n * job that blocks the event loop for longer than this can be run twice.\n */\n visibilityTimeout?: number;\n\n /**\n * How often, in milliseconds, to ask a driver without `subscribe` for work.\n * The memory driver wakes the queue itself and is never polled.\n *\n * It is also how long the queue waits before retrying a `claim` that\n * rejected — for every driver, `subscribe` or not, because the wake that\n * prompted the lost claim is spent and a subscribing driver has no reason to\n * send another. That delay doubles per consecutive failure, up to a minute,\n * so storage that is down is not asked this often for as long as it is down.\n */\n pollInterval?: number;\n\n /**\n * How long, in milliseconds, a job under a name this process has no class\n * for is left for another process before it is dead-lettered. Default one\n * hour.\n *\n * Only a driver other processes share waits: during a blue/green ramp both\n * releases claim from one table, and a job only the new release has is\n * usually one of its replicas' to run, not a dead letter. The database driver\n * does not claim such a job at all until it has been claimable for this\n * long; a driver that cannot filter by name hands it out, and the queue gives\n * it back without spending an attempt. Past the window the name is taken to\n * be gone — a job class that was deleted or renamed — and the job is\n * dead-lettered with its error, as it always was.\n *\n * Longer than a ramp, then, and than a rollback that should find the other\n * release's jobs still waiting. `Infinity` never dead-letters an unknown\n * name. The memory driver ignores this: nothing else can run its jobs, so an\n * unknown name there is dead-lettered at once.\n */\n unknownJobGrace?: number;\n\n /**\n * Where locks are kept: the ones unique jobs, a cron job's\n * `withoutOverlapping` and `onOneServer`, and the `Lock` facade take.\n *\n * `\"auto\"`, the default, keeps them where the driver keeps jobs: with\n * `\"database\"` that is the `gemi_locks` table of the same connection, so\n * they hold across every process sharing it; with `\"memory\"` it is this\n * process. `\"memory\"` and `\"database\"` (the default connection) choose\n * explicitly, and a `LockStore`, or a function returning one, is used as\n * given. Nothing is read or written until one of those features is used.\n */\n locks?:\n | \"auto\"\n | \"memory\"\n | \"database\"\n | LockStore\n | ((application: Application) => LockStore);\n}\n\nexport function defineQueueConfig(config: QueueConfig): QueueConfig {\n return config;\n}\n\nexport function queueConfigDefaults(): Required<QueueConfig> {\n return {\n jobs: [],\n jobsDir: \"app/jobs\",\n workflows: [],\n workflowsDir: \"app/workflows\",\n concurrency: 1,\n driver: \"memory\",\n visibilityTimeout: 5 * 60_000,\n pollInterval: 1000,\n unknownJobGrace: 60 * 60_000,\n locks: \"auto\",\n };\n}\n",
|
|
13
|
+
"import type { EnqueueBatch, EnqueueJob } from \"../QueueDriver\";\nimport {\n type AcquireResult,\n type ItemRecord,\n type ItemRunStatus,\n type StepRecord,\n type UpdateOptions,\n WORKFLOW_TICK_JOB,\n type WorkflowChange,\n WorkflowLeaseLostError,\n sameTick,\n type WorkflowRecord,\n type WorkflowState,\n type WorkflowStore,\n} from \"./WorkflowStore\";\n\n/** What the memory driver lends its workflow store: its own writes, done synchronously. */\nexport type MemoryQueueWrites = {\n enqueue(job: EnqueueJob): void;\n enqueueBatch(batch: EnqueueBatch): void;\n cancelBatch(id: string): void;\n};\n\n/** How long an ended workflow is kept for `find`. */\nconst FINISHED_WORKFLOW_TTL = 24 * 60 * 60_000;\n\n/**\n * Workflows in this process's memory, beside the memory driver's jobs, and\n * lost with them when the process exits. Every change happens synchronously\n * inside the call that makes it, so it is atomic without further care.\n */\nexport class MemoryWorkflowStore implements WorkflowStore {\n private workflows = new Map<string, WorkflowRecord>();\n private steps = new Map<string, Map<string, StepRecord>>();\n /** Item rows of `step.each`, by workflow, then step key. */\n private items = new Map<string, Map<string, ItemRows>>();\n /** Item sources, by id. */\n private sources = new Map<\n string,\n { workflowId: string | null; createdAt: number; rows: Map<number, string> }\n >();\n\n constructor(private readonly queue: MemoryQueueWrites) {}\n\n async create(workflow: { id: string; name: string; args: string }): Promise<void> {\n if (this.workflows.has(workflow.id)) {\n throw new Error(`A workflow with the id ${workflow.id} already exists.`);\n }\n // Nothing else removes an ended workflow, and a long-running process\n // would otherwise keep every one it ever ran.\n void this.prune(FINISHED_WORKFLOW_TTL);\n const now = Date.now();\n this.workflows.set(workflow.id, {\n ...workflow,\n status: \"running\",\n currentStep: null,\n progress: 0,\n result: null,\n error: null,\n wakeAt: null,\n lockedBy: null,\n lockedUntil: null,\n retick: false,\n createdAt: now,\n updatedAt: now,\n });\n this.steps.set(workflow.id, new Map());\n this.tick(workflow.id, 0);\n }\n\n async find(id: string, options: { steps?: boolean } = {}): Promise<WorkflowState | null> {\n const workflow = this.workflows.get(id);\n if (!workflow) return null;\n return {\n workflow: { ...workflow },\n steps: options.steps === false ? [] : this.stepsOf(id),\n };\n }\n\n async acquire(id: string, owner: string, leaseMs: number): Promise<AcquireResult> {\n const workflow = this.workflows.get(id);\n if (!workflow) return { kind: \"missing\" };\n const now = Date.now();\n if (\n workflow.lockedBy !== null &&\n !sameTick(workflow.lockedBy, owner) &&\n (workflow.lockedUntil ?? 0) > now\n ) {\n workflow.retick = true;\n return { kind: \"busy\" };\n }\n workflow.lockedBy = owner;\n workflow.lockedUntil = now + leaseMs;\n workflow.retick = false;\n return { kind: \"acquired\", workflow: { ...workflow }, steps: this.stepsOf(id) };\n }\n\n async renew(id: string, owner: string, leaseMs: number): Promise<boolean> {\n const workflow = this.workflows.get(id);\n if (!workflow || workflow.lockedBy !== owner) return false;\n workflow.lockedUntil = Date.now() + leaseMs;\n return true;\n }\n\n /** The workflow's status, synchronously, for the memory driver's slots. */\n statusOf(id: string): WorkflowRecord[\"status\"] | undefined {\n return this.workflows.get(id)?.status;\n }\n\n async update<T>(\n id: string,\n options: UpdateOptions,\n decide: (snapshot: {\n workflow: WorkflowRecord;\n step: StepRecord | null;\n steps: StepRecord[];\n items: ItemRecord[];\n now: number;\n }) => WorkflowChange<T>,\n ): Promise<T | undefined> {\n const workflow = this.workflows.get(id);\n if (!workflow) return undefined;\n if (options.owner !== undefined && workflow.lockedBy !== options.owner) {\n throw new WorkflowLeaseLostError(id);\n }\n const steps = this.steps.get(id)!;\n const current = options.key === undefined ? undefined : steps.get(options.key);\n const now = Date.now();\n const change = decide({\n workflow: { ...workflow },\n step: current ? { ...current } : null,\n steps: options.allSteps ? this.stepsOf(id) : [],\n items:\n options.items === undefined\n ? []\n : this.itemsOf(id, options.items, [\"running\", \"retrying\"], -1, Infinity),\n now,\n });\n\n if (change.step) {\n const previous = steps.get(change.step.key);\n // A Map keeps insertion order, so a step keeps its first-recorded place.\n steps.set(change.step.key, { ...change.step, createdAt: previous?.createdAt ?? now, updatedAt: now });\n }\n if (change.items) {\n const rows = this.rowsOf(id, change.items.step);\n for (const index of change.items.delete ?? []) {\n rows.all.delete(index);\n rows.open.delete(index);\n }\n for (const item of [...(change.items.insert ?? []), ...(change.items.update ?? [])]) {\n const previous = rows.all.get(item.index);\n rows.all.set(item.index, {\n ...item,\n step: change.items.step,\n createdAt: previous?.createdAt ?? now,\n updatedAt: now,\n });\n if (item.status === \"running\" || item.status === \"retrying\") rows.open.add(item.index);\n else rows.open.delete(item.index);\n }\n }\n if (change.batch) this.queue.enqueueBatch(change.batch);\n for (const batchId of change.cancelBatches ?? []) this.queue.cancelBatch(batchId);\n if (change.workflow) Object.assign(workflow, change.workflow);\n workflow.updatedAt = now;\n if (change.tick) this.tick(id, change.tick.delayMs);\n if (change.unlock) {\n workflow.lockedBy = null;\n workflow.lockedUntil = null;\n if (workflow.retick) {\n workflow.retick = false;\n this.tick(id, 0);\n }\n }\n return change.result;\n }\n\n async prune(olderThanMs: number): Promise<number> {\n const cutoff = Date.now() - olderThanMs;\n let count = 0;\n for (const [id, workflow] of this.workflows) {\n const ended = [\"completed\", \"failed\", \"cancelled\"].includes(workflow.status);\n if (ended && workflow.updatedAt <= cutoff) {\n this.workflows.delete(id);\n this.steps.delete(id);\n this.items.delete(id);\n for (const [sourceId, source] of this.sources) {\n if (source.workflowId === id) this.sources.delete(sourceId);\n }\n count++;\n }\n }\n return count;\n }\n\n async writeSource(\n sourceId: string,\n workflowId: string | null,\n rows: Array<{ index: number; payload: string }>,\n ): Promise<void> {\n let source = this.sources.get(sourceId);\n if (!source) {\n source = { workflowId, createdAt: Date.now(), rows: new Map() };\n this.sources.set(sourceId, source);\n }\n for (const row of rows) {\n if (source.rows.has(row.index)) {\n throw new Error(`Item source \"${sourceId}\" already has an item at index ${row.index}.`);\n }\n source.rows.set(row.index, row.payload);\n }\n }\n\n async readSource(\n sourceId: string,\n from: number,\n to: number,\n ): Promise<Array<{ index: number; payload: string }>> {\n const rows = this.sources.get(sourceId)?.rows;\n const found: Array<{ index: number; payload: string }> = [];\n if (!rows) return found;\n for (let index = Math.max(0, from); index < to; index++) {\n const payload = rows.get(index);\n if (payload !== undefined) found.push({ index, payload });\n }\n return found;\n }\n\n async deleteSource(sourceId: string): Promise<number> {\n const count = this.sources.get(sourceId)?.rows.size ?? 0;\n this.sources.delete(sourceId);\n return count;\n }\n\n async pruneSources(olderThanMs: number): Promise<number> {\n const cutoff = Date.now() - olderThanMs;\n let count = 0;\n for (const [sourceId, source] of this.sources) {\n if (source.workflowId === null && source.createdAt <= cutoff) {\n count += source.rows.size;\n this.sources.delete(sourceId);\n }\n }\n return count;\n }\n\n async listItems(\n workflowId: string,\n step: string,\n options: { statuses: ItemRunStatus[]; after?: number; limit: number },\n ): Promise<ItemRecord[]> {\n return this.itemsOf(workflowId, step, options.statuses, options.after ?? -1, options.limit);\n }\n\n private itemsOf(\n id: string,\n step: string,\n statuses: ItemRunStatus[],\n after: number,\n limit: number,\n ): ItemRecord[] {\n const rows = this.items.get(id)?.get(step);\n if (!rows) return [];\n const open = statuses.every((status) => status === \"running\" || status === \"retrying\");\n const indexes = open ? [...rows.open] : [...rows.all.keys()];\n const found: ItemRecord[] = [];\n for (const index of indexes.sort((a, b) => a - b)) {\n if (index <= after) continue;\n const item = rows.all.get(index)!;\n if (!statuses.includes(item.status)) continue;\n found.push({ ...item });\n if (found.length >= limit) break;\n }\n return found;\n }\n\n private rowsOf(id: string, step: string): ItemRows {\n let steps = this.items.get(id);\n if (!steps) this.items.set(id, (steps = new Map()));\n let rows = steps.get(step);\n if (!rows) steps.set(step, (rows = { all: new Map(), open: new Set() }));\n return rows;\n }\n\n private stepsOf(id: string): StepRecord[] {\n return [...(this.steps.get(id)?.values() ?? [])].map((step) => ({ ...step }));\n }\n\n private tick(id: string, delayMs: number) {\n this.queue.enqueue({\n name: WORKFLOW_TICK_JOB,\n args: JSON.stringify([id]),\n delayMs: Math.max(0, Math.round(delayMs)),\n });\n }\n}\n\n/** One `step.each`'s rows, and which of them are in flight or retrying. */\ntype ItemRows = { all: Map<number, ItemRecord>; open: Set<number> };\n",
|
|
14
|
+
"/**\n * Concurrency slots (#1319): at most `limit` holders per key, handed out in\n * the order the work first asked, with waiting work parked rather than\n * polling.\n *\n * ### The model\n *\n * Each key has a **line**: the holders of its slots and, behind them, the\n * waiters, ordered by when each first asked (`order`, then the holder's id).\n * A request is granted when the holders plus the waiters ahead of it are\n * fewer than the limit, so work that asked later never overtakes work that\n * asked earlier, however often either is re-admitted. A waiter keeps its\n * place until it is granted or ends.\n *\n * A **holder** is a job (by its id) or a workflow (`workflow:<id>`). Several\n * keys are taken in the order given and all are needed; a waiter for a later\n * key keeps the earlier ones, since it is first in their lines anyway.\n *\n * ### Nothing waits in a process\n *\n * A request that cannot be granted parks its job: the claim goes back to\n * waiting, its attempt taken back, due after `recheckMs` — `near` for a\n * waiter among the first `limit` of its line (at least the first one), `far`\n * for the rest — and in\n * the same atomic step as the decision, so a slot freed a moment later is\n * not missed. Whenever a line has free slots (a holder released, a limit\n * was raised, a holder turned out to be gone), the step that sees it makes\n * the first waiters due at once. The rechecks are only a safety net for a\n * process that died between ending its work and handing its slot on.\n *\n * ### Holders that are gone\n *\n * A slot is never leased. A job's is valid while its job is still waiting\n * or claimed (a crashed holder's job is reclaimed and takes its own slot\n * back), and a workflow's while the workflow is neither ended nor paused.\n * Every step on a line first drops the holders that are no longer valid, so\n * a slot whose release was lost frees itself at the line's next step.\n */\nimport type { ClaimedJob } from \"./QueueDriver\";\n\n/** One limit: at most `limit` holders of `key` at once. */\nexport type SlotLimit = { key: string; limit: number };\n\nexport type SlotRequest = {\n /** A job's id, or `workflow:<id>` for a workflow's slots. */\n holder: string;\n /** For a workflow's slots: the workflow, whose status decides whether its slots are still held. */\n workflowId?: string;\n /** The claim that asks: parked when the request is not granted, and woken when its turn comes. */\n job: ClaimedJob;\n /** The limits, taken in this order. */\n slots: SlotLimit[];\n /** When a parked request is claimed again to re-check, in milliseconds. */\n recheckMs: { near: number; far: number };\n};\n\n/** The holder a workflow's slots are kept under. */\nexport function workflowHolder(workflowId: string): string {\n return `workflow:${workflowId}`;\n}\n\n/** The longest key a slot may have: it is a VARCHAR(191) column on MySQL. */\nexport const SLOT_KEY_LIMIT = 191;\n\n/**\n * What a job's or a workflow's `concurrency` returned, checked: one limit or\n * a list, `undefined` or `null` for none. Throws, on the caller's attempt,\n * for a key or a limit the line could not hold.\n */\nexport function slotLimits(value: unknown, owner: string): SlotLimit[] {\n if (value === undefined || value === null) return [];\n const list = (Array.isArray(value) ? value : [value]) as unknown[];\n const seen = new Set<string>();\n const limits: SlotLimit[] = [];\n for (const entry of list) {\n if (entry === undefined || entry === null) continue;\n const { key, limit } = (entry ?? {}) as { key?: unknown; limit?: unknown };\n if (typeof key !== \"string\" || key.length === 0 || key.length > SLOT_KEY_LIMIT) {\n throw new TypeError(\n `${owner}.concurrency returned a key that is not a string of 1 to ` +\n `${SLOT_KEY_LIMIT} characters: ${JSON.stringify(key)}.`,\n );\n }\n if (typeof limit !== \"number\" || !Number.isInteger(limit) || limit < 0) {\n throw new TypeError(\n `${owner}.concurrency returned the limit ${String(limit)} for \"${key}\"; ` +\n `a limit is a whole number, 0 or more.`,\n );\n }\n if (seen.has(key)) {\n throw new TypeError(`${owner}.concurrency returned the key \"${key}\" twice.`);\n }\n seen.add(key);\n limits.push({ key, limit });\n }\n return limits;\n}\n\n/** What `MemorySlots` needs from the memory driver, all synchronous. */\nexport type MemorySlotHost = {\n /** Whether the job is still waiting or claimed. */\n jobAlive(id: string): boolean;\n /** Whether the workflow exists and is neither ended nor paused. */\n workflowAlive(id: string): boolean;\n /** Puts a current claim back to waiting, due after `ms`, its attempt taken back. */\n park(job: ClaimedJob, ms: number): void;\n /** Makes a waiting job due now; `false` when there is no such job. */\n wake(id: string): boolean;\n /** Enqueues a tick for the workflow, and returns its job id. */\n tick(workflowId: string): string;\n};\n\ntype Ticket = {\n holder: string;\n state: \"waiting\" | \"holding\";\n order: number;\n jobId: string;\n workflowId: string | undefined;\n};\n\ntype Line = { key: string; limit: number; tickets: Map<string, Ticket> };\n\n/**\n * The lines in this process's memory, for the memory driver: the same\n * order, parking and waking as the database driver's, and like everything\n * on that driver, per process.\n */\nexport class MemorySlots {\n private lines = new Map<string, Line>();\n private keysOf = new Map<string, Set<string>>();\n private order = 0;\n\n constructor(private readonly host: MemorySlotHost) {}\n\n /** Holders and waiters of `key`, for tests. */\n line(key: string): { holding: string[]; waiting: string[] } {\n const line = this.lines.get(key);\n const tickets = line ? this.sorted(line) : [];\n return {\n holding: tickets.filter((t) => t.state === \"holding\").map((t) => t.holder),\n waiting: tickets.filter((t) => t.state === \"waiting\").map((t) => t.holder),\n };\n }\n\n acquire(request: SlotRequest): boolean {\n let order: number | undefined;\n for (const key of this.keysOf.get(request.holder) ?? []) {\n const ticket = this.lines.get(key)?.tickets.get(request.holder);\n if (ticket && (order === undefined || ticket.order < order)) order = ticket.order;\n }\n order ??= this.order++;\n\n for (const { key, limit } of request.slots) {\n const line = this.lines.get(key) ?? { key, limit, tickets: new Map() };\n this.lines.set(key, line);\n line.limit = limit;\n this.prune(line);\n\n let ticket = line.tickets.get(request.holder);\n if (!ticket) {\n ticket = {\n holder: request.holder,\n state: \"waiting\",\n order,\n jobId: request.job.id,\n workflowId: request.workflowId,\n };\n line.tickets.set(request.holder, ticket);\n const keys = this.keysOf.get(request.holder) ?? new Set();\n keys.add(key);\n this.keysOf.set(request.holder, keys);\n }\n ticket.jobId = request.job.id;\n\n const grantable = () => this.holders(line) + this.ahead(line, ticket) < limit;\n if (ticket.state === \"waiting\" && !grantable()) {\n // Waking drops the dead waiters ahead, which may leave room.\n this.wake(line, request.holder);\n }\n if (ticket.state === \"waiting\" && grantable()) ticket.state = \"holding\";\n if (ticket.state === \"holding\") {\n // A raised limit, or holders that were gone, can leave room behind this one too.\n this.wake(line, request.holder);\n continue;\n }\n\n // The first waiter re-checks soon even under a limit of 0, so a limit\n // raised while nothing else happens on the key is seen.\n const near = this.ahead(line, ticket) < Math.max(1, limit);\n this.host.park(request.job, near ? request.recheckMs.near : request.recheckMs.far);\n return false;\n }\n return true;\n }\n\n release(holder: string): void {\n const keys = this.keysOf.get(holder);\n if (!keys) return;\n this.keysOf.delete(holder);\n for (const key of keys) {\n const line = this.lines.get(key);\n if (!line) continue;\n line.tickets.delete(holder);\n this.prune(line);\n this.wake(line, holder);\n if (line.tickets.size === 0) this.lines.delete(key);\n }\n }\n\n private sorted(line: Line): Ticket[] {\n return [...line.tickets.values()].sort(\n (a, b) => a.order - b.order || (a.holder < b.holder ? -1 : a.holder > b.holder ? 1 : 0),\n );\n }\n\n private holders(line: Line): number {\n let count = 0;\n for (const ticket of line.tickets.values()) if (ticket.state === \"holding\") count++;\n return count;\n }\n\n private ahead(line: Line, ticket: Ticket): number {\n let count = 0;\n for (const other of line.tickets.values()) {\n if (other.state !== \"waiting\" || other === ticket) continue;\n if (\n other.order < ticket.order ||\n (other.order === ticket.order && other.holder < ticket.holder)\n ) {\n count++;\n }\n }\n return count;\n }\n\n private alive(ticket: Ticket): boolean {\n return ticket.workflowId !== undefined\n ? this.host.workflowAlive(ticket.workflowId)\n : this.host.jobAlive(ticket.jobId);\n }\n\n /** Drops holders whose job or workflow is gone. */\n private prune(line: Line) {\n for (const ticket of line.tickets.values()) {\n if (ticket.state === \"holding\" && !this.alive(ticket)) this.forget(line, ticket);\n }\n }\n\n /** Makes the first waiters due, as many as the line has free slots, dropping dead ones. */\n private wake(line: Line, except: string) {\n let free = line.limit - this.holders(line);\n for (const ticket of this.sorted(line)) {\n if (free <= 0) return;\n if (ticket.state !== \"waiting\" || ticket.holder === except) continue;\n if (!this.alive(ticket)) {\n this.forget(line, ticket);\n continue;\n }\n if (!this.host.wake(ticket.jobId)) {\n if (ticket.workflowId === undefined) {\n this.forget(line, ticket);\n continue;\n }\n // A workflow whose parked tick is gone gets a new one.\n ticket.jobId = this.host.tick(ticket.workflowId);\n }\n free--;\n }\n }\n\n private forget(line: Line, ticket: Ticket) {\n line.tickets.delete(ticket.holder);\n const keys = this.keysOf.get(ticket.holder);\n keys?.delete(line.key);\n if (keys?.size === 0) this.keysOf.delete(ticket.holder);\n }\n}\n",
|
|
15
|
+
"import {\n type BatchOutcome,\n type BatchRecord,\n type BatchStatus,\n cancelsBatch,\n clampProgress,\n countOutcome,\n markCancelled,\n newBatchRecord,\n settle,\n statusOf,\n} from \"./batch\";\nimport type {\n ClaimOptions,\n ClaimedJob,\n EnqueueBatch,\n EnqueueJob,\n JobFailure,\n JobRelease,\n QueueDriver,\n} from \"./QueueDriver\";\nimport { MemorySlots, type SlotRequest } from \"./slots\";\nimport { MemoryWorkflowStore } from \"./workflow/MemoryWorkflowStore\";\nimport { WORKFLOW_TICK_JOB, type WorkflowStore } from \"./workflow/WorkflowStore\";\n\ntype Entry = {\n job: ClaimedJob;\n /** Waiting: when it becomes due. Leased: when the lease runs out. */\n until: number;\n leased: boolean;\n /** Tie-break for `until`, so jobs that became claimable together stay FIFO. */\n seq: number;\n /** What a job of a batch last reported with `this.progress()`. */\n progress: number;\n};\n\n/**\n * How long a finished batch is kept for `findBatch`. Nothing else removes\n * one, and a long-running process would otherwise keep every batch it ever\n * ran.\n */\nconst FINISHED_BATCH_TTL = 24 * 60 * 60_000;\n\n/**\n * The default driver: a Map in this process's memory.\n *\n * **Everything in it is lost when the process exits.** A job that is waiting,\n * one waiting out a retry's backoff, and one halfway through `run` all vanish\n * with the process, and no hook fires for any of them — `Job.dispatch()`\n * resolved long ago, so nothing upstream is told. A deploy, a scale-in or a\n * crash is enough. Use it for development, tests, and work that is safe to\n * lose; anything that is not needs a driver backed by storage that outlives\n * the process.\n *\n * It implements the whole claim contract anyway — leases, reclaim on expiry,\n * stale-claim rejection — rather than the subset one process strictly needs.\n * That keeps it a faithful stand-in for a persistent driver in tests, and lets\n * the shared contract suite run against it unchanged. A lease can only lapse\n * here if the event loop was blocked for longer than the visibility timeout,\n * since the manager heartbeats every job it is running.\n *\n * It ignores `registered` in `claim` and hands out every name. Nothing but\n * this process can run its jobs, so a name this process does not know will\n * not be known by anyone, and the manager dead-letters it at once with a line\n * saying so; filtered out, it would wait here unseen until the process exited.\n *\n * Batches are kept in a Map beside the jobs, and a finished one for a day.\n * Everything a batch does happens synchronously inside the call that causes\n * it, so the counters and the callbacks need no further care here.\n *\n * One timer at most, for the next moment something becomes claimable, and it\n * is unref'd: a queue with nothing due does not hold the process open, and\n * neither does one waiting out a backoff — the same way the queue never has.\n */\nexport class MemoryQueueDriver implements QueueDriver {\n private entries = new Map<string, Entry>();\n private batches = new Map<string, BatchRecord>();\n private workflows: MemoryWorkflowStore | undefined;\n /** Concurrency slots (#1319), per process like the jobs. */\n readonly slots = new MemorySlots({\n jobAlive: (id) => this.entries.has(id),\n workflowAlive: (id) => {\n const status = this.workflows?.statusOf(id);\n return (\n status !== undefined &&\n status !== \"completed\" &&\n status !== \"failed\" &&\n status !== \"cancelled\" &&\n status !== \"paused\"\n );\n },\n park: (job, ms) => {\n const entry = this.current(job);\n if (!entry) return;\n entry.job = { ...entry.job, attempt: entry.job.attempt - 1 };\n entry.leased = false;\n entry.until = Date.now() + Math.max(0, ms);\n this.changed();\n },\n wake: (id) => {\n const entry = this.entries.get(id);\n if (!entry) return false;\n if (!entry.leased && entry.until > Date.now()) {\n entry.until = Date.now();\n // Its place among the due jobs is the one it parked with.\n this.changed();\n }\n return true;\n },\n tick: (workflowId) => {\n const id = this.add({ name: WORKFLOW_TICK_JOB, args: JSON.stringify([workflowId]) });\n this.changed();\n return id;\n },\n });\n private listeners = new Set<() => void>();\n private timer: ReturnType<typeof setTimeout> | undefined;\n private timerAt = Infinity;\n private seq = 0;\n\n /** Jobs waiting to be claimed, including ones not yet due. */\n get waiting(): number {\n let count = 0;\n for (const entry of this.entries.values()) if (!entry.leased) count++;\n return count;\n }\n\n /** Jobs currently claimed and not yet reported on. */\n get leased(): number {\n return this.entries.size - this.waiting;\n }\n\n async enqueue(job: EnqueueJob): Promise<string> {\n const id = this.add(job);\n this.changed();\n return id;\n }\n\n private add(\n { name, args, delayMs = 0, id = crypto.randomUUID() }: EnqueueJob,\n batchId?: string,\n ): string {\n const now = Date.now();\n this.entries.set(id, {\n job: {\n id,\n name,\n args,\n attempt: 0,\n createdAt: now,\n ...(batchId === undefined ? {} : { batchId }),\n },\n until: now + Math.max(0, delayMs),\n leased: false,\n seq: this.seq++,\n progress: 0,\n });\n return id;\n }\n\n async enqueueBatch(batch: EnqueueBatch): Promise<void> {\n this.recordBatch(batch);\n }\n\n /** `enqueueBatch`, synchronously, for the workflow store too. */\n private recordBatch(batch: EnqueueBatch) {\n const now = Date.now();\n this.forgetFinishedBatches(now);\n const record = newBatchRecord({ ...batch, total: batch.args.length, now });\n for (const args of batch.args) this.add({ name: batch.job, args }, batch.id);\n // A batch of no jobs is finished as soon as it exists.\n const { record: settled, calls } = settle(record, record, now);\n this.batches.set(batch.id, settled);\n for (const call of calls) this.add(call);\n this.changed();\n }\n\n async findBatch(id: string, options: { progress?: boolean } = {}): Promise<BatchStatus | null> {\n const record = this.batches.get(id);\n if (!record) return null;\n if (options.progress === false || record.pending === 0) return statusOf(record);\n let running = 0;\n for (const entry of this.entries.values()) {\n if (entry.job.batchId === id) running += entry.progress;\n }\n return statusOf(record, running);\n }\n\n async cancelBatch(id: string): Promise<boolean> {\n return this.cancelBatchNow(id);\n }\n\n private cancelBatchNow(id: string): boolean {\n const prev = this.batches.get(id);\n if (!prev || prev.finishedAt !== null || prev.cancelledAt !== null) return false;\n const now = Date.now();\n const next = markCancelled(prev, now, this.cancelWaiting(id));\n this.save(prev, next, now);\n this.changed();\n return true;\n }\n\n /**\n * Workflows (#846), kept in memory beside the jobs and lost with them. The\n * store's writes, ticks and batches included, happen synchronously here.\n */\n workflowStore(): WorkflowStore {\n this.workflows ??= new MemoryWorkflowStore({\n enqueue: (job) => {\n this.add(job);\n this.changed();\n },\n enqueueBatch: (batch) => this.recordBatch(batch),\n cancelBatch: (id) => void this.cancelBatchNow(id),\n });\n return this.workflows;\n }\n\n /**\n * Concurrency slots (#1319), in this process's memory: the same order,\n * parking and waking as the database driver's, and per process, as every\n * job here is.\n */\n async acquireSlots(request: SlotRequest): Promise<boolean> {\n return this.slots.acquire(request);\n }\n\n async releaseSlots(holder: string): Promise<void> {\n this.slots.release(holder);\n }\n\n async reportProgress(job: ClaimedJob, progress: number): Promise<void> {\n const entry = this.current(job);\n if (entry) entry.progress = clampProgress(progress);\n }\n\n async claim(limit: number, options: ClaimOptions): Promise<ClaimedJob[]> {\n const now = Date.now();\n const due = [...this.entries.values()]\n .filter((entry) => entry.until <= now)\n .sort((a, b) => a.until - b.until || a.seq - b.seq)\n .slice(0, Math.max(0, limit));\n\n for (const entry of due) {\n entry.job = { ...entry.job, attempt: entry.job.attempt + 1 };\n entry.leased = true;\n entry.until = now + options.visibilityTimeoutMs;\n }\n if (due.length > 0) this.schedule();\n\n // Copies, so a caller holding one cannot move the record underneath us.\n return due.map((entry) => ({ ...entry.job }));\n }\n\n async complete(job: ClaimedJob): Promise<void> {\n const entry = this.current(job);\n if (!entry) return;\n this.entries.delete(job.id);\n this.count(entry, \"succeeded\");\n this.schedule();\n }\n\n async fail(job: ClaimedJob, failure: JobFailure): Promise<void> {\n const entry = this.current(job);\n if (!entry) return;\n\n // A retry of a job whose batch was cancelled meanwhile would only be\n // ended as cancelled when it was next claimed; ended here instead.\n const batch = entry.job.batchId === undefined ? undefined : this.batches.get(entry.job.batchId);\n const cancelled =\n failure.cancelled === true || (failure.retryInMs !== null && batch?.cancelledAt != null);\n\n if (failure.retryInMs === null || cancelled) {\n this.entries.delete(job.id);\n this.count(entry, cancelled ? \"cancelled\" : \"failed\");\n this.schedule();\n return;\n }\n\n entry.leased = false;\n entry.until = Date.now() + Math.max(0, failure.retryInMs);\n entry.seq = this.seq++;\n entry.progress = 0;\n this.changed();\n }\n\n async release(job: ClaimedJob, release: JobRelease): Promise<void> {\n const entry = this.current(job);\n if (!entry) return;\n\n entry.job = { ...entry.job, attempt: entry.job.attempt - 1 };\n entry.leased = false;\n entry.until = Date.now() + Math.max(0, release.retryInMs);\n entry.seq = this.seq++;\n this.changed();\n }\n\n async heartbeat(jobs: ClaimedJob[], options: ClaimOptions): Promise<void> {\n const until = Date.now() + options.visibilityTimeoutMs;\n for (const job of jobs) {\n const entry = this.current(job);\n if (entry) entry.until = until;\n }\n this.schedule();\n }\n\n /** Counts a job's end against its batch, if it has one. */\n private count(entry: Entry, outcome: BatchOutcome) {\n const batchId = entry.job.batchId;\n if (batchId === undefined) return;\n const prev = this.batches.get(batchId);\n if (!prev) return;\n const now = Date.now();\n let next = countOutcome(prev, outcome, entry.job.id);\n if (cancelsBatch(prev, next)) {\n next = markCancelled(next, now, this.cancelWaiting(batchId));\n }\n this.save(prev, next, now);\n this.changed();\n }\n\n /** Stores the batch's new state and enqueues the callbacks it made due. */\n private save(prev: BatchRecord, next: BatchRecord, now: number) {\n const { record, calls } = settle(prev, next, now);\n this.batches.set(record.id, record);\n for (const call of calls) this.add(call);\n }\n\n /** Drops the batch's waiting jobs, and says how many there were. */\n private cancelWaiting(batchId: string): number {\n let count = 0;\n for (const [id, entry] of this.entries) {\n if (entry.job.batchId === batchId && !entry.leased) {\n this.entries.delete(id);\n count++;\n }\n }\n return count;\n }\n\n private forgetFinishedBatches(now: number) {\n for (const [id, record] of this.batches) {\n if (record.finishedAt !== null && now - record.finishedAt > FINISHED_BATCH_TTL) {\n this.batches.delete(id);\n }\n }\n }\n\n subscribe(wake: () => void): () => void {\n this.listeners.add(wake);\n return () => void this.listeners.delete(wake);\n }\n\n /**\n * The entry for a report, if the report is about the claim that currently\n * holds it. A stale claimer — one whose lease lapsed and was re-issued —\n * gets nothing, so its late `complete` cannot end the newer claim.\n */\n private current(job: ClaimedJob): Entry | undefined {\n const entry = this.entries.get(job.id);\n if (!entry || !entry.leased || entry.job.attempt !== job.attempt) {\n return undefined;\n }\n return entry;\n }\n\n private changed() {\n this.schedule();\n const now = Date.now();\n for (const entry of this.entries.values()) {\n if (entry.until <= now) {\n this.wake();\n return;\n }\n }\n }\n\n private wake() {\n for (const listener of [...this.listeners]) listener();\n }\n\n /** Points the one timer at the next moment something becomes claimable. */\n private schedule() {\n const now = Date.now();\n let next = Infinity;\n for (const entry of this.entries.values()) {\n if (entry.until > now && entry.until < next) next = entry.until;\n }\n if (next === this.timerAt) return;\n\n clearTimeout(this.timer);\n this.timer = undefined;\n this.timerAt = next;\n if (next === Infinity) return;\n\n this.timer = setTimeout(() => {\n this.timer = undefined;\n this.timerAt = Infinity;\n this.changed();\n }, next - now);\n this.timer.unref?.();\n }\n}\n",
|
|
16
|
+
"import { AsyncResource } from \"node:async_hooks\";\nimport { existsSync } from \"node:fs\";\nimport { isMainThread } from \"node:worker_threads\";\n\nimport type { Application } from \"../../foundation/Application\";\nimport { DatabaseManager } from \"../../database/DatabaseManager\";\nimport { kernelContext } from \"../../kernel/context\";\nimport { deferUntilCommit } from \"../../orm/context\";\nimport { isShuttingDown } from \"../../server/shutdown\";\nimport { DatabaseLockStore } from \"../lock/DatabaseLockStore\";\nimport { type HeldLock, LockManager } from \"../lock/LockManager\";\nimport type { LockStore } from \"../lock/LockStore\";\nimport { MemoryLockStore } from \"../lock/MemoryLockStore\";\nimport { DatabaseQueueDriver } from \"./DatabaseQueueDriver\";\nimport { Job } from \"./Job\";\nimport { queueConfigDefaults, type QueueConfig } from \"./config\";\nimport { MemoryQueueDriver } from \"./MemoryQueueDriver\";\nimport type { ClaimOptions, ClaimedJob, EnqueueBatch, QueueDriver } from \"./QueueDriver\";\nimport type { BatchCallbacks, BatchStatus, JobCall } from \"./batch\";\nimport { withDefaults } from \"../../support/withDefaults\";\nimport { backoffFor } from \"./backoff\";\nimport { type SlotLimit, slotLimits } from \"./slots\";\nimport type { WorkflowClass } from \"./workflow/Workflow\";\nimport { WorkflowRuntime } from \"./workflow/WorkflowRuntime\";\n\nexport { backoffFor };\n\n/**\n * The thread a `worker = true` job runs in.\n *\n * The `await` on `dispatchJob` is load-bearing and its absence was a hang.\n * `postMessage` structured-clones its argument and a Promise is not cloneable,\n * so an un-awaited `dispatchJob` posted the pending promise, threw\n * `DataCloneError` inside this handler, and posted nothing at all. `runInWorker`\n * then never settled: `run` below never returned, its concurrency slot was\n * never decremented, and neither the retry path nor `onDeadletter` ever fired —\n * after `concurrency` such jobs the queue sits at its limit forever, with no\n * error anywhere. Any job whose `run` is `async` hit it, which is every job\n * that touches IO; a queued listener hits it unconditionally, because the\n * synthetic job's `run` awaits `handle`.\n *\n * The await earns two more things. A rejecting job now reaches the `catch` and\n * comes back as `{error}`, where the queue's ordinary retry-then-dead-letter\n * path can have it, instead of being lost with the promise. And `destroy()` now\n * runs after the job rather than under it, so the cloned kernel — its database\n * connections included — outlives the work it was cloned for.\n *\n * ### Where the thread finds the application (#1318)\n *\n * The thread boots its own copy of the application. It used to import it from\n * `app/bootstrap.ts` (`dist/server/bootstrap.mjs` in production), a file no\n * template has and no build had emitted since the server moved to `Bun.build`,\n * so the import failed inside the thread and the job hung. Now an app's own\n * bootstrap is used when it exists, and otherwise the thread does what\n * `gemi queue:work` does: `new App({ kernel })` from `app/kernel/Kernel.ts`,\n * with `App` resolved from the application's own gemi, the copy its kernel\n * extends.\n */\nexport function workerEntry(env: Record<string, string | undefined> = process.env): {\n bootstrap: string | undefined;\n kernel: string;\n app: string;\n} {\n const rootDir = env.ROOT_DIR ?? process.cwd();\n const appDir = env.APP_DIR ?? `${rootDir}/app`;\n const bootstrap =\n env.NODE_ENV === \"production\"\n ? `${rootDir}/dist/server/bootstrap.mjs`\n : `${appDir}/bootstrap.ts`;\n let app: string;\n try {\n app = Bun.resolveSync(\"gemi/app\", rootDir);\n } catch {\n // Run from outside a project (a test, a script): this copy's own,\n // through the package's reference to itself.\n app = Bun.resolveSync(\"gemi/app\", __dirname);\n }\n return {\n bootstrap: existsSync(bootstrap) ? bootstrap : undefined,\n kernel: `${appDir}/kernel/Kernel.ts`,\n app,\n };\n}\n\nfunction createWorker() {\n const entry = workerEntry();\n const load = entry.bootstrap\n ? `const { app } = await import(${JSON.stringify(entry.bootstrap)});`\n : `const { App } = await import(${JSON.stringify(entry.app)});\n const { default: Kernel } = await import(${JSON.stringify(entry.kernel)});\n const app = new App({ kernel: Kernel });\n await app.waitForBoot();`;\n\n const file = new File(\n [\n `\n ${load}\n self.onmessage = async (event) => {\n const clone = app.clone()\n let result = null;\n let error = null;\n try {\n result = await clone.dispatchJob(event.data.jobName, event.data.args)\n } catch (err) {\n error = err\n }\n clone.destroy()\n if(error) {\n self.postMessage({error});\n } else {\n self.postMessage({result});\n }\n };\n self.postMessage({ ready: true });\n `,\n ],\n \"worker.ts\",\n );\n const url = URL.createObjectURL(file);\n return new Worker(url);\n}\n\n/**\n * Runs one job in a thread of its own, and ends the thread after it.\n *\n * The thread posts `ready` once it has loaded the application, and only then\n * is it handed the job: a message posted earlier would reach a thread whose\n * top-level `await` has not set `onmessage` yet. A thread that fails to load\n * (a missing kernel, a syntax error in the app) or throws outside the job\n * rejects with that error, so the job fails and retries like any other one.\n * It used to listen for `message` alone, and a thread that never posted left\n * the job unsettled, holding its slot for good (#1318).\n */\nasync function runInWorker(jobName: string, args: string) {\n const worker = createWorker();\n try {\n return await new Promise((resolve, reject) => {\n worker.onmessage = (e) => {\n const data = e.data;\n if (data && \"ready\" in data) {\n worker.postMessage({ jobName, args });\n } else if (\"error\" in data) {\n reject(data.error);\n } else {\n resolve(data.result);\n }\n };\n worker.onerror = (event) => {\n const error = (event as ErrorEvent).error ?? (event as ErrorEvent).message ?? event;\n reject(\n error instanceof Error\n ? error\n : new Error(`The worker thread for ${jobName} failed: ${String(error)}`),\n );\n };\n worker.addEventListener(\"close\", () => {\n reject(new Error(`The worker thread for ${jobName} exited before the job finished.`));\n });\n });\n } finally {\n worker.terminate();\n }\n}\n\n/**\n * The async context every job runs in: the one this module was evaluated in,\n * which is boot, outside any request.\n *\n * The worker loop is long-lived and started lazily, by the first dispatch, and\n * an async function keeps the context it was started in across every `await`.\n * Started from a request, it would run every later job — dispatched by any\n * request at all — inside the first one's `RequestContext`, and with its ORM\n * transaction handle if it had one open: one user's identity leaking into\n * another's work. Captured here, where no request exists, and entered by `start()`, a job\n * sees no request at all; the Application is entered separately, per job.\n */\nconst bootScope = new AsyncResource(\"gemi.queue\");\n\n/**\n * The longest the loop waits between retries while `claim` keeps rejecting.\n *\n * Long enough that a database which is properly down is not asked once a\n * second by every worker process for as long as it stays down, short enough\n * that the queue is claiming again within a minute of it coming back.\n */\nconst maxClaimBackoff = 60_000;\n\ndeclare global {\n /**\n * The queue loop a `gemi dev` server is running over a driver that outlives\n * the process, kept where a `bun --hot` reload cannot lose it. A reload\n * re-evaluates every module and boots a new application, but the previous\n * application's loop is a live closure and keeps claiming — from the same\n * table, with the code it was loaded with. This is how the next\n * application finds it to stop it; see `startClaimingIfServing`.\n *\n * Typed by what is called on it, not as `QueueManager`: after a reload the\n * one held here is an instance of the previous module graph's class.\n */\n var __gemiDevQueue: { stop(): Promise<unknown> } | undefined;\n}\n\n/** What `Job.dispatchBatch` resolves to. */\nexport type DispatchedBatch = {\n /** The batch's id, for `Job.findBatch` and `Job.cancelBatch`. */\n id: string;\n /** How many jobs it was dispatched with. */\n total: number;\n};\n\n/** The options of `Job.dispatchBatch`. */\nexport type JobBatchOptions = {\n /** A label kept with the batch, for finding it in storage and in its status. */\n name?: string;\n /**\n * Whether a dead-lettered job leaves the rest running. Default `false`: the\n * first one cancels the batch.\n */\n allowFailures?: boolean;\n /**\n * Enqueued once every job has ended, when the batch was not cancelled and\n * no job failed (or `allowFailures` is set). Build it with `Job.with(...)`.\n */\n then?: JobCall;\n /** Enqueued at the first failed job, or at `cancelBatch`, whichever is first. */\n catch?: JobCall;\n /** Enqueued once every job has ended, whatever happened. */\n finally?: JobCall;\n};\n\n/** What `drain` could not wait out. */\nexport type DrainResult = {\n /**\n * Jobs still running when the timeout elapsed. They keep running, and keep\n * their leases, until they settle or the process exits; with a driver that\n * outlives the process, an exit leaves them to be reclaimed once their lease\n * runs out. Waiting jobs are not listed — they were never taken, and are\n * wherever the driver keeps them.\n */\n unfinished: ClaimedJob[];\n};\n\nexport class QueueManager {\n static token = \"queue\";\n\n jobs: Record<string, new () => Job> = {};\n\n readonly config: Required<QueueConfig>;\n readonly driver: QueueDriver;\n\n private readonly application: Application | undefined;\n /**\n * Keyed by claim, `id:attempt`, not by job id. A lease that lapses while\n * its job is still running here — heartbeats failing through a database\n * blip, or an event loop blocked past the visibility timeout — lets this\n * same process claim the job again. Both runs are then really running, so\n * both take a slot. Keyed by id alone, the second claim overwrote the first\n * and the first one's `finally` then deleted it: the live run stopped being\n * counted, drained or heartbeated, so its lease lapsed in turn and the job\n * was claimed again into a slot that was never free.\n */\n private readonly inFlight = new Map<\n string,\n { job: ClaimedJob; done: Promise<void> }\n >();\n private state: \"idle\" | \"running\" | \"stopped\" = \"idle\";\n private looping = false;\n private claiming: Promise<unknown> | undefined;\n private woken = false;\n /** Consecutive `claim` rejections; see `sleep`. Cleared by a claim that returns. */\n private claimFailures = 0;\n private resume: (() => void) | undefined;\n private unsubscribe: (() => void) | undefined;\n private heartbeatTimer: ReturnType<typeof setInterval> | undefined;\n /** Unknown names already reported as left for another replica; see `run`. */\n private readonly releasedNames = new Set<string>();\n private lockManager: LockManager | undefined;\n private workflowRuntime: WorkflowRuntime | undefined;\n\n /**\n * `application` is entered around every job, so `app()` inside one resolves\n * to it rather than to whichever application happens to be the static\n * fallback. The provider always passes it; a manager built bare, as the unit\n * tests do, runs jobs with no application entered.\n */\n constructor(\n config: QueueConfig = {},\n options: { application?: Application } = {},\n ) {\n this.config = withDefaults(queueConfigDefaults(), config);\n this.application = options.application;\n this.driver = resolveDriver(this.config.driver, this.application);\n this.useJobs(this.config.jobs);\n if (this.config.workflows.length > 0) this.useWorkflows(this.config.workflows);\n }\n\n /**\n * Replaces the registered set, for the provider to hand over what it found\n * under `app/jobs`.\n *\n * This exists because the two phases disagree about when the answer is\n * knowable. The manager is constructed in `register()`, which is synchronous\n * and must resolve nothing; reading a directory and importing what is in it is\n * neither. So the manager is built from whatever the config slice declared —\n * nothing, when the app left `jobs` out — and the discovered set arrives in\n * `boot()`.\n *\n * The consequence worth knowing: anything that constructs an application and\n * skips phase two sees an empty registry, and every dispatch against an empty\n * registry is dropped — loudly on stderr, but after `Job.dispatch` has already\n * returned, so no caller finds out. On a durable driver not even that is\n * immediate: the job is left for another replica, and the stderr line comes\n * only once `unknownJobGrace` has passed. An app that lists its jobs explicitly is\n * unaffected, because that list is already in place by the end of `register()`.\n */\n useJobs(jobs: Array<new () => Job>) {\n this.config.jobs = jobs;\n\n // Built one at a time rather than by `Object.fromEntries`, which resolves a\n // repeated key by keeping the last and saying nothing.\n //\n // Two classes with one name is the worst failure in this subsystem, and it\n // is worse than the dropped dispatch the rest of this file is about: the\n // registry is keyed by class name, a dispatch carries a class name, so\n // `SendEmail.dispatch(...)` on the one under `app/jobs/auth` would run the\n // body of the one under `app/jobs/billing`. Nothing is dropped and nothing\n // errors — the wrong work happens and reports success.\n //\n // Discovery is what makes it ordinary. A hand-written list forces an import\n // alias in one visible file the moment two names clash; a directory walk\n // does not, and `auth/SendEmail.ts` beside `billing/SendEmail.ts` is a\n // perfectly natural thing to write. So the first claim wins and the second\n // is refused out loud — the same rule `Scheduler.start` applies to a cron\n // name, and the reverse of the silent last-wins this replaces.\n this.jobs = {};\n for (const job of jobs) {\n this.claim(job);\n }\n this.registerTickJob();\n }\n\n /**\n * Replaces the registered workflows, for the provider to hand over what it\n * found under `app/workflows`. With at least one, the internal job their\n * passes run in is registered too. See `Workflow`.\n */\n useWorkflows(workflows: WorkflowClass[]) {\n this.config.workflows = workflows;\n this.workflows.use(workflows);\n this.registerTickJob();\n }\n\n /** The registered workflow classes, as handed over. */\n get registeredWorkflows(): ReadonlyArray<WorkflowClass> {\n return [...this.config.workflows];\n }\n\n /**\n * Workflows (#846) over this queue's driver: what `Workflow.start`,\n * `signal`, `find` and `cancel` call.\n */\n get workflows(): WorkflowRuntime {\n this.workflowRuntime ??= new WorkflowRuntime(this);\n return this.workflowRuntime;\n }\n\n /** @internal The application this queue belongs to, when it was built with one. */\n get boundApplication(): Application | undefined {\n return this.application;\n }\n\n /**\n * The tick job, beside the app's own, once there is a workflow to tick.\n * Not in `registeredJobs`, which reports what the app handed over.\n */\n private registerTickJob() {\n if (!this.workflowRuntime || Object.keys(this.workflowRuntime.workflows).length === 0) return;\n const tick = this.workflowRuntime.tickJob;\n if (this.jobs[tick.name] && this.jobs[tick.name] !== tick) {\n console.error(\n `A queued job is named \"${tick.name}\", which the workflow runtime uses. ` +\n `Workflows will not run until it is renamed.`,\n );\n return;\n }\n this.jobs[tick.name] = tick;\n }\n\n /**\n * Registers one more job beside whatever `useJobs` already took.\n *\n * This exists for the queued-listener adapter, which registers a synthetic\n * job per queued listener from `EventServiceProvider.boot()` — after the\n * queue's own `boot()` has filled the registry. `useJobs` cannot serve that\n * caller: it *replaces* the registry, so a second call would discard every\n * job the app wrote and leave the queue holding listeners alone. Reading\n * `registeredJobs` back, concatenating and calling `useJobs` again avoids\n * that and is still the wrong shape — it re-runs the collision check over\n * jobs that already passed it, so a duplicate the author has already been\n * told about is reported a second time on every boot.\n *\n * Same rule as `useJobs`, deliberately: the first claim on a name wins and\n * the second is refused out loud. And recorded in `config.jobs` either way,\n * so `registeredJobs` keeps reporting everything the manager was handed\n * rather than what it accepted — a refused job is visible to a test there.\n *\n * A new array rather than a `push`, because `useJobs` keeps the caller's\n * array by reference and appending to it would edit the config slice or the\n * discovered list under whoever else is holding it.\n */\n registerJob(job: new () => Job) {\n this.config.jobs = [...this.config.jobs, job];\n this.claim(job);\n }\n\n /**\n * Puts one job in the registry, or refuses it because the name is taken.\n *\n * The rule and the reason are in `useJobs` above; this is only the shape both\n * entry points share, so that a job arriving one at a time cannot be admitted\n * on terms the batch would have refused.\n */\n private claim(job: new () => Job) {\n if (this.jobs[job.name]) {\n console.error(\n `Two queued jobs are named \"${job.name}\" — the first is registered ` +\n `and this one is not, so dispatching either would have run one of ` +\n `them. A class name is the queue's key, so only one job can hold ` +\n `it. Rename one.`,\n );\n return;\n }\n this.jobs[job.name] = job;\n }\n\n /**\n * What the manager was handed, discovered or declared.\n *\n * The registry is keyed by name, and a name is exactly what a dispatch\n * carries, so \"is this job registered?\" is a question with a silent wrong\n * answer — `run()` drops an unknown name long after the caller moved on.\n * This is where a test asks it out loud.\n *\n * It reports what came in, not what the registry accepted, so a name claimed\n * twice appears twice here — deliberately, the same way `Scheduler.jobs`\n * does. A test walking this should see the collision rather than have it\n * tidied away. A copy, so that walk cannot edit the registry underneath it.\n */\n get registeredJobs(): ReadonlyArray<new () => Job> {\n return [...this.config.jobs];\n }\n\n /**\n * Runs a job's `run` here and now, with no queue around it: what a\n * `worker = true` job's thread calls. Throws for a name nothing is\n * registered under, which in a thread means it booted a different build of\n * the application; returning `undefined` there reported success for work\n * that never ran.\n */\n dispatchJob(jobName: string, args: string) {\n const Class = this.jobs[jobName];\n if (!Class) {\n throw new Error(\n `No job is registered under the name \"${jobName}\" in this thread, so it ` +\n `did not run. The thread boots the application from app/kernel/Kernel.ts ` +\n `(or app/bootstrap.ts); check that the job is discovered there.`,\n );\n }\n // Spread, as `run` is called everywhere else (#1318).\n return new Class().run(...(JSON.parse(args) as unknown[]));\n }\n\n /**\n * Queues a job and resolves to its id once the driver has recorded it, then\n * makes sure the worker loop is running — unless `drain` stopped it, in which\n * case the job waits in the driver for whichever process claims next. With\n * the memory driver that is nobody; see `drain`. A durable driver's job also\n * waits there when this process does not claim: it is not a server, or it is\n * one started with `GEMI_QUEUE_CLAIM=off`; see `claimsInThisProcess`.\n *\n * Inside an open ORM transaction the job belongs to the transaction. A\n * driver that can write it on the transaction does (`joinsTransaction`);\n * for any other, it is held and recorded once the transaction commits, and\n * never if it rolls back. Either way no claimer can see the job before the\n * data it was dispatched about exists. A held dispatch resolves at once, to\n * the id the job will be recorded under: the transaction does not commit\n * until its callback returns, so a caller awaiting a promise that waited for\n * the commit would never return.\n */\n push(\n job: new () => Job,\n args: string,\n options: {\n /**\n * Whether a driver that cannot record the job is reported from here.\n * On by default, because the usual caller is a fire-and-forget\n * `Job.dispatch(...)` whose promise nobody reads. A caller with\n * something better to say — `EventManager`, which knows the event and\n * the listener — turns it off and says that instead. A held dispatch is\n * reported here whatever this says, because its promise has already\n * resolved and the caller has nothing left to catch.\n */\n reportFailure?: boolean;\n } = {},\n ): Promise<string> {\n // A unique job takes its key before it is recorded; see `pushUnique`.\n // Computed here so a `uniqueId` that throws does so on the caller's stack.\n const unique = this.uniqueKey(job, args);\n if (unique) return this.pushUnique(job, args, unique, options);\n\n // Asked before anything is written, and in the caller's async context,\n // which is where the transaction is. The held branch is the fallback\n // rather than the rule because it loses the job to a crash between the\n // commit and the enqueue; written on the transaction, the job commits\n // with the rows or not at all.\n const joins = this.driver.joinsTransaction?.() === true;\n if (!joins) {\n // `deferUntilCommit` is the ORM's commit hook, and the same one an\n // `afterCommit` event waits on: a savepoint that rolls back takes its\n // held dispatches with it, and the callback runs outside the\n // transaction, so the enqueue cannot be pulled back into it.\n const id = Bun.randomUUIDv7();\n const held = deferUntilCommit(() =>\n // Awaited, so the transaction's own promise waits for the enqueue and\n // a script that exits after its last transaction does not exit under\n // it. The rejection is swallowed only because `record` has already\n // reported it; rethrown, the drain would report it a second time.\n this.record(job, args, {\n id,\n reportFailure: true,\n committed: true,\n }).then(\n () => {},\n () => {},\n ),\n );\n if (held) return Promise.resolve(id);\n }\n return this.record(job, args, {\n reportFailure: options.reportFailure,\n joins,\n });\n }\n\n /**\n * Queues a batch: every job, the batch and its callbacks in one atomic\n * write. See `Job.dispatchBatch`.\n *\n * Inside an ORM transaction the batch belongs to it, exactly as a single\n * dispatch does in `push`: written on it by a driver that joins, otherwise\n * held and recorded at the commit, resolving at once to the id it will have.\n */\n pushBatch(\n job: new () => Job,\n args: string[],\n options: JobBatchOptions = {},\n ): Promise<DispatchedBatch> {\n const batch = this.buildBatch(job, args, options);\n const dispatched: DispatchedBatch = { id: batch.id, total: args.length };\n\n const joins = this.driver.joinsTransaction?.() === true;\n if (!joins) {\n const held = deferUntilCommit(() =>\n this.recordBatch(batch, { committed: true }).then(\n () => {},\n () => {},\n ),\n );\n if (held) return Promise.resolve(dispatched);\n }\n return this.recordBatch(batch, { joins }).then(() => dispatched);\n }\n\n /**\n * @internal The batch `pushBatch` records, checked: for `pushBatch` and for\n * a workflow's `step.batch`, which records it in a write of its own. Throws\n * on the caller's stack for a driver without batches, a worker job, a\n * unique job and a callback that is not a job call.\n */\n buildBatch(job: new () => Job, args: string[], options: JobBatchOptions = {}): EnqueueBatch {\n if (!this.driver.enqueueBatch) {\n throw new Error(\n `This queue's driver does not support batches. The memory and ` +\n `database drivers do.`,\n );\n }\n const instance = new job();\n if (instance.worker) {\n throw new Error(\n `${job.name} is a worker job, and a worker job cannot be dispatched ` +\n `in a batch: its thread has no way to report progress or reach the ` +\n `batch.`,\n );\n }\n if (job.prototype.uniqueId !== Job.prototype.uniqueId) {\n throw new Error(\n `${job.name} is unique (it defines uniqueId), and a unique job cannot ` +\n `be dispatched in a batch: a duplicate would resolve to a job outside ` +\n `the batch, and the batch would wait for it forever.`,\n );\n }\n\n const callbacks: BatchCallbacks = {};\n for (const key of [\"then\", \"catch\", \"finally\"] as const) {\n const call = options[key];\n if (call === undefined) continue;\n if (typeof call?.name !== \"string\" || !Array.isArray(call.args)) {\n throw new Error(\n `The batch's ${key} callback is not a job call. Build it with ` +\n `SomeJob.with(...args).`,\n );\n }\n callbacks[key] = { name: call.name, args: call.args };\n }\n\n return {\n id: Bun.randomUUIDv7(),\n name: options.name ?? null,\n job: job.name,\n args,\n allowFailures: options.allowFailures === true,\n callbacks,\n };\n }\n\n /** `pushBatch`, once it is known that the batch is recorded now; see `record`. */\n private recordBatch(\n batch: EnqueueBatch,\n options: { joins?: boolean; committed?: boolean },\n ): Promise<void> {\n const written = this.driver.enqueueBatch!(batch);\n this.startIfIdle();\n const wake = () => !this.driver.subscribe && this.state === \"running\" && this.wake();\n const wakeAtCommit = options.joins === true && deferUntilCommit(wake);\n written.then(\n () => wakeAtCommit || wake(),\n (error: unknown) => {\n // Only a held batch is reported here: its caller's promise resolved\n // inside the transaction, so it has nothing left to catch. Every\n // other caller awaits the rejection, as it needs the batch's id.\n if (!options.committed) return;\n console.error(\n `[gemi] The queue driver could not record a batch of ${batch.job}, ` +\n `which was held until its transaction committed. The transaction ` +\n `stays committed; the batch's jobs did not run and will not be ` +\n `retried.`,\n error,\n );\n },\n );\n return written;\n }\n\n /** The batch's status, or `null` for an unknown id. See `Job.findBatch`. */\n async findBatch(id: string): Promise<BatchStatus | null> {\n if (!this.driver.findBatch) {\n throw new Error(`This queue's driver does not support batches.`);\n }\n return this.driver.findBatch(id);\n }\n\n /**\n * Cancels a running batch, and resolves to whether it did. See\n * `Job.cancelBatch`.\n */\n async cancelBatch(id: string): Promise<boolean> {\n if (!this.driver.cancelBatch) {\n throw new Error(`This queue's driver does not support batches.`);\n }\n const cancelled = await this.driver.cancelBatch(id);\n // Cancelling can make `catch` and `finally` due.\n if (cancelled) this.claimSoon();\n return cancelled;\n }\n\n /**\n * The locks unique jobs, cron jobs' `withoutOverlapping` and `onOneServer`,\n * and the `Lock` facade use, over the store the `locks` setting names. Built\n * on first use, so an app that uses none of them never touches the store.\n */\n get locks(): LockManager {\n this.lockManager ??= new LockManager(this.resolveLockStore());\n return this.lockManager;\n }\n\n private resolveLockStore(): LockStore {\n const locks = this.config.locks;\n if (locks === \"auto\") {\n const store = this.driver.lockStore?.();\n if (store) return store;\n if (this.durable) {\n console.warn(\n `[gemi] The queue driver keeps no locks, so unique jobs, ` +\n `withoutOverlapping and onOneServer only hold within this process. ` +\n `Set the queue slice's \\`locks\\` to \"database\" or a LockStore.`,\n );\n }\n return new MemoryLockStore();\n }\n if (locks === \"memory\") return new MemoryLockStore();\n if (locks === \"database\" || typeof locks === \"function\") {\n if (!this.application && (locks === \"database\" || locks.length > 0)) {\n throw new Error(\n `The queue's locks need the application they belong to, and this ` +\n `QueueManager was built without one. Pass { application }.`,\n );\n }\n if (locks === \"database\") {\n return new DatabaseLockStore(this.application!.make(DatabaseManager));\n }\n return locks(this.application!);\n }\n if (typeof locks === \"string\") {\n throw new Error(\n `Unknown queue locks \"${locks}\". The queue slice's locks is \"auto\", ` +\n `\"memory\", \"database\", a LockStore, or a function returning one.`,\n );\n }\n return locks;\n }\n\n /**\n * The lock key a dispatch of a unique job takes, or `undefined` for a job\n * that does not declare `uniqueId` or a dispatch it returned nothing for.\n */\n private uniqueKey(job: new () => Job, args: string) {\n if (job.prototype.uniqueId === Job.prototype.uniqueId) return undefined;\n const instance = new job();\n const id = instance.uniqueId(...(JSON.parse(args) as unknown[]));\n if (id === undefined || id === null || id === \"\") return undefined;\n return { key: uniqueLockName(job.name, id), ttl: Math.max(1, instance.uniqueFor) };\n }\n\n /**\n * Records a unique job if its key is free, and otherwise resolves to the id\n * of the job holding it. The key's lock is owned by the job's id, which is\n * how the job frees it when it ends and how a duplicate finds it.\n *\n * Inside a transaction the whole dispatch waits for the commit, even on a\n * driver that could join the transaction. The key is taken outside it, so\n * written on the transaction the job could roll back and leave its key held\n * for `uniqueFor` with nothing queued under it. A held dispatch resolves to\n * the id the job will have, and is dropped at the commit if a job with the\n * same key is queued by then.\n */\n private pushUnique(\n job: new () => Job,\n args: string,\n unique: { key: string; ttl: number },\n options: { reportFailure?: boolean },\n ): Promise<string> {\n const id = Bun.randomUUIDv7();\n const held = deferUntilCommit(() =>\n this.recordUnique(job, args, unique, id, { report: true, committed: true }).then(\n () => {},\n () => {},\n ),\n );\n if (held) return Promise.resolve(id);\n return this.recordUnique(job, args, unique, id, {\n report: options.reportFailure !== false,\n committed: false,\n });\n }\n\n private recordUnique(\n job: new () => Job,\n args: string,\n unique: { key: string; ttl: number },\n id: string,\n options: { report: boolean; committed: boolean },\n ): Promise<string> {\n const store = this.locks.store;\n const recorded = (async () => {\n // A few rounds, for a key freed between a refused `acquire` and the\n // `holder` read that follows it.\n for (let round = 0; round < 5; round++) {\n if ((await store.acquire(unique.key, id, unique.ttl)) !== null) {\n try {\n return await this.record(job, args, { id, reportFailure: false });\n } catch (error) {\n await store.release(unique.key, id).catch(() => {});\n throw error;\n }\n }\n const holder = await store.holder(unique.key);\n if (holder) return holder.owner;\n }\n throw new Error(\n `The unique key \"${unique.key}\" kept changing hands, so ${job.name} ` +\n `was not queued.`,\n );\n })();\n recorded.catch((error: unknown) => {\n if (!options.report) return;\n console.error(\n `[gemi] The queue could not record the unique job ${job.name}` +\n (options.committed\n ? `, which was held until its transaction committed. The ` +\n `transaction stays committed; the job did not run and will ` +\n `not be retried.`\n : `, so it did not run and will not be retried.`),\n error,\n );\n });\n return recorded;\n }\n\n /**\n * Frees a unique job's key once the job has ended for good: completed or\n * dead-lettered. Released by the job's id, so a key a newer dispatch holds\n * after `uniqueFor` ran out is left alone.\n */\n private async releaseUnique(job: Job, args: unknown[], claimed: ClaimedJob) {\n if (job.uniqueId === Job.prototype.uniqueId) return;\n try {\n const id = job.uniqueId(...args);\n if (id === undefined || id === null || id === \"\") return;\n await this.locks.store.release(uniqueLockName(claimed.name, id), claimed.id);\n } catch (error) {\n console.error(\n `[gemi] Could not free the unique key of ${claimed.name} (${claimed.id}); ` +\n `it frees itself after uniqueFor.`,\n error,\n );\n }\n }\n\n /** `push`, once it is known that the job is recorded now. */\n private record(\n job: new () => Job,\n args: string,\n options: {\n id?: string;\n reportFailure?: boolean;\n /** Written on the caller's open transaction; see `push`. */\n joins?: boolean;\n /** Held until a transaction committed; changes only the error line. */\n committed?: boolean;\n },\n ): Promise<string> {\n const id = this.driver.enqueue({\n name: job.name,\n args,\n ...(options.id === undefined ? {} : { id: options.id }),\n });\n // A driver that outlives the process is shared with every other one, so\n // a script or console command that dispatches would otherwise claim up to\n // `concurrency` of the table's jobs — other replicas' included — and exit\n // under them, costing each an attempt and a lease's wait. There the job\n // waits in the driver for a server or a worker. A manager built by hand,\n // with no application, is its caller's to run and keeps starting.\n this.startIfIdle();\n // A driver without `subscribe` is only polled, so without the wake a job\n // dispatched here would wait up to `pollInterval` in a queue with room.\n // A spurious wake just claims nothing.\n //\n // A job written on the caller's transaction is not claimable until that\n // commits, so its wake waits for the commit too — woken now, the loop\n // would claim nothing and then sleep a whole `pollInterval` past it.\n // Registered here, synchronously, because the commit hook is found\n // through the caller's async context, and this is the one place that is\n // certainly still current.\n const wake = () =>\n !this.driver.subscribe && this.state === \"running\" && this.wake();\n const wakeAtCommit = options.joins === true && deferUntilCommit(wake);\n\n // The rejection is reported here unless the caller says it will do it\n // itself, and whatever the driver is. It used to depend on both, and was\n // lost either way: a polled driver got an empty rejection arm, which marks\n // `id` handled — and `id` is what `push` returns — so a fire-and-forget\n // `SendReceiptJob.dispatch(...)` whose INSERT failed (a failover, a pool\n // timeout, a table not migrated yet) produced no unhandled rejection and\n // no line anywhere, and the job simply never ran. A subscribing driver got\n // no arm at all, so the same failure surfaced as a bare unhandled\n // rejection. A caller that awaits still gets the rejection either way and\n // can still decide what to do about it.\n id.then(\n () => wakeAtCommit || wake(),\n (error: unknown) => {\n if (options.reportFailure === false) return;\n console.error(\n `[gemi] The queue driver could not record ${job.name}` +\n (options.committed\n ? `, which was held until its transaction committed. The ` +\n `transaction stays committed; the job did not run and will ` +\n `not be retried.`\n : `, so it did not run and will not be retried.`),\n error,\n );\n },\n );\n return id;\n }\n\n /**\n * Runs a dead-lettered job again, from attempt 1 with its whole\n * `maxAttempts`, and resolves to whether a dead job was found under `id`.\n * `false` for an id that is waiting, running, finished or unknown: only a\n * dead job is brought back, so this cannot restart one that is running\n * somewhere.\n *\n * The job is claimed the way a dispatch's is. On a server it is run here as\n * soon as there is room; from a console command it waits in the driver for\n * a server or a worker, which with a polling driver means up to\n * `pollInterval`.\n *\n * Refused for a driver without `retryDead`. The memory driver keeps nothing\n * of a dead job, so there is no id it could bring back, and resolving\n * `false` would read as \"no such job\" to someone holding an id they just saw\n * in a log.\n */\n async retryDead(id: string): Promise<boolean> {\n if (!this.driver.retryDead) {\n throw new Error(\n `This queue's driver keeps nothing of a dead-lettered job, so there ` +\n `is nothing to retry. The database driver keeps them.`,\n );\n }\n const found = await this.driver.retryDead(id);\n if (found) this.claimSoon();\n return found;\n }\n\n /**\n * Starts the loop unless `drain` stopped it or this process should leave a\n * shared driver's jobs to a server — the rule `push` explains.\n */\n private startIfIdle() {\n if (this.state === \"idle\" && (!this.durable || this.mayClaimHere())) {\n this.start();\n }\n }\n\n /**\n * For a job the driver has just made claimable: start the loop, or wake a\n * running one that only polls, as `push` does for a dispatch.\n */\n /** @internal */\n claimSoon() {\n this.startIfIdle();\n if (!this.driver.subscribe && this.state === \"running\") this.wake();\n }\n\n /**\n * Starts claiming. Idempotent, and called by the first `push`, so an app\n * does not need to; it is public for a process that should run jobs it\n * never dispatched — ones a driver kept across a restart — and for resuming\n * after `drain`.\n */\n start() {\n if (this.state === \"running\") return;\n this.state = \"running\";\n // Only a development server's loop over a shared driver: a memory queue\n // is only ever fed by its own application, and a hand-built manager or a\n // test's is its caller's to stop.\n if (this.durable && this.application && this.mayClaimHere() && !isProduction()) {\n globalThis.__gemiDevQueue = this;\n }\n this.unsubscribe = this.driver.subscribe?.(() => this.wake());\n // A loop a `drain` has not yet seen off picks the new state up itself;\n // starting a second would claim twice per wake.\n if (this.looping) return this.wake();\n bootScope.runInAsyncScope(() => void this.loop());\n }\n\n /**\n * Stops claiming, waits up to `timeoutMs` for the jobs already running, and\n * reports the ones that did not finish.\n *\n * Nothing is cancelled — a job has no way to be told — so an unfinished job\n * keeps running after this resolves. What happens to it then is the\n * driver's: the memory driver loses it with the process, along with every\n * job still waiting; one that outlives the process lets another claim it\n * once the lease runs out.\n *\n * A later `push` records its job but does not restart the loop. `start()`\n * does.\n */\n async drain(timeoutMs = Infinity): Promise<DrainResult> {\n this.state = \"stopped\";\n if (globalThis.__gemiDevQueue === this) globalThis.__gemiDevQueue = undefined;\n this.unsubscribe?.();\n this.unsubscribe = undefined;\n this.wake();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<void>((resolve) => {\n if (timeoutMs !== Infinity) timer = setTimeout(resolve, timeoutMs);\n });\n // The claim in progress first, because what it returns is run: those jobs\n // are leased to this process already, and handing them back would cost\n // each of them an attempt it never made.\n const settled = (async () => {\n await this.claiming?.catch(() => {});\n await Promise.allSettled([...this.inFlight.values()].map((e) => e.done));\n })();\n await Promise.race([settled, deadline]);\n clearTimeout(timer);\n\n return {\n unfinished: [...this.inFlight.values()].map((e) => ({ ...e.job })),\n };\n }\n\n /** `drain(0)`: stop claiming, and report what is running without waiting. */\n stop(): Promise<DrainResult> {\n return this.drain(0);\n }\n\n /** How many jobs this process is running right now. */\n get running(): number {\n return this.inFlight.size;\n }\n\n /**\n * Claims while there is room, runs what it claims, and otherwise sleeps\n * until something changes: a job finishing frees a slot, or the driver's\n * `subscribe` says there is work. A driver without `subscribe` is polled\n * every `pollInterval` instead. This replaces a one-second timer that\n * spun while the queue was full.\n *\n * `woken` records a wake that arrived while a claim was in flight, when\n * there was nothing yet to resume; without it that job would wait for the\n * next unrelated wake.\n */\n private async loop() {\n this.looping = true;\n try {\n await this.claimWhileRunning();\n } finally {\n this.looping = false;\n }\n }\n\n private async claimWhileRunning() {\n while (this.state === \"running\") {\n // Once the server has been told to stop, a driver that outlives the\n // process gets nothing new taken from it: a job claimed now would likely\n // be cut off by the exit, and cost an attempt and a lease's wait, when\n // another replica can run it instead. The memory driver keeps claiming\n // until the provider's `drain()` stops it, because nobody else can run\n // its jobs — one waiting at the signal, or dispatched by a request\n // still draining, is run here or not at all.\n const room = this.durable && isShuttingDown()\n ? 0\n : this.config.concurrency - this.inFlight.size;\n\n if (room > 0) {\n this.woken = false;\n const claim = this.driver.claim(room, {\n ...this.lease(),\n registered: {\n names: Object.keys(this.jobs),\n graceMs: this.config.unknownJobGrace,\n },\n });\n this.claiming = claim;\n let claimed: ClaimedJob[] = [];\n try {\n claimed = await claim;\n this.claimFailures = 0;\n } catch (error) {\n this.claimFailures++;\n console.error(\n `The queue could not claim jobs from its driver; it will try ` +\n `again in ${this.retryDelay()}ms.`,\n error,\n );\n } finally {\n this.claiming = undefined;\n }\n for (const job of claimed) this.execute(job);\n\n // A full batch may have left more behind; the next pass either claims\n // it or, with no room left, sleeps until a slot frees.\n if (claimed.length === room) continue;\n if (this.woken && this.inFlight.size < this.config.concurrency) {\n continue;\n }\n }\n\n await this.sleep();\n }\n }\n\n /**\n * Waits for the next thing worth waking for: a slot freeing, a `subscribe`\n * driver saying there is work, or the poll timer a driver without\n * `subscribe` gets.\n *\n * A claim that rejected arms a timer whatever the driver does, and that is\n * the whole reason this is not just the `subscribe` test. The wake that\n * prompted the lost claim has already been consumed, so a driver that only\n * speaks up on an enqueue — LISTEN/NOTIFY, say — has nothing left to\n * announce: an idle worker whose one claim died on a connection reset would\n * sit there, with every job already waiting, until some unrelated process\n * enqueued again. On a busy worker an in-flight job's `wake` covers it; an\n * idle one has nothing to be rescued by.\n *\n * The delay doubles per consecutive failure so that storage which is\n * properly down is not asked once a `pollInterval` for as long as it stays\n * down, and the first claim that returns clears the count.\n */\n private sleep() {\n return new Promise<void>((resolve) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const delay = this.claimFailures > 0\n ? this.retryDelay()\n : this.driver.subscribe\n ? undefined\n : this.config.pollInterval;\n if (delay !== undefined) {\n // Unref'd: a polling queue alone should not hold the process open.\n timer = setTimeout(() => this.wake(), delay);\n timer.unref?.();\n }\n this.resume = () => {\n clearTimeout(timer);\n resolve();\n };\n });\n }\n\n /** `pollInterval`, doubled once per consecutive claim failure, capped. */\n private retryDelay() {\n const doublings = Math.min(Math.max(0, this.claimFailures - 1), 30);\n return Math.min(this.config.pollInterval * 2 ** doublings, maxClaimBackoff);\n }\n\n private wake() {\n this.woken = true;\n const resume = this.resume;\n this.resume = undefined;\n resume?.();\n }\n\n /**\n * Whether the driver keeps jobs past this process: anything but memory.\n * Only such a queue can be fed by one process and drained by another.\n */\n get durable() {\n return !(this.driver instanceof MemoryQueueDriver);\n }\n\n /** See `claimsInThisProcess`. A manager built by hand always may. */\n private mayClaimHere() {\n return !this.application || claimsInThisProcess();\n }\n\n private lease(): ClaimOptions {\n return { visibilityTimeoutMs: this.config.visibilityTimeout };\n }\n\n private execute(claimed: ClaimedJob) {\n const key = `${claimed.id}:${claimed.attempt}`;\n const attempt = () => this.run(claimed);\n const done = (\n this.application\n ? kernelContext.run(this.application, attempt)\n : attempt()\n )\n .catch((error) => {\n // Only the driver's own reports reach here. The claim was not ended,\n // so its lease runs out and the job is claimed again.\n console.error(\n `The queue could not record the outcome of ${claimed.name}.`,\n error,\n );\n })\n .finally(() => {\n this.inFlight.delete(key);\n this.wake();\n });\n this.inFlight.set(key, { job: claimed, done });\n this.heartbeat();\n }\n\n /**\n * Keeps every running job's lease alive, at a third of the visibility\n * timeout so one late tick does not lose it. Stops itself once nothing is\n * running, and is unref'd, like the poll.\n */\n private heartbeat() {\n const driver = this.driver;\n if (!driver.heartbeat || this.heartbeatTimer) return;\n this.heartbeatTimer = setInterval(\n () => {\n if (this.inFlight.size === 0) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = undefined;\n return;\n }\n const jobs = [...this.inFlight.values()].map((e) => e.job);\n driver.heartbeat!(jobs, this.lease()).catch((error) => {\n console.error(`The queue could not extend its job leases.`, error);\n });\n },\n Math.max(1, Math.floor(this.config.visibilityTimeout / 3)),\n );\n this.heartbeatTimer.unref?.();\n }\n\n /**\n * One attempt at one claimed job, ending the claim either way.\n *\n * `onSuccess` is inside the `try`, as it always was, so a throw from it is a\n * failed attempt and is retried. `onFail` and `onDeadletter` are not: a\n * throw from either is logged and the claim still ends, where it used to\n * escape the queue with the job's slot still counted as taken.\n */\n private async run(claimed: ClaimedJob) {\n const Job = this.jobs[claimed.name];\n\n if (!Job) {\n // A driver other processes share may have handed this out because it\n // cannot filter by name, and while a blue/green ramp has both releases\n // claiming from one table, a name this replica lacks is usually one only\n // the other release has. So it goes back, without spending an attempt,\n // for a replica that has the class — until `unknownJobGrace` has passed\n // since the dispatch, after which the name is taken to be gone. Measured\n // from `createdAt` because that is all a claim carries; it is the\n // driver's clock against this one, and the skew is seconds against a\n // window of minutes. A driver that does filter only hands out an unknown\n // name once it has waited out the same window, so it normally lands\n // below; with this clock a few seconds behind the driver's, one handed\n // out right at the boundary is released instead, and — its window now\n // restarting from the release — waits one more `unknownJobGrace`. Late,\n // not lost, so no slack is subtracted for it.\n const age = Date.now() - claimed.createdAt;\n if (this.durable && age < this.config.unknownJobGrace) {\n // Once per name: with a driver that cannot filter, every poll can\n // claim the same job again, and a line per poll would bury the one\n // that matters — a replica whose discovery missed a job, say.\n if (!this.releasedNames.has(claimed.name)) {\n this.releasedNames.add(claimed.name);\n console.error(\n `Left a queued \"${claimed.name}\" for another replica: nothing is ` +\n `registered here under that name. It is dead-lettered if no ` +\n `replica has run it within unknownJobGrace ` +\n `(${this.config.unknownJobGrace}ms) of its dispatch.`,\n );\n }\n // Off this replica's own rhythm, and differently each time. It claims\n // again the moment the release lands, finds nothing due, and then\n // polls every `pollInterval`; a delay of exactly one interval made the\n // job due at the instant of that next poll, so the replica that could\n // not run it won the race for it every time. Any fixed fraction has\n // the same flaw for a replica whose polls happen to fall just before\n // the due moment each cycle — it loses every race, for good. Random\n // within one interval, every other replica's next poll has a chance.\n await this.driver.release(claimed, {\n retryInMs: Math.round(\n this.config.pollInterval * (1 + Math.random()),\n ),\n });\n return;\n }\n\n // The one place this is observable. A dispatch carries a name, the\n // registry is keyed by name, and a name nobody registered matches\n // nothing — which is exactly the silence #322 is about, except here it\n // has already happened and the work is gone. Saying so is all that is\n // left to do about it. Dead-lettered, which for the memory driver is the\n // drop it always was and for a durable one leaves a record to find.\n console.error(\n `Dropped a queued job: nothing is registered under the name ` +\n `\"${claimed.name}\". If the class exists, it was not ` +\n `discovered — check that it is under the queue slice's jobsDir ` +\n `(app/jobs by default), or list it in app/config/queue.ts.`,\n );\n await this.driver.fail(claimed, {\n error: `No job is registered under the name \"${claimed.name}\".`,\n retryInMs: null,\n });\n return;\n }\n\n let job: InstanceType<typeof Job>;\n try {\n job = new Job();\n } catch (error) {\n // A constructor or a class field that throws — `private mailer =\n // app(Mailer)` with nothing bound, say. Every other failure in here is\n // reported against the instance, and this one has no instance to report\n // against, which is exactly why it has to be caught here rather than\n // left to the generic path: that path never ends the claim, so the lease\n // lapses, the job is claimed again, and the constructor throws again,\n // once per visibility timeout, forever. The `maxAttempts` guard below\n // would normally stop that, and it cannot — answering \"how many attempts\n // does this job get?\" needs the instance that cannot be built. So it is\n // dead-lettered unrun, like a job whose arguments are not JSON: no\n // attempt of it can ever do anything but this.\n console.error(\n `Dropped a queued ${claimed.name}: it could not be constructed.`,\n error,\n );\n await this.driver.fail(claimed, {\n error: `The job could not be constructed: ${String(error)}`,\n retryInMs: null,\n });\n return;\n }\n\n let args: any[];\n try {\n args = JSON.parse(claimed.args);\n } catch (error) {\n // Not something `Job.dispatch` writes, so a driver changed it. Left\n // alone, the claim would never end and the job would be reclaimed,\n // unparseable, forever.\n console.error(\n `Dropped a queued ${claimed.name}: its arguments are not JSON.`,\n error,\n );\n await this.driver.fail(claimed, {\n error: `The arguments are not JSON: ${String(error)}`,\n retryInMs: null,\n });\n return;\n }\n\n // Claimed past its last attempt: an earlier claim used that attempt up and\n // never reported, which is what a process exiting mid-run looks like from\n // here. Running it again would exceed `maxAttempts`, so it is dead-lettered\n // unrun. `Math.max` keeps a `maxAttempts` below one meaning what it always\n // did — one attempt.\n if (claimed.attempt > Math.max(1, job.maxAttempts)) {\n const error = new Error(\n `${claimed.name} was claimed for attempt ${claimed.attempt} of ` +\n `${job.maxAttempts}: an earlier attempt never finished, most likely ` +\n `because the process running it exited. Dead-lettered without ` +\n `running it again.`,\n );\n hook(`${claimed.name}.onDeadletter`, () =>\n job.onDeadletter(error, ...args),\n );\n await this.driver.fail(claimed, {\n error: error.message,\n retryInMs: null,\n });\n await this.releaseUnique(job, args, claimed);\n return;\n }\n\n job.$claimed = { ...claimed };\n\n // A job of a cancelled batch is ended unrun. Its batch dead-lettered it\n // while it was waiting, unless it had been claimed already: its lease\n // lapsed, say, or it was waiting out a retry's claim.\n if (claimed.batchId !== undefined) {\n const batch = await this.driver.findBatch?.(claimed.batchId, { progress: false });\n if (batch?.cancelledAt != null) {\n await this.driver.fail(claimed, {\n error: `Its batch was cancelled before it ran.`,\n retryInMs: null,\n cancelled: true,\n });\n return;\n }\n const handle = this.batchHandle(claimed);\n job.batch = handle.batch;\n job.$progress = handle.progress;\n }\n\n // Per-key limits (#661), before the job runs. A job over a limit goes\n // back without spending an attempt: it is waiting for capacity, not\n // failing.\n let error: Error | undefined;\n let admitted: { done(): Promise<void> } | undefined;\n try {\n admitted = await this.admit(job, args, claimed);\n } catch (err) {\n // A `concurrency` or `throttle` that threw fails the attempt like `run`\n // would; the job never started.\n error = err as Error;\n }\n if (!admitted && error === undefined) return;\n\n let result: unknown;\n if (admitted) {\n try {\n result = await (job.worker\n ? runInWorker(claimed.name, claimed.args)\n : job.run(...args));\n } catch (err) {\n error = err as Error;\n } finally {\n await admitted.done();\n }\n }\n\n const outcome = job.$outcome;\n // Parked by a workflow's tick to wait for its slots: the driver has put\n // the claim back already.\n if (error === undefined && outcome?.kind === \"parked\") return;\n if (error === undefined && outcome?.kind === \"release\") {\n // `this.release(delay)`: back to waiting, the attempt taken back.\n await this.driver.release(claimed, { retryInMs: Math.max(0, outcome.delayMs) });\n return;\n }\n if (error === undefined && outcome?.kind === \"fail\") error = outcome.error;\n const retry = outcome?.kind === \"fail\" ? outcome.retry : true;\n\n if (error === undefined) {\n try {\n job.onSuccess(result, ...args);\n } catch (err) {\n error = err as Error;\n }\n }\n\n if (error !== undefined) {\n const recorded = String(error?.stack ?? error);\n hook(`${claimed.name}.onFail`, () => job.onFail(error, ...args));\n\n if (!retry || claimed.attempt >= job.maxAttempts) {\n hook(`${claimed.name}.onDeadletter`, () =>\n job.onDeadletter(error, ...args),\n );\n await this.driver.fail(claimed, { error: recorded, retryInMs: null });\n await this.releaseUnique(job, args, claimed);\n } else {\n await this.driver.fail(claimed, {\n error: recorded,\n retryInMs: backoffFor(job.backoff, claimed.attempt),\n });\n }\n return;\n }\n\n await this.driver.complete(claimed);\n await this.releaseUnique(job, args, claimed);\n }\n\n /** What `this.batch` and `this.progress()` reach in a job of a batch. */\n private batchHandle(claimed: ClaimedJob) {\n const id = claimed.batchId!;\n const driver = this.driver;\n return {\n batch: {\n id,\n cancelled: async () =>\n (await driver.findBatch?.(id, { progress: false }))?.cancelledAt != null,\n },\n progress: (value: number) => driver.reportProgress?.(claimed, value) ?? Promise.resolve(),\n };\n }\n\n /**\n * Takes the job's `concurrency` slots and a hit under each of its\n * `throttle` keys, so the limits hold across every process sharing the\n * queue's storage. Resolves to what to undo after the run, or `undefined`\n * when the job was put back to wait for capacity.\n *\n * Slots are the driver's lines (#1319, `slots.ts`): first come first\n * served, and a job without a slot is parked by the driver, holding\n * nothing, until one frees. A driver without them falls back to `limit`\n * slot locks per key in the lock store, leased for the visibility timeout\n * and renewed while the job runs, with a waiter put back to poll.\n * Throttles are fixed windows counted when a job is admitted, whether it\n * then succeeds or not.\n */\n private async admit(\n job: Job,\n args: unknown[],\n claimed: ClaimedJob,\n ): Promise<{ done(): Promise<void> } | undefined> {\n const limits = slotLimits(await job.concurrency(...args), claimed.name);\n const throttles = [job.throttle(...args) ?? []].flat();\n if (limits.length === 0 && throttles.length === 0) return { done: async () => {} };\n\n const driver = this.driver;\n let free = async () => {};\n if (limits.length > 0 && driver.acquireSlots && driver.releaseSlots) {\n const granted = await driver.acquireSlots({\n holder: claimed.id,\n job: claimed,\n slots: limits,\n recheckMs: this.slotRecheck(),\n });\n if (!granted) return undefined;\n free = () => driver.releaseSlots!(claimed.id);\n } else if (limits.length > 0) {\n const held = await this.lockSlots(limits);\n if (!held) {\n await driver.release(claimed, {\n retryInMs: Math.round(this.config.pollInterval * (1 + Math.random())),\n });\n return undefined;\n }\n free = async () => {\n await Promise.all(held.map((slot) => slot.release()));\n };\n }\n\n const locks = this.locks;\n const counted: string[] = [];\n try {\n for (const throttle of throttles) {\n const name = `gemi:throttle:${throttle.key}`;\n const hit = await locks.store.hit(name, throttle.limit, throttle.window);\n if (!hit.allowed) {\n await Promise.all(counted.map((counted) => locks.store.refund(counted)));\n await free();\n await driver.release(claimed, { retryInMs: Math.max(1, hit.resetInMs) });\n return undefined;\n }\n counted.push(name);\n }\n } catch (error) {\n // The slots were taken for a run that is not going to happen.\n await free().catch(() => {});\n throw error;\n }\n\n return {\n done: async () => {\n await free().catch((error) => {\n console.error(`[gemi] Could not free a concurrency slot of ${claimed.name}.`, error);\n });\n },\n };\n }\n\n /**\n * When a job or workflow parked for a slot is claimed again to re-check\n * (see `SlotRequest.recheckMs`): after the visibility timeout for the first\n * waiters of a line, by when a holder whose process died has had its job\n * reclaimed, and hourly for the rest. Neither is how a waiter normally\n * moves up; a freed slot wakes it at once.\n */\n /** @internal */\n slotRecheck() {\n return { near: Math.max(1000, this.config.visibilityTimeout), far: 60 * 60_000 };\n }\n\n /**\n * The fallback for a driver without `acquireSlots`: one of `limit` slot\n * locks per key, all keys or none. No order, and a waiter polls.\n */\n private async lockSlots(limits: SlotLimit[]): Promise<HeldLock[] | undefined> {\n const ttl = this.config.visibilityTimeout;\n const held: HeldLock[] = [];\n for (const { key, limit } of limits) {\n let slot: HeldLock | undefined;\n for (let i = 0; i < limit && !slot; i++) {\n slot =\n (await this.locks.acquire(`gemi:concurrency:${key}:${i}`, { ttl, renew: true })) ??\n undefined;\n }\n if (!slot) {\n await Promise.all(held.map((other) => other.release()));\n return undefined;\n }\n held.push(slot);\n }\n return held;\n }\n}\n\n/** The lock a unique job's key takes, namespaced by the job's name. */\nfunction uniqueLockName(job: string, id: string | number) {\n return `gemi:job:${job}:${String(id)}`;\n}\n\nfunction hook(name: string, fn: () => void) {\n try {\n fn();\n } catch (error) {\n console.error(`${name} threw; the job's claim was ended anyway.`, error);\n }\n}\n\nfunction isProduction() {\n return process.env.NODE_ENV === \"production\";\n}\n\n/**\n * Whether this process should claim from a driver shared with other\n * processes: a `gemi queue:work` worker, or a server's main thread unless\n * `GEMI_QUEUE_CLAIM=off` hands its jobs to workers. `ROOT_DIR` is set only by\n * a starting server or worker, so a console command, a seed\n * or a migration — which boot the same providers — is not one, and neither is\n * a `worker` job's thread, which clones the application and exits after it.\n *\n * A worker claims whatever `GEMI_QUEUE_CLAIM` says, because the variable is\n * for the web process, and a deploy that sets it once for every container\n * would otherwise leave nothing claiming at all.\n */\nexport function claimsInThisProcess() {\n if (!isMainThread) return false;\n if (isQueueWorker()) return true;\n return process.env.ROOT_DIR !== undefined && !claimingTurnedOff();\n}\n\n/**\n * `GEMI_QUEUE_CLAIM=off` (any case): this server dispatches into a shared\n * driver and leaves the claiming to `gemi queue:work` processes. Anything else\n * claims, as before. An environment variable rather than a config field for\n * the reason `GEMI_NO_SCHEDULE` is one: the web and the worker run the same\n * build with the same config, and only the process knows which it is.\n */\nexport function claimingTurnedOff(env: Record<string, string | undefined> = process.env) {\n return (env.GEMI_QUEUE_CLAIM ?? \"\").trim().toLowerCase() === \"off\";\n}\n\n// On `globalThis` under a registry symbol, like the shutdown flag, so the mark\n// the worker entry sets is the one this module reads if two copies of it are\n// loaded. Not an environment variable: a job that spawns a child process\n// would hand it on, and the child, a script, would start claiming.\nconst QUEUE_WORKER = Symbol.for(\"gemi.queue.worker\");\n\n/** Marks this process as a `gemi queue:work` worker; see `claimsInThisProcess`. */\nexport function markQueueWorker(worker = true) {\n (globalThis as { [QUEUE_WORKER]?: boolean })[QUEUE_WORKER] = worker;\n}\n\nexport function isQueueWorker(): boolean {\n return (globalThis as { [QUEUE_WORKER]?: boolean })[QUEUE_WORKER] === true;\n}\n\nfunction resolveDriver(\n driver: Required<QueueConfig>[\"driver\"],\n application: Application | undefined,\n): QueueDriver {\n if (driver === \"memory\") return new MemoryQueueDriver();\n if (driver === \"database\" || typeof driver === \"function\") {\n // Only a manager built by hand has no application. A factory that takes\n // one would otherwise fail on `undefined` with a TypeError that names\n // neither the queue nor what is missing.\n if (!application && (driver === \"database\" || driver.length > 0)) {\n throw new Error(\n `The queue driver needs the application it belongs to, and this ` +\n `QueueManager was built without one. Pass { application }.`,\n );\n }\n if (driver === \"database\") {\n return new DatabaseQueueDriver(application!.make(DatabaseManager));\n }\n return driver(application!);\n }\n if (typeof driver === \"string\") {\n throw new Error(\n `Unknown queue driver \"${driver}\". The queue slice's driver is ` +\n `\"memory\", \"database\", a QueueDriver, or a function returning one.`,\n );\n }\n return driver;\n}\n",
|
|
17
|
+
"import { app } from \"../../foundation/app\";\nimport { type BatchStatus, type JobCall, clampProgress } from \"./batch\";\nimport type { ClaimedJob } from \"./QueueDriver\";\nimport { type DispatchedBatch, type JobBatchOptions, QueueManager } from \"./QueueManager\";\n\n/** `this.batch` inside a job dispatched with `dispatchBatch`. */\nexport type JobBatch = {\n /** The batch's id. */\n id: string;\n /**\n * Whether the batch has been cancelled — by `Job.cancelBatch`, or by a\n * failed job of a batch without `allowFailures`. Running jobs are not\n * stopped; a long one checks this between steps and returns early.\n */\n cancelled(): Promise<boolean>;\n};\n\n/**\n * The arguments `Job.with` takes for a job whose `run` ends with a\n * `BatchStatus` parameter: the ones before it, because the batch appends its\n * status when it enqueues the callback. Any other `run` takes its parameters\n * as they are.\n */\nexport type JobCallArgs<A extends any[]> = A extends [...infer Rest, infer Last]\n ? BatchStatus extends Last\n ? Rest\n : A\n : A;\n\nexport class Job {\n static name = \"unset\";\n worker = false;\n maxAttempts = 3;\n\n /**\n * Milliseconds to wait before each retry. A number is used for every retry;\n * an array gives the delay before the first retry, the second, and so on,\n * repeating its last entry. `0`, the default, retries as soon as a slot is\n * free.\n */\n backoff: number | number[] = 0;\n\n /**\n * Makes the job unique per key, across every process sharing the queue's\n * storage. Return a key from the dispatch arguments, or `undefined` for a\n * dispatch that should not be unique. While a job with the same key is\n * waiting or running, another dispatch is not queued: it resolves to the\n * id of the job already there. The key is freed when that job completes or\n * is dead-lettered, and at the latest after `uniqueFor`.\n *\n * The default returns `undefined`: a job is not unique unless it says so.\n */\n uniqueId(..._args: any[]): string | number | undefined | null {\n return undefined;\n }\n\n /**\n * How long a unique job's key is held at most, in milliseconds, so a job\n * lost with its process does not block its key forever. Default one hour.\n */\n uniqueFor = 60 * 60_000;\n\n /**\n * Rate limits per key, computed from the dispatch arguments: at most\n * `limit` jobs admitted per fixed `window` (milliseconds) under each `key`,\n * across every process sharing the queue's storage. A job over a limit is\n * put back until the window resets, without spending an attempt. Counted\n * when the job is admitted to run, whether it then succeeds or not.\n */\n throttle(..._args: any[]): JobThrottle | JobThrottle[] | undefined | null {\n return undefined;\n }\n\n /**\n * At most `limit` jobs with this `key` running at once, across every process\n * sharing the queue's storage (#1319). Called each time the job is about to\n * run, so it may be `async` and read the limit from config or the database.\n * Return a list for several limits (\"1 per org, 5 overall\"): they are taken\n * in order and all are needed, so list the narrowest first, in the same\n * order everywhere.\n *\n * A job with no free slot waits its turn, first come first served, without\n * spending an attempt and without holding a queue slot or a connection: it\n * is put back and made due again as soon as a slot frees.\n */\n concurrency(\n ..._args: any[]\n ): JobConcurrencyResult | Promise<JobConcurrencyResult> {\n return undefined;\n }\n\n /**\n * Called from `run`: puts the job back to wait `delayMs` once `run`\n * returns, without counting the attempt or calling any hook. For a provider\n * that answered \"slow down\". Not available to `worker` jobs.\n */\n release(delayMs = 0): void {\n this.$outcome = { kind: \"release\", delayMs };\n }\n\n /**\n * Called from `run`: fails this attempt once `run` returns, as a throw\n * would. With `retry: false` it is dead-lettered at once, whatever\n * `maxAttempts` says: for work that must not be repeated, such as a send\n * whose acceptance is uncertain. A throw after `fail(..., { retry: false })`\n * is dead-lettered too. Not available to `worker` jobs.\n */\n fail(error: unknown, options: { retry?: boolean } = {}): void {\n this.$outcome = {\n kind: \"fail\",\n error: error instanceof Error ? error : new Error(String(error)),\n retry: options.retry ?? true,\n };\n }\n\n /**\n * The batch this run belongs to, when the job was dispatched with\n * `dispatchBatch`; `undefined` otherwise. Set by the queue before `run`.\n */\n batch: JobBatch | undefined = undefined;\n\n /**\n * Called from `run` in a job of a batch: how far this job is, from 0 to 1,\n * for the batch's `progress`. A retry starts again from 0, and a job that\n * ends counts as 1 whatever it last said. Outside a batch it does nothing.\n * Each call is a write, so report at steps, not per item of a hot loop.\n */\n async progress(value: number): Promise<void> {\n const clamped = clampProgress(value);\n await this.$progress?.(clamped);\n }\n\n /** @internal Where `progress` writes; set by the queue for a job of a batch. */\n $progress: ((value: number) => Promise<void>) | undefined;\n\n /** @internal The claim this run is, set by the queue before `run`. */\n $claimed: ClaimedJob | undefined;\n\n /** @internal What `release` or `fail` asked for during this run. */\n $outcome:\n | { kind: \"release\"; delayMs: number }\n | { kind: \"fail\"; error: Error; retry: boolean }\n /** The claim was parked to wait for a concurrency slot; nothing is reported on it. */\n | { kind: \"parked\" }\n | undefined;\n\n run(..._args: any[]): Promise<any> | any {}\n\n onFail(_error: Error, ..._args: any[]): void {}\n onSuccess(_result: any, ..._args: any[]): void {}\n onDeadletter(_error: Error, ..._args: any[]): void {}\n\n /**\n * Queues the job and resolves to its id once the driver has recorded it.\n *\n * Not `async`, deliberately: a missing name and arguments JSON cannot carry\n * still throw here, on the caller's stack, as they did when this returned\n * `void`. Only the driver's answer is asynchronous. Ignoring the promise is\n * fine with the memory driver, whose enqueue cannot fail; with a driver\n * that can, an ignored rejection is an unhandled one, so await it.\n */\n static dispatch<T extends Job>(\n this: new () => T,\n ...args: Parameters<T[\"run\"]>\n ): Promise<string> {\n if (this.name === \"unset\") {\n throw new Error(\"Cannot dispatch a job with no name\");\n }\n\n return app(QueueManager).push(this, JSON.stringify(args));\n }\n\n /**\n * Queues one job per argument tuple as a batch, and resolves to the batch's\n * id and size once every job is recorded. The jobs, the batch and its\n * callbacks are recorded in one atomic write: all of them or none.\n *\n * ```ts\n * const { id } = await BuildPageJob.dispatchBatch(\n * pages.map((page) => [page.id, importId] as const),\n * {\n * name: `import:${importId}`,\n * allowFailures: true,\n * then: ImportFinishedJob.with(importId),\n * catch: ImportFailedJob.with(importId),\n * finally: ImportCleanupJob.with(importId),\n * },\n * );\n * ```\n *\n * Callbacks are jobs, enqueued exactly once, by whichever process ends the\n * job that makes them due, with the batch's status appended to their\n * arguments. Each job's own hooks run as usual. A worker job, a unique job\n * and a driver without batches are refused here, on the caller's stack.\n */\n static dispatchBatch<T extends Job>(\n this: new () => T,\n args: ReadonlyArray<Readonly<Parameters<T[\"run\"]>>>,\n options: JobBatchOptions = {},\n ): Promise<DispatchedBatch> {\n if (this.name === \"unset\") {\n throw new Error(\"Cannot dispatch a job with no name\");\n }\n return app(QueueManager).pushBatch(\n this,\n args.map((tuple) => JSON.stringify(tuple)),\n options,\n );\n }\n\n /**\n * A job and its arguments, without dispatching it: a batch's `then`,\n * `catch` or `finally`. When the job runs, the batch's `BatchStatus` is\n * appended to these arguments.\n */\n static with<T extends Job>(\n this: new () => T,\n ...args: JobCallArgs<Parameters<T[\"run\"]>>\n ): JobCall {\n if (this.name === \"unset\") {\n throw new Error(\"Cannot use a job with no name as a callback\");\n }\n // Thrown here, on the caller's stack, rather than when the batch is\n // recorded, for arguments JSON cannot carry.\n JSON.stringify(args);\n return { name: this.name, args };\n }\n\n /** A batch's status, or `null` for an id the queue has no batch under. */\n static findBatch(id: string): Promise<BatchStatus | null> {\n return app(QueueManager).findBatch(id);\n }\n\n /**\n * Cancels a batch that is still running, and resolves to whether it did.\n * Its waiting jobs never run; running ones finish unless they check\n * `this.batch.cancelled()`. `catch` and then `finally` run; `then` does not.\n */\n static cancelBatch(id: string): Promise<boolean> {\n return app(QueueManager).cancelBatch(id);\n }\n}\n\nexport type JobThrottle = {\n /** Shared by every job that counts against the same budget. */\n key: string;\n limit: number;\n /** The window, in milliseconds. */\n window: number;\n};\n\n/**\n * One concurrency limit: at most `limit` holders of `key` at once. `limit`\n * is a whole number; `0` holds every job of the key until it is raised.\n */\nexport type JobConcurrency = { key: string; limit: number };\n\n/** What `concurrency` returns: one limit, several, or none. */\nexport type JobConcurrencyResult = JobConcurrency | readonly JobConcurrency[] | undefined | null;\n",
|
|
18
|
+
"/**\n * The delay before the retry that follows attempt `attempt`: the number\n * itself, or the array's entry for that retry with its last entry repeated.\n */\nexport function backoffFor(backoff: number | number[], attempt: number) {\n const delay = Array.isArray(backoff)\n ? backoff[Math.min(attempt, backoff.length) - 1]\n : backoff;\n return Math.max(0, delay ?? 0);\n}\n",
|
|
19
|
+
"import type { EachProgress } from \"./wire\";\nimport { isShuttingDown } from \"../../../server/shutdown\";\nimport { backoffFor } from \"../backoff\";\nimport { type BatchStatus, clampProgress } from \"../batch\";\nimport type { EnqueueBatch } from \"../QueueDriver\";\nimport type { Job } from \"../Job\";\nimport { type Duration, toMilliseconds } from \"./duration\";\nimport { type ItemSourceInput, type SourceRef, sourceReader, writeSource } from \"./ItemSource\";\nimport {\n type ItemChange,\n type ItemRecord,\n type StepRecord,\n type StepRunStatus,\n WORKFLOW_OUTPUT_LIMIT,\n type WorkflowChange,\n WorkflowLeaseLostError,\n type WorkflowSnapshot,\n type WorkflowStore,\n} from \"./WorkflowStore\";\n\n/** What a `step.run` function is handed. */\nexport type StepContext = {\n /**\n * `<workflow id>:<step key>`: the same on every attempt of this step, and\n * different for every other step. Pass it to a payment provider, say, so\n * that an attempt repeated after a crash is not charged twice.\n */\n idempotencyKey: string;\n /** Which attempt this is, counting from 1. */\n attempt: number;\n /**\n * Aborted when the step's `timeout` passes or the workflow is cancelled.\n * Pass it to `fetch` and friends. The workflow stops waiting for the step\n * at that moment, whether or not the function notices.\n */\n signal: AbortSignal;\n};\n\nexport type StepRunOptions = {\n /** How many attempts the step gets, counting the first. Default 3. */\n attempts?: number;\n /**\n * Milliseconds to wait before each retry: one number for every retry, or\n * one per retry with the last repeated, as `Job.backoff`. Default 0. A\n * retry with a delay suspends the workflow until it is due.\n */\n backoff?: number | number[];\n /** How long one attempt may take before it counts as failed. */\n timeout?: Duration;\n};\n\nexport type StepWaitOptions = {\n /**\n * How long to wait for the signal. Past it, `waitFor` throws a\n * `WaitTimeoutError`. Without it, the workflow waits until it is signalled\n * or cancelled.\n */\n timeout?: Duration;\n};\n\nexport type StepBatchOptions = {\n /** A label kept with the batch. Default `workflow:<id>:<key>`. */\n name?: string;\n /**\n * Whether a failed job leaves the rest running. Default `false`: the first\n * dead-lettered job cancels the batch and `step.batch` throws a\n * `StepFailedError`. With `true`, `step.batch` returns the status, failed\n * jobs and all.\n */\n allowFailures?: boolean;\n};\n\n/** What a `step.each` function is handed for one item. */\nexport type ItemContext = StepContext & {\n /** The item's index in the list, from 0. */\n index: number;\n /** The item key: what `key(input, index)` returned, or the index. */\n key: string;\n /**\n * Ends this item as `skipped`: not an error and not retried. The reason\n * (at most 500 characters) and `data` (at most 1 KB as JSON) are kept with\n * the item and listed in the step's `problems`.\n */\n skip(reason: string, data?: unknown): never;\n /**\n * Puts this item back, to start again after `delayMs`, without using an\n * attempt (a provider answered \"slow down\"). The whole step holds back\n * for as long: no item starts until then.\n */\n release(delayMs: number): never;\n};\n\n/** What a `step.each` function with `chunk` is handed for one chunk of items. */\nexport type ChunkContext = StepContext & {\n /** The chunk's items, in the order of the inputs. */\n items: Array<{ index: number; key: string; idempotencyKey: string }>;\n /**\n * Ends the item at `position` in the chunk as `skipped`, as `ctx.skip`\n * does for one item, while the rest of the chunk succeeds. Does not throw.\n */\n skip(position: number, reason: string, data?: unknown): void;\n /** As `ItemContext.release`, for every item of the chunk. */\n release(delayMs: number): never;\n};\n\n/** A rate limit across processes, counted in the queue's lock store. */\nexport type EachThrottle = {\n /** Shared by everything that counts against the same budget, jobs included. */\n key: string;\n /** How many items may start per window. */\n limit: number;\n /** The window. */\n window: Duration;\n};\n\n/** Where `step.each` takes its items from: a count and a transformer, or a stored source. */\nexport type StepEachInput<I> =\n | {\n /**\n * How many items there are. Stored when the step first runs; a later pass\n * that computes another number goes on with the stored one.\n */\n count: number;\n /**\n * The transformer: produces the input for `index`, from 0 to `count - 1`.\n * Called once per attempt of that item, and never for the whole list at\n * once, so the list does not have to fit in memory. It must give the same\n * input for the same index for as long as the step runs (read it from a\n * table, a file or a snapshot of ids, not from a query whose order moves).\n * A throw counts as a failed attempt of the item.\n */\n item(index: number): I | Promise<I>;\n source?: never;\n }\n | {\n /**\n * A stored list (`step.source`, `ItemSource.write`): its items, in order,\n * read a window at a time.\n */\n source: SourceRef<I>;\n count?: never;\n item?: never;\n };\n\nexport type StepEachOptions<I> = StepEachInput<I> & {\n /**\n * The item's identity, from 1 to 191 characters: the last part of\n * `ctx.idempotencyKey`. Default: the index. gemi does not check that two\n * items have different keys.\n */\n key?(input: I, index: number): string | number;\n /** How many items run at once, in this process. Default 1. */\n concurrency?: number;\n /** How many attempts each item gets, counting the first. Default 3. */\n attempts?: number;\n /**\n * Milliseconds to wait before an item's retry, as `step.run`'s `backoff`.\n * Default 0. A retry that waits does not hold up the items after it.\n */\n backoff?: number | number[];\n /** How long one attempt of an item may take before it counts as failed. */\n timeout?: Duration;\n /**\n * How long one tick works through items before it hands the workflow back\n * to the queue and continues in the next tick. Default 30 seconds.\n */\n tickBudget?: Duration;\n /**\n * Whether the step sets the workflow's `progress` to the share of its\n * items that have ended. Default `true`.\n */\n progress?: boolean;\n /**\n * At most `limit` items start per `window`, across every process sharing\n * the queue's lock store: one hit per item started (retries included). An\n * item over the limit waits without using an attempt, and a wait past the\n * tick hands the workflow back until the window resets. Several limits\n * all apply. A throttle key is shared with jobs' `throttle` of that key.\n */\n throttle?: EachThrottle | EachThrottle[];\n /**\n * Runs `fn` in an ORM transaction on the queue's connection, and records\n * the item's end as the last statement of that transaction: the item's\n * database writes and its being done commit together, or not at all. A\n * crash, a lost lease, a timeout or a cancel rolls both back, and the item\n * runs again. On a workflow store that cannot (the memory driver, SQLite)\n * `fn` runs without one and the item is at least once, as without this\n * option. A throw, `ctx.skip` and `ctx.release` roll back too.\n */\n transaction?: boolean;\n /**\n * Hands `fn` up to `chunk` items at once (an array of inputs, and a\n * `ChunkContext`), so their writes go in one statement or, with\n * `transaction`, one transaction. `concurrency` then counts chunks. A\n * throw fails the attempt of every item in the chunk.\n */\n chunk?: number;\n /**\n * Fails the step (a `StepFailedError` carrying the summary) once more\n * items than this have failed, or, as `{ ratio, after }`, once the share\n * of failed items among those that ended is over `ratio` (0 to 1) and at\n * least `after` items (default 20) have ended. Items in flight are\n * stopped. Default: never; the summary reports the failures.\n */\n maxFailures?: number | { ratio: number; after?: number };\n};\n\n/** An item that failed or was skipped, as `step.each` and `Workflow.items` list it. */\nexport type EachProblem = {\n index: number;\n /** The item key, or `null` when its input could not be produced. */\n key: string | null;\n status: \"failed\" | \"skipped\";\n /** The last error's message, or the reason given to `ctx.skip`. */\n reason: string;\n /** The `data` given to `ctx.skip`. */\n data?: unknown;\n /** Attempts started. */\n attempt: number;\n};\n\nexport type { EachProgress } from \"./wire\";\n\n/** What `step.each` returns once every item has ended. */\nexport type EachSummary = EachProgress & {\n /** The first 100 problems, by index. `Workflow.items` lists them all. */\n problems: EachProblem[];\n /** Whether there are more problems than `problems` holds. */\n moreProblems: boolean;\n};\n\n/** A step that ran out of attempts, a batch that failed, or a `step.each` past `maxFailures`. */\nexport class StepFailedError extends Error {\n constructor(\n /** The step's key. */\n readonly step: string,\n message: string,\n /** The batch's final status, for a `step.batch` that failed. */\n readonly batch?: BatchStatus,\n /** Where the items stood, for a `step.each` that failed. */\n readonly summary?: EachSummary,\n ) {\n super(message);\n this.name = \"StepFailedError\";\n }\n}\n\n/** A `step.waitFor` whose `timeout` passed before the signal arrived. */\nexport class WaitTimeoutError extends Error {\n constructor(readonly step: string) {\n super(`No signal \"${step}\" arrived before its timeout.`);\n this.name = \"WaitTimeoutError\";\n }\n}\n\n/** Why a step's `ctx.signal` was aborted by its `timeout`. */\nexport class StepTimeoutError extends Error {\n constructor(step: string, timeoutMs: number) {\n super(`Step \"${step}\" took longer than its timeout of ${timeoutMs}ms.`);\n this.name = \"StepTimeoutError\";\n }\n}\n\n/** Why a step's `ctx.signal` was aborted by `Workflow.cancel`. */\nexport class WorkflowCancelledError extends Error {\n constructor(id: string) {\n super(`Workflow ${id} was cancelled.`);\n this.name = \"WorkflowCancelledError\";\n }\n}\n\n/**\n * Thrown through the workflow's code when a step cannot finish in this tick\n * (a sleep, a wait, a batch, a retry with a delay), so the tick can end and\n * the workflow resume later. Not exported: code that catches everything\n * should rethrow what it does not know, and the tick treats the workflow as\n * suspended even if this is swallowed.\n */\nexport class WorkflowSuspended extends Error {\n constructor() {\n super(\n \"The workflow is suspended until a step can continue. Rethrow this \" +\n \"error if you catch it.\",\n );\n this.name = \"WorkflowSuspended\";\n }\n}\n\n/** What the runtime gives the steps of one tick. */\nexport type StepTick = {\n workflowId: string;\n /** The tick's hold on the workflow; every write is fenced by it. */\n owner: string;\n store: WorkflowStore;\n /** The steps as they were when the tick took the workflow. */\n steps: StepRecord[];\n /** This tick runs `onCancel`, not `run`. */\n cancelling: boolean;\n findBatch(id: string): Promise<BatchStatus | null>;\n buildBatch(\n job: new () => Job,\n args: ReadonlyArray<ReadonlyArray<unknown>>,\n options: { name: string; allowFailures: boolean },\n ): EnqueueBatch;\n /** Jobs were recorded: wake the queue. */\n scheduled(): void;\n /** How often a running step checks whether the workflow was cancelled. */\n cancelCheckMs: number;\n /** Whether the queue's storage outlives this process. */\n durable?: boolean;\n /** The queue's lock store's fixed windows, for `step.each`'s `throttle`. */\n throttle?: {\n hit(name: string, limit: number, windowMs: number): Promise<{ allowed: boolean; resetInMs: number }>;\n refund(name: string): Promise<void>;\n };\n};\n\n/** Why a tick stopped where it did. */\nexport type Suspension = {\n /**\n * `running`: a `step.each` used up its tick and continues in the next one.\n * `paused`: the workflow was paused, and waits for `resume`.\n */\n status: \"running\" | \"sleeping\" | \"waiting\" | \"paused\";\n /** When a tick is needed to continue; none for a wait on a signal or batch. */\n wakes: number[];\n};\n\nconst DONE = Symbol(\"done\");\nconst PAUSED = Symbol(\"paused\");\n\n/**\n * What `run` receives as its first argument. Every method takes a **key**,\n * unique within the workflow and the same on every pass: a step whose key has\n * a stored result returns it without running again, which is how a workflow\n * resumes where it stopped. Code outside the steps runs again on every pass.\n */\nexport class Step {\n /** The workflow's id. */\n readonly workflowId: string;\n\n private readonly steps: Map<string, StepRecord>;\n private readonly seen = new Set<string>();\n private readonly pending = new Set<Promise<unknown>>();\n /** @internal Why the tick stopped, once a step suspended it. */\n suspension: Suspension | undefined;\n /** @internal The tick lost its hold on the workflow. */\n lost = false;\n /** The workflow was cancelled during this tick. */\n private cancelled = false;\n /** @internal The step the workflow is on, for its status. */\n current: string | null = null;\n\n /** @internal Built by the workflow runtime, once per tick. */\n constructor(private readonly tick: StepTick) {\n this.workflowId = tick.workflowId;\n this.steps = new Map(tick.steps.map((step) => [step.key, step]));\n }\n\n /**\n * Runs `fn` once and stores what it returns, as JSON; on every later pass\n * the stored value is returned without running it again. A throw is retried\n * up to `attempts`, after which the step fails and this throws a\n * `StepFailedError`, which the workflow may catch. The value comes back as\n * JSON makes it, the first time too: a `Date` becomes a string.\n *\n * At least once: a process that dies after `fn` and before its result is\n * stored runs it again. Use `ctx.idempotencyKey` for anything that must not\n * happen twice, or `attempts: 1`.\n */\n run<T>(\n key: string,\n fn: (ctx: StepContext) => T | Promise<T>,\n options: StepRunOptions = {},\n ): Promise<Awaited<T>> {\n return this.track(key, () => this.runStep(key, fn, options)) as Promise<Awaited<T>>;\n }\n\n /** Suspends the workflow for `duration`, without holding a process. */\n sleep(key: string, duration: Duration): Promise<void> {\n const ms = toMilliseconds(duration);\n return this.track(key, () => this.sleepStep(key, ms));\n }\n\n /**\n * Suspends the workflow until `Workflow.signal(id, key, payload)` and\n * returns the payload. A signal that arrives before the workflow gets here\n * is kept, and returned at once.\n */\n waitFor<T = unknown>(key: string, options: StepWaitOptions = {}): Promise<T> {\n const timeout = options.timeout === undefined ? undefined : toMilliseconds(options.timeout);\n return this.track(key, () => this.waitStep(key, timeout)) as Promise<T>;\n }\n\n /**\n * Dispatches `job` once per argument tuple as a batch (`Job.dispatchBatch`)\n * and suspends the workflow until every job has ended; then returns the\n * batch's status. The step is recorded and the batch dispatched in one\n * atomic write, so a crash cannot dispatch it twice.\n */\n batch<J extends Job>(\n key: string,\n job: new () => J,\n args: ReadonlyArray<Readonly<Parameters<J[\"run\"]>>>,\n options: StepBatchOptions = {},\n ): Promise<BatchStatus> {\n return this.track(key, () => this.batchStep(key, job, args, options));\n }\n\n /**\n * Works through a list of `count` items, one item at a time (or\n * `concurrency` at once), and returns a summary once every item has\n * ended. `item(index)` produces each input, so the list is never held in\n * memory, and `fn` handles it.\n *\n * ```ts\n * const summary = await step.each(\"rows\", {\n * count: source.count,\n * item: (index) => readRow(source.id, index),\n * key: (row) => row.sku,\n * concurrency: 4,\n * }, async (row, ctx) => {\n * if (!row.name) ctx.skip(\"no name\");\n * await createProduct(row, ctx.idempotencyKey);\n * });\n * // { total, done, succeeded, skipped, failed, problems, moreProblems }\n * ```\n *\n * The step keeps a cursor and a row for each item that is in flight,\n * waiting for a retry, failed or skipped; an item that succeeded leaves\n * nothing behind. A failed attempt is retried on its own (`attempts`,\n * `backoff`) while the next items go on, and an item out of attempts is\n * recorded as `failed` without failing the step. A tick works for at most\n * `tickBudget`, then the workflow continues in a new tick, so a long list\n * does not hold a queue slot and a deploy loses no more than the items in\n * flight, which run again.\n *\n * At least once, like `step.run`: an item whose process died runs again,\n * as its next attempt. Pass `ctx.idempotencyKey`\n * (`<workflow id>:<step key>:<item key>`) to anything that must not\n * happen twice.\n */\n each<I>(\n key: string,\n options: StepEachOptions<I> & { chunk?: undefined },\n fn: (input: I, ctx: ItemContext) => unknown,\n ): Promise<EachSummary>;\n each<I>(\n key: string,\n options: StepEachOptions<I> & { chunk: number },\n fn: (inputs: I[], ctx: ChunkContext) => unknown,\n ): Promise<EachSummary>;\n each<I>(\n key: string,\n options: StepEachOptions<I>,\n fn: (input: never, ctx: never) => unknown,\n ): Promise<EachSummary> {\n return this.track(key, () => this.eachStep(key, options, fn));\n }\n\n /**\n * Writes the list `fn` returns (an array, or any iterable or async\n * iterable, such as a parser over an uploaded file's stream) to an item\n * source, once, and returns it for `step.each({ source })`. The items are\n * written as they come, so a long list is never held in memory, and kept\n * until the workflow is pruned. A step like `step.run`: a write that fails\n * part way is written again from the start.\n *\n * ```ts\n * const rows = await step.source(\"rows\", async () => parseRows(await Storage.read(file)));\n * const summary = await step.each(\"import\", { source: rows, concurrency: 4 }, importRow);\n * ```\n */\n source<T>(\n key: string,\n fn: () => ItemSourceInput<T> | Promise<ItemSourceInput<T>>,\n options: Pick<StepRunOptions, \"attempts\" | \"backoff\" | \"timeout\"> = {},\n ): Promise<SourceRef<T>> {\n const id = `${this.workflowId}:${key}`;\n return this.run(\n key,\n async () => writeSource(this.tick.store, id, await fn(), this.workflowId),\n options,\n ) as Promise<SourceRef<T>>;\n }\n\n /**\n * Sets the workflow's `progress`, 0 to 1. Not a step: it writes on every\n * pass that reaches it.\n */\n async progress(value: number): Promise<void> {\n const progress = clampProgress(value);\n this.assertRunning();\n const write = this.write(undefined, () => ({ result: undefined, workflow: { progress } }));\n this.remember(write);\n await write;\n }\n\n /** @internal Waits for every step this tick started, however each ended. */\n async settled(): Promise<void> {\n while (this.pending.size > 0) {\n await Promise.allSettled(this.pending);\n }\n }\n\n // ---------------------------------------------------------------------\n\n private track<T>(key: string, body: () => Promise<T>): Promise<T> {\n if (typeof key !== \"string\" || key.length === 0 || key.length > 191) {\n throw new TypeError(\n `A step key is a string of 1 to 191 characters; got ${JSON.stringify(key)}.`,\n );\n }\n if (this.seen.has(key)) {\n throw new Error(\n `Two steps of workflow ${this.workflowId} use the key \"${key}\". Each step ` +\n `needs a key of its own, or the second would return the first one's result.`,\n );\n }\n this.seen.add(key);\n this.assertRunning();\n const promise = body();\n this.remember(promise);\n return promise;\n }\n\n private remember(promise: Promise<unknown>) {\n this.pending.add(promise);\n const forget = () => void this.pending.delete(promise);\n promise.then(forget, forget);\n }\n\n /** Once suspended, nothing else may start in this tick. */\n private assertRunning() {\n if (this.lost) throw new WorkflowLeaseLostError(this.workflowId);\n if (this.suspension) throw new WorkflowSuspended();\n }\n\n private suspend(status: Suspension[\"status\"], wakeAt?: number | null): never {\n if (!this.suspension) this.suspension = { status, wakes: [] };\n if (wakeAt != null) this.suspension.wakes.push(wakeAt);\n throw new WorkflowSuspended();\n }\n\n /**\n * One atomic write, fenced by the tick's hold. A workflow that is being\n * cancelled takes no new work from `run`: the write is skipped and the\n * tick suspended, so `onCancel` runs next. With `start` (a write that\n * starts work), a paused workflow is suspended the same way.\n */\n private async write<T>(\n key: string | undefined,\n decide: (snapshot: WorkflowSnapshot) => WorkflowChange<T>,\n options: { items?: boolean; start?: boolean; joinTransaction?: boolean } = {},\n ): Promise<T> {\n type Wrapped = { value: T } | typeof DONE | typeof PAUSED;\n let outcome: Wrapped | undefined;\n try {\n outcome = await this.tick.store.update<Wrapped>(\n this.tick.workflowId,\n {\n owner: this.tick.owner,\n ...(key === undefined ? {} : { key }),\n ...(options.items && key !== undefined ? { items: key } : {}),\n ...(options.joinTransaction ? { joinTransaction: true } : {}),\n },\n (snapshot) => {\n if (snapshot.workflow.status === \"cancelling\" && !this.tick.cancelling) {\n return { result: DONE };\n }\n if (options.start && snapshot.workflow.status === \"paused\" && !this.tick.cancelling) {\n return { result: PAUSED };\n }\n const change = decide(snapshot);\n return { ...change, result: { value: change.result } };\n },\n );\n } catch (error) {\n if (error instanceof WorkflowLeaseLostError) this.lost = true;\n throw error;\n }\n if (outcome === undefined) {\n this.lost = true;\n throw new WorkflowLeaseLostError(this.tick.workflowId);\n }\n if (outcome === DONE) {\n this.cancelled = true;\n this.suspend(\"waiting\");\n }\n if (outcome === PAUSED) this.suspend(\"paused\");\n return outcome.value;\n }\n\n private record(key: string, step: StepRecord | null, fields: Partial<StepRecord>): StepRecord {\n const record: StepRecord = {\n workflowId: this.tick.workflowId,\n key,\n status: \"running\",\n attempt: 0,\n output: null,\n error: null,\n batchId: null,\n wakeAt: null,\n startedAt: null,\n finishedAt: null,\n createdAt: 0,\n updatedAt: 0,\n ...step,\n ...fields,\n };\n this.steps.set(key, record);\n return record;\n }\n\n private mismatch(key: string, status: StepRunStatus, wanted: string): never {\n throw new Error(\n `Step \"${key}\" of workflow ${this.tick.workflowId} was recorded as a ` +\n `${status} step, and is now used as ${wanted}. A key belongs to one step; ` +\n `rename one of them.`,\n );\n }\n\n private async runStep<T>(\n key: string,\n fn: (ctx: StepContext) => T | Promise<T>,\n options: StepRunOptions,\n ): Promise<T> {\n const attempts = Math.max(1, Math.floor(options.attempts ?? 3));\n const timeoutMs = options.timeout === undefined ? undefined : toMilliseconds(options.timeout);\n const cached = this.steps.get(key);\n if (cached?.status === \"completed\") return decode(cached.output) as T;\n if (cached?.status === \"failed\") throw failure(key, cached);\n if (cached?.status === \"retrying\" && cached.wakeAt !== null && cached.wakeAt > Date.now()) {\n this.current = key;\n this.suspend(\"sleeping\", cached.wakeAt);\n }\n\n for (;;) {\n type Begin =\n | { kind: \"done\"; output: string | null }\n | { kind: \"failed\"; step: StepRecord }\n | { kind: \"wait\"; wakeAt: number }\n | { kind: \"run\"; attempt: number };\n const begin = await this.write<Begin>(key, ({ workflow, step, now }) => {\n if (step?.status === \"completed\") return { result: { kind: \"done\", output: step.output } };\n if (step?.status === \"failed\") return { result: { kind: \"failed\", step } };\n if (step && step.status !== \"running\" && step.status !== \"retrying\") {\n this.mismatch(key, step.status, \"step.run\");\n }\n if (step?.status === \"retrying\" && step.wakeAt !== null && step.wakeAt > now) {\n return { result: { kind: \"wait\", wakeAt: step.wakeAt } };\n }\n const attempt = (step?.attempt ?? 0) + 1;\n if (attempt > attempts) {\n const failed = this.record(key, step, {\n status: \"failed\",\n error:\n `Attempt ${attempt - 1} of ${attempts} never finished, most likely ` +\n `because the process running it exited.` +\n (step?.error ? ` The last error was: ${step.error}` : \"\"),\n finishedAt: now,\n wakeAt: null,\n });\n return { result: { kind: \"failed\", step: failed }, step: failed };\n }\n const running = this.record(key, step, {\n status: \"running\",\n attempt,\n startedAt: now,\n finishedAt: null,\n wakeAt: null,\n });\n return {\n result: { kind: \"run\", attempt },\n step: running,\n // `onCancel` runs while the workflow is `cancelling`, and stays so.\n workflow:\n workflow.status === \"cancelling\"\n ? { currentStep: key }\n : { currentStep: key, status: \"running\" },\n };\n }, { start: true });\n this.current = key;\n if (begin.kind === \"done\") return decode(begin.output) as T;\n if (begin.kind === \"failed\") throw failure(key, begin.step);\n if (begin.kind === \"wait\") this.suspend(\"sleeping\", begin.wakeAt);\n const attempt = begin.attempt;\n\n let value: T | undefined;\n let error: unknown;\n let retry = true;\n try {\n value = await this.execute(key, fn, attempt, timeoutMs);\n } catch (thrown) {\n error = thrown;\n }\n // Cancelled while the step ran: leave it as it is; `onCancel` is next.\n if (this.cancelled) throw new WorkflowSuspended();\n\n let output: string | null = null;\n if (error === undefined) {\n try {\n output = encode(value, `The result of step \"${key}\"`);\n } catch (tooLarge) {\n error = tooLarge;\n retry = false;\n }\n }\n if (error === undefined) {\n await this.write(key, ({ step, now }) => ({\n result: undefined,\n step: this.record(key, step, {\n status: \"completed\",\n output,\n error: null,\n wakeAt: null,\n finishedAt: now,\n }),\n }));\n return decode(output) as T;\n }\n\n const message = describe(error);\n if (retry && attempt < attempts) {\n const delay = backoffFor(options.backoff ?? 0, attempt);\n const wakeAt = await this.write(key, ({ step, now }) => {\n const at = delay > 0 ? now + delay : null;\n return {\n result: at,\n step: this.record(key, step, { status: \"retrying\", error: message, wakeAt: at }),\n };\n });\n if (wakeAt !== null) this.suspend(\"sleeping\", wakeAt);\n continue;\n }\n\n const failed = await this.write(key, ({ step, now }) => {\n const record = this.record(key, step, {\n status: \"failed\",\n error: message,\n wakeAt: null,\n finishedAt: now,\n });\n return { result: record, step: record };\n });\n throw failure(key, failed);\n }\n }\n\n /**\n * One attempt of a `step.run` function, abandoned when its timeout passes\n * or the workflow is cancelled meanwhile.\n */\n private async execute<T>(\n key: string,\n fn: (ctx: StepContext) => T | Promise<T>,\n attempt: number,\n timeoutMs: number | undefined,\n ): Promise<T> {\n const controller = new AbortController();\n const context: StepContext = {\n idempotencyKey: `${this.tick.workflowId}:${key}`,\n attempt,\n signal: controller.signal,\n };\n const work = Promise.resolve().then(() => fn(context));\n let timer: ReturnType<typeof setTimeout> | undefined;\n let poll: ReturnType<typeof setInterval> | undefined;\n const abandoned = new Promise<never>((_, reject) => {\n const abort = (reason: Error) => {\n controller.abort(reason);\n reject(reason);\n };\n if (timeoutMs !== undefined) {\n timer = setTimeout(() => abort(new StepTimeoutError(key, timeoutMs)), timeoutMs);\n }\n if (!this.tick.cancelling) {\n poll = setInterval(() => {\n this.tick.store\n .find(this.tick.workflowId, { steps: false })\n .then((state) => {\n if (state?.workflow.status !== \"cancelling\" || controller.signal.aborted) return;\n this.cancelled = true;\n if (!this.suspension) this.suspension = { status: \"waiting\", wakes: [] };\n abort(new WorkflowCancelledError(this.tick.workflowId));\n })\n .catch(() => {});\n }, this.tick.cancelCheckMs);\n poll.unref?.();\n }\n });\n try {\n return await Promise.race([work, abandoned]);\n } finally {\n clearTimeout(timer);\n clearInterval(poll);\n // An abandoned attempt may still settle; its outcome is nobody's now.\n work.catch(() => {});\n abandoned.catch(() => {});\n }\n }\n\n private async sleepStep(key: string, ms: number): Promise<void> {\n const cached = this.steps.get(key);\n if (cached?.status === \"completed\") return;\n this.current = key;\n if (cached?.status === \"sleeping\" && cached.wakeAt !== null && cached.wakeAt > Date.now()) {\n this.suspend(\"sleeping\", cached.wakeAt);\n }\n const wakeAt = await this.write<number | null>(key, ({ step, now }) => {\n if (step?.status === \"completed\") return { result: null };\n if (step && step.status !== \"sleeping\") this.mismatch(key, step.status, \"step.sleep\");\n const at = step?.wakeAt ?? now + ms;\n if (at <= now) {\n return {\n result: null,\n step: this.record(key, step, {\n status: \"completed\",\n wakeAt: at,\n startedAt: step?.startedAt ?? now,\n finishedAt: now,\n }),\n };\n }\n if (step) return { result: at };\n return {\n result: at,\n step: this.record(key, null, { status: \"sleeping\", wakeAt: at, startedAt: now }),\n workflow: { currentStep: key },\n };\n });\n if (wakeAt !== null) this.suspend(\"sleeping\", wakeAt);\n }\n\n private async waitStep(key: string, timeoutMs: number | undefined): Promise<unknown> {\n const cached = this.steps.get(key);\n if (cached?.status === \"completed\") return decode(cached.output);\n if (cached?.status === \"timed_out\") throw new WaitTimeoutError(key);\n this.current = key;\n if (\n cached?.status === \"waiting\" &&\n (cached.wakeAt === null || cached.wakeAt > Date.now())\n ) {\n this.suspend(\"waiting\", cached.wakeAt);\n }\n type Outcome =\n | { kind: \"value\"; output: string | null }\n | { kind: \"timeout\" }\n | { kind: \"wait\"; wakeAt: number | null };\n const outcome = await this.write<Outcome>(key, ({ step, now }) => {\n if (step?.status === \"completed\") return { result: { kind: \"value\", output: step.output } };\n if (step?.status === \"timed_out\") return { result: { kind: \"timeout\" } };\n if (step?.status === \"signalled\") {\n return {\n result: { kind: \"value\", output: step.output },\n step: this.record(key, step, {\n status: \"completed\",\n wakeAt: null,\n startedAt: step.startedAt ?? now,\n finishedAt: now,\n }),\n };\n }\n if (step && step.status !== \"waiting\") this.mismatch(key, step.status, \"step.waitFor\");\n if (step) {\n if (step.wakeAt !== null && step.wakeAt <= now) {\n return {\n result: { kind: \"timeout\" },\n step: this.record(key, step, { status: \"timed_out\", finishedAt: now }),\n };\n }\n return { result: { kind: \"wait\", wakeAt: step.wakeAt } };\n }\n const wakeAt = timeoutMs === undefined ? null : now + timeoutMs;\n return {\n result: { kind: \"wait\", wakeAt },\n step: this.record(key, null, { status: \"waiting\", wakeAt, startedAt: now }),\n workflow: { currentStep: key },\n };\n });\n if (outcome.kind === \"value\") return decode(outcome.output);\n if (outcome.kind === \"timeout\") throw new WaitTimeoutError(key);\n this.suspend(\"waiting\", outcome.wakeAt);\n }\n\n private async eachStep<I>(\n key: string,\n options: StepEachOptions<I>,\n fn: (input: never, ctx: never) => unknown,\n ): Promise<EachSummary> {\n const source = options.source;\n const count = source ? source.count : options.count;\n if (!source && typeof options.item !== \"function\") {\n throw new TypeError(`step.each \"${key}\" needs either { count, item } or { source }.`);\n }\n if (!Number.isSafeInteger(count) || count < 0 || count > MAX_EACH_COUNT) {\n throw new TypeError(\n `step.each \"${key}\" needs a count that is a whole number from 0 to ` +\n `${MAX_EACH_COUNT}; got ${String(count)}.`,\n );\n }\n const concurrency = Math.max(1, Math.floor(options.concurrency ?? 1));\n const attempts = Math.max(1, Math.floor(options.attempts ?? 3));\n const timeoutMs = options.timeout === undefined ? undefined : toMilliseconds(options.timeout);\n const budgetMs =\n options.tickBudget === undefined ? EACH_TICK_BUDGET_MS : toMilliseconds(options.tickBudget);\n const setsProgress = options.progress !== false;\n const chunked = options.chunk !== undefined;\n const chunk = chunked ? Math.max(1, Math.floor(options.chunk!)) : 1;\n const throttles = [options.throttle ?? []].flat().map((throttle) => ({\n name: `gemi:throttle:${throttle.key}`,\n limit: Math.max(0, Math.floor(throttle.limit)),\n windowMs: toMilliseconds(throttle.window),\n }));\n const exceeded = failurePolicy(options.maxFailures);\n const store = this.tick.store;\n const inTransaction =\n options.transaction === true && store.transaction\n ? <T>(body: () => Promise<T>) => store.transaction!(body)\n : undefined;\n if (options.transaction === true && !inTransaction) warnNoTransaction();\n const produce: (index: number) => I | Promise<I> = source\n ? sourceReader(store, source, Math.max(EACH_SOURCE_WINDOW, concurrency * chunk * 4))\n : options.item!;\n if (!store.listItems) {\n throw new Error(\n `This queue's workflow store does not support step.each. The memory and ` +\n `database drivers do.`,\n );\n }\n if (throttles.length > 0 && !this.tick.throttle) {\n throw new Error(`step.each \"${key}\" has a throttle, and this queue has no lock store.`);\n }\n\n const cached = this.steps.get(key);\n if (cached?.status === \"completed\") return summaryOf(cached.output);\n if (cached?.status === \"failed\") throw failure(key, cached);\n if (cached && cached.status !== \"iterating\") this.mismatch(key, cached.status, \"step.each\");\n this.current = key;\n if (this.tick.durable === false) warnNotDurable();\n\n type Begin =\n | { kind: \"done\"; output: string | null }\n | { kind: \"failed\"; step: StepRecord }\n | { kind: \"go\"; state: EachState; open: ItemRecord[] };\n const begin = await this.write<Begin>(\n key,\n ({ workflow, step, items, now }) => {\n if (step?.status === \"completed\") return { result: { kind: \"done\", output: step.output } };\n if (step?.status === \"failed\") return { result: { kind: \"failed\", step } };\n if (step && step.status !== \"iterating\") this.mismatch(key, step.status, \"step.each\");\n const state = step ? stateOf(step.output) : newState(count);\n return {\n result: { kind: \"go\", state, open: items },\n ...(step\n ? {}\n : {\n step: this.record(key, null, {\n status: \"iterating\",\n output: stateOutput(state),\n startedAt: now,\n }),\n }),\n workflow:\n workflow.status === \"cancelling\"\n ? { currentStep: key }\n : { currentStep: key, status: \"running\" },\n };\n },\n { items: true, start: true },\n );\n if (begin.kind === \"done\") return summaryOf(begin.output);\n if (begin.kind === \"failed\") throw failure(key, begin.step);\n let state = begin.state;\n if (state.count !== count) warnCountChanged(this.workflowId, key, state.count, count);\n const total = state.count;\n const open = new Map(begin.open.map((item) => [item.index, item]));\n\n /**\n * How an attempt that finished ended, waiting to be recorded; `recorded`\n * when its own transaction already did.\n */\n type Ending = {\n index: number;\n row: ItemRecord | null;\n counter: \"succeeded\" | \"skipped\" | \"failed\" | null;\n recorded?: boolean;\n };\n const ended: Ending[] = [];\n /** Units (an item, or a chunk) in flight, by their first index. */\n const inFlight = new Map<number, Promise<void>>();\n /** Every item in flight, to the first index of its unit. */\n const inFlightIndex = new Map<number, number>();\n const deadline = Date.now() + budgetMs;\n /** No item starts before this: a throttle's window, or `ctx.release`. */\n let holdUntil = 0;\n let pausing = false;\n /** Why the step fails, once `maxFailures` is passed. */\n let failing: string | null = null;\n // One controller for every item of this tick: aborted when the workflow\n // is cancelled, when the step fails, and when the tick stops early.\n const tickAbort = new AbortController();\n const poll = setInterval(() => {\n store\n .find(this.workflowId, { steps: false })\n .then((found) => {\n if (found?.workflow.status === \"paused\") pausing = true;\n if (found?.workflow.status !== \"cancelling\" || tickAbort.signal.aborted) return;\n this.cancelled = true;\n if (!this.suspension) this.suspension = { status: \"waiting\", wakes: [] };\n tickAbort.abort(new WorkflowCancelledError(this.workflowId));\n })\n .catch(() => {});\n }, this.tick.cancelCheckMs);\n poll.unref?.();\n failing = exceeded(state);\n\n /** The counters after `endings`, from what is stored. */\n const advance = (stored: EachState, endings: Ending[]) => {\n const next: EachState = { ...stored };\n for (const ending of endings) if (ending.counter) next[ending.counter]++;\n return next;\n };\n const progressChange = (next: EachState) => {\n const done = next.succeeded + next.skipped + next.failed;\n return setsProgress\n ? { workflow: { progress: total === 0 ? 1 : clampProgress(done / total) } }\n : {};\n };\n /** Takes in a newer state (writes may resolve out of order: every field only grows). */\n const adopt = (next: EachState) => {\n state = {\n count: state.count,\n next: Math.max(state.next, next.next),\n succeeded: Math.max(state.succeeded, next.succeeded),\n skipped: Math.max(state.skipped, next.skipped),\n failed: Math.max(state.failed, next.failed),\n };\n if (!failing) failing = exceeded(state);\n if (failing && !tickAbort.signal.aborted) tickAbort.abort(new WorkflowSuspended());\n };\n\n const attempt = async (rows: ItemRecord[]): Promise<void> => {\n const keys: Array<string | null> = rows.map(() => null);\n const skips = new Map<number, { reason: string; data: unknown }>();\n const controller = new AbortController();\n const onAbort = () => controller.abort(tickAbort.signal.reason);\n tickAbort.signal.addEventListener(\"abort\", onAbort, { once: true });\n let timer: ReturnType<typeof setTimeout> | undefined;\n const label = rows.length === 1 ? `${key}[${rows[0]!.index}]` : `${key}[${rows[0]!.index}..${rows.at(-1)!.index}]`;\n const abandoned = new Promise<never>((_, reject) => {\n controller.signal.addEventListener(\"abort\", () => reject(controller.signal.reason), {\n once: true,\n });\n if (timeoutMs !== undefined) {\n timer = setTimeout(\n () => controller.abort(new StepTimeoutError(label, timeoutMs)),\n timeoutMs,\n );\n }\n });\n const release = (delayMs: number): never => {\n throw new ItemReleased(Math.max(0, Math.floor(Number(delayMs) || 0)));\n };\n /** Each item's end, once `fn` returned. */\n const successes = (now: number): Ending[] =>\n rows.map((row, position) => {\n const skipped = skips.get(position);\n if (!skipped) return { index: row.index, row: null, counter: \"succeeded\" };\n return {\n index: row.index,\n row: skippedRow(row, keys[position]!, skipped.reason, skipped.data, now),\n counter: \"skipped\",\n };\n });\n let recorded: Ending[] | null = null;\n const work = (async () => {\n const inputs = await Promise.all(rows.map((row) => produce(row.index)));\n rows.forEach((row, position) => {\n keys[position] = itemKeyOf(options.key ? options.key(inputs[position]!, row.index) : row.index);\n });\n const idempotencyKey = (position: number) => `${this.workflowId}:${key}:${keys[position]}`;\n const attemptNo = Math.max(...rows.map((row) => row.attempt));\n const call = async () => {\n if (chunked) {\n const context: ChunkContext = {\n idempotencyKey: idempotencyKey(0),\n attempt: attemptNo,\n signal: controller.signal,\n items: rows.map((row, position) => ({\n index: row.index,\n key: keys[position]!,\n idempotencyKey: idempotencyKey(position),\n })),\n skip: (position, reason, data) => {\n if (!Number.isInteger(position) || position < 0 || position >= rows.length) {\n throw new RangeError(`ctx.skip: no item at position ${position} of this chunk.`);\n }\n skips.set(position, { reason: String(reason), data });\n },\n release,\n };\n await (fn as (inputs: I[], ctx: ChunkContext) => unknown)(inputs, context);\n } else {\n const context: ItemContext = {\n idempotencyKey: idempotencyKey(0),\n attempt: attemptNo,\n signal: controller.signal,\n index: rows[0]!.index,\n key: keys[0]!,\n skip: (reason: string, data?: unknown): never => {\n throw new ItemSkipped(reason, data);\n },\n release,\n };\n await (fn as (input: I, ctx: ItemContext) => unknown)(inputs[0]!, context);\n }\n };\n if (!inTransaction) return call();\n await inTransaction(async () => {\n await call();\n // Abandoned meanwhile (a timeout, a cancel): roll back.\n if (controller.signal.aborted) throw controller.signal.reason;\n const endings = successes(Date.now());\n const next = await this.write(\n key,\n ({ step }) => {\n const change: Required<ItemChange> = { step: key, insert: [], update: [], delete: [] };\n for (const ending of endings) {\n if (ending.row === null) change.delete.push(ending.index);\n else change.update.push(ending.row);\n }\n const after = advance(step ? stateOf(step.output) : state, endings);\n return {\n result: after,\n step: this.record(key, step, { status: \"iterating\", output: stateOutput(after) }),\n items: change,\n ...progressChange(after),\n };\n },\n { joinTransaction: true },\n );\n recorded = endings.map((ending) => ({ ...ending, recorded: true }));\n adopt(next);\n });\n })();\n let error: unknown;\n let failed = false;\n try {\n await Promise.race([work, abandoned]);\n } catch (thrown) {\n failed = true;\n error = thrown;\n } finally {\n clearTimeout(timer);\n tickAbort.signal.removeEventListener(\"abort\", onAbort);\n work.catch(() => {});\n abandoned.catch(() => {});\n }\n // Recorded in its own transaction: only the bookkeeping is left.\n if (recorded) {\n ended.push(...(recorded as Ending[]));\n return;\n }\n // Cancelled, stopped or lost meanwhile: the items stay as they are.\n if (tickAbort.signal.aborted || this.cancelled || this.lost) return;\n const now = Date.now();\n if (!failed) {\n ended.push(...successes(now));\n return;\n }\n if (error instanceof ItemSkipped) {\n ended.push({\n index: rows[0]!.index,\n row: skippedRow(rows[0]!, keys[0], error.reason, error.data, now),\n counter: \"skipped\",\n });\n return;\n }\n if (error instanceof ItemReleased) {\n holdUntil = Math.max(holdUntil, now + error.delayMs);\n rows.forEach((row, position) => {\n ended.push({\n index: row.index,\n row: {\n ...row,\n key: keys[position],\n status: \"retrying\",\n // Not an attempt: the next one has this one's number again.\n attempt: Math.max(0, row.attempt - 1),\n wakeAt: now + error.delayMs,\n },\n counter: null,\n });\n });\n return;\n }\n const message = clip(describe(error), 2000);\n rows.forEach((row, position) => {\n if (row.attempt < attempts) {\n const delay = backoffFor(options.backoff ?? 0, row.attempt);\n ended.push({\n index: row.index,\n row: { ...row, key: keys[position], status: \"retrying\", error: message, wakeAt: now + delay },\n counter: null,\n });\n return;\n }\n ended.push({\n index: row.index,\n row: { ...row, key: keys[position], status: \"failed\", error: message, wakeAt: null, finishedAt: now },\n counter: \"failed\",\n });\n });\n };\n\n /**\n * Counts one hit per item against every throttle, for up to `wanted`\n * items, and resolves to how many may start. The first refused hit holds\n * the step until its window resets.\n */\n const admit = async (wanted: number): Promise<number> => {\n if (throttles.length === 0 || wanted === 0) return wanted;\n const limiter = this.tick.throttle!;\n for (let admitted = 0; admitted < wanted; admitted++) {\n const counted: string[] = [];\n for (const throttle of throttles) {\n const hit = await limiter.hit(throttle.name, throttle.limit, throttle.windowMs);\n if (!hit.allowed) {\n await Promise.all(counted.map((name) => limiter.refund(name)));\n holdUntil = Math.max(holdUntil, Date.now() + Math.max(1, hit.resetInMs));\n return admitted;\n }\n counted.push(throttle.name);\n }\n }\n return wanted;\n };\n const refund = async (count: number) => {\n if (throttles.length === 0) return;\n for (let i = 0; i < count; i++) {\n for (const throttle of throttles) await this.tick.throttle!.refund(throttle.name);\n }\n };\n\n try {\n for (;;) {\n const now = Date.now();\n const stopping =\n now >= deadline || isShuttingDown() || this.cancelled || pausing || failing !== null;\n // What to start: items left by a tick that died, retries that are\n // due, then new items, up to `concurrency` units (items, or chunks)\n // in flight; and never more than a window of open items, so a run of\n // retries cannot grow the rows without bound.\n let rerun: ItemRecord[] = [];\n let fresh = 0;\n if (!stopping && now >= holdUntil) {\n const free = (concurrency - inFlight.size) * chunk;\n // An attempt that ended here and is not recorded yet is not a rerun.\n const ending = new Set(ended.map((end) => end.index));\n for (const row of [...open.values()].sort((a, b) => a.index - b.index)) {\n if (rerun.length >= free) break;\n if (inFlightIndex.has(row.index) || ending.has(row.index)) continue;\n if (row.status === \"running\" || (row.wakeAt ?? 0) <= now) rerun.push(row);\n }\n const window = concurrency * chunk + EACH_RETRY_WINDOW - open.size;\n fresh = Math.max(0, Math.min(free - rerun.length, total - state.next, window));\n const admitted = await admit(rerun.length + fresh);\n if (admitted < rerun.length) {\n rerun = rerun.slice(0, admitted);\n fresh = 0;\n } else {\n fresh = admitted - rerun.length;\n }\n }\n\n if (ended.length > 0 || rerun.length > 0 || fresh > 0) {\n const endings = ended.splice(0, ended.length);\n const unrecorded = endings.filter((ending) => !ending.recorded);\n const wanted = rerun.length + fresh;\n const committed = await this.write(key, ({ workflow, step, now: at }) => {\n const next = advance(step ? stateOf(step.output) : state, unrecorded);\n const change: Required<ItemChange> = { step: key, insert: [], update: [], delete: [] };\n const started: ItemRecord[] = [];\n const closed: ItemRecord[] = [];\n for (const ending of unrecorded) {\n if (ending.row === null) change.delete.push(ending.index);\n else change.update.push(ending.row);\n }\n // Paused since: record what ended, start nothing.\n const paused = workflow.status === \"paused\" && !this.tick.cancelling;\n for (const row of paused ? [] : rerun) {\n if (row.attempt + 1 > attempts) {\n const dead: ItemRecord = {\n ...row,\n status: \"failed\",\n error: clip(\n `Attempt ${row.attempt} of ${attempts} never finished, most likely ` +\n `because the process running it exited.` +\n (row.error ? ` The last error was: ${row.error}` : \"\"),\n 2000,\n ),\n wakeAt: null,\n finishedAt: at,\n };\n next.failed++;\n change.update.push(dead);\n closed.push(dead);\n continue;\n }\n const running: ItemRecord = {\n ...row,\n status: \"running\",\n attempt: row.attempt + 1,\n wakeAt: null,\n startedAt: at,\n };\n change.update.push(running);\n started.push(running);\n }\n const starting = paused ? 0 : fresh;\n const reruns = started.length;\n for (let i = 0; i < starting; i++) {\n const running = newItem(this.workflowId, key, next.next + i, at);\n change.insert.push(running);\n started.push(running);\n }\n next.next += starting;\n return {\n result: { next, started, closed, reruns, paused },\n step: this.record(key, step, { status: \"iterating\", output: stateOutput(next) }),\n items: change,\n ...progressChange(next),\n };\n });\n adopt(committed.next);\n if (committed.paused) pausing = true;\n await refund(wanted - committed.started.length);\n for (const ending of endings) {\n if (ending.row?.status === \"retrying\") open.set(ending.index, ending.row);\n else open.delete(ending.index);\n }\n for (const row of committed.closed) open.delete(row.index);\n for (const row of committed.started) open.set(row.index, row);\n // Reruns and new items in chunks of their own: a chunk is a run of\n // new items, or of retries.\n const units = [\n ...chunksOf(committed.started.slice(0, committed.reruns), chunk),\n ...chunksOf(committed.started.slice(committed.reruns), chunk),\n ];\n for (const unit of units) {\n const first = unit[0]!.index;\n for (const row of unit) inFlightIndex.set(row.index, first);\n inFlight.set(\n first,\n attempt(unit).finally(() => {\n inFlight.delete(first);\n for (const row of unit) inFlightIndex.delete(row.index);\n }),\n );\n }\n }\n\n if (inFlight.size > 0) {\n await Promise.race(inFlight.values());\n continue;\n }\n if (ended.length > 0) continue;\n if (this.cancelled) throw new WorkflowSuspended();\n if (failing) break;\n if (state.next >= total && open.size === 0) break;\n if (pausing) this.suspend(\"paused\");\n if (stopping) this.suspend(\"running\", Date.now());\n // When something can start next: now (the slots went to items that\n // turned out to be out of attempts), when a retry is due, or when a\n // throttle or `ctx.release` lets go, whichever is latest.\n const nowAgain = Date.now();\n let earliest = Infinity;\n if (state.next < total && open.size < concurrency * chunk + EACH_RETRY_WINDOW) earliest = nowAgain;\n for (const row of open.values()) {\n if (row.status === \"running\") earliest = nowAgain;\n else if (row.status === \"retrying\") earliest = Math.min(earliest, row.wakeAt ?? 0);\n }\n const at = Math.max(earliest, holdUntil);\n if (at <= nowAgain) continue;\n const wait = at - nowAgain;\n if (wait <= Math.min(EACH_SHORT_WAIT_MS, deadline - nowAgain)) {\n await new Promise((resolve) => setTimeout(resolve, Math.max(0, wait)));\n continue;\n }\n this.suspend(\"sleeping\", at);\n }\n } finally {\n clearInterval(poll);\n if (!tickAbort.signal.aborted) tickAbort.abort(new WorkflowSuspended());\n }\n\n const listed = await store.listItems(this.workflowId, key, {\n statuses: [\"failed\", \"skipped\"],\n limit: EACH_SUMMARY_PROBLEMS + 1,\n });\n const summary: EachSummary = {\n ...progressOf(state),\n problems: listed.slice(0, EACH_SUMMARY_PROBLEMS).map(problemOf),\n moreProblems: listed.length > EACH_SUMMARY_PROBLEMS,\n };\n const output = JSON.stringify({ $each: state, problems: summary.problems, moreProblems: summary.moreProblems });\n const reason = failing;\n const record = await this.write(key, ({ step, now }) => {\n const next = this.record(key, step, {\n status: reason ? \"failed\" : \"completed\",\n output,\n error: reason,\n finishedAt: now,\n });\n return {\n result: next,\n step: next,\n ...(setsProgress && !reason ? { workflow: { progress: 1 } } : {}),\n };\n });\n if (reason) throw failure(key, record);\n return summary;\n }\n\n private async batchStep<J extends Job>(\n key: string,\n job: new () => J,\n args: ReadonlyArray<Readonly<Parameters<J[\"run\"]>>>,\n options: StepBatchOptions,\n ): Promise<BatchStatus> {\n const allowFailures = options.allowFailures === true;\n let cached = this.steps.get(key);\n if (cached?.status === \"completed\") return decode(cached.output) as BatchStatus;\n if (cached?.status === \"failed\") throw failure(key, cached);\n if (cached && cached.status !== \"batching\") this.mismatch(key, cached.status, \"step.batch\");\n this.current = key;\n\n if (!cached) {\n const batch = this.tick.buildBatch(job, args, {\n name: options.name ?? `workflow:${this.tick.workflowId}:${key}`,\n allowFailures,\n });\n cached = await this.write<StepRecord>(key, ({ step, now }) => {\n if (step) return { result: step };\n const record = this.record(key, null, {\n status: \"batching\",\n batchId: batch.id,\n startedAt: now,\n });\n return { result: record, step: record, batch, workflow: { currentStep: key } };\n }, { start: true });\n this.tick.scheduled();\n if (cached.status === \"completed\") return decode(cached.output) as BatchStatus;\n if (cached.status === \"failed\") throw failure(key, cached);\n }\n\n const status = cached.batchId === null ? null : await this.tick.findBatch(cached.batchId);\n if (status && status.finishedAt === null) this.suspend(\"waiting\");\n\n const succeeded =\n status !== null && status.cancelledAt === null && (status.failed === 0 || allowFailures);\n const output = status === null ? null : JSON.stringify(status);\n const error = succeeded\n ? null\n : status === null\n ? `The batch of step \"${key}\" (${cached.batchId}) no longer exists.`\n : `The batch of step \"${key}\" failed: ${status.failed} failed and ` +\n `${status.cancelled} cancelled of ${status.total}.`;\n const record = await this.write(key, ({ step, now }) => {\n const next = this.record(key, step, {\n status: succeeded ? \"completed\" : \"failed\",\n output,\n error,\n finishedAt: now,\n });\n return { result: next, step: next };\n });\n if (!succeeded) throw failure(key, record);\n return status!;\n }\n}\n\n/** The error a failed step throws, on the pass it failed and every later one. */\nfunction failure(key: string, step: StepRecord): StepFailedError {\n if (step.output?.startsWith('{\"$each\"')) {\n return new StepFailedError(\n key,\n `Step \"${key}\" failed: ${step.error ?? \"unknown error\"}`,\n undefined,\n summaryOf(step.output),\n );\n }\n const batch = step.batchId !== null && step.output !== null\n ? (JSON.parse(step.output) as BatchStatus)\n : undefined;\n return new StepFailedError(\n key,\n batch ? (step.error ?? `Step \"${key}\" failed.`) : `Step \"${key}\" failed: ${step.error ?? \"unknown error\"}`,\n batch,\n );\n}\n\n/**\n * A value as stored: JSON, or `null` for `undefined`. Refused past\n * `WORKFLOW_OUTPUT_LIMIT`, and for what JSON cannot carry.\n */\nexport function encode(value: unknown, what: string): string | null {\n if (value === undefined) return null;\n const json = JSON.stringify(value);\n if (json === undefined) {\n throw new TypeError(`${what} cannot be stored: JSON has no form for it.`);\n }\n const bytes = Buffer.byteLength(json, \"utf8\");\n if (bytes > WORKFLOW_OUTPUT_LIMIT) {\n throw new RangeError(\n `${what} is ${bytes} bytes as JSON, over the ${WORKFLOW_OUTPUT_LIMIT}-byte ` +\n `limit. Store it elsewhere and return its id.`,\n );\n }\n return json;\n}\n\nexport function decode(output: string | null): unknown {\n return output === null ? undefined : JSON.parse(output);\n}\n\nexport function describe(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** The most items a `step.each` may have: the items table's `INTEGER` index. */\nconst MAX_EACH_COUNT = 2_147_483_647;\n/** How long a tick works through items by default. */\nconst EACH_TICK_BUDGET_MS = 30_000;\n/** Open items allowed beyond `concurrency`: the retries waiting their turn. */\nconst EACH_RETRY_WINDOW = 100;\n/** A retry due sooner than this is waited for in the tick. */\nconst EACH_SHORT_WAIT_MS = 1_000;\n/** How many items of a source `step.each` reads at a time, at least. */\nconst EACH_SOURCE_WINDOW = 64;\n/** How many problems the summary carries. */\nconst EACH_SUMMARY_PROBLEMS = 100;\n\n/** What a `step.each` keeps on its step row, beside its item rows. */\ntype EachState = {\n count: number;\n /** The next index nothing has started yet: the cursor. */\n next: number;\n succeeded: number;\n skipped: number;\n failed: number;\n};\n\n/** Thrown by `ctx.skip`. */\nclass ItemSkipped extends Error {\n constructor(\n readonly reason: string,\n readonly data: unknown,\n ) {\n super(`Skipped: ${reason}`);\n this.name = \"ItemSkipped\";\n }\n}\n\n/** Thrown by `ctx.release`. */\nclass ItemReleased extends Error {\n constructor(readonly delayMs: number) {\n super(`Released for ${delayMs}ms`);\n this.name = \"ItemReleased\";\n }\n}\n\n/** An item's row, ended as skipped. */\nfunction skippedRow(\n row: ItemRecord,\n key: string | null,\n reason: string,\n data: unknown,\n now: number,\n): ItemRecord {\n let output: string | null = null;\n let text = clip(String(reason));\n try {\n output = encodeSmall(data);\n } catch (tooLarge) {\n text = clip(`${text} (${describe(tooLarge)})`);\n }\n return { ...row, key, status: \"skipped\", error: text, output, wakeAt: null, finishedAt: now };\n}\n\nfunction chunksOf<T>(list: T[], size: number): T[][] {\n const chunks: T[][] = [];\n for (let i = 0; i < list.length; i += size) chunks.push(list.slice(i, i + size));\n return chunks;\n}\n\n/** `maxFailures` as a test: why the step fails at `state`, or `null`. */\nfunction failurePolicy(\n policy: StepEachOptions<unknown>[\"maxFailures\"],\n): (state: EachState) => string | null {\n if (policy === undefined) return () => null;\n if (typeof policy === \"number\") {\n const most = Math.max(0, Math.floor(policy));\n return (state) =>\n state.failed > most\n ? `${state.failed} items failed, more than maxFailures (${most}).`\n : null;\n }\n const ratio = Math.min(1, Math.max(0, policy.ratio));\n const after = Math.max(1, Math.floor(policy.after ?? 20));\n return (state) => {\n const done = state.succeeded + state.skipped + state.failed;\n if (done < after || state.failed / done <= ratio) return null;\n return (\n `${state.failed} of ${done} items failed, more than maxFailures ` +\n `allows (a ratio of ${ratio}).`\n );\n };\n}\n\nfunction newState(count: number): EachState {\n return { count, next: 0, succeeded: 0, skipped: 0, failed: 0 };\n}\n\nfunction stateOutput(state: EachState): string {\n return JSON.stringify({ $each: state });\n}\n\nfunction stateOf(output: string | null): EachState {\n const parsed = output === null ? null : (JSON.parse(output) as { $each?: EachState });\n if (!parsed?.$each) throw new Error(\"A step.each step has no state.\");\n return parsed.$each;\n}\n\n/** `step.each`'s progress from its step's stored output, or `null` for another kind of step. */\nexport function eachProgressOf(output: string | null): EachProgress | null {\n if (output === null || !output.startsWith('{\"$each\"')) return null;\n try {\n return progressOf(stateOf(output));\n } catch {\n return null;\n }\n}\n\nfunction progressOf(state: EachState): EachProgress {\n return {\n total: state.count,\n done: state.succeeded + state.skipped + state.failed,\n succeeded: state.succeeded,\n skipped: state.skipped,\n failed: state.failed,\n };\n}\n\nfunction summaryOf(output: string | null): EachSummary {\n const parsed = JSON.parse(output ?? \"null\") as {\n $each: EachState;\n problems?: EachProblem[];\n moreProblems?: boolean;\n };\n return {\n ...progressOf(parsed.$each),\n problems: parsed.problems ?? [],\n moreProblems: parsed.moreProblems === true,\n };\n}\n\n/** An item row as `step.each` and `Workflow.items` list it. */\nexport function problemOf(item: ItemRecord): EachProblem {\n const problem: EachProblem = {\n index: item.index,\n key: item.key,\n status: item.status === \"skipped\" ? \"skipped\" : \"failed\",\n reason: clip(item.error ?? \"\"),\n attempt: item.attempt,\n };\n if (item.output !== null) problem.data = JSON.parse(item.output);\n return problem;\n}\n\nfunction newItem(workflowId: string, step: string, index: number, now: number): ItemRecord {\n return {\n workflowId,\n step,\n index,\n key: null,\n status: \"running\",\n attempt: 1,\n error: null,\n output: null,\n wakeAt: null,\n startedAt: now,\n finishedAt: null,\n createdAt: now,\n updatedAt: now,\n };\n}\n\nfunction itemKeyOf(value: unknown): string {\n const key = typeof value === \"number\" && Number.isFinite(value) ? String(value) : value;\n if (typeof key !== \"string\" || key.length === 0 || key.length > 191) {\n throw new TypeError(\n `An item key is a string of 1 to 191 characters, or a number; got ${JSON.stringify(value)}.`,\n );\n }\n return key;\n}\n\nfunction clip(text: string, max = 500): string {\n return text.length <= max ? text : `${text.slice(0, max - 1)}…`;\n}\n\n/** `ctx.skip`'s data as JSON, refused past 1 KB. */\nfunction encodeSmall(value: unknown): string | null {\n if (value === undefined) return null;\n const json = JSON.stringify(value);\n if (json === undefined) throw new TypeError(\"its data has no JSON form, so it was not kept\");\n if (Buffer.byteLength(json, \"utf8\") > 1024) {\n throw new RangeError(\"its data is over 1 KB as JSON, so it was not kept\");\n }\n return json;\n}\n\nlet warnedNotDurable = false;\n\n/** D4: a list worked on a queue that a restart empties, in production. */\nfunction warnNotDurable() {\n if (warnedNotDurable || process.env.NODE_ENV !== \"production\") return;\n warnedNotDurable = true;\n console.warn(\n `[gemi] step.each is running on a queue whose driver keeps nothing across ` +\n `restarts (the memory driver), so a deploy or a crash loses the workflow ` +\n `and the rest of its list. Use the database driver for work that must finish.`,\n );\n}\n\n/** @internal For tests. */\nlet warnedNoTransaction = false;\n\nfunction warnNoTransaction() {\n if (warnedNoTransaction) return;\n warnedNoTransaction = true;\n console.warn(\n `[gemi] step.each with transaction: true runs its items without a transaction: ` +\n `this queue's workflow store cannot record an item in the app's transaction ` +\n `(only the database driver on Postgres or MySQL can). Items are at least once.`,\n );\n}\n\nexport function resetEachWarnings() {\n warnedNoTransaction = false;\n warnedNotDurable = false;\n warnedCounts.clear();\n}\n\nconst warnedCounts = new Set<string>();\n\nfunction warnCountChanged(workflowId: string, key: string, stored: number, now: number) {\n const id = `${workflowId}:${key}`;\n if (warnedCounts.has(id)) return;\n warnedCounts.add(id);\n console.warn(\n `[gemi] step.each \"${key}\" of workflow ${workflowId} was started with a count of ` +\n `${stored} and is now given ${now}. It goes on with ${stored}: the count is ` +\n `fixed when the step first runs.`,\n );\n}\n",
|
|
20
|
+
"// What a workflow's status looks like on the wire, between `Workflow.stream`\n// and `useWorkflow`. Kept free of runtime imports so the browser build can\n// name it.\n\n/**\n * Where a workflow stands.\n *\n * - `running`: a tick is running it, or one is queued to.\n * - `sleeping`: waiting for a `step.sleep` or a step's retry backoff.\n * - `waiting`: waiting for a signal (`step.waitFor`) or a batch (`step.batch`).\n * - `paused`: `Workflow.pause` stopped it; nothing runs until `Workflow.resume`.\n * - `cancelling`: `cancel` was accepted, and `onCancel` has not finished yet.\n * - `completed`, `failed`, `cancelled`: final.\n */\nexport type WorkflowRunStatus =\n | \"running\"\n | \"sleeping\"\n | \"waiting\"\n | \"paused\"\n | \"completed\"\n | \"failed\"\n | \"cancelling\"\n | \"cancelled\";\n\n/**\n * Where one step stands. `signalled` is a signal that arrived before its\n * `step.waitFor`, kept until the workflow gets there. `iterating` is a\n * `step.each` that has items left.\n */\nexport type StepRunStatus =\n | \"running\"\n | \"retrying\"\n | \"completed\"\n | \"failed\"\n | \"sleeping\"\n | \"waiting\"\n | \"signalled\"\n | \"timed_out\"\n | \"batching\"\n | \"iterating\";\n\n/** How far a `step.each` is. */\nexport type EachProgress = {\n total: number;\n /** Items that ended: `succeeded + skipped + failed`. */\n done: number;\n succeeded: number;\n skipped: number;\n failed: number;\n};\n\n/** One step, as `Workflow.find` and the workflow's stream show it. Times are epoch milliseconds. */\nexport type WorkflowStepStatus = {\n key: string;\n status: StepRunStatus;\n /** Attempts started; `step.run` only. */\n attempt: number;\n error: string | null;\n /** The batch a `step.batch` dispatched. */\n batchId: string | null;\n /**\n * 0 to 1: the batch's progress for a `step.batch`, or the share of items\n * that have ended for a `step.each`.\n */\n progress?: number;\n /** How far a `step.each` is. */\n items?: EachProgress;\n /** When a sleep ends, a wait times out, or a retry is due. */\n wakeAt: number | null;\n startedAt: number | null;\n finishedAt: number | null;\n};\n\n/**\n * What a workflow's channel publishes on every change, and what\n * `useWorkflow` returns: its status without `args` and `result`, which can\n * hold what a browser must not see.\n */\nexport type WorkflowUpdate = {\n id: string;\n /** The workflow class's `static name`. */\n name: string;\n status: WorkflowRunStatus;\n /** The key of the step it is on, or `null`. */\n currentStep: string | null;\n /** 0 to 1, as `step.progress` or a running `step.each` last set it; 1 once completed. */\n progress: number;\n /** Why it failed; for a cancelled one, why `onCancel` failed. */\n error: string | null;\n /** Every step recorded so far, in the order they were first reached. */\n steps: WorkflowStepStatus[];\n createdAt: number;\n /** When it last changed: of two updates, the later one has the larger `updatedAt`. */\n updatedAt: number;\n};\n\n/** Whether a workflow has ended: `completed`, `failed` or `cancelled`. */\nexport function workflowEnded(status: WorkflowRunStatus): boolean {\n return status === \"completed\" || status === \"failed\" || status === \"cancelled\";\n}\n",
|
|
21
|
+
"import { afterCommit, deferUntilCommit } from \"../../../orm/context\";\nimport type { ChangeFeedEvent } from \"../../change-feed/ChangeFeedDriver\";\nimport { ChangeFeedManager } from \"../../change-feed/ChangeFeedManager\";\nimport type { ChangeFeedResponse, StreamOptions } from \"../../change-feed/stream\";\nimport { Job } from \"../Job\";\nimport type { QueueManager } from \"../QueueManager\";\nimport { type SlotLimit, slotLimits, workflowHolder } from \"../slots\";\nimport {\n type EachProblem,\n Step,\n WorkflowSuspended,\n decode,\n describe,\n eachProgressOf,\n encode,\n problemOf,\n} from \"./Step\";\nimport type { WorkflowClass, WorkflowStatus } from \"./Workflow\";\nimport { type WorkflowUpdate, workflowEnded } from \"./wire\";\nimport {\n WORKFLOW_TICK_JOB,\n type WorkflowChange,\n WorkflowLeaseLostError,\n type WorkflowRecord,\n type WorkflowRunStatus,\n type WorkflowStore,\n} from \"./WorkflowStore\";\n\nconst ENDED: readonly WorkflowRunStatus[] = [\"completed\", \"failed\", \"cancelled\"];\n\n/** How often a running `step.run` checks whether its workflow was cancelled. */\nconst CANCEL_CHECK_MS = 1000;\n\n/** The least time between two publishes of one workflow's channel. */\nconst PUBLISH_INTERVAL_MS = 250;\n\n/**\n * How often `subscribe` re-reads the workflow whatever it hears: a safety net\n * for a publish that was lost.\n */\nconst RECHECK_MS = 30_000;\n\ntype Outcome =\n | { kind: \"completed\"; result: string | null }\n | { kind: \"failed\"; error: string }\n | { kind: \"suspended\" };\n\n/**\n * The queue's half of workflows: the registry of workflow classes, what\n * `Workflow.start`, `signal`, `find` and `cancel` do, and the tick.\n *\n * ### The tick\n *\n * A workflow advances only inside its tick job, which takes the workflow\n * from the store for a lease (the queue's `visibilityTimeout`, renewed while\n * it runs), runs one pass of `run`, and lets go with the outcome written in\n * the same step. Every write of the pass is fenced by that hold, so a tick\n * that lost it (it was too slow and another took over) changes nothing.\n *\n * A tick that finds the workflow held by another is dropped, after marking\n * the workflow so the holder enqueues a fresh tick when it lets go: a signal\n * that lands mid-pass is never lost, and two passes of one workflow never\n * overlap. A tick that failed or died holds the workflow under its job's id,\n * so its own retry takes it straight back.\n */\nexport class WorkflowRuntime {\n private registry: Record<string, WorkflowClass> = {};\n private storeInstance: WorkflowStore | undefined;\n private ownFeed: ChangeFeedManager | undefined;\n /** Workflows with a publish scheduled, and when each was last published. */\n private readonly publishing = new Map<string, ReturnType<typeof setTimeout>>();\n private readonly published = new Map<string, number>();\n private tickClass: (new () => Job) | undefined;\n private readonly reportedNames = new Set<string>();\n\n constructor(private readonly queue: QueueManager) {}\n\n /** The workflow classes this process can run, by `static name`. */\n get workflows(): Readonly<Record<string, WorkflowClass>> {\n return this.registry;\n }\n\n /** Replaces the registry. The first class to claim a name wins. */\n use(workflows: readonly WorkflowClass[]) {\n this.registry = {};\n for (const workflow of workflows) {\n if (workflow.name === \"unset\" || !workflow.name) {\n console.error(\n `A workflow class has no \\`static name\\`, so it was not registered. Add one.`,\n );\n continue;\n }\n if (this.registry[workflow.name]) {\n console.error(\n `Two workflows are named \"${workflow.name}\" — the first is registered ` +\n `and this one is not. A workflow's name is its key in storage. Rename one.`,\n );\n continue;\n }\n this.registry[workflow.name] = workflow;\n }\n }\n\n /** The internal job a workflow's passes run in, one class per manager. */\n get tickJob(): new () => Job {\n this.tickClass ??= tickJobFor(this);\n return this.tickClass;\n }\n\n get store(): WorkflowStore {\n if (!this.storeInstance) {\n const store = this.queue.driver.workflowStore?.();\n if (!store || !this.queue.driver.enqueueBatch) {\n throw new Error(\n `This queue's driver does not support workflows. The memory and ` +\n `database drivers do.`,\n );\n }\n this.storeInstance = this.publishingStore(store);\n }\n return this.storeInstance;\n }\n\n /**\n * The change feed workflow changes are published to: the application's,\n * or one of this runtime's own (in memory) without one.\n */\n get feed(): ChangeFeedManager {\n const application = this.queue.boundApplication;\n if (application?.bound(ChangeFeedManager)) return application.make(ChangeFeedManager);\n this.ownFeed ??= new ChangeFeedManager();\n return this.ownFeed;\n }\n\n /** The ChangeFeed channel a workflow's changes are published to. */\n channel(id: string): string {\n return `gemi:workflow:${id}`;\n }\n\n /** What a change publishes: the status without `args` and `result`. */\n async update(id: string): Promise<WorkflowUpdate | null> {\n const status = await this.find(id);\n if (!status) return null;\n const { args: _args, result: _result, ...update } = status;\n return update;\n }\n\n /**\n * An SSE response following workflow `id`: each event's `data` is a\n * `WorkflowUpdate`, for a route that has already decided the caller may\n * read it.\n */\n stream(\n request: { rawRequest: Request } | Request,\n id: string,\n options: StreamOptions = {},\n ): ChangeFeedResponse<WorkflowUpdate> {\n return this.feed.stream<WorkflowUpdate>(request, this.channel(id), options);\n }\n\n /** A cursor at the workflow's channel head, for a view to hand its client. */\n cursor(id: string): Promise<string> {\n return this.feed.cursor(this.channel(id));\n }\n\n /**\n * Follows workflow `id` on the server: yields it as it is now, then each\n * newer update, and ends after the one that ended it. Yields nothing for\n * an unknown id.\n */\n async *subscribe(\n id: string,\n options: { signal?: AbortSignal } = {},\n ): AsyncGenerator<WorkflowUpdate, void, undefined> {\n const subscription = this.feed.subscribe(this.channel(id), { signal: options.signal });\n try {\n await subscription.ready();\n let current = await this.update(id);\n if (!current) return;\n yield current;\n if (workflowEnded(current.status)) return;\n const events = subscription[Symbol.asyncIterator]();\n let pending = events.next();\n for (;;) {\n const next = await raceTimeout(pending, RECHECK_MS);\n let update: WorkflowUpdate | null;\n if (next === \"timeout\") {\n update = await this.update(id);\n } else {\n if (next.done) return;\n pending = events.next();\n update = updateOf(next.value, id) ?? (await this.update(id));\n }\n if (!update || update.updatedAt < current.updatedAt) continue;\n if (JSON.stringify(update) === JSON.stringify(current)) continue;\n current = update;\n yield current;\n if (workflowEnded(current.status)) return;\n }\n } finally {\n subscription.close();\n }\n }\n\n /**\n * The store, with every change scheduling a publish of the workflow it\n * changed. Publishes are coalesced: at most one per workflow every\n * `PUBLISH_INTERVAL_MS`, each carrying the workflow as it is then, so the\n * last change is always published.\n */\n private publishingStore(store: WorkflowStore): WorkflowStore {\n const changed = (id: string) => void afterCommit(() => this.schedulePublish(id));\n const wrapped: WorkflowStore = {\n create: (workflow) =>\n store.create(workflow).then((value) => {\n changed(workflow.id);\n return value;\n }),\n find: (id, options) => store.find(id, options),\n acquire: (id, owner, leaseMs) => store.acquire(id, owner, leaseMs),\n renew: (id, owner, leaseMs) => store.renew(id, owner, leaseMs),\n update: (id, options, decide) =>\n store.update(id, options, decide).then((value) => {\n changed(id);\n return value;\n }),\n };\n if (store.joinsTransaction) wrapped.joinsTransaction = () => store.joinsTransaction!();\n if (store.transaction) wrapped.transaction = (fn) => store.transaction!(fn);\n if (store.listItems) wrapped.listItems = (...args) => store.listItems!(...args);\n if (store.prune) wrapped.prune = (olderThanMs) => store.prune!(olderThanMs);\n if (store.writeSource) {\n wrapped.writeSource = (...args) => store.writeSource!(...args);\n wrapped.readSource = (...args) => store.readSource!(...args);\n wrapped.deleteSource = (...args) => store.deleteSource!(...args);\n wrapped.pruneSources = (...args) => store.pruneSources!(...args);\n }\n return wrapped;\n }\n\n private schedulePublish(id: string) {\n if (this.publishing.has(id)) return;\n const wait = Math.max(0, (this.published.get(id) ?? 0) + PUBLISH_INTERVAL_MS - Date.now());\n const timer = setTimeout(() => {\n this.publishing.delete(id);\n this.published.set(id, Date.now());\n void this.publish(id);\n }, wait);\n timer.unref?.();\n this.publishing.set(id, timer);\n }\n\n private async publish(id: string) {\n try {\n const update = await this.update(id);\n if (!update) return;\n if (workflowEnded(update.status)) this.published.delete(id);\n await this.feed.publish(this.channel(id), update);\n } catch (error) {\n console.error(`[gemi] Workflow ${id}: could not publish its change.`, error);\n }\n }\n\n /** Ends this runtime's own feed, if it made one, and drops pending publishes. For tests. */\n async close(): Promise<void> {\n for (const timer of this.publishing.values()) clearTimeout(timer);\n this.publishing.clear();\n await this.ownFeed?.close();\n this.ownFeed = undefined;\n }\n\n start(workflow: WorkflowClass, args: unknown[]): Promise<string> {\n if (workflow.name === \"unset\" || !workflow.name) {\n throw new Error(\"Cannot start a workflow with no name\");\n }\n const store = this.store;\n const record = {\n id: Bun.randomUUIDv7(),\n name: workflow.name,\n args: encode(args, `The arguments of ${workflow.name}`) ?? \"[]\",\n };\n const wake = () => this.queue.claimSoon();\n\n // As `QueueManager.push`: on the caller's transaction when the store\n // joins it, otherwise held until it commits.\n const joins = store.joinsTransaction?.() === true;\n if (!joins) {\n const held = deferUntilCommit(() =>\n store.create(record).then(wake, (error: unknown) => {\n console.error(\n `[gemi] The queue could not record the workflow ${workflow.name}, which ` +\n `was held until its transaction committed. The transaction stays ` +\n `committed; the workflow did not start.`,\n error,\n );\n }),\n );\n if (held) return Promise.resolve(record.id);\n }\n const written = store.create(record);\n const wakeAtCommit = joins && deferUntilCommit(wake);\n return written.then(() => {\n if (!wakeAtCommit) wake();\n return record.id;\n });\n }\n\n async signal(id: string, key: string, payload?: unknown): Promise<boolean> {\n if (typeof key !== \"string\" || key.length === 0 || key.length > 191) {\n throw new TypeError(`A signal key is a string of 1 to 191 characters.`);\n }\n const output = encode(payload, `The payload of signal \"${key}\"`);\n const taken = await this.store.update(id, { key }, ({ workflow, step, now }) => {\n if (ENDED.includes(workflow.status) || workflow.status === \"cancelling\") {\n return { result: false };\n }\n if (!step) {\n return {\n result: true,\n step: {\n workflowId: id,\n key,\n status: \"signalled\",\n attempt: 0,\n output,\n error: null,\n batchId: null,\n wakeAt: null,\n startedAt: null,\n finishedAt: now,\n createdAt: now,\n updatedAt: now,\n },\n };\n }\n if (step.status !== \"waiting\") return { result: false };\n return {\n result: true,\n step: { ...step, status: \"signalled\", output, wakeAt: step.wakeAt, finishedAt: now },\n tick: { delayMs: 0 },\n };\n });\n if (taken) this.queue.claimSoon();\n return taken === true;\n }\n\n async cancel(id: string): Promise<boolean> {\n const cancelled = await this.store.update(id, { allSteps: true }, ({ workflow, steps }) => {\n if (ENDED.includes(workflow.status) || workflow.status === \"cancelling\") {\n return { result: false };\n }\n return {\n result: true,\n workflow: { status: \"cancelling\" },\n cancelBatches: steps\n .filter((step) => step.status === \"batching\" && step.batchId !== null)\n .map((step) => step.batchId!),\n tick: { delayMs: 0 },\n };\n });\n if (cancelled) this.queue.claimSoon();\n return cancelled === true;\n }\n\n async pause(id: string): Promise<boolean> {\n const paused = await this.store.update(id, {}, ({ workflow }) => {\n if (\n ENDED.includes(workflow.status) ||\n workflow.status === \"cancelling\" ||\n workflow.status === \"paused\"\n ) {\n return { result: false };\n }\n return { result: true, workflow: { status: \"paused\" } };\n });\n // A paused workflow gives up its concurrency slots (#1319), and takes a\n // new place in line when resumed.\n if (paused === true) void this.releaseSlotsOf(id);\n return paused === true;\n }\n\n async resume(id: string): Promise<boolean> {\n const resumed = await this.store.update(id, {}, ({ workflow }) => {\n if (workflow.status !== \"paused\") return { result: false };\n // `wakeAt` forgotten, so the pass schedules its own wake-up: one\n // scheduled before the pause may have come and gone.\n return {\n result: true,\n workflow: { status: \"running\", wakeAt: null },\n tick: { delayMs: 0 },\n };\n });\n if (resumed) this.queue.claimSoon();\n return resumed === true;\n }\n\n async find(id: string): Promise<WorkflowStatus | null> {\n const state = await this.store.find(id);\n if (!state) return null;\n const { workflow, steps } = state;\n let args: unknown[] = [];\n try {\n args = JSON.parse(workflow.args) as unknown[];\n } catch {}\n return {\n id: workflow.id,\n name: workflow.name,\n status: workflow.status,\n args,\n currentStep: workflow.currentStep,\n progress: workflow.progress,\n result: safeDecode(workflow.result),\n error: workflow.error,\n steps: await Promise.all(\n steps.map(async (step) => {\n const status = {\n key: step.key,\n status: step.status,\n attempt: step.attempt,\n error: step.error,\n batchId: step.batchId,\n wakeAt: step.wakeAt,\n startedAt: step.startedAt,\n finishedAt: step.finishedAt,\n };\n const items = eachProgressOf(step.output);\n if (items) {\n return {\n ...status,\n items,\n progress: items.total === 0 ? 1 : items.done / items.total,\n };\n }\n if (step.batchId === null) return status;\n const batch = await this.queue.driver.findBatch?.(step.batchId);\n return batch ? { ...status, progress: batch.progress } : status;\n }),\n ),\n createdAt: workflow.createdAt,\n updatedAt: workflow.updatedAt,\n };\n }\n\n async items(\n id: string,\n key: string,\n options: { status?: \"failed\" | \"skipped\"; after?: number; limit?: number } = {},\n ): Promise<EachProblem[]> {\n const store = this.store;\n if (!store.listItems) return [];\n const limit = Math.max(1, Math.min(1000, Math.floor(options.limit ?? 100)));\n const rows = await store.listItems(id, key, {\n statuses: options.status ? [options.status] : [\"failed\", \"skipped\"],\n ...(options.after === undefined ? {} : { after: options.after }),\n limit,\n });\n return rows.map(problemOf);\n }\n\n /** One pass of the workflow `id`, run by its tick job. */\n async tick(id: string, job: Job): Promise<void> {\n const store = this.store;\n const claimed = job.$claimed;\n const owner = claimed\n ? `${claimed.id}:${claimed.attempt}`\n : `${crypto.randomUUID()}:1`;\n const lease = Math.max(1, this.queue.config.visibilityTimeout);\n const acquired = await store.acquire(id, owner, lease);\n if (acquired.kind !== \"acquired\") return;\n const { workflow } = acquired;\n\n const letGo = (change: Partial<WorkflowChange<undefined>> = {}) =>\n store\n .update(id, { owner }, () => ({ ...change, result: undefined, unlock: true }))\n .then(() => this.queue.claimSoon())\n .catch((error) => {\n if (!(error instanceof WorkflowLeaseLostError)) throw error;\n });\n\n // Paused: the tick ends here, and `resume` queues the next one. A tick\n // parked for a slot that finds its workflow ended or paused hands the\n // slot on.\n if (ENDED.includes(workflow.status) || workflow.status === \"paused\") {\n await letGo();\n await this.releaseSlotsOf(id, workflow);\n return;\n }\n\n const Class = this.registry[workflow.name];\n if (!Class) return this.unknown(workflow, job, letGo);\n\n let args: unknown[];\n try {\n args = JSON.parse(workflow.args) as unknown[];\n } catch (error) {\n return letGo({\n workflow: { status: \"failed\", error: `The arguments are not JSON: ${describe(error)}` },\n });\n }\n\n const cancelling = workflow.status === \"cancelling\";\n\n // Concurrency (#1319): one set of slots for the whole workflow, taken\n // before a pass that does not hold them yet. A workflow without a free\n // slot is parked by the driver, its tick back to waiting, until one\n // frees. `onCancel` runs without one.\n let limits: SlotLimit[];\n try {\n limits = await this.limitsOf(Class, args);\n } catch (error) {\n // Most likely the limit could not be read (the database it lives in,\n // say): the tick is retried with its backoff.\n await letGo();\n throw error;\n }\n if (limits.length > 0 && !cancelling && claimed) {\n const driver = this.queue.driver;\n if (!driver.acquireSlots || !driver.releaseSlots) {\n return letGo({\n workflow: {\n status: \"failed\",\n error:\n `${workflow.name} declares concurrency, and this queue's driver has no ` +\n `concurrency slots. The memory and database drivers do.`,\n },\n });\n }\n const granted = await driver.acquireSlots({\n holder: workflowHolder(id),\n workflowId: id,\n job: claimed,\n slots: limits,\n recheckMs: this.queue.slotRecheck(),\n });\n if (!granted) {\n job.$outcome = { kind: \"parked\" };\n return letGo();\n }\n }\n\n const renew = setInterval(\n () => {\n store.renew(id, owner, lease).catch((error) => {\n console.error(`[gemi] Could not extend the hold on workflow ${id}.`, error);\n });\n },\n Math.max(1, Math.floor(lease / 3)),\n );\n renew.unref?.();\n\n const step = new Step({\n workflowId: id,\n owner,\n store,\n steps: acquired.steps,\n cancelling,\n findBatch: (batchId) =>\n this.queue.driver.findBatch?.(batchId, { progress: false }) ?? Promise.resolve(null),\n buildBatch: (batchJob, tuples, options) =>\n this.queue.buildBatch(\n batchJob,\n tuples.map((tuple) => JSON.stringify(tuple)),\n {\n name: options.name,\n allowFailures: options.allowFailures,\n finally: { name: WORKFLOW_TICK_JOB, args: [id] },\n },\n ),\n scheduled: () => this.queue.claimSoon(),\n cancelCheckMs: CANCEL_CHECK_MS,\n durable: this.queue.durable,\n throttle: {\n hit: (name, limit, windowMs) => this.queue.locks.store.hit(name, limit, windowMs),\n refund: (name) => this.queue.locks.store.refund(name),\n },\n });\n\n try {\n let outcome: Outcome;\n try {\n const instance = new Class();\n const value = await (cancelling\n ? instance.onCancel(step, ...args)\n : instance.run(step, ...args));\n outcome = step.suspension\n ? { kind: \"suspended\" }\n : {\n kind: \"completed\",\n result: cancelling ? null : encode(value, `The result of ${workflow.name}`),\n };\n } catch (error) {\n outcome =\n step.suspension || error instanceof WorkflowSuspended\n ? { kind: \"suspended\" }\n : { kind: \"failed\", error: describe(error) };\n if (error instanceof WorkflowLeaseLostError) step.lost = true;\n }\n // A step the code did not await (or one that ran beside a sleep in a\n // `Promise.all`) is still writing; it finishes inside this pass.\n await step.settled();\n if (step.lost) return;\n // One of those suspended the workflow after `run` had returned: it is\n // not done until that step is.\n if (outcome.kind === \"completed\" && step.suspension) outcome = { kind: \"suspended\" };\n\n let next: WorkflowRunStatus | undefined;\n await store.update(id, { owner }, ({ workflow: current, now }) => {\n const change = this.finish(current, outcome, step, cancelling, now);\n next = change.workflow?.status ?? current.status;\n return change;\n });\n this.queue.claimSoon();\n if (limits.length > 0 && next !== undefined && (ENDED.includes(next) || next === \"paused\")) {\n await this.releaseSlots(id);\n }\n } catch (error) {\n if (error instanceof WorkflowLeaseLostError) return;\n throw error;\n } finally {\n clearInterval(renew);\n }\n }\n\n /** The tick's last write: the pass's outcome, and letting go. */\n private finish(\n current: WorkflowRecord,\n outcome: Outcome,\n step: Step,\n cancelling: boolean,\n now: number,\n ): WorkflowChange<undefined> {\n const change: WorkflowChange<undefined> = { result: undefined, unlock: true };\n\n // Cancelled during this pass of `run`: `onCancel` is next, whatever the\n // pass came to.\n if (current.status === \"cancelling\" && !cancelling) {\n return { ...change, tick: { delayMs: 0 } };\n }\n\n if (outcome.kind === \"completed\") {\n return {\n ...change,\n workflow: cancelling\n ? { status: \"cancelled\", currentStep: null, wakeAt: null }\n : {\n status: \"completed\",\n result: outcome.result,\n progress: 1,\n currentStep: null,\n wakeAt: null,\n error: null,\n },\n };\n }\n if (outcome.kind === \"failed\") {\n return {\n ...change,\n workflow: { status: cancelling ? \"cancelled\" : \"failed\", error: outcome.error, wakeAt: null },\n };\n }\n\n const suspension = step.suspension ?? { status: \"waiting\" as const, wakes: [] };\n if (!cancelling && (current.status === \"paused\" || suspension.status === \"paused\")) {\n // Paused: no tick until `resume`. Stopped for a pause that `resume`\n // has already undone: go on at once.\n return current.status === \"paused\"\n ? { ...change, workflow: { currentStep: step.current ?? current.currentStep } }\n : { ...change, workflow: { status: \"running\" }, tick: { delayMs: 0 } };\n }\n const next: WorkflowChange<undefined> = {\n ...change,\n workflow: {\n status: cancelling ? \"cancelling\" : suspension.status,\n currentStep: step.current ?? current.currentStep,\n },\n };\n if (suspension.wakes.length > 0) {\n const wakeAt = Math.min(...suspension.wakes);\n // A tick already scheduled no later than this one wakes the workflow\n // in time, and schedules this one itself; a second would only run the\n // pass twice.\n const scheduled =\n current.wakeAt !== null && current.wakeAt > now && current.wakeAt <= wakeAt;\n if (!scheduled) {\n next.tick = { delayMs: Math.max(0, wakeAt - now) };\n next.workflow!.wakeAt = wakeAt;\n }\n }\n return next;\n }\n\n /** What the workflow's `concurrency` returns, checked. */\n private async limitsOf(Class: WorkflowClass, args: unknown[]): Promise<SlotLimit[]> {\n const instance = new Class() as { concurrency?: (...args: unknown[]) => unknown };\n if (typeof instance.concurrency !== \"function\") return [];\n return slotLimits(await instance.concurrency(...args), Class.name);\n }\n\n /** Hands the workflow's slots on. A failure is logged: the line drops them itself later. */\n private async releaseSlots(id: string) {\n try {\n await this.queue.driver.releaseSlots?.(workflowHolder(id));\n } catch (error) {\n console.error(`[gemi] Could not free the concurrency slots of workflow ${id}.`, error);\n }\n }\n\n /**\n * `releaseSlots` for a workflow whose `concurrency` is not at hand: when\n * its class declares any, so a queue that uses none never touches the\n * slots table.\n */\n private async releaseSlotsOf(id: string, record?: WorkflowRecord) {\n try {\n const workflow = record ?? (await this.store.find(id, { steps: false }))?.workflow;\n const Class = workflow && this.registry[workflow.name];\n if (!workflow || !Class) return;\n const limits = await this.limitsOf(Class, JSON.parse(workflow.args) as unknown[]);\n if (limits.length > 0) await this.releaseSlots(id);\n } catch (error) {\n console.error(`[gemi] Could not free the concurrency slots of workflow ${id}.`, error);\n }\n }\n\n /**\n * A tick for a workflow this process has no class for. During a\n * blue/green ramp that is usually one only the other release has, so on a\n * shared driver it goes back for another replica until `unknownJobGrace`\n * has passed since the workflow started; then it fails.\n */\n private async unknown(\n workflow: WorkflowRecord,\n job: Job,\n letGo: (change?: Partial<WorkflowChange<undefined>>) => Promise<void>,\n ) {\n const age = Date.now() - workflow.createdAt;\n if (this.queue.durable && age < this.queue.config.unknownJobGrace) {\n if (!this.reportedNames.has(workflow.name)) {\n this.reportedNames.add(workflow.name);\n console.error(\n `Left workflow \"${workflow.name}\" for another replica: nothing is ` +\n `registered here under that name.`,\n );\n }\n await letGo();\n job.release(Math.round(this.queue.config.pollInterval * (1 + Math.random())));\n return;\n }\n console.error(\n `Failed workflow ${workflow.id}: nothing is registered under the name ` +\n `\"${workflow.name}\". If the class exists, it was not discovered: check ` +\n `that it is under the queue slice's workflowsDir (app/workflows by ` +\n `default), or list it in app/config/queue.ts.`,\n );\n await letGo({\n workflow: {\n status: \"failed\",\n error: `No workflow is registered under the name \"${workflow.name}\".`,\n },\n });\n }\n\n /**\n * The tick job ran out of attempts, which only a store that stayed\n * unreachable causes. Fails the workflow if it still can, so it does not\n * sit in `running` with nothing left to advance it.\n */\n /** @internal */\n tickDeadLettered(id: string, error: Error) {\n console.error(`[gemi] The tick of workflow ${id} was dead-lettered.`, error);\n void this.store\n .update(id, {}, ({ workflow }) =>\n ENDED.includes(workflow.status)\n ? { result: undefined }\n : {\n result: undefined,\n workflow: {\n status: \"failed\",\n error: `Its tick job was dead-lettered: ${error.message}`,\n },\n unlock: true,\n },\n )\n .then(() => this.releaseSlotsOf(id))\n .catch(() => {});\n }\n}\n\n/** The internal job a workflow's passes run in, bound to one runtime. */\nfunction tickJobFor(runtime: WorkflowRuntime): new () => Job {\n return class WorkflowTickJob extends Job {\n static name = WORKFLOW_TICK_JOB;\n // A tick fails only when the store cannot be reached (a workflow's own\n // errors are recorded, not thrown), so it keeps trying for a while rather\n // than leaving the workflow stuck.\n maxAttempts = 20;\n backoff = [1000, 5000, 15000, 30000, 60000];\n async run(id: string) {\n await runtime.tick(id, this);\n }\n onDeadletter(error: Error, id: string) {\n runtime.tickDeadLettered(id, error);\n }\n };\n}\n\nfunction safeDecode(output: string | null): unknown {\n try {\n return decode(output);\n } catch {\n return output;\n }\n}\n\n/** The update a change event carries, when it is one for workflow `id`. */\nfunction updateOf(event: ChangeFeedEvent, id: string): WorkflowUpdate | null {\n if (event.type !== \"change\") return null;\n const data = event.data as Partial<WorkflowUpdate> | null;\n if (!data || typeof data !== \"object\" || data.id !== id || typeof data.updatedAt !== \"number\") {\n return null;\n }\n return data as WorkflowUpdate;\n}\n\n/** What `promise` resolves to, or `\"timeout\"` after `ms`. */\nasync function raceTimeout<T>(promise: Promise<T>, ms: number): Promise<T | \"timeout\"> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), ms);\n });\n try {\n return await Promise.race([promise, timeout]);\n } finally {\n clearTimeout(timer);\n }\n}\n",
|
|
22
|
+
"import { app } from \"../../../foundation/app\";\nimport { QueueManager } from \"../QueueManager\";\nimport { type Duration, toMilliseconds } from \"./duration\";\nimport type { WorkflowStore } from \"./WorkflowStore\";\n\ndeclare const itemType: unique symbol;\n\n/**\n * A stored list: what `ItemSource.write` and `step.source` resolve to, and\n * what `step.each` takes as its `source`. Small, so it can be a step's result.\n */\nexport type SourceRef<T = unknown> = {\n /** The source's id. */\n id: string;\n /** How many items it holds. */\n count: number;\n /** The item type, carried only in the type. */\n readonly [itemType]?: T;\n};\n\n/** The most one item may be, as JSON, in bytes. */\nexport const ITEM_SOURCE_ITEM_LIMIT = 64 * 1024;\n\n/** How many items one insert writes. */\nconst WRITE_CHUNK = 500;\n\n/** What `write` takes: a list, or anything that yields one, sync or async. */\nexport type ItemSourceInput<T> = Iterable<T> | AsyncIterable<T>;\n\n/**\n * Lists kept in a table of the queue's database (#1309), item by item, so a\n * long list (the rows of an uploaded file, a snapshot of ids) lives between\n * the steps of a workflow without being held in memory or in a step's\n * result. `step.each({ source })` reads it a window at a time.\n *\n * ```ts\n * const rows = await ItemSource.write(`import:${importId}`, parseRows(file.stream()));\n * await ImportWorkflow.start(importId, rows);\n * // In the workflow: step.each(\"rows\", { source: rows }, (row, ctx) => …)\n * ```\n *\n * Inside a workflow, prefer `step.source(key, fn)`: the list is written once,\n * and deleted with the workflow when it is pruned.\n */\nexport class ItemSource {\n /**\n * Writes `items` under `id`, replacing what was there, and resolves to the\n * source. Items are written as they come, 500 per insert, so an async\n * iterable (a parser over a stream) is never held in memory whole. Each\n * item is JSON, at most 64 KB. Not atomic: a write that fails part way\n * leaves the items so far; write it again.\n */\n static write<T>(id: string, items: ItemSourceInput<T>): Promise<SourceRef<T>> {\n return writeSource(storeOf(), id, items, null);\n }\n\n /** The item at `index`, or `undefined`. */\n static async read<T = unknown>(id: string, index: number): Promise<T | undefined> {\n const [row] = await readStore(storeOf()).readSource!(id, index, index + 1);\n return row ? (JSON.parse(row.payload) as T) : undefined;\n }\n\n /** The items from `from` up to, not including, `to`. */\n static async readRange<T = unknown>(id: string, from: number, to: number): Promise<T[]> {\n const rows = await readStore(storeOf()).readSource!(id, from, to);\n return rows.map((row) => JSON.parse(row.payload) as T);\n }\n\n /** Deletes the source, and resolves to how many items it held. */\n static delete(id: string): Promise<number> {\n return readStore(storeOf()).deleteSource!(id);\n }\n\n /**\n * Deletes sources written with `ItemSource.write` more than `olderThan`\n * ago, and resolves to how many items. Sources of `step.source` are\n * deleted with their workflow instead.\n */\n static prune(olderThan: Duration): Promise<number> {\n return readStore(storeOf()).pruneSources!(toMilliseconds(olderThan));\n }\n}\n\nfunction storeOf(): WorkflowStore {\n return app(QueueManager).workflows.store;\n}\n\n/** The store, once it is known to keep item sources. */\nexport function readStore(store: WorkflowStore): WorkflowStore {\n if (!store.writeSource || !store.readSource || !store.deleteSource || !store.pruneSources) {\n throw new Error(\n `This queue's workflow store does not keep item sources. The memory and ` +\n `database drivers do.`,\n );\n }\n return store;\n}\n\n/** Writes a source: what `ItemSource.write` and `step.source` do. */\nexport async function writeSource<T>(\n store: WorkflowStore,\n id: string,\n items: ItemSourceInput<T>,\n workflowId: string | null,\n): Promise<SourceRef<T>> {\n if (typeof id !== \"string\" || id.length === 0 || id.length > 191) {\n throw new TypeError(`An item source id is a string of 1 to 191 characters; got ${JSON.stringify(id)}.`);\n }\n readStore(store);\n await store.deleteSource!(id);\n let count = 0;\n let chunk: Array<{ index: number; payload: string }> = [];\n for await (const item of items as AsyncIterable<T>) {\n const payload = JSON.stringify(item === undefined ? null : item);\n if (payload === undefined) {\n throw new TypeError(`Item ${count} of source \"${id}\" has no JSON form.`);\n }\n const bytes = Buffer.byteLength(payload, \"utf8\");\n if (bytes > ITEM_SOURCE_ITEM_LIMIT) {\n throw new RangeError(\n `Item ${count} of source \"${id}\" is ${bytes} bytes as JSON, over the ` +\n `${ITEM_SOURCE_ITEM_LIMIT}-byte limit. Store it elsewhere and keep its id.`,\n );\n }\n chunk.push({ index: count++, payload });\n if (chunk.length >= WRITE_CHUNK) {\n await store.writeSource!(id, workflowId, chunk);\n chunk = [];\n }\n }\n await store.writeSource!(id, workflowId, chunk);\n return { id, count } as SourceRef<T>;\n}\n\n/**\n * Reads a source for `step.each`, a window at a time: the first read of an\n * index loads the window it starts, and each item is handed out once. A\n * second read of an index (a retry) loads that one item again.\n */\nexport function sourceReader<T>(\n store: WorkflowStore,\n source: SourceRef<T>,\n window: number,\n): (index: number) => Promise<T> {\n readStore(store);\n const cache = new Map<number, string>();\n const loading = new Map<string, Promise<void>>();\n let loadedUpTo = 0;\n const load = (from: number, to: number) => {\n const key = `${from}:${to}`;\n let pending = loading.get(key);\n if (!pending) {\n pending = store.readSource!(source.id, from, to).then(\n (rows) => {\n for (const row of rows) cache.set(row.index, row.payload);\n loading.delete(key);\n },\n (error: unknown) => {\n loading.delete(key);\n throw error;\n },\n );\n loading.set(key, pending);\n }\n return pending;\n };\n return async (index) => {\n if (!cache.has(index)) {\n const from = index - (index % window);\n const to = Math.min(from + window, source.count);\n if (loading.has(`${from}:${to}`)) {\n await loading.get(`${from}:${to}`);\n } else if (index >= loadedUpTo) {\n loadedUpTo = Math.max(loadedUpTo, to);\n await load(from, to);\n }\n // Read before (a retry), or by a window that has been handed out.\n if (!cache.has(index)) await load(index, index + 1);\n }\n const payload = cache.get(index);\n cache.delete(index);\n if (payload === undefined) {\n throw new Error(`Item source \"${source.id}\" has no item at index ${index}.`);\n }\n return JSON.parse(payload) as T;\n };\n}\n"
|
|
23
|
+
],
|
|
24
|
+
"mappings": ";kXAuCO,AAAM,JAAuC,LACzC,AACQ,FACA,QACA,WACA,YACT,WAER,WAAW,CACT,EAEA,EAAoC,CAAC,EACrC,CACA,IAAM,EAAQ,EAAQ,OAAS,aAC/B,GAAI,CAAC,2BAA2B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