diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 1ad899d..0000000 Binary files a/.DS_Store and /dev/null differ diff --git a/.changeset/hardening-and-packaging.md b/.changeset/hardening-and-packaging.md new file mode 100644 index 0000000..e2de6ed --- /dev/null +++ b/.changeset/hardening-and-packaging.md @@ -0,0 +1,9 @@ +--- +"txob": patch +--- + +- `instanceof` now recognizes txob's error classes (`ErrorUnprocessableEventHandler`, `TxOBError`, `TxOBValidationError`, `TxOBTimeoutError`) when an app loads both the ESM and the CommonJS build, so a CommonJS handler's `ErrorUnprocessableEventHandler` is dead-lettered by an ESM processor instead of being retried. +- MongoDB: txob's collections always read from the primary, even when the client's read preference is `secondaryPreferred`, so claims can't exceed concurrency limits or lose claimed deliveries to replication lag. +- Postgres: a table created before 0.6 now fails with an error that names the missing `defer_until` column and the `ALTER TABLE` to run, instead of a bare SQL error. +- The npm package no longer ships the CommonJS build cache (`dist/tsconfig.cjs.tsbuildinfo`, 532 kB). +- Docs: passing a pool or a non-transaction handle to `publish`, handlers that ignore their timeout signal, fan-out fencing, and the Redis cost of many keys at their per-key limit. diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 92af103..1ab8718 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -1,6 +1,13 @@ name: Running Code Coverage -on: [push, pull_request] +on: + push: + pull_request: + # Called by the release workflow, so nothing is published from a commit whose tests fail + workflow_call: + +permissions: + contents: read jobs: build: @@ -56,9 +63,10 @@ jobs: done fail "replica set never became PRIMARY" - - name: Start Redis and DynamoDB Local + - name: Start Redis, Valkey and DynamoDB Local run: | docker run -d --name redis -p 6379:6379 redis:8-alpine + docker run -d --name valkey -p 6380:6379 valkey/valkey:8-alpine docker run -d --name dynamodb -p 8000:8000 amazon/dynamodb-local:latest - name: Generate Prisma Client for the adapter tests @@ -67,6 +75,9 @@ jobs: - name: Typecheck run: pnpm typecheck + - name: Typecheck the examples + run: pnpm --filter ./examples/pg typecheck + - name: Run the tests run: pnpm test:ci env: @@ -75,6 +86,11 @@ jobs: TXOB_TEST_REDIS_URL: redis://localhost:6379 TXOB_TEST_DYNAMODB_URL: http://localhost:8000 + - name: Run the Redis store tests against Valkey + run: pnpm test --run test/redis.test.ts + env: + TXOB_TEST_REDIS_URL: redis://localhost:6380 + - name: Upload coverage to Codecov uses: codecov/codecov-action@v2 with: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ba2ba19..7caaf8d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -7,14 +7,23 @@ on: # One release run at a time; a newer push to main supersedes a queued one concurrency: ${{ github.workflow }}-${{ github.ref }} -permissions: - contents: write # push the version branch and tags, create GitHub releases - pull-requests: write # open and update the "Version Packages" PR - id-token: write # npm trusted publishing (OIDC) and provenance +permissions: {} jobs: + # The full test suite against every store; the release job only runs once it passes + test: + uses: ./.github/workflows/coverage.yml + permissions: + contents: read + secrets: inherit + release: + needs: test runs-on: ubuntu-latest + permissions: + contents: write # push the version branch and tags, create GitHub releases + pull-requests: write # open and update the "Version Packages" PR + id-token: write # npm trusted publishing (OIDC) and provenance steps: - name: Checkout repository uses: actions/checkout@v4 diff --git a/.gitignore b/.gitignore index e17bc77..2d31f67 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ coverage *.tsbuildinfo tsconfig.tsbuildinfo test/prisma/generated +.DS_Store diff --git a/README.md b/README.md index ff20ce1..e7c561a 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ - + @@ -26,7 +26,7 @@

-> **txob 0.5** reworks the processing model and is not backwards compatible. Coming from 0.4? See [MIGRATING.md](./MIGRATING.md). +> **txob 0.5** reworks the processing model and is not backwards compatible. Coming from 0.4? See [MIGRATING.md](./MIGRATING.md). Upgrading Postgres from 0.5 to 0.6 needs a new column; the same guide has the `ALTER TABLE`. ## The Problem @@ -133,6 +133,8 @@ try { `publish` validates the data against the event's schema (throwing `TxOBValidationError` on failure) and inserts it using the connection you pass, so it commits or rolls back with your data. +> **Pass the transaction, not the pool.** `publish` takes whatever handle the store can write through, and txob can't tell whether it is inside your transaction. A `pg.Pool`, a pooled client before `BEGIN`, Prisma's root client (instead of the `tx` from `$transaction`), or a MongoDB session that isn't in a transaction all type-check, but the event is then written on its own and stays even if your transaction rolls back. That is what you want for a standalone event with no business write, and the wrong thing everywhere else. + **How event data is stored.** The event keeps the data you published (the schema's _input_). The processor parses it with the schema again before calling `priority`, `perKey` and `defer` functions and handlers, so they all get the schema's _output_, with transforms applied once. Two consequences: - **The data must survive the store's serialization.** Postgres, Redis, DynamoDB and the memory store keep event data as JSON, so a `Date` comes back as an ISO string, and `z.date()` would reject it at delivery. `publish` checks the data the way the store will hand it back and throws `TxOBValidationError` right away if the schema won't accept that form. For dates, use a schema that accepts strings too, such as `z.coerce.date()`. MongoDB keeps `Date`s as they are, but stores `undefined` as `null`. @@ -214,7 +216,7 @@ publish(tx) ──► txob_events ──fan-out──► txob_deliveries ──c 2. **Fan-out.** A processor leases unfanned events of the types it handles and, in a single statement, creates one **delivery** per handler registered **in that processor** and marks the events fanned out. Each event is fanned out once, so which handlers it reaches is decided then (see [Changing handlers](#changing-handlers)). Fan-out is idempotent: deliveries are keyed by `(event_id, handler)`. 3. **Claim.** The processor claims pending deliveries up to its free capacity, highest priority first, within each handler's concurrency, per-key concurrency and rate limits. Limits count deliveries leased by **all** processors, and claims for a limited handler are serialized in the store, so they hold however many processors run. Claiming sets a lease (`leaseMs`, default 30s) and a fresh lease token, then commits. No transaction is held while handlers run. 4. **Run.** Claimed deliveries run immediately. Leases of in-flight deliveries are renewed every `leaseMs / 3`. -5. **Record.** Success marks the delivery `completed`. Failure schedules a retry with backoff, or marks it `dead` after `maxAttempts` (or immediately for `ErrorUnprocessableEventHandler`). Every write is conditional on the lease token, so a processor that lost its lease can't overwrite the work of the processor that took over. +5. **Record.** Success marks the delivery `completed`. Failure schedules a retry with backoff, or marks it `dead` after `maxAttempts` (or immediately for `ErrorUnprocessableEventHandler`). Every write to a delivery is conditional on its lease token, so a processor that lost its lease can't overwrite the work of the processor that took over. Fan-out isn't fenced the same way; it is idempotent instead: if two processors fan out the same event, the second one's deliveries are dropped as duplicates. If a processor crashes, its leases expire and other processors pick the work up. A claim counts as an attempt, so a handler that crashes the process can't loop forever: once its attempts are used up, the delivery is marked dead without running again. @@ -274,7 +276,7 @@ Each handler is either a function or a config object: - **Concurrency, per-key concurrency and rate limits are global.** `concurrency: 5` means at most 5 deliveries of the handler run at once across all processors. Running deliveries are counted by their live leases, so a processor that crashes keeps holding its share until its leases expire (at most `leaseMs`). - **Claims for a limited handler are serialized** (a transaction-scoped advisory lock on Postgres, a short-lived lock document on MongoDB). Claims take milliseconds, but if one handler sees very high claim rates, prefer a higher `concurrency` on the processor over many tiny claims. - **`priority`, the `perKey` key and `defer` are computed at fan-out** and stored with the delivery, so they're evaluated once per event, not per attempt. A key of `null` or `undefined` means the delivery has no key. If one of these functions throws or returns an invalid value, the event stays unfanned and is retried when its fan-out lease expires; once that has happened `retry.maxAttempts` times, the failing handler's delivery is created `dead` with the error as `last_error` (without calling `onDeliveryDead`), and the event's other handlers get their deliveries. -- **`timeoutMs` cancels the handler's context.** When it elapses, the `signal` passed to the handler is aborted with a `TxOBTimeoutError` reason. Honoring it is up to the handler: pass the signal to `fetch`, database drivers and so on, or check `signal.aborted`. Whatever the handler then does decides the outcome. If it throws, the attempt fails and is retried; if it finishes successfully anyway, the delivery is completed. The lease stays renewed while the handler runs. +- **`timeoutMs` cancels the handler's context.** When it elapses, the `signal` passed to the handler is aborted with a `TxOBTimeoutError` reason. Honoring it is up to the handler: pass the signal to `fetch`, database drivers and so on, or check `signal.aborted`. Whatever the handler then does decides the outcome. If it throws, the attempt fails and is retried; if it finishes successfully anyway, the delivery is completed. The lease stays renewed while the handler runs, so a handler that ignores the signal and never settles keeps its delivery, and its concurrency slot, until the process exits (`stop()` times out waiting for it). Another processor then claims it once the lease expires, which counts as an attempt. - **Process-wide defaults** go in `handlerDefaults: { retry, timeoutMs }`. ### Deferred delivery @@ -570,6 +572,7 @@ const processor = createEventProcessor({ - **Durability** is whatever your persistence settings give you. For an outbox, use AOF (`appendfsync always` for no loss, `everysec` to risk up to a second) and `maxmemory-policy noeviction` so txob's keys are never evicted. - **Cluster:** all of txob's keys share the `{txob}` hash tag, so they live in one slot. To publish in the same `MULTI` as your writes, your keys must use the same hash tag. Cluster mode isn't covered by the test suite yet. - **ORMs:** Redis OM's `repository.save` can't join a `MULTI`, so writes made through it can't be published atomically. Write those keys with the client on the same `MULTI` instead. +- **Per-key limits:** each claim checks, inside one script, every key of the handler that is at its `perKey` limit and still has pending deliveries. Measured on Redis 8: about 36 ms per claim with 10,000 such keys and 270 ms with 50,000, during which the server serves no other command. With very many keys saturated at once, prefer a higher per-key limit or fewer processors polling. - **Retention:** completed deliveries keep their hash. Prune `{txob}:d:*`, `{txob}:e:*` and their entries in the `{txob}:deliveries` / `{txob}:events` sorted sets on a schedule, removing an event only once none of its deliveries is `pending`. A pending delivery whose event is gone is marked dead when it is next claimed, without running its handler. ## DynamoDB diff --git a/package.json b/package.json index fcf2d79..23716a6 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,7 @@ "homepage": "https://github.com/osbytes/txob", "repository": { "type": "git", - "url": "git://github.com/osbytes/txob.git" + "url": "git+https://github.com/osbytes/txob.git" }, "version": "0.6.0", "type": "module", diff --git a/src/error.test.ts b/src/error.test.ts index 1318c5c..489d547 100644 --- a/src/error.test.ts +++ b/src/error.test.ts @@ -24,3 +24,31 @@ describe("ErrorUnprocessableEventHandler", () => { expect(err.error).toBe(inner); }); }); + +describe("instanceof across copies of the package", () => { + it("recognizes errors from another copy of the module, as with the ESM and CommonJS builds", async () => { + // A query string makes the bundler load a second, separate instance of the module + const other = (await import( + // @ts-expect-error a module id with a query string has no types + "./error.js?copy" + )) as typeof import("./error.js"); + expect(other.ErrorUnprocessableEventHandler).not.toBe( + ErrorUnprocessableEventHandler, + ); + expect( + new other.ErrorUnprocessableEventHandler(new Error("x")), + ).toBeInstanceOf(ErrorUnprocessableEventHandler); + expect(new other.TxOBError("x")).toBeInstanceOf(TxOBError); + expect(new other.TxOBError("x")).not.toBeInstanceOf( + ErrorUnprocessableEventHandler, + ); + expect(new Error("x")).not.toBeInstanceOf(TxOBError); + }); + + it("keeps the default instanceof for subclasses", () => { + class RateLimited extends TxOBError {} + expect(new RateLimited("x")).toBeInstanceOf(TxOBError); + expect(new RateLimited("x")).toBeInstanceOf(RateLimited); + expect(new TxOBError("x")).not.toBeInstanceOf(RateLimited); + }); +}); diff --git a/src/error.ts b/src/error.ts index 000973c..dcc0efd 100644 --- a/src/error.ts +++ b/src/error.ts @@ -1,5 +1,30 @@ import type { StandardSchemaV1 } from "@standard-schema/spec"; +/** + * The package ships ESM and CommonJS builds. When both load in one process (an ESM app with a + * CommonJS dependency that also imports txob), each has its own copy of these classes, and a + * plain `instanceof` fails across them: a handler throwing the CommonJS + * `ErrorUnprocessableEventHandler` would be retried by the ESM processor. Brand each class with a + * registered symbol so `instanceof` recognizes instances from either copy. Subclasses keep the + * default `instanceof`. + */ +const brand = (cls: abstract new (...args: never[]) => Error, name: string) => { + const key = Symbol.for(`txob.${name}`); + Object.defineProperty(cls.prototype, key, { value: true }); + Object.defineProperty(cls, Symbol.hasInstance, { + value: function (this: unknown, value: unknown): boolean { + if (this !== cls) { + return Function.prototype[Symbol.hasInstance].call(this, value); + } + return ( + typeof value === "object" && + value !== null && + (value as Record)[key] === true + ); + }, + }); +}; + /** * TxOBError can be thrown by an event handler to indicate that the delivery should be retried. * It allows handlers to specify a custom backoff time via the `backoffUntil` property. @@ -77,3 +102,8 @@ export class TxOBTimeoutError extends Error { this.name = "TxOBTimeoutError"; } } + +brand(TxOBError, "TxOBError"); +brand(ErrorUnprocessableEventHandler, "ErrorUnprocessableEventHandler"); +brand(TxOBValidationError, "TxOBValidationError"); +brand(TxOBTimeoutError, "TxOBTimeoutError"); diff --git a/src/mongodb/store.ts b/src/mongodb/store.ts index 9a864b2..d308a3e 100644 --- a/src/mongodb/store.ts +++ b/src/mongodb/store.ts @@ -66,7 +66,9 @@ type RateLimitClaimDoc = { export const resolveCollections = (opts: CreateMongoStoreOpts) => { const prefix = opts.collectionPrefix ?? "txob_"; - const db = opts.client.db(opts.db); + // Claims read back what they just wrote (counts, leased documents), so they must not go to a + // lagging secondary even when the client prefers secondaries for the application's reads + const db = opts.client.db(opts.db, { readPreference: "primary" }); return { names: { events: `${prefix}events`, diff --git a/src/pg/store.ts b/src/pg/store.ts index 9050cd2..b0eb9b3 100644 --- a/src/pg/store.ts +++ b/src/pg/store.ts @@ -121,6 +121,25 @@ const toJson = (value: unknown) => const ms = (param: string) => `(${param}::float8 * interval '1 millisecond')`; +/** + * Explains the error from tables created before 0.6, which lack `defer_until`: `migrate` + * creates missing tables but doesn't add columns to existing ones. + */ +const explainMissingDeferUntil = (error: unknown, events: string): unknown => { + for (let e: unknown = error; e instanceof Error; e = e.cause) { + if ( + e.message.includes("defer_until") && + e.message.includes("does not exist") + ) { + return new Error( + `${events} has no defer_until column. txob 0.6 added it, and migrate() doesn't add columns to existing tables; run ALTER TABLE ${events} ADD COLUMN IF NOT EXISTS defer_until TIMESTAMPTZ (see MIGRATING.md)`, + { cause: error }, + ); + } + } + return error; +}; + /** * Postgres store. Run `migrate` (or apply `getMigrationSql`) before use. * @@ -236,28 +255,36 @@ UPDATE ${deliveries} SET WHERE event_id = $1 AND handler = $2 AND lease_token = $3::uuid RETURNING 1`; + const withColumnCheck = (query: Promise): Promise => + query.catch((error: unknown) => { + throw explainMissingDeferUntil(error, events); + }); + return { roundTripData: jsonRoundTrip, insertEvent: async (tx, event) => { - await db.queryIn( - tx, - `INSERT INTO ${events} (id, type, data, correlation_id, created_at, defer_until) VALUES ($1, $2, $3::text::jsonb, $4, $5, $6)`, - [ - event.id, - event.type, - JSON.stringify(event.data), - event.correlation_id, - // ISO strings: some drivers (e.g. Drizzle on postgres.js) don't encode Dates - event.created_at.toISOString(), - event.defer_until?.toISOString() ?? null, - ], + await withColumnCheck( + db.queryIn( + tx, + `INSERT INTO ${events} (id, type, data, correlation_id, created_at, defer_until) VALUES ($1, $2, $3::text::jsonb, $4, $5, $6)`, + [ + event.id, + event.type, + JSON.stringify(event.data), + event.correlation_id, + // ISO strings: some drivers (e.g. Drizzle on postgres.js) don't encode Dates + event.created_at.toISOString(), + event.defer_until?.toISOString() ?? null, + ], + ), ); }, claimEventsForFanout: async ({ types, limit, leaseMs }) => { - const rows = await db.query( - ` + const rows = await withColumnCheck( + db.query( + ` UPDATE ${events} e SET fanout_run_after = now() + ${ms("$3")}, fanout_lease_token = gen_random_uuid(), @@ -271,7 +298,8 @@ FROM ( ) claimable WHERE e.id = claimable.id RETURNING e.id, e.type, e.data, e.correlation_id, e.created_at, e.defer_until, e.fanout_attempts, e.fanout_lease_token`, - [types, limit, leaseMs], + [types, limit, leaseMs], + ), ); return rows.map((row) => ({ ...row, @@ -331,23 +359,29 @@ WHERE id = ANY($7::text[])`, s.rateLimit !== undefined, ); if (limited.length === 0) { - const rows = await db.query(claimSql, params); + const rows = await withColumnCheck(db.query(claimSql, params)); return (rows as DeliveryRow[]).map(toDelivery); } // Limits are checked against deliveries leased by every processor. Claims for a limited // handler are serialized with a transaction-scoped advisory lock so two processors can't // both see the same free capacity. Locks are taken in a fixed order to avoid deadlocks. - return db.transaction(async (tx) => { - await db.queryIn( - tx, - // Counted because some clients (Prisma) can't read the void lock results - `SELECT count(*)::int AS locked FROM (SELECT pg_advisory_xact_lock(hashtextextended(k, 0)) FROM (SELECT unnest($1::text[]) AS k ORDER BY 1) keys) locks`, - [limited.map((s) => `${lockNamespace}:${s.event_type}:${s.handler}`)], - ); - const rows = await db.queryIn(tx, claimSql, params); - return (rows as DeliveryRow[]).map(toDelivery); - }); + return withColumnCheck( + db.transaction(async (tx) => { + await db.queryIn( + tx, + // Counted because some clients (Prisma) can't read the void lock results + `SELECT count(*)::int AS locked FROM (SELECT pg_advisory_xact_lock(hashtextextended(k, 0)) FROM (SELECT unnest($1::text[]) AS k ORDER BY 1) keys) locks`, + [ + limited.map( + (s) => `${lockNamespace}:${s.event_type}:${s.handler}`, + ), + ], + ); + const rows = await db.queryIn(tx, claimSql, params); + return (rows as DeliveryRow[]).map(toDelivery); + }), + ); }, completeDelivery: async (delivery) => { diff --git a/test/mongodb.test.ts b/test/mongodb.test.ts index 9cc96e4..92be215 100644 --- a/test/mongodb.test.ts +++ b/test/mongodb.test.ts @@ -6,6 +6,7 @@ import { createMongoWakeupEmitter, migrate, } from "../src/mongodb/index.js"; +import { resolveCollections } from "../src/mongodb/store.js"; import { runStoreContract } from "./contract.js"; /** @@ -58,6 +59,19 @@ describe.skipIf(!url)("mongodb", () => { }; }); + it("reads its collections from the primary when the client prefers secondaries", () => { + const client = new MongoClient(url!, { + readPreference: "secondaryPreferred", + }); + const { names: _, ...collections } = resolveCollections({ + client, + db: "txob_read_preference", + }); + for (const collection of Object.values(collections)) { + expect(collection.readPreference?.mode).toBe("primary"); + } + }); + describe("migrate", () => { it("is idempotent", async () => { const client = await new MongoClient(url!).connect(); diff --git a/test/pg.test.ts b/test/pg.test.ts index f82aaa9..86d95e0 100644 --- a/test/pg.test.ts +++ b/test/pg.test.ts @@ -7,7 +7,9 @@ import { getMigrationSql, migrate, } from "../src/pg/index.js"; +import { createOutbox } from "../src/index.js"; import { runStoreContract } from "./contract.js"; +import { schema } from "./helpers.js"; /** * Integration tests against a real Postgres. Skipped unless TXOB_TEST_PG_URL is set, e.g. @@ -100,6 +102,46 @@ describe.skipIf(!connectionString)("postgres", () => { }); }); + describe("tables created before 0.6", () => { + it("explains the missing defer_until column instead of failing with a bare SQL error", async () => { + const { pool, tablePrefix } = await createIsolated(); + try { + await pool.query( + `ALTER TABLE ${tablePrefix}events DROP COLUMN defer_until`, + ); + const store = createPgStore({ pool, tablePrefix }); + const outbox = createOutbox({ + eventSchemas: { E: schema<{ n: number }>() }, + store, + }); + const expected = + /events" has no defer_until column\..*ADD COLUMN IF NOT EXISTS defer_until TIMESTAMPTZ \(see MIGRATING\.md\)/; + await expect(outbox.publish(pool, "E", { n: 1 })).rejects.toThrow( + expected, + ); + await expect( + store.claimEventsForFanout({ + types: ["E"], + limit: 1, + leaseMs: 1_000, + }), + ).rejects.toThrow(expected); + await expect( + store.claimDeliveries({ + slots: [{ event_type: "E", handler: "h", limit: 1 }], + limit: 1, + leaseMs: 1_000, + }), + ).rejects.toThrow(expected); + } finally { + await pool.query( + `DROP TABLE ${tablePrefix}deliveries, ${tablePrefix}events, ${tablePrefix}rate_limit_claims; DROP FUNCTION ${tablePrefix}notify`, + ); + await pool.end(); + } + }); + }); + describe("migrate", () => { it("is idempotent and safe to run concurrently", async () => { const { pool, tablePrefix } = await createIsolated(); diff --git a/tsconfig.cjs.json b/tsconfig.cjs.json index 9b06eeb..66ff273 100644 --- a/tsconfig.cjs.json +++ b/tsconfig.cjs.json @@ -6,6 +6,8 @@ "ignoreDeprecations": "6.0", "outDir": "./dist/cjs", "declarationDir": "./dist/cjs", - "composite": false + "composite": false, + // Keep the build cache out of dist/ so it isn't published; `clean` removes it from here + "tsBuildInfoFile": "./tsconfig.cjs.tsbuildinfo" } }