diff --git a/.changeset/commex-2324-once-only.md b/.changeset/commex-2324-once-only.md new file mode 100644 index 000000000..c1c2d6d04 --- /dev/null +++ b/.changeset/commex-2324-once-only.md @@ -0,0 +1,7 @@ +--- +'@godaddy/app-connect': minor +--- + +Add a once-only helper, exported from the package root and from `@godaddy/app-connect/once`. `once(store, key, fn, { leaseMs })` records one outcome per key, runs `fn` one caller at a time, and answers `done`, `duplicate`, `in_flight` or `refused` (when `fn` throws `Refused`). A claim whose lease passes is taken over, so work a crashed instance held is retried instead of lost; work that outlives its lease can run again, so pair it with an idempotency key. + +Stores implement `OnceStore`. `createMysqlOnceStore` keeps claims in MySQL 8 or later through a `mysql2/promise` pool and ships its table DDL (`onceTableDdl`); `createMemoryOnceStore` is for tests and local runs. `deriveId(namespace, name)` builds RFC 9562 version 5 ids for stable keys and idempotency keys. diff --git a/packages/app-connect/README.md b/packages/app-connect/README.md index 2f0165279..6decd5bd1 100644 --- a/packages/app-connect/README.md +++ b/packages/app-connect/README.md @@ -9,7 +9,7 @@ A collection of tools and utilities for building applications that integrate wit This library provides essential functionality for developers building applications that work with the GoDaddy platform. It handles platform integration concerns like request verification, webhook validation, authentication, and API communication. -> **Note:** This library is under active development. Currently, it provides request verification and webhook subscription verification functionality, with more features planned for future releases. +> **Note:** This library is under active development. Currently, it provides request verification, webhook subscription verification and once-only work, with more features planned for future releases. ## Installation @@ -51,6 +51,15 @@ Verify that incoming webhook subscriptions are genuinely from the GoDaddy platfo - Express.js middleware for easy integration - Configurable via environment variables or runtime options +### Once-only Work + +Record one outcome per key across every instance of the app, and run the work for it one caller at a time, so a redelivered webhook or a retried job doesn't repeat a side effect. Work that outlives its lease can run again, so pair it with an idempotency key. + +- `once(store, key, fn)` with the outcomes `done`, `duplicate`, `in_flight` and `refused` +- A lease, so work a crashed instance claimed is taken over instead of lost +- A MySQL 8 store (a `mysql2/promise` pool) and an in-memory store for tests +- `deriveId(namespace, name)` for stable name-based ids (RFC 9562 version 5) + ## Usage ### Configuration @@ -215,6 +224,43 @@ function processWebhookSubscription(req) { } ``` +### Once-only Work + +```typescript +import { createPool } from 'mysql2/promise'; +import { Refused, createMysqlOnceStore, deriveId, once } from '@godaddy/app-connect/once'; + +const store = createMysqlOnceStore(createPool(process.env.DATABASE_URL!)); +// One random UUID per app (run crypto.randomUUID() once), never changed. +// Don't copy someone else's: apps sharing it would share idempotency keys. +const NAMESPACE = process.env.ONCE_NAMESPACE!; + +const result = await once(store, `order-event:${eventId}`, async () => { + const response = await sendToVendor(order, { idempotencyKey: deriveId(NAMESPACE, eventId) }); + if (response.status === 422) throw new Refused('vendor_rejected'); // recorded; never retried + if (!response.ok) throw new Error(`vendor answered ${response.status}`); // released; a retry runs again + return response.id; +}); + +switch (result.status) { + case 'done': // the work ran now; result.value is what it returned + case 'duplicate': // it already finished earlier (result.outcome says how) + case 'refused': // it ran now and was refused for good + return res.status(200).end(); + case 'in_flight': // another instance holds it (or a claim whose response was lost, until its lease passes); ask the sender to retry + return res.status(503).end(); +} +``` + +- Pass a `mysql2/promise` Pool, not a connection the app uses for its own transactions: claims must commit on their own to be seen by other instances. A claim that waits on a row lock answers `in_flight` only after the server's `innodb_lock_wait_timeout` (50 seconds by default); lower it for the store's pool if senders time out sooner. A claim that waited has its lease renewed from when it got the row. Keep the pool's charset utf8mb4 (the mysql2 default), or keys with characters outside the BMP can be cut short and collide. +- The store creates its table (`app_connect_once`) on first use. To create it from a migration instead, use `onceTableDdl()` and pass `createTable: false`. The store needs MySQL 8 or later (the key uses `utf8mb4_0900_bin`, which MariaDB doesn't have). +- Rows are kept. Prune finished rows and claims whose lease has passed in small batches, for example `DELETE FROM app_connect_once WHERE updated_at < ? AND (state <> 'claimed' OR lease_until < ?) LIMIT 1000` (both in Unix milliseconds), so claims aren't kept waiting on a long delete. A pruned key can run again, so keep rows longer than any sender may redeliver or retry the same key. +- Leases are judged by each instance's own clock, so keep instances' clocks in sync (NTP) to well inside a lease. A clock that runs ahead by more than the lease takes over claims that are still live. +- `createMemoryOnceStore()` keeps claims in one process and never forgets finished keys, so use it for tests and local runs only. +- `leaseMs` (default 5 minutes) must be longer than the work can take. Once it passes, another caller may take the key over and run the work again, so make the work safe to repeat, for example with an idempotency key from `deriveId`. +- Keys are at most 255 characters; derive a shorter one with `deriveId` when needed. A `Refused` reason is stored, so keep it a short code, never vendor text or shopper data. +- When the work finished but its outcome could not be recorded, `once` throws `OnceNotRecordedError` (with the work's return value as `value`); answer the delivery as failed so it is retried. + ## API Reference ### Core Functions @@ -263,6 +309,46 @@ import { verifyAction, verifyWebhookSubscription, VerifiableRequest } from '@god See the [Next.js App Router Integration](#nextjs-app-router-integration-nextjs-13) example for action verification details. The pattern is similar for webhook verification. +### Once-only Work + +All of these are exported from `@godaddy/app-connect/once` and from the package root. + +#### `once(store, key, fn, options?): Promise>` + +Records one outcome for `key`, running `fn` one caller at a time. Answers `{ status: 'done', value }`, `{ status: 'duplicate', outcome }`, `{ status: 'in_flight' }` or `{ status: 'refused', reason }`. `options.leaseMs` defaults to 5 minutes; `options.onReleaseError` hears about a claim that couldn't be released after `fn` threw (pass a wrapper such as `(err, key) => logger.error({ err, key }, 'release failed')`, so the logger keeps its `this`). It throws a `TypeError` for a bad key or lease, whatever `store.claim` throws, whatever `fn` throws other than `Refused` (after releasing the claim), and `OnceNotRecordedError` when `fn` finished but its outcome could not be recorded. After any of these this caller didn't record an outcome, so answer the delivery as failed; the retry's `once` call shows whether another caller finished the key meanwhile (see `OnceClaimLostError` below). + +#### `Refused` + +Throw `new Refused(reason)` from `fn` to record a refusal for good. + +#### `createMysqlOnceStore(pool, options?): OnceStore` + +A store in MySQL 8. Options: `table` (default `app_connect_once`), `createTable` (default true) and `now`. + +#### `onceTableDdl(table?): string` + +The `CREATE TABLE IF NOT EXISTS` statement for a migration. + +#### `createMemoryOnceStore(options?): OnceStore` + +A store in this process's memory, for tests and local runs. + +#### `deriveId(namespace, name): string` + +An RFC 9562 version 5 UUID for `name` in the `namespace` UUID. + +#### `OnceNotRecordedError` and `OnceClaimLostError` + +`OnceNotRecordedError` has `key`, `outcome`, `value` (what `fn` returned, not enumerable) and `cause`. When `cause` is an `OnceClaimLostError`, the lease passed and another caller took the key over, so it may already be done; otherwise the store failed and the key stays claimed until its lease passes. Neither error puts the key in its message, but keep shopper data out of keys anyway: they're stored. + +#### `OnceStore` + +The port for a custom store: `claim(key, leaseMs)` answers `claimed` (with a token), `done`, `refused` or `in_flight`, atomically across processes, taking over a claim whose lease has passed; `complete(key, token, outcome)` records the outcome for the token's holder and throws `OnceClaimLostError` otherwise; `release(key, token)` forgets the holder's claim and does nothing otherwise. + +#### Constants + +`DEFAULT_LEASE_MS` (5 minutes), `DEFAULT_ONCE_TABLE` (`app_connect_once`), `MAX_KEY_LENGTH` and `MAX_REASON_LENGTH` (255 characters each). + ### Helper Functions #### `getWebhookSecret(options?): string` diff --git a/packages/app-connect/package.json b/packages/app-connect/package.json index 99a3de795..7b07041ae 100644 --- a/packages/app-connect/package.json +++ b/packages/app-connect/package.json @@ -1,7 +1,7 @@ { "name": "@godaddy/app-connect", "version": "1.0.2", - "description": "GoDaddy App Connect - A verification library for GoDaddy Platform App requests", + "description": "GoDaddy App Connect - Request verification and once-only work for GoDaddy Platform Apps", "type": "module", "types": "./dist/index.d.ts", "files": [ @@ -27,6 +27,11 @@ "types": "./dist/tanstack/index.d.ts", "import": "./dist/tanstack/index.js", "default": "./dist/tanstack/index.js" + }, + "./once": { + "types": "./dist/once/index.d.ts", + "import": "./dist/once/index.js", + "default": "./dist/once/index.js" } }, "scripts": { @@ -62,6 +67,7 @@ "@biomejs/biome": "1.9.4", "@types/express": "^5.0.2", "@types/node": "^22.13.1", + "mysql2": "3.24.6", "pino-pretty": "^13.0.0", "tsdown": "^0.15.6", "typescript": "~5.7.3", diff --git a/packages/app-connect/src/index.ts b/packages/app-connect/src/index.ts index 0094023ef..829bb3e3c 100644 --- a/packages/app-connect/src/index.ts +++ b/packages/app-connect/src/index.ts @@ -7,6 +7,32 @@ export { createActionMiddleware, createWebhookMiddleware } from './express'; export * as next from './next'; export * as tanstack from './tanstack'; +// Export the once-only helper +export { + DEFAULT_LEASE_MS, + DEFAULT_ONCE_TABLE, + MAX_KEY_LENGTH, + MAX_REASON_LENGTH, + OnceClaimLostError, + OnceNotRecordedError, + Refused, + createMemoryOnceStore, + createMysqlOnceStore, + deriveId, + once, + onceTableDdl, +} from './once'; +export type { + MemoryOnceStoreOptions, + MysqlOnceStoreOptions, + OnceClaim, + OnceOptions, + OnceOutcome, + OnceResult, + OnceStore, + SqlQueryRunner, +} from './once'; + // Export types export type { Result } from './types/result'; export type { VerifiableRequest } from './types/verifiable-request'; diff --git a/packages/app-connect/src/once/derive-id.test.ts b/packages/app-connect/src/once/derive-id.test.ts new file mode 100644 index 000000000..c10f7b823 --- /dev/null +++ b/packages/app-connect/src/once/derive-id.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest'; +import { deriveId } from './derive-id'; + +const DNS_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; + +describe('deriveId', () => { + it('matches the RFC 9562 version 5 example', () => { + // RFC 9562, Appendix A.4: the DNS namespace and "www.example.com". + expect(deriveId(DNS_NAMESPACE, 'www.example.com')).toBe( + '2ed6657d-e927-568b-95e1-2665a8aea6a2', + ); + expect(deriveId(DNS_NAMESPACE.toUpperCase(), 'www.example.com')).toBe( + '2ed6657d-e927-568b-95e1-2665a8aea6a2', + ); + }); + + it('is stable for a name and differs across names and namespaces', () => { + const id = deriveId(DNS_NAMESPACE, 'a'); + expect(deriveId(DNS_NAMESPACE, 'a')).toBe(id); + expect(deriveId(DNS_NAMESPACE, 'b')).not.toBe(id); + expect(deriveId('6ba7b811-9dad-11d1-80b4-00c04fd430c8', 'a')).not.toBe(id); + expect(id).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/, + ); + }); + + it('hashes the name as UTF-8', () => { + expect(deriveId(DNS_NAMESPACE, 'café')).not.toBe( + deriveId(DNS_NAMESPACE, 'cafe'), + ); + }); + + it('refuses a name with a lone surrogate, which would share an id', () => { + expect(() => deriveId(DNS_NAMESPACE, 'a\uD800')).toThrow(TypeError); + expect(deriveId(DNS_NAMESPACE, '😀')).toMatch(/^[0-9a-f-]{36}$/); + }); + + it('refuses a namespace that is not a UUID', () => { + for (const namespace of [ + '', + 'not-a-uuid', + '6ba7b8109dad11d180b400c04fd430c8', + ]) { + expect(() => deriveId(namespace, 'a')).toThrow(TypeError); + } + }); +}); diff --git a/packages/app-connect/src/once/derive-id.ts b/packages/app-connect/src/once/derive-id.ts new file mode 100644 index 000000000..9f0327281 --- /dev/null +++ b/packages/app-connect/src/once/derive-id.ts @@ -0,0 +1,39 @@ +import { createHash } from 'node:crypto'; +import { isWellFormed } from './store'; + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +/** + * A name-based id (RFC 9562 version 5 UUID): the same namespace and name + * always give the same id, and different names give different ids. + * + * Use it for ids that must not change across retries, such as a once key, an + * idempotency key sent to a vendor, or the id of a record written for an + * outside event: `deriveId(MY_APP_NAMESPACE, storeId + ':sale:' + paymentId)`. + * Pick one random namespace UUID per app and never change it, or every + * derived id changes with it. + * + * @param namespace A UUID, in the usual 8-4-4-4-12 hex form + * @param name Any string; it is hashed as UTF-8 + * @returns A lowercase UUID string + */ +export function deriveId(namespace: string, name: string): string { + if (!UUID.test(namespace)) { + throw new TypeError('deriveId: the namespace must be a UUID'); + } + if (!isWellFormed(name)) { + // A lone surrogate hashes as U+FFFD, so two names would share an id. + throw new TypeError( + 'deriveId: the name must be well-formed text (no lone surrogates)', + ); + } + const hash = createHash('sha1') + .update(Buffer.from(namespace.replace(/-/g, ''), 'hex')) + .update(name, 'utf8') + .digest(); + const bytes = hash.subarray(0, 16); + bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x50; + bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80; + const hex = bytes.toString('hex'); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} diff --git a/packages/app-connect/src/once/index.ts b/packages/app-connect/src/once/index.ts new file mode 100644 index 000000000..7368e9e46 --- /dev/null +++ b/packages/app-connect/src/once/index.ts @@ -0,0 +1,28 @@ +export { + DEFAULT_LEASE_MS, + OnceNotRecordedError, + type OnceOptions, + type OnceResult, + Refused, + once, +} from './once'; +export { + MAX_KEY_LENGTH, + MAX_REASON_LENGTH, + type OnceClaim, + OnceClaimLostError, + type OnceOutcome, + type OnceStore, +} from './store'; +export { + type MemoryOnceStoreOptions, + createMemoryOnceStore, +} from './memory-store'; +export { + DEFAULT_ONCE_TABLE, + type MysqlOnceStoreOptions, + type SqlQueryRunner, + createMysqlOnceStore, + onceTableDdl, +} from './mysql-store'; +export { deriveId } from './derive-id'; diff --git a/packages/app-connect/src/once/memory-store.test.ts b/packages/app-connect/src/once/memory-store.test.ts new file mode 100644 index 000000000..79bfe5ddf --- /dev/null +++ b/packages/app-connect/src/once/memory-store.test.ts @@ -0,0 +1,7 @@ +import { describe } from 'vitest'; +import { createMemoryOnceStore } from './memory-store'; +import { onceStoreContract } from './store-contract.test-helper'; + +describe('memory once store', () => { + onceStoreContract((now) => createMemoryOnceStore({ now })); +}); diff --git a/packages/app-connect/src/once/memory-store.ts b/packages/app-connect/src/once/memory-store.ts new file mode 100644 index 000000000..ff0b195ce --- /dev/null +++ b/packages/app-connect/src/once/memory-store.ts @@ -0,0 +1,78 @@ +import { randomUUID } from 'node:crypto'; +import { + type OnceClaim, + OnceClaimLostError, + type OnceOutcome, + type OnceStore, + checkClaim, + checkOutcome, + trimReason, +} from './store'; + +type Entry = + | { state: 'claimed'; token: string; leaseUntil: number } + | { state: 'done' } + | { state: 'refused'; reason?: string }; + +export interface MemoryOnceStoreOptions { + /** Unix milliseconds. Injected so tests control time. */ + now?: () => number; +} + +/** + * A `OnceStore` held in this process's memory. Claims hold only inside one + * process, are lost on restart, and finished keys are never forgotten, so use + * it for tests and local runs only. Use the MySQL store in an app. + */ +export function createMemoryOnceStore( + options: MemoryOnceStoreOptions = {}, +): OnceStore { + const now = options.now ?? Date.now; + const entries = new Map(); + + return { + async claim(key: string, leaseMs: number): Promise { + checkClaim(key, leaseMs); + const at = now(); + const entry = entries.get(key); + if (entry?.state === 'done') { + return { status: 'done' }; + } + if (entry?.state === 'refused') { + return { status: 'refused', reason: entry.reason }; + } + // A new key, or a claim whose lease has passed, is claimed. + if (entry === undefined || entry.leaseUntil < at) { + const token = randomUUID(); + entries.set(key, { state: 'claimed', token, leaseUntil: at + leaseMs }); + return { status: 'claimed', token }; + } + return { status: 'in_flight' }; + }, + + async complete( + key: string, + token: string, + outcome: OnceOutcome, + ): Promise { + checkOutcome(outcome); + const entry = entries.get(key); + if (entry?.state !== 'claimed' || entry.token !== token) { + throw new OnceClaimLostError(key); + } + entries.set( + key, + outcome.status === 'done' + ? { state: 'done' } + : { state: 'refused', reason: trimReason(outcome.reason) }, + ); + }, + + async release(key: string, token: string): Promise { + const entry = entries.get(key); + if (entry?.state === 'claimed' && entry.token === token) { + entries.delete(key); + } + }, + }; +} diff --git a/packages/app-connect/src/once/mysql-store.mysql.test.ts b/packages/app-connect/src/once/mysql-store.mysql.test.ts new file mode 100644 index 000000000..00725a574 --- /dev/null +++ b/packages/app-connect/src/once/mysql-store.mysql.test.ts @@ -0,0 +1,127 @@ +import { randomBytes } from 'node:crypto'; +import { type Pool, createPool } from 'mysql2/promise'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { createMysqlOnceStore, onceTableDdl } from './mysql-store'; +import { once } from './once'; +import { onceStoreContract } from './store-contract.test-helper'; + +/** + * Runs against a real MySQL 8.4 server, only when APP_CONNECT_TEST_MYSQL_URL + * is set, for example: + * + * docker run --rm -d --cpus=2 -p 3307:3306 -e MYSQL_ROOT_PASSWORD=test \ + * -e MYSQL_DATABASE=once_test mysql:8.4 + * APP_CONNECT_TEST_MYSQL_URL=mysql://root:test@127.0.0.1:3307/once_test pnpm test + * + * Each run uses its own tables and drops them afterwards, except the + * reserved-word test, which needs the fixed name `order`: it skips when that + * table exists, so point the URL at a scratch database no other run is using. + */ +const url = process.env.APP_CONNECT_TEST_MYSQL_URL; + +describe.runIf(Boolean(url))('MySQL once store (MySQL 8.4)', () => { + let pool: Pool; + const tables: string[] = []; + const prefix = `once_${randomBytes(4).toString('hex')}`; + + function nextTable(): string { + const table = `${prefix}_${tables.length}`; + tables.push(table); + return table; + } + + beforeAll(() => { + pool = createPool({ uri: url, connectionLimit: 8 }); + }); + + afterAll(async () => { + for (const table of tables) { + await pool.query(`DROP TABLE IF EXISTS \`${table}\``); + } + await pool.end(); + }); + + onceStoreContract((now) => + createMysqlOnceStore(pool, { table: nextTable(), now }), + ); + + it('lets exactly one of many concurrent callers claim a key', async () => { + const store = createMysqlOnceStore(pool, { table: nextTable() }); + await store.claim('warm-up', 60_000); + const claims = await Promise.all( + Array.from({ length: 12 }, () => store.claim('evt_race', 60_000)), + ); + expect(claims.filter((claim) => claim.status === 'claimed')).toHaveLength( + 1, + ); + expect(claims.filter((claim) => claim.status === 'in_flight')).toHaveLength( + 11, + ); + }); + + it('runs the work once across stores sharing a table', async () => { + const table = nextTable(); + const first = createMysqlOnceStore(pool, { table }); + const second = createMysqlOnceStore(pool, { table }); + let runs = 0; + const work = async () => { + runs += 1; + return 'sent'; + }; + expect(await once(first, 'evt_1', work)).toEqual({ + status: 'done', + value: 'sent', + }); + expect(await once(second, 'evt_1', work)).toEqual({ + status: 'duplicate', + outcome: { status: 'done' }, + }); + expect(runs).toBe(1); + }); + + it('works on a table created from the shipped DDL by a migration', async () => { + const table = nextTable(); + await pool.query(onceTableDdl(table)); + const store = createMysqlOnceStore(pool, { table, createTable: false }); + expect((await store.claim('evt_1', 60_000)).status).toBe('claimed'); + }); + + it('keeps a key of 255 characters outside the BMP', async () => { + const store = createMysqlOnceStore(pool, { table: nextTable() }); + const key = '😀'.repeat(255); + expect((await store.claim(key, 60_000)).status).toBe('claimed'); + expect(await store.claim(key, 60_000)).toEqual({ status: 'in_flight' }); + }); + + it('quotes a table name that is a reserved word', async (context) => { + const table = 'order'; + // Never touch an `order` table this run didn't create. + const [existing] = await pool.query( + 'SELECT COUNT(*) AS n FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?', + [table], + ); + if (Number((existing as Array<{ n: unknown }>)[0]?.n) > 0) { + context.skip(); + } + tables.push(table); + const store = createMysqlOnceStore(pool, { table }); + expect((await store.claim('evt_1', 60_000)).status).toBe('claimed'); + }); + + it('never throws when claims race a release of the same key', async () => { + const store = createMysqlOnceStore(pool, { table: nextTable() }); + for (let round = 0; round < 5; round += 1) { + const key = `evt_release_${round}`; + const first = await store.claim(key, 60_000); + if (first.status !== 'claimed') throw new Error('not claimed'); + const results = await Promise.all([ + store.release(key, first.token).then(() => 'released'), + ...Array.from({ length: 6 }, () => + store.claim(key, 60_000).then((claim) => claim.status), + ), + ]); + const claimed = results.filter((status) => status === 'claimed'); + expect(claimed.length).toBeLessThanOrEqual(1); + } + }); +}); diff --git a/packages/app-connect/src/once/mysql-store.test.ts b/packages/app-connect/src/once/mysql-store.test.ts new file mode 100644 index 000000000..d4bb22454 --- /dev/null +++ b/packages/app-connect/src/once/mysql-store.test.ts @@ -0,0 +1,469 @@ +import { describe, expect, it } from 'vitest'; +import { + type SqlQueryRunner, + createMysqlOnceStore, + onceTableDdl, +} from './mysql-store'; +import { onceStoreContract } from './store-contract.test-helper'; + +type Row = { + state: string; + claim_token: string | null; + lease_until: number; + reason: string | null; +}; + +/** + * Runs the store's statements against an in-memory table with MySQL's + * semantics for the cases the store depends on: a duplicate primary key fails + * with ER_DUP_ENTRY, UPDATE and DELETE report how many rows matched, and every + * answer is mysql2's [result, fields] tuple. The real database is covered by + * mysql-store.mysql.test.ts. + */ +function fakeMysql(table = 'app_connect_once') { + const rows = new Map(); + const statements: string[] = []; + const header = (affectedRows: number) => [{ affectedRows }, undefined]; + const runner: SqlQueryRunner = { + async query(sql: string, values: unknown[] = []) { + const text = sql.replace(/\s+/g, ' ').replace(/`/g, '').trim(); + statements.push(text); + if (text.startsWith(`CREATE TABLE IF NOT EXISTS ${table} `)) { + return header(0); + } + if (text.startsWith(`INSERT INTO ${table} `)) { + const [key, token, leaseUntil] = values as [string, string, number]; + if (rows.has(key)) { + throw Object.assign(new Error('Duplicate entry'), { + code: 'ER_DUP_ENTRY', + errno: 1062, + }); + } + rows.set(key, { + state: 'claimed', + claim_token: token, + lease_until: leaseUntil, + reason: null, + }); + return header(1); + } + if (text.startsWith(`UPDATE ${table} SET claim_token`)) { + const [token, leaseUntil, , key, at] = values as [ + string, + number, + number, + string, + number, + ]; + const row = rows.get(key); + if (!row || row.state !== 'claimed' || row.lease_until >= at) { + return header(0); + } + Object.assign(row, { claim_token: token, lease_until: leaseUntil }); + return header(1); + } + if (text.startsWith(`UPDATE ${table} SET lease_until`)) { + const [leaseUntil, , key, token] = values as [ + number, + number, + string, + string, + ]; + const row = rows.get(key); + if (!row || row.state !== 'claimed' || row.claim_token !== token) { + return header(0); + } + row.lease_until = leaseUntil; + return header(1); + } + if (text.startsWith(`UPDATE ${table} SET state`)) { + const [state, reason, , key, token] = values as [ + string, + string | null, + number, + string, + string, + ]; + const row = rows.get(key); + if (!row || row.state !== 'claimed' || row.claim_token !== token) { + return header(0); + } + Object.assign(row, { state, reason, claim_token: null }); + return header(1); + } + if (text.startsWith('SELECT state, reason')) { + const row = rows.get(values[0] as string); + return [row ? [{ state: row.state, reason: row.reason }] : [], []]; + } + if (text.startsWith(`DELETE FROM ${table} `)) { + const [key, token] = values as [string, string]; + const row = rows.get(key); + if (row?.state === 'claimed' && row.claim_token === token) { + rows.delete(key); + return header(1); + } + return header(0); + } + throw new Error(`unexpected statement: ${text}`); + }, + }; + return { runner, rows, statements }; +} + +describe('MySQL once store (statement fake)', () => { + onceStoreContract((now) => createMysqlOnceStore(fakeMysql().runner, { now })); + + it('creates its table once, and again after a failure', async () => { + const db = fakeMysql(); + let failures = 1; + const flaky: SqlQueryRunner = { + async query(sql, values) { + if (sql.startsWith('CREATE TABLE') && failures > 0) { + failures -= 1; + throw new Error('connection reset'); + } + return db.runner.query(sql, values); + }, + }; + const store = createMysqlOnceStore(flaky); + await expect(store.claim('a', 1_000)).rejects.toThrow('connection reset'); + await store.claim('a', 1_000); + await store.claim('b', 1_000); + expect( + db.statements.filter((statement) => statement.startsWith('CREATE TABLE')), + ).toHaveLength(1); + }); + + it('leaves the table to migrations when createTable is false', async () => { + const db = fakeMysql('gpa_once'); + const store = createMysqlOnceStore(db.runner, { + table: 'gpa_once', + createTable: false, + }); + await store.claim('a', 1_000); + expect( + db.statements.some((statement) => statement.startsWith('CREATE TABLE')), + ).toBe(false); + expect(db.rows.has('a')).toBe(true); + }); + + it('rethrows an insert error that is not a duplicate key or lock conflict', async () => { + const store = createMysqlOnceStore({ + async query(sql) { + if (sql.startsWith('INSERT')) throw new Error('connection reset'); + return [{ affectedRows: 0 }, undefined]; + }, + }); + await expect(store.claim('a', 1_000)).rejects.toThrow('connection reset'); + }); + + it('refuses a runner that does not answer like mysql2', async () => { + const store = createMysqlOnceStore( + { query: async () => ({ affectedRows: 1 }) }, + { createTable: false }, + ); + // Before the work runs, at the claim. + await expect(store.claim('a', 1_000)).rejects.toThrow('[result, fields]'); + const statements: string[] = []; + const noCount = createMysqlOnceStore( + { + async query(sql) { + statements.push(sql); + return [{}, undefined]; + }, + }, + { createTable: false }, + ); + await expect(noCount.claim('a', 1_000)).rejects.toThrow('affectedRows'); + // The row the insert may have written is taken back. + expect(statements.at(-1)).toMatch(/^DELETE FROM/); + }); + + it('runs complete and release again when picked as a deadlock victim', async () => { + const db = fakeMysql(); + let deadlocks = 0; + const store = createMysqlOnceStore({ + async query(sql, values) { + if (/^(UPDATE \S+ SET state|DELETE)/.test(sql) && deadlocks % 2 === 0) { + deadlocks += 1; + throw Object.assign(new Error('deadlock'), { errno: 1213 }); + } + if (/^(UPDATE \S+ SET state|DELETE)/.test(sql)) deadlocks += 1; + return db.runner.query(sql, values); + }, + }); + const first = await store.claim('a', 60_000); + if (first.status !== 'claimed') throw new Error('not claimed'); + await store.complete('a', first.token, { status: 'done' }); + expect(await store.claim('a', 60_000)).toEqual({ status: 'done' }); + const second = await store.claim('b', 60_000); + if (second.status !== 'claimed') throw new Error('not claimed'); + await store.release('b', second.token); + expect((await store.claim('b', 60_000)).status).toBe('claimed'); + expect(deadlocks).toBe(4); + }); + + it('renews the lease when the claim waited on a lock', async () => { + const db = fakeMysql(); + const clock = { now: 1_000 }; + const store = createMysqlOnceStore( + { + async query(sql, values) { + const result = await db.runner.query(sql, values); + // The insert waited 40s behind a prune. + if (sql.startsWith('INSERT')) clock.now += 40_000; + return result; + }, + }, + { now: () => clock.now }, + ); + const claim = await store.claim('a', 30_000); + expect(claim.status).toBe('claimed'); + expect(db.rows.get('a')?.lease_until).toBe(41_000 + 30_000); + }); + + it('answers in_flight when the key was taken over while the claim waited', async () => { + const db = fakeMysql(); + const store = createMysqlOnceStore( + { + async query(sql, values) { + const result = await db.runner.query(sql, values); + if (sql.startsWith('INSERT')) { + const row = db.rows.get('a'); + if (row) row.claim_token = 'someone-else'; + } + return result; + }, + }, + { + now: (() => { + let calls = 0; + return () => (calls++ === 0 ? 1_000 : 50_000); + })(), + }, + ); + expect(await store.claim('a', 30_000)).toEqual({ status: 'in_flight' }); + }); + + it('gives the key back when renewing the lease fails', async () => { + const db = fakeMysql(); + const clock = { now: 1_000 }; + const store = createMysqlOnceStore( + { + async query(sql, values) { + if (sql.startsWith('UPDATE') && sql.includes('SET lease_until')) { + throw Object.assign(new Error('deadlock'), { errno: 1213 }); + } + const result = await db.runner.query(sql, values); + if (sql.startsWith('INSERT')) clock.now += 40_000; + return result; + }, + }, + { now: () => clock.now }, + ); + expect(await store.claim('a', 30_000)).toEqual({ status: 'in_flight' }); + // Not held by a token nobody uses: the next claim gets it. + expect(db.rows.has('a')).toBe(false); + }); + + it('renews a short lease after a wait that used a real share of it', async () => { + const db = fakeMysql(); + const clock = { now: 1_000 }; + const store = createMysqlOnceStore( + { + async query(sql, values) { + const result = await db.runner.query(sql, values); + if (sql.startsWith('INSERT')) clock.now += 900; + return result; + }, + }, + { now: () => clock.now }, + ); + expect((await store.claim('a', 1_500)).status).toBe('claimed'); + expect(db.rows.get('a')?.lease_until).toBe(1_900 + 1_500); + }); + + it('claims a key released between its insert and its takeover', async () => { + const db = fakeMysql(); + db.rows.set('a', { + state: 'claimed', + claim_token: 'holder', + lease_until: Number.MAX_SAFE_INTEGER, + reason: null, + }); + let inserts = 0; + const claim = createMysqlOnceStore( + { + async query(sql, values) { + if (sql.startsWith('INSERT')) inserts += 1; + try { + return await db.runner.query(sql, values); + } finally { + // The holder releases right after this caller's insert collided. + if (sql.startsWith('INSERT') && inserts === 1) db.rows.delete('a'); + } + }, + }, + { createTable: false }, + ).claim('a', 60_000); + await expect(claim).resolves.toMatchObject({ status: 'claimed' }); + expect(inserts).toBe(2); + }); + + it('runs the claim again when its insert is a deadlock victim', async () => { + const db = fakeMysql(); + let deadlocks = 1; + const store = createMysqlOnceStore( + { + async query(sql, values) { + if (sql.startsWith('INSERT') && deadlocks > 0) { + deadlocks -= 1; + throw Object.assign(new Error('deadlock'), { errno: 1213 }); + } + return db.runner.query(sql, values); + }, + }, + { createTable: false }, + ); + expect((await store.claim('a', 60_000)).status).toBe('claimed'); + }); + + it('leaves the row alone after a lock wait on the renewal', async () => { + const db = fakeMysql(); + const clock = { now: 1_000 }; + const statements: string[] = []; + const store = createMysqlOnceStore( + { + async query(sql, values) { + statements.push(sql); + if (sql.includes('SET lease_until')) { + throw Object.assign(new Error('lock wait'), { errno: 1205 }); + } + const result = await db.runner.query(sql, values); + if (sql.startsWith('INSERT')) clock.now += 40_000; + return result; + }, + }, + { now: () => clock.now, createTable: false }, + ); + expect(await store.claim('a', 30_000)).toEqual({ status: 'in_flight' }); + expect(statements.some((sql) => sql.startsWith('DELETE'))).toBe(false); + }); + + it('gives up on a deadlock that keeps coming back', async () => { + let attempts = 0; + const store = createMysqlOnceStore( + { + async query() { + attempts += 1; + throw Object.assign(new Error('deadlock'), { errno: 1213 }); + }, + }, + { createTable: false }, + ); + await expect( + store.complete('a', 'token', { status: 'done' }), + ).rejects.toThrow('deadlock'); + expect(attempts).toBe(3); + }); + + it('answers in_flight when the takeover or the read hits a lock conflict', async () => { + for (const failing of ['UPDATE', 'SELECT']) { + const store = createMysqlOnceStore( + { + async query(sql) { + if (sql.startsWith('INSERT')) { + throw Object.assign(new Error('dup'), { errno: 1062 }); + } + if (sql.startsWith(failing)) { + throw Object.assign(new Error('deadlock'), { + code: 'ER_LOCK_DEADLOCK', + }); + } + return [{ affectedRows: 0 }, undefined]; + }, + }, + { createTable: false }, + ); + expect(await store.claim('a', 1_000)).toEqual({ status: 'in_flight' }); + } + }); + + it('answers in_flight when the claim insert hits a lock conflict', async () => { + for (const errno of [1213, 1205]) { + const store = createMysqlOnceStore( + { + async query(sql) { + if (sql.startsWith('INSERT')) { + throw Object.assign(new Error('lock'), { errno }); + } + return [{ affectedRows: 0 }, undefined]; + }, + }, + { createTable: false }, + ); + expect(await store.claim('a', 1_000)).toEqual({ status: 'in_flight' }); + } + }); + + it('carries on when the database user may not create tables', async () => { + const db = fakeMysql(); + let creates = 0; + const store = createMysqlOnceStore({ + async query(sql, values) { + if (sql.startsWith('CREATE TABLE')) { + creates += 1; + throw Object.assign(new Error('CREATE command denied'), { + code: 'ER_TABLEACCESS_DENIED_ERROR', + errno: 1142, + }); + } + return db.runner.query(sql, values); + }, + }); + expect((await store.claim('a', 1_000)).status).toBe('claimed'); + expect((await store.claim('b', 1_000)).status).toBe('claimed'); + expect(creates).toBe(1); + }); + + it('refuses rows that are not objects keyed by column name', async () => { + const store = createMysqlOnceStore( + { + async query(sql) { + if (sql.startsWith('INSERT')) { + throw Object.assign(new Error('dup'), { errno: 1062 }); + } + if (sql.startsWith('SELECT')) return [[['done', null]], []]; + return [{ affectedRows: 0 }, undefined]; + }, + }, + { createTable: false }, + ); + await expect(store.claim('a', 1_000)).rejects.toThrow('objects'); + }); + + it('quotes the table name, so a reserved word works', () => { + expect(onceTableDdl('order')).toContain( + 'CREATE TABLE IF NOT EXISTS `order` (', + ); + }); + it('refuses a table name that is not a plain identifier', () => { + for (const table of ['', 'once; DROP TABLE x', 'a-b', 'x'.repeat(65)]) { + expect(() => createMysqlOnceStore(fakeMysql().runner, { table })).toThrow( + TypeError, + ); + expect(() => onceTableDdl(table)).toThrow(TypeError); + } + // null means the default table, for the DDL as for the store. + expect(onceTableDdl(null)).toContain('`app_connect_once`'); + expect(() => onceTableDdl(42 as unknown as string)).toThrow(TypeError); + }); + + it('ships DDL that compares keys byte for byte', () => { + const ddl = onceTableDdl(); + expect(ddl).toContain('CREATE TABLE IF NOT EXISTS `app_connect_once`'); + expect(ddl).toContain( + 'once_key VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin NOT NULL PRIMARY KEY', + ); + }); +}); diff --git a/packages/app-connect/src/once/mysql-store.ts b/packages/app-connect/src/once/mysql-store.ts new file mode 100644 index 000000000..bce0daaec --- /dev/null +++ b/packages/app-connect/src/once/mysql-store.ts @@ -0,0 +1,403 @@ +import { randomUUID } from 'node:crypto'; +import { + type OnceClaim, + OnceClaimLostError, + type OnceOutcome, + type OnceStore, + checkClaim, + checkOutcome, + trimReason, +} from './store'; + +/** + * The part of mysql2 the store uses: `query(sql, values)` resolving to + * mysql2's `[result, fields]` tuple. Pass a `mysql2/promise` Pool. Don't pass + * a connection the app also uses for transactions: the store's writes must + * commit on their own, or other instances can't see the claims, and the + * table's `CREATE TABLE IF NOT EXISTS` would commit the app's open transaction. + * Rows must come back as objects (the mysql2 default, not `rowsAsArray`). + * The server must be MySQL 8 or later; the table uses `utf8mb4_0900_bin`, + * which MariaDB doesn't have. Keep the connection charset utf8mb4 (the mysql2 + * default): with `utf8`/utf8mb3 and a non-strict `sql_mode`, MySQL cuts a key + * at its first character outside the BMP, and two keys can share a row. + */ +export interface SqlQueryRunner { + query(sql: string, values?: unknown[]): Promise; +} + +export interface MysqlOnceStoreOptions { + /** The table name. Defaults to `app_connect_once`. */ + table?: string; + /** + * Create the table on first use with `CREATE TABLE IF NOT EXISTS`. Defaults + * to true. Turn it off when migrations create it from `onceTableDdl()`. When + * the database user may not create tables, the store carries on as if a + * migration had made it. + */ + createTable?: boolean; + /** + * Unix milliseconds. Injected so tests control time. Leases are judged by + * the caller's clock, so instances' clocks should agree to well inside a lease. + */ + now?: () => number; +} + +export const DEFAULT_ONCE_TABLE = 'app_connect_once'; + +/** A claim that took longer than this to write has its lease renewed. */ +const LEASE_RENEW_AFTER_MS = 1000; + +const TABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/; + +function checkTable(table: unknown): string { + if (typeof table !== 'string' || !TABLE_NAME.test(table)) { + throw new TypeError( + `Invalid table name "${String(table)}": use letters, digits and underscores, at most 64 characters`, + ); + } + return table; +} + +/** + * The DDL for the once-only table (MySQL 8). The key is compared byte for + * byte (`utf8mb4_0900_bin`, which also doesn't pad), so keys that differ only + * in case, accents or trailing spaces stay apart. Rows hold the key, the claim + * and the outcome, never the work's data. Rows are kept; the `updated_at` + * index makes pruning old ones cheap. A pruned key can run again, so prune + * only rows older than the longest time a sender may redeliver or retry the + * same key. Prune finished rows and claims whose lease has passed, in small + * batches so claims aren't kept waiting, for example + * `DELETE FROM app_connect_once WHERE updated_at < ? AND (state <> 'claimed' OR lease_until < ?) LIMIT 1000`. + * The table is InnoDB with dynamic rows: the claims rely on its row locks, and + * the 255-character key needs its longer index limit. + */ +export function onceTableDdl(table?: string | null): string { + // The same default as the store, so a migration and a store given the same + // config value use the same table. + return `CREATE TABLE IF NOT EXISTS \`${checkTable(table ?? DEFAULT_ONCE_TABLE)}\` ( + once_key VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin NOT NULL PRIMARY KEY, + state VARCHAR(16) NOT NULL, + claim_token CHAR(36) NULL, + lease_until BIGINT NOT NULL, + reason VARCHAR(255) CHARACTER SET utf8mb4 NULL, + updated_at BIGINT NOT NULL, + KEY updated_at (updated_at) +) ENGINE=InnoDB ROW_FORMAT=DYNAMIC`; +} + +function errorFields(error: unknown): { code?: unknown; errno?: unknown } { + return typeof error === 'object' && error !== null + ? (error as { code?: unknown; errno?: unknown }) + : {}; +} + +function isDuplicateKey(error: unknown): boolean { + const { code, errno } = errorFields(error); + return code === 'ER_DUP_ENTRY' || errno === 1062; +} + +/** + * A deadlock or lock wait on a claim statement: another caller is inserting, + * releasing or pruning the same rows right now, so the key is busy. A deadlock comes back + * at once; a lock wait only after the server's `innodb_lock_wait_timeout`. + */ +function isLockConflict(error: unknown): boolean { + const { code, errno } = errorFields(error); + return ( + code === 'ER_LOCK_DEADLOCK' || + errno === 1213 || + code === 'ER_LOCK_WAIT_TIMEOUT' || + errno === 1205 + ); +} + +function isLockWait(error: unknown): boolean { + const { code, errno } = errorFields(error); + return code === 'ER_LOCK_WAIT_TIMEOUT' || errno === 1205; +} + +function isDeadlock(error: unknown): boolean { + const { code, errno } = errorFields(error); + return code === 'ER_LOCK_DEADLOCK' || errno === 1213; +} + +/** + * Runs a statement again when InnoDB picked it as a deadlock victim (with a + * prune, say). The victim's statement was rolled back, so running it again is + * safe. A lock wait isn't retried: it has already waited the server's timeout. + */ +async function retryDeadlock(run: () => Promise): Promise { + for (let attempt = 1; ; attempt += 1) { + try { + return await run(); + } catch (error: unknown) { + if (attempt >= 3 || !isDeadlock(error)) { + throw error; + } + } + } +} + +/** The database user may not create tables (CREATE command denied). */ +function isCreateDenied(error: unknown): boolean { + const { code, errno } = errorFields(error); + return code === 'ER_TABLEACCESS_DENIED_ERROR' || errno === 1142; +} + +/** The first element of mysql2's `[result, fields]` tuple. */ +function resultOf(response: unknown): unknown { + if (!Array.isArray(response)) { + throw new TypeError( + 'The SQL runner must resolve to a mysql2 [result, fields] tuple', + ); + } + return response[0]; +} + +function affectedRows(response: unknown): number { + const result = resultOf(response) as { affectedRows?: unknown } | undefined; + return typeof result?.affectedRows === 'number' ? result.affectedRows : 0; +} + +function insertCounted(response: unknown): boolean { + if (!Array.isArray(response)) { + return false; + } + return ( + (response[0] as { affectedRows?: unknown } | undefined)?.affectedRows === 1 + ); +} + +function firstRow( + response: unknown, +): { state: string; reason?: unknown } | undefined { + const rows = resultOf(response); + if (!Array.isArray(rows)) { + throw new TypeError('The SQL runner must answer a SELECT with rows'); + } + const row: unknown = rows[0]; + if (row === undefined) { + return undefined; + } + const state = (row as { state?: unknown } | null)?.state; + if (typeof state !== 'string') { + // rowsAsArray or nestTables: reading it as in_flight would never end. + throw new TypeError( + 'The SQL runner must return rows as objects keyed by column name', + ); + } + return { state, reason: (row as { reason?: unknown }).reason }; +} + +/** + * A `OnceStore` in a MySQL 8 database, shared by every instance of the app. + * + * A claim is a conditional insert keyed by the once key, so it holds across + * processes. A claim that was never completed can be taken over once its + * lease has passed, so a crash delays the work instead of losing it. Each + * claim carries a token, so only the caller that holds it can record its + * outcome or release it. + */ +export function createMysqlOnceStore( + sql: SqlQueryRunner, + options: MysqlOnceStoreOptions = {}, +): OnceStore { + const tableName = checkTable(options.table ?? DEFAULT_ONCE_TABLE); + const table = `\`${tableName}\``; + const ddl = onceTableDdl(tableName); + const now = options.now ?? Date.now; + const createTable = options.createTable ?? true; + let schemaReady: Promise | null = null; + + function ensureSchema(): Promise { + if (!createTable) { + return Promise.resolve(); + } + if (!schemaReady) { + schemaReady = (async () => { + try { + await sql.query(ddl, []); + } catch (error: unknown) { + // A least-privilege user: the table comes from a migration. If it + // doesn't exist, the first statement on it says so. + if (!isCreateDenied(error)) { + throw error; + } + } + })().catch((error: unknown) => { + // Try again on the next call instead of remembering the failure. + schemaReady = null; + throw error; + }); + } + return schemaReady; + } + + /** + * A statement that waited on a lock (behind a prune, say) used up part of the + * lease it wrote. Renew the lease from now, so the caller gets all of it, or + * answer in_flight if another caller took the key over in the meantime. + */ + async function withFullLease( + key: string, + token: string, + at: number, + leaseMs: number, + ): Promise { + const after = now(); + // Renew once the wait used a real share of the lease, short leases included. + if (after - at < Math.min(LEASE_RENEW_AFTER_MS, leaseMs / 4)) { + return { status: 'claimed', token }; + } + let renewed: unknown; + try { + renewed = await retryDeadlock(() => + sql.query( + `UPDATE ${table} SET lease_until = ?, updated_at = ? + WHERE once_key = ? AND state = 'claimed' AND claim_token = ?`, + [after + leaseMs, after, key, token], + ), + ); + } catch (error: unknown) { + // Don't leave the key held under a token nobody will use: give it back, + // so a retry can claim it, then report the failure (a lock conflict + // reads as in_flight). After a lock wait the row is still locked, so a + // DELETE would only wait out the timeout again; the key then stays held + // until its lease passes. + // If the DELETE fails too, the key is held until its lease passes. + if (!isLockWait(error)) { + await retryDeadlock(() => + sql.query( + `DELETE FROM ${table} WHERE once_key = ? AND state = 'claimed' AND claim_token = ?`, + [key, token], + ), + ).catch(() => undefined); + } + throw error; + } + return affectedRows(renewed) === 1 + ? { status: 'claimed', token } + : { status: 'in_flight' }; + } + + /** One claim attempt; null when the key's row vanished mid-attempt. */ + async function tryClaim( + key: string, + leaseMs: number, + ): Promise { + const at = now(); + const token = randomUUID(); + let inserted = false; + try { + const response = await sql.query( + `INSERT INTO ${table} (once_key, state, claim_token, lease_until, updated_at) VALUES (?, 'claimed', ?, ?, ?)`, + [key, token, at + leaseMs, at], + ); + if (!insertCounted(response)) { + // Checked before the work runs, not after it in complete(). Take back + // the row it may have written, so the key isn't held by nobody. + await sql + .query( + `DELETE FROM ${table} WHERE once_key = ? AND claim_token = ?`, + [key, token], + ) + .catch(() => undefined); + throw new TypeError( + 'The SQL runner must resolve to a mysql2 [result, fields] tuple with affectedRows', + ); + } + inserted = true; + } catch (error: unknown) { + if (!isDuplicateKey(error)) { + throw error; + } + } + if (inserted) { + return withFullLease(key, token, at, leaseMs); + } + // The key is known. Take it over only if its earlier claim has expired. + const takeover = await sql.query( + `UPDATE ${table} SET claim_token = ?, lease_until = ?, updated_at = ? + WHERE once_key = ? AND state = 'claimed' AND lease_until < ?`, + [token, at + leaseMs, at, key, at], + ); + if (affectedRows(takeover) === 1) { + return withFullLease(key, token, at, leaseMs); + } + const row = firstRow( + await sql.query(`SELECT state, reason FROM ${table} WHERE once_key = ?`, [ + key, + ]), + ); + if (row?.state === 'done') { + return { status: 'done' }; + } + if (row?.state === 'refused') { + return { + status: 'refused', + reason: typeof row.reason === 'string' ? row.reason : undefined, + }; + } + // Held by another caller, or (no row) released between the statements, so + // the key is free: the caller tries the insert once more. + return row === undefined ? null : { status: 'in_flight' }; + } + + return { + async claim(key: string, leaseMs: number): Promise { + checkClaim(key, leaseMs); + await ensureSchema(); + try { + // A deadlock victim was rolled back, so the whole claim runs again. + const first = await retryDeadlock(() => tryClaim(key, leaseMs)); + return ( + first ?? + (await retryDeadlock(() => tryClaim(key, leaseMs))) ?? { + status: 'in_flight', + } + ); + } catch (error: unknown) { + // A lock wait, or a deadlock that keeps coming back, on any of the + // claim's statements (with a release, a takeover or a prune of the + // same rows) means the key is busy. + if (isLockConflict(error)) { + return { status: 'in_flight' }; + } + throw error; + } + }, + + async complete( + key: string, + token: string, + outcome: OnceOutcome, + ): Promise { + checkOutcome(outcome); + await ensureSchema(); + const reason = + outcome.status === 'refused' + ? (trimReason(outcome.reason) ?? null) + : null; + const result = await retryDeadlock(() => + sql.query( + `UPDATE ${table} SET state = ?, reason = ?, claim_token = NULL, updated_at = ? + WHERE once_key = ? AND state = 'claimed' AND claim_token = ?`, + [outcome.status, reason, now(), key, token], + ), + ); + if (affectedRows(result) !== 1) { + throw new OnceClaimLostError(key); + } + }, + + async release(key: string, token: string): Promise { + await ensureSchema(); + await retryDeadlock(() => + sql.query( + `DELETE FROM ${table} WHERE once_key = ? AND state = 'claimed' AND claim_token = ?`, + [key, token], + ), + ); + }, + }; +} diff --git a/packages/app-connect/src/once/once.test.ts b/packages/app-connect/src/once/once.test.ts new file mode 100644 index 000000000..7d92bf631 --- /dev/null +++ b/packages/app-connect/src/once/once.test.ts @@ -0,0 +1,315 @@ +import { describe, expect, it, vi } from 'vitest'; +import { createMemoryOnceStore } from './memory-store'; +import { OnceNotRecordedError, Refused, once } from './once'; +import type { OnceClaim, OnceStore } from './store'; + +function clockedStore() { + const clock = { now: 1_000 }; + return { clock, store: createMemoryOnceStore({ now: () => clock.now }) }; +} + +describe('once', () => { + it('runs the work and returns its value, then reports a duplicate', async () => { + const { store } = clockedStore(); + const fn = vi.fn(async () => 'sent'); + expect(await once(store, 'evt_1', fn)).toEqual({ + status: 'done', + value: 'sent', + }); + expect(await once(store, 'evt_1', fn)).toEqual({ + status: 'duplicate', + outcome: { status: 'done' }, + }); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it('accepts work that is not async', async () => { + const { store } = clockedStore(); + expect(await once(store, 'evt_1', () => 42)).toEqual({ + status: 'done', + value: 42, + }); + }); + + it('runs the work once when two callers race for the same key', async () => { + const { store } = clockedStore(); + let release: () => void = () => {}; + const gate = new Promise((resolve) => { + release = resolve; + }); + const fn = vi.fn(async () => { + await gate; + return 'sent'; + }); + const first = once(store, 'evt_1', fn); + const second = await once(store, 'evt_1', fn); + release(); + expect(second).toEqual({ status: 'in_flight' }); + expect(await first).toEqual({ status: 'done', value: 'sent' }); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it('records a Refused for good and returns its reason', async () => { + const { clock, store } = clockedStore(); + const fn = vi.fn(async () => { + throw new Refused('invalid_email'); + }); + expect(await once(store, 'evt_1', fn)).toEqual({ + status: 'refused', + reason: 'invalid_email', + }); + clock.now += 24 * 3600_000; + expect(await once(store, 'evt_1', fn)).toEqual({ + status: 'duplicate', + outcome: { status: 'refused', reason: 'invalid_email' }, + }); + expect(fn).toHaveBeenCalledTimes(1); + }); + + it('recognizes a Refused from another copy of this package by its brand', async () => { + const { store } = clockedStore(); + const foreign = Object.assign(new Error('gone'), { + reason: 'gone', + [Symbol.for('@godaddy/app-connect/once/refused')]: true, + }); + expect( + await once(store, 'evt_1', async () => { + throw foreign; + }), + ).toEqual({ status: 'refused', reason: 'gone' }); + }); + + it('still records a refusal whose reason cannot become text', async () => { + const { store } = clockedStore(); + const foreign = Object.assign(new Error('odd'), { + reason: Object.create(null), + [Symbol.for('@godaddy/app-connect/once/refused')]: true, + }); + expect( + await once(store, 'evt_1', async () => { + throw foreign; + }), + ).toEqual({ status: 'refused', reason: '' }); + }); + + it('never runs the work on a claim status it does not know', async () => { + const store: OnceStore = { + claim: async () => ({ status: 'busy' }) as unknown as OnceClaim, + complete: async () => {}, + release: async () => {}, + }; + const fn = vi.fn(async () => 'sent'); + await expect(once(store, 'evt_1', fn)).rejects.toThrow(TypeError); + expect(fn).not.toHaveBeenCalled(); + }); + + it('releases the claim and rethrows when the thrown value can not be inspected', async () => { + const { store } = clockedStore(); + const { proxy, revoke } = Proxy.revocable({}, {}); + revoke(); + await expect( + once(store, 'evt_1', async () => { + throw proxy; + }), + ).rejects.toBe(proxy); + // Released, so a retry runs the work. + expect(await once(store, 'evt_1', async () => 'sent')).toEqual({ + status: 'done', + value: 'sent', + }); + }); + + it('still records a refusal whose reason getter throws', async () => { + const { store } = clockedStore(); + const foreign = Object.defineProperty( + Object.assign(new Error('odd'), { + [Symbol.for('@godaddy/app-connect/once/refused')]: true, + }), + 'reason', + { + get() { + throw new Error('no reason for you'); + }, + }, + ); + expect( + await once(store, 'evt_1', async () => { + throw foreign; + }), + ).toEqual({ status: 'refused', reason: '' }); + expect(await once(store, 'evt_1', async () => 'sent')).toEqual({ + status: 'duplicate', + outcome: { status: 'refused', reason: '' }, + }); + }); + + it('reports a recorded refusal without a reason with an empty one', async () => { + const store: OnceStore = { + claim: async () => ({ status: 'refused' }), + complete: async () => {}, + release: async () => {}, + }; + expect(await once(store, 'evt_1', async () => 'sent')).toEqual({ + status: 'duplicate', + outcome: { status: 'refused', reason: '' }, + }); + }); + + it('stores a refusal reason that is not a string as text', async () => { + const { store } = clockedStore(); + const foreign = Object.assign(new Error('422'), { + reason: 422, + [Symbol.for('@godaddy/app-connect/once/refused')]: true, + }); + expect( + await once(store, 'evt_1', async () => { + throw foreign; + }), + ).toEqual({ status: 'refused', reason: '422' }); + expect(await once(store, 'evt_1', async () => 'sent')).toEqual({ + status: 'duplicate', + outcome: { status: 'refused', reason: '422' }, + }); + }); + + it('releases the key and rethrows any other error, so a retry runs again', async () => { + const { store } = clockedStore(); + const failure = new Error('vendor unavailable'); + await expect( + once(store, 'evt_1', async () => { + throw failure; + }), + ).rejects.toBe(failure); + expect(await once(store, 'evt_1', async () => 'sent')).toEqual({ + status: 'done', + value: 'sent', + }); + }); + + it('rethrows the work error even when the release fails', async () => { + const { store } = clockedStore(); + const failing: OnceStore = { + ...store, + release: async () => { + throw new Error('db down'); + }, + }; + const failure = new Error('vendor unavailable'); + await expect( + once(failing, 'evt_1', async () => { + throw failure; + }), + ).rejects.toBe(failure); + const onReleaseError = vi.fn(() => { + throw new Error('logger broke'); + }); + await expect( + once( + failing, + 'evt_2', + async () => { + throw failure; + }, + { onReleaseError }, + ), + ).rejects.toBe(failure); + expect(onReleaseError).toHaveBeenCalledWith( + expect.objectContaining({ message: 'db down' }), + 'evt_2', + ); + }); + + it('takes over a key whose lease passed, after a crash mid-work', async () => { + const { clock, store } = clockedStore(); + const claim = await store.claim('evt_1', 1_000); + expect(claim.status).toBe('claimed'); + expect( + await once(store, 'evt_1', async () => 'x', { leaseMs: 1_000 }), + ).toEqual({ status: 'in_flight' }); + clock.now += 1_001; + expect( + await once(store, 'evt_1', async () => 'x', { leaseMs: 1_000 }), + ).toEqual({ status: 'done', value: 'x' }); + }); + + it('throws OnceNotRecordedError when the work finished but could not be recorded', async () => { + const { clock, store } = clockedStore(); + // The lease passes during the work and another caller takes the key over. + const result = once( + store, + 'evt_1', + async () => { + clock.now += 2_000; + await store.claim('evt_1', 60_000); + return 'sent'; + }, + { leaseMs: 1_000 }, + ); + await expect(result).rejects.toBeInstanceOf(OnceNotRecordedError); + await expect(result).rejects.toMatchObject({ + key: 'evt_1', + outcome: { status: 'done' }, + }); + const error = (await result.catch((caught: unknown) => caught)) as + | OnceNotRecordedError + | undefined; + expect(error?.value).toBe('sent'); + // Kept out of serialized logs: it may hold vendor or shopper data. + expect(Object.keys(error ?? {})).not.toContain('value'); + }); + + it('records a refusal reason with lone surrogates as well-formed text', async () => { + const { store } = clockedStore(); + expect( + await once(store, 'evt_1', async () => { + throw new Refused('bad_\uD800'); + }), + ).toEqual({ status: 'refused', reason: 'bad_�' }); + }); + + it('never lets a rejecting onReleaseError go unhandled', async () => { + const { store } = clockedStore(); + const failing: OnceStore = { + ...store, + release: async () => { + throw new Error('db down'); + }, + }; + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + const failure = new Error('vendor unavailable'); + await expect( + once( + failing, + 'evt_1', + async () => { + throw failure; + }, + { onReleaseError: async () => Promise.reject(new Error('log down')) }, + ), + ).rejects.toBe(failure); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } + }); + + it('refuses a key that is empty or too long, and a bad lease', async () => { + const { store } = clockedStore(); + const fn = vi.fn(); + await expect(once(store, '', fn)).rejects.toThrow(TypeError); + await expect(once(store, 'x'.repeat(256), fn)).rejects.toThrow(TypeError); + await expect(once(store, 'evt_\uD800', fn)).rejects.toThrow(TypeError); + await expect(once(store, '😀'.repeat(255), fn)).resolves.toMatchObject({ + status: 'done', + }); + for (const leaseMs of [0, -1, 1.5, Number.NaN]) { + await expect(once(store, 'evt_1', fn, { leaseMs })).rejects.toThrow( + TypeError, + ); + } + expect(fn).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/app-connect/src/once/once.ts b/packages/app-connect/src/once/once.ts new file mode 100644 index 000000000..23454eaf3 --- /dev/null +++ b/packages/app-connect/src/once/once.ts @@ -0,0 +1,231 @@ +import { + type OnceOutcome, + type OnceStore, + checkClaim, + trimReason, +} from './store'; + +const REFUSED = Symbol.for('@godaddy/app-connect/once/refused'); + +/** + * Throw from the work passed to `once` when the work was refused for good, for + * example a vendor answered 422 for this exact input. The refusal is recorded, + * so a retry of the same key is not run again. + * + * The reason is stored, so keep it a short code (`invalid_email`), never + * vendor text or shopper data. It is cut to 255 characters. + */ +export class Refused extends Error { + readonly reason: string; + readonly [REFUSED] = true; + + constructor(reason: string, options?: { cause?: unknown }) { + super(reason, options); + this.name = 'Refused'; + this.reason = reason; + } +} + +/** A branded error from elsewhere may carry a reason that isn't a string. */ +function reasonText(error: { reason?: unknown }): string { + try { + const reason = error.reason; + return typeof reason === 'string' ? reason : String(reason ?? ''); + } catch { + // A reason getter that throws, or an object with no usable toString: + // still record the refusal. + return ''; + } +} + +function isRefused(error: unknown): error is Refused { + // A brand, not only instanceof, so a second copy of this package still matches. + try { + return ( + error instanceof Refused || + (typeof error === 'object' && + error !== null && + (error as { [REFUSED]?: unknown })[REFUSED] === true) + ); + } catch { + // A revoked Proxy or a throwing getter: not a refusal, so the claim is + // still released and the work's own error rethrown. + return false; + } +} + +/** + * Thrown by `once` when the work finished but its outcome could not be + * recorded. Answer the delivery as failed, so it is retried. What the retry + * finds depends on the cause: + * - the store failed: the key stays claimed until its lease passes, then the + * work runs again; + * - the claim was lost (`cause` is `OnceClaimLostError`): the lease passed and + * another caller took the key over, so it may already be done or running. + * + * `value` is what the work returned, when it finished without `Refused`. It + * may hold vendor or shopper data, so it isn't enumerable: loggers that + * serialize errors leave it out. + */ +export class OnceNotRecordedError extends Error { + readonly key: string; + readonly outcome: OnceOutcome; + declare readonly value: unknown; + + constructor( + key: string, + outcome: OnceOutcome, + cause: unknown, + value?: unknown, + ) { + super( + // The key is on `.key`, not in the message, in case it names a shopper. + `The work finished (${outcome.status}) but its outcome was not recorded`, + { cause }, + ); + this.name = 'OnceNotRecordedError'; + this.key = key; + this.outcome = outcome; + Object.defineProperty(this, 'value', { value, enumerable: false }); + } +} + +/** What `once` did with the key. */ +export type OnceResult = + /** The work ran now and finished. */ + | { status: 'done'; value: T } + /** The work already finished earlier with this outcome, so it did not run. */ + | { + status: 'duplicate'; + outcome: { status: 'done' } | { status: 'refused'; reason: string }; + } + /** Another caller is running the work now, so it did not run. Retry later. */ + | { status: 'in_flight' } + /** The work ran now and threw `Refused`; the refusal is recorded. */ + | { status: 'refused'; reason: string }; + +export interface OnceOptions { + /** + * How long a claim keeps the key from other callers, in milliseconds. Make + * it longer than the work can take: once it passes, another caller may take + * the key over and run the work again. Defaults to 5 minutes. + */ + leaseMs?: number; + /** + * Called when the work threw and releasing its claim then failed too. The + * work's error is still the one thrown; until the lease passes, retries of + * the key answer `in_flight`. Pass your logger here to see why, wrapped so + * it keeps its `this`: `(err, key) => logger.error({ err, key }, 'release failed')`. + * An error from the callback itself is dropped. + */ + onReleaseError?: (error: unknown, key: string) => void | Promise; +} + +export const DEFAULT_LEASE_MS = 5 * 60 * 1000; + +/** + * Records one outcome for `key` across every process that shares `store`, and + * runs `fn` for it one caller at a time. Once an outcome is recorded, `fn` is + * not run for that key again. + * + * - The key is claimed first. A key that already finished returns `duplicate` + * with its recorded outcome; a key another caller holds returns `in_flight`. + * - When `fn` returns, the key is recorded as done and `done` is returned. + * - When `fn` throws `Refused`, the refusal is recorded and `refused` is + * returned, so the same key is never tried again. + * - When `fn` throws anything else, the claim is released and the error is + * rethrown, so a retry can run the work again. + * + * A claim whose lease passes (the process crashed, or the work ran long) is + * taken over by the next caller, so `fn` can run more than once in that case: + * make it safe to repeat, for example by sending a stable idempotency key built + * with `deriveId`. + * + * @throws TypeError for a bad key or lease, or a store answering a claim + * status it doesn't know (before `fn` runs) + * @throws whatever `store.claim` throws, such as a lost database connection + * (before `fn` runs) + * @throws whatever `fn` throws other than `Refused`, after releasing the claim + * @throws OnceNotRecordedError when `fn` finished but the outcome could not be recorded + * + * After any of these, this caller didn't record an outcome: answer the + * delivery as failed so it's retried. The key may still be done, though: when + * `OnceNotRecordedError`'s cause is `OnceClaimLostError`, another caller took + * it over, and a lost database response can hide a write that committed. The + * retry's `once` call tells you which. + */ +export async function once( + store: OnceStore, + key: string, + fn: () => Promise | T, + options: OnceOptions = {}, +): Promise> { + const leaseMs = options.leaseMs ?? DEFAULT_LEASE_MS; + checkClaim(key, leaseMs); + + const claim = await store.claim(key, leaseMs); + if (claim.status === 'in_flight') { + return { status: 'in_flight' }; + } + if (claim.status === 'done') { + return { status: 'duplicate', outcome: { status: 'done' } }; + } + if (claim.status === 'refused') { + return { + status: 'duplicate', + // The same shape as a fresh refusal: always a string. + outcome: { status: 'refused', reason: claim.reason ?? '' }, + }; + } + if (claim.status !== 'claimed' || typeof claim.token !== 'string') { + // A custom store answering something else: never run the work on it. + throw new TypeError( + `once: the store answered an unknown claim status "${String((claim as { status?: unknown }).status)}"`, + ); + } + + const record = async ( + outcome: OnceOutcome, + value?: unknown, + ): Promise => { + try { + await store.complete(key, claim.token, outcome); + } catch (error: unknown) { + throw new OnceNotRecordedError(key, outcome, error, value); + } + }; + + let value: T; + try { + value = await fn(); + } catch (error: unknown) { + if (isRefused(error)) { + // A branded error from elsewhere may carry a reason that isn't a string. + const reason = trimReason(reasonText(error)) ?? ''; + await record({ status: 'refused', reason }); + return { status: 'refused', reason }; + } + try { + await store.release(key, claim.token); + } catch (releaseError: unknown) { + // The claim expires after its lease, so the work is retried even when + // the release fails. The work's own error is the one worth throwing. + // A failing callback, sync or async, must not hide the work's error. + try { + const reported: unknown = options.onReleaseError?.(releaseError, key); + if ( + typeof (reported as { catch?: unknown } | undefined)?.catch === + 'function' + ) { + (reported as Promise).catch(() => undefined); + } + } catch { + // Ignored, as above. + } + } + throw error; + } + + await record({ status: 'done' }, value); + return { status: 'done', value }; +} diff --git a/packages/app-connect/src/once/store-contract.test-helper.ts b/packages/app-connect/src/once/store-contract.test-helper.ts new file mode 100644 index 000000000..a365fbca4 --- /dev/null +++ b/packages/app-connect/src/once/store-contract.test-helper.ts @@ -0,0 +1,143 @@ +import { expect, it } from 'vitest'; +import { OnceClaimLostError, type OnceOutcome, type OnceStore } from './store'; + +export interface Clock { + now: number; +} + +/** + * The semantics every OnceStore adapter shares. `makeStore` builds an empty + * store that reads the time from the clock it is given. + */ +export function onceStoreContract( + makeStore: (clock: () => number) => Promise | OnceStore, +): void { + async function setup() { + const clock: Clock = { now: 1_000 }; + const store = await makeStore(() => clock.now); + return { clock, store }; + } + + it('claims a new key once, then reports it done after completion', async () => { + const { store } = await setup(); + const claim = await store.claim('evt_1', 60_000); + expect(claim.status).toBe('claimed'); + expect(await store.claim('evt_1', 60_000)).toEqual({ status: 'in_flight' }); + if (claim.status !== 'claimed') throw new Error('unreachable'); + await store.complete('evt_1', claim.token, { status: 'done' }); + expect(await store.claim('evt_1', 60_000)).toEqual({ status: 'done' }); + }); + + it('records a refusal with its reason, and never runs it again', async () => { + const { clock, store } = await setup(); + const claim = await store.claim('evt_1', 60_000); + if (claim.status !== 'claimed') throw new Error('not claimed'); + await store.complete('evt_1', claim.token, { + status: 'refused', + reason: 'invalid_email', + }); + clock.now += 10 * 60_000; + expect(await store.claim('evt_1', 60_000)).toEqual({ + status: 'refused', + reason: 'invalid_email', + }); + }); + + it('cuts a long refusal reason to 255 characters', async () => { + const { store } = await setup(); + const claim = await store.claim('evt_1', 60_000); + if (claim.status !== 'claimed') throw new Error('not claimed'); + await store.complete('evt_1', claim.token, { + status: 'refused', + reason: 'é'.repeat(300), + }); + expect(await store.claim('evt_1', 60_000)).toEqual({ + status: 'refused', + reason: 'é'.repeat(255), + }); + }); + + it('holds a claim until its lease has passed, then lets another caller take it over', async () => { + const { clock, store } = await setup(); + const first = await store.claim('evt_1', 60_000); + if (first.status !== 'claimed') throw new Error('not claimed'); + clock.now += 60_000; + expect(await store.claim('evt_1', 60_000)).toEqual({ status: 'in_flight' }); + clock.now += 1; + const second = await store.claim('evt_1', 60_000); + expect(second.status).toBe('claimed'); + if (second.status !== 'claimed') throw new Error('not claimed'); + expect(second.token).not.toBe(first.token); + + // The caller that lost the claim can neither record nor release it. + await expect( + store.complete('evt_1', first.token, { status: 'done' }), + ).rejects.toBeInstanceOf(OnceClaimLostError); + await store.release('evt_1', first.token); + expect(await store.claim('evt_1', 60_000)).toEqual({ status: 'in_flight' }); + + await store.complete('evt_1', second.token, { status: 'done' }); + expect(await store.claim('evt_1', 60_000)).toEqual({ status: 'done' }); + }); + + it('forgets a released claim, so a retry can run the work again', async () => { + const { store } = await setup(); + const claim = await store.claim('evt_1', 60_000); + if (claim.status !== 'claimed') throw new Error('not claimed'); + await store.release('evt_1', claim.token); + expect((await store.claim('evt_1', 60_000)).status).toBe('claimed'); + }); + + it('never releases or reopens a finished key', async () => { + const { store } = await setup(); + const claim = await store.claim('evt_1', 60_000); + if (claim.status !== 'claimed') throw new Error('not claimed'); + await store.complete('evt_1', claim.token, { status: 'done' }); + await store.release('evt_1', claim.token); + await expect( + store.complete('evt_1', claim.token, { status: 'refused', reason: 'x' }), + ).rejects.toBeInstanceOf(OnceClaimLostError); + expect(await store.claim('evt_1', 60_000)).toEqual({ status: 'done' }); + }); + + it('refuses to record a key nobody claimed', async () => { + const { store } = await setup(); + await expect( + store.complete('evt_unknown', 'token', { status: 'done' }), + ).rejects.toBeInstanceOf(OnceClaimLostError); + }); + + it('keeps keys apart that differ only in case, accents or trailing spaces', async () => { + const { store } = await setup(); + for (const key of ['evt_a', 'EVT_A', 'evt_á', 'evt_a ']) { + expect((await store.claim(key, 60_000)).status).toBe('claimed'); + } + }); + + it('refuses a bad key or lease when called directly', async () => { + const { store } = await setup(); + for (const key of ['', 'x'.repeat(256), 'evt_\uD800']) { + await expect(store.claim(key, 60_000)).rejects.toThrow(TypeError); + } + for (const leaseMs of [0, -1, 1.5, Number.NaN, undefined]) { + await expect( + store.claim('evt_1', leaseMs as unknown as number), + ).rejects.toThrow(TypeError); + } + expect((await store.claim('evt_1', 60_000)).status).toBe('claimed'); + }); + + it('refuses an outcome that is neither done nor refused', async () => { + const { store } = await setup(); + const claim = await store.claim('evt_1', 60_000); + if (claim.status !== 'claimed') throw new Error('not claimed'); + await expect( + store.complete('evt_1', claim.token, { + status: 'failed', + } as unknown as OnceOutcome), + ).rejects.toThrow(TypeError); + // The claim is untouched and can still be recorded. + await store.complete('evt_1', claim.token, { status: 'done' }); + expect(await store.claim('evt_1', 60_000)).toEqual({ status: 'done' }); + }); +} diff --git a/packages/app-connect/src/once/store.ts b/packages/app-connect/src/once/store.ts new file mode 100644 index 000000000..c3d180d3d --- /dev/null +++ b/packages/app-connect/src/once/store.ts @@ -0,0 +1,119 @@ +/** + * What a store says about a key when a caller tries to claim it. + * - `claimed`: this caller now holds the key until it completes or releases it, + * or until the lease passes. + * - `done` / `refused`: the work for the key already finished with that outcome. + * - `in_flight`: another caller holds an unexpired claim. + */ +export type OnceClaim = + | { status: 'claimed'; token: string } + | { status: 'done' } + | { status: 'refused'; reason?: string } + | { status: 'in_flight' }; + +/** The final outcome recorded for a key. */ +export type OnceOutcome = + | { status: 'done' } + | { status: 'refused'; reason?: string }; + +/** + * Where `once` keeps its claims. Every adapter has the same semantics: + * - `claim` is atomic across every process that shares the store. A new key is + * claimed. A claimed key whose lease has passed is taken over, so a crash + * delays the work instead of losing it. Any other claimed key is `in_flight`. + * - `complete` records the outcome for good, and only for the caller holding + * the claim (`token`). It throws when that caller no longer holds it. + * - `release` forgets the caller's claim, so a retry can run the work again. + * It does nothing when that caller no longer holds the claim. + */ +export interface OnceStore { + claim(key: string, leaseMs: number): Promise; + complete(key: string, token: string, outcome: OnceOutcome): Promise; + release(key: string, token: string): Promise; +} + +/** + * Thrown by a store's `complete` when the caller no longer holds the claim, + * for example because its lease passed and another caller took the key over. + */ +export class OnceClaimLostError extends Error { + readonly key: string; + + constructor(key: string) { + // The key is on `.key`, not in the message, in case it names a shopper. + super('The claim is no longer held, so its outcome was not recorded'); + this.name = 'OnceClaimLostError'; + this.key = key; + } +} + +/** A lone surrogate: a string that is not well-formed UTF-16. */ +const LONE_SURROGATE = + /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? MAX_KEY_LENGTH) { + throw new TypeError( + `once: the key must be at most ${MAX_KEY_LENGTH} characters; derive a shorter one with deriveId`, + ); + } + if (!Number.isSafeInteger(leaseMs) || leaseMs <= 0) { + throw new TypeError('once: leaseMs must be a positive whole number'); + } +} + +/** + * Checks an outcome before a store records it, so untyped code can't write a + * state that no later claim understands. + */ +export function checkOutcome(outcome: OnceOutcome): void { + const status = (outcome as { status?: unknown } | null)?.status; + if (status !== 'done' && status !== 'refused') { + throw new TypeError( + `once: an outcome must be done or refused, not "${String(status)}"`, + ); + } +} + +export function trimReason(reason: string | undefined): string | undefined { + if (reason === undefined) { + return undefined; + } + // Lone surrogates become U+FFFD, as they would on the way to a database, so + // every store reads the same reason back. Then cut by code point, so a + // character outside the BMP is never split. + const wellFormed = reason.replace(LONE_SURROGATES, '\u{FFFD}'); + const characters = Array.from(wellFormed); + return characters.length > MAX_REASON_LENGTH + ? characters.slice(0, MAX_REASON_LENGTH).join('') + : wellFormed; +} diff --git a/packages/app-connect/tsdown.config.ts b/packages/app-connect/tsdown.config.ts index 96e56fc98..0fbc80f74 100644 --- a/packages/app-connect/tsdown.config.ts +++ b/packages/app-connect/tsdown.config.ts @@ -5,7 +5,8 @@ export default defineConfig({ 'src/index.ts', 'src/express/index.ts', 'src/next/index.ts', - 'src/tanstack/index.ts' + 'src/tanstack/index.ts', + 'src/once/index.ts' ], plugins: [], tsconfig: './tsconfig.json', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 396ae3142..afac7310a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -167,6 +167,9 @@ importers: '@vitest/coverage-v8': specifier: 5.0.0 version: 5.0.0(vitest@5.0.0) + mysql2: + specifier: 3.24.6 + version: 3.24.6(@types/node@22.18.12) pino-pretty: specifier: ^13.0.0 version: 13.1.2 @@ -3285,6 +3288,10 @@ packages: resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} engines: {node: '>= 0.4'} + aws-ssl-profiles@1.1.2: + resolution: {integrity: sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==} + engines: {node: '>= 6.0.0'} + axe-core@4.10.3: resolution: {integrity: sha512-Xm7bpRXnDSX2YE2YFfBk2FnF0ep6tmG7xPh8iHee8MIcrgq762Nkce856dYtJYLkuIoYZvGfTs/PbZhideTcEg==} engines: {node: '>=4'} @@ -3952,6 +3959,9 @@ packages: functions-have-names@1.2.3: resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==} + generate-function@2.3.1: + resolution: {integrity: sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==} + gensync@1.0.0-beta.2: resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==} engines: {node: '>=6.9.0'} @@ -4236,6 +4246,9 @@ packages: is-promise@4.0.0: resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==} + is-property@1.0.2: + resolution: {integrity: sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==} + is-regex@1.2.1: resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} engines: {node: '>= 0.4'} @@ -4459,6 +4472,9 @@ packages: lodash@4.17.21: resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} + long@5.3.2: + resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==} + loose-envify@1.4.0: resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} hasBin: true @@ -4473,6 +4489,10 @@ packages: lru-cache@5.1.1: resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==} + lru.min@1.1.5: + resolution: {integrity: sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==} + engines: {bun: '>=1.0.0', deno: '>=1.30.0', node: '>=8.0.0'} + lucide-react@0.475.0: resolution: {integrity: sha512-NJzvVu1HwFVeZ+Gwq2q00KygM1aBhy/ZrhY9FsAgJtpB+E4R7uxRk9M2iKvHa6/vNxZydIB59htha4c2vvwvVg==} peerDependencies: @@ -4558,9 +4578,19 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + mysql2@3.24.6: + resolution: {integrity: sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==} + engines: {node: '>= 8.0'} + peerDependencies: + '@types/node': '>= 8' + mz@2.7.0: resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} + named-placeholders@1.1.6: + resolution: {integrity: sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==} + engines: {node: '>=8.0.0'} + nanoid@3.3.11: resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -5242,6 +5272,10 @@ packages: sprintf-js@1.0.3: resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==} + sql-escaper@1.9.1: + resolution: {integrity: sha512-4p522TVYaJXTbMlYgAwacjyg3EJyYe9KYWYlYJVwZG1YjtzxU5m5iSzsZoGI69Po7j3i/2tKlpZQi7uvhTL+WA==} + engines: {bun: '>=1.0.0', deno: '>=2.0.0', node: '>=12.0.0'} + srvx@0.8.16: resolution: {integrity: sha512-hmcGW4CgroeSmzgF1Ihwgl+Ths0JqAJ7HwjP2X7e3JzY7u4IydLMcdnlqGQiQGUswz+PO9oh/KtCpOISIvs9QQ==} engines: {node: '>=20.16.0'} @@ -8448,6 +8482,8 @@ snapshots: dependencies: possible-typed-array-names: 1.1.0 + aws-ssl-profiles@1.1.2: {} + axe-core@4.10.3: {} axobject-query@4.1.0: {} @@ -9275,6 +9311,10 @@ snapshots: functions-have-names@1.2.3: {} + generate-function@2.3.1: + dependencies: + is-property: 1.0.2 + gensync@1.0.0-beta.2: {} get-intrinsic@1.3.0: @@ -9561,6 +9601,8 @@ snapshots: is-promise@4.0.0: {} + is-property@1.0.2: {} + is-regex@1.2.1: dependencies: call-bound: 1.0.4 @@ -9767,6 +9809,8 @@ snapshots: lodash@4.17.21: {} + long@5.3.2: {} + loose-envify@1.4.0: dependencies: js-tokens: 4.0.0 @@ -9779,6 +9823,8 @@ snapshots: dependencies: yallist: 3.1.1 + lru.min@1.1.5: {} + lucide-react@0.475.0(react@19.2.0): dependencies: react: 19.2.0 @@ -9850,12 +9896,27 @@ snapshots: ms@2.1.3: {} + mysql2@3.24.6(@types/node@22.18.12): + dependencies: + '@types/node': 22.18.12 + aws-ssl-profiles: 1.1.2 + generate-function: 2.3.1 + iconv-lite: 0.7.3 + long: 5.3.2 + lru.min: 1.1.5 + named-placeholders: 1.1.6 + sql-escaper: 1.9.1 + mz@2.7.0: dependencies: any-promise: 1.3.0 object-assign: 4.1.1 thenify-all: 1.6.0 + named-placeholders@1.1.6: + dependencies: + lru.min: 1.1.5 + nanoid@3.3.11: {} nanoid@3.3.19: {} @@ -10615,6 +10676,8 @@ snapshots: sprintf-js@1.0.3: {} + sql-escaper@1.9.1: {} + srvx@0.8.16: {} stackback@0.0.2: {}