/** * Job dispatch idempotency (stacksjs/stacks#1872 Q-8). * * Background: nothing in the dispatch path prevented the same job * from being enqueued twice. A double-clicked button, a retry inside * a webhook handler, or a `dispatchIf(condition, ...)` that re-fires * after a config reload would enqueue duplicate work — and once * in-flight, the worker had no way to recognize the duplication. * * Fix: callers attach an `idempotencyKey` via `JobDispatchOptions` * (or the new `.withIdempotencyKey(key)` chainable). Before * dispatching to the driver, `dispatch()` consults a dedup side- * table — hit means we skip the dispatch and return; miss means * we dispatch and record the key. * * Mirrors the dedup tables we ship across the framework: * - `order_idempotency` (stacksjs/stacks#1879 Co-3) * - `email_idempotency` (stacksjs/stacks#1871 M-8) * - `stripe_webhook_events` (stacksjs/stacks#1879 Co-17) * * Same insert-or-skip semantics, same warn-once-and-degrade when * the table doesn't exist yet so apps that haven't run the * migration aren't broken by the new behavior. * * Schema (provision via the framework migration that introduces * the `job_idempotency` table): * * - `idempotency_key` TEXT NOT NULL UNIQUE * - `job_name` TEXT NOT NULL * - `queue` TEXT * - `dispatched_at` TEXT NOT NULL * * Failed dispatches are NOT recorded — if the driver insert throws, * the caller can retry with the same key and the next attempt is * the one that should land. */ import { isUniqueViolation } from '@stacksjs/error-handling' import { isMissingTableError } from './missing-table' let databaseModule: Promise | undefined function loadDatabaseModule(): Promise { return databaseModule ??= import('@stacksjs/database/runtime').catch((error) => { databaseModule = undefined throw error }) } let warnedAboutMissingJobIdempotencyTable = false function warnOnceAboutMissingTable(): void { if (warnedAboutMissingJobIdempotencyTable) return warnedAboutMissingJobIdempotencyTable = true // eslint-disable-next-line no-console console.warn( '[queue/idempotency] job_idempotency table missing - idempotency keys are accepted but NOT enforced. ' + 'Run migrations to enable dedup.', ) } /** * Check whether a job has already been dispatched under this key. * Returns `true` when the dedup row exists (skip dispatch), `false` * when it doesn't (proceed with dispatch). Degrades to "always * false" with a startup warn when the table is missing. */ export async function hasDispatchedKey(key: string): Promise { try { const { db } = await loadDatabaseModule() const row = await db .selectFrom('job_idempotency') .where('idempotency_key', '=', key) .select(['idempotency_key']) .executeTakeFirst() return Boolean(row) } catch (err) { if (isMissingTableError(err)) { warnOnceAboutMissingTable() return false } throw err } } /** * Record that a job was successfully dispatched under this key. * Called after the driver-side insert/push succeeds. No-op when * the table is missing; collisions (concurrent dispatch of the * same key) are swallowed because the existing row is already * what the next lookup would return. */ export async function recordDispatchedKey( key: string, jobName: string, queue?: string, ): Promise { try { const { db } = await loadDatabaseModule() await db .insertInto('job_idempotency') .values({ idempotency_key: key, job_name: jobName, queue: queue ?? 'default', dispatched_at: new Date().toISOString().slice(0, 19).replace('T', ' '), }) .execute() } catch (err) { if (isMissingTableError(err)) { warnOnceAboutMissingTable() return } // Every dialect's spelling of a duplicate, not just SQLite's and MySQL's: // Postgres says "duplicate key value violates unique constraint", and the // case-sensitive match this was threw on it instead of skipping. if (isUniqueViolation(err)) return throw err } } export type DispatchKeyClaim = 'claimed' | 'duplicate' | 'unenforced' /** * Atomically claim an idempotency key by INSERTing its dedup row UP FRONT and * letting the UNIQUE constraint be the concurrency gate: * - `'claimed'` this caller owns the key; proceed to dispatch (and call * {@link releaseDispatchKey} if the dispatch then fails). * - `'duplicate'` another dispatch already claimed it; skip — do NOT dispatch. * - `'unenforced'` the `job_idempotency` table isn't migrated; dedup is off, * proceed to dispatch (degrade, warn-once). * * Replaces the previous check-then-act (`hasDispatchedKey` → dispatch → * `recordDispatchedKey`), which let two concurrent dispatches both pass the * SELECT and both enqueue — precisely the double-dispatch the feature exists * to prevent (stacksjs/stacks#1984). */ export async function claimDispatchKey(key: string, jobName: string, queue?: string): Promise { try { const { db, getDatabaseDialect, sqlHelpers } = await loadDatabaseModule() const dialect = sqlHelpers(getDatabaseDialect()) if (!dialect.isMysql) { // A duplicate is this function's ordinary second answer, so it is asked // for as one: the insert that loses writes no row and raises nothing. // Left to the unique constraint, every duplicate was first written to // the query log at error level ("Query failed: duplicate key value") // and reached the app's error tracker as a failure, once per skipped // dispatch, although the dispatch was skipped exactly as intended. const claimed = await db.unsafe( `INSERT INTO "job_idempotency" ("idempotency_key", "job_name", "queue", "dispatched_at") VALUES (${[1, 2, 3, 4].map(index => dialect.param(index)).join(', ')}) ON CONFLICT ("idempotency_key") DO NOTHING RETURNING "idempotency_key"`, [key, jobName, queue ?? 'default', new Date().toISOString().slice(0, 19).replace('T', ' ')], ).execute() return (claimed as unknown[]).length > 0 ? 'claimed' : 'duplicate' } await db .insertInto('job_idempotency') .values({ idempotency_key: key, job_name: jobName, queue: queue ?? 'default', dispatched_at: new Date().toISOString().slice(0, 19).replace('T', ' '), }) .execute() return 'claimed' } catch (err) { if (isMissingTableError(err)) { warnOnceAboutMissingTable() return 'unenforced' } if (isUniqueViolation(err)) return 'duplicate' throw err } } /** * Release a previously-claimed key — the compensating action when the dispatch * that claimed it subsequently fails. Preserves the "failed dispatches are NOT * recorded" contract so a retry with the same key can re-claim and land. * Best-effort: a lingering key only over-dedups (never loses work), so a delete * failure is swallowed rather than masking the original dispatch error. */ export async function releaseDispatchKey(key: string): Promise { try { const { db } = await loadDatabaseModule() await db.deleteFrom('job_idempotency').where('idempotency_key', '=', key).execute() } catch { // best-effort compensation } }