From ad8505178bf389643f0dbe885d3315383584a00a Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:26:42 -0600 Subject: [PATCH 1/8] fix: keep the CommonJS build cache out of the published package tsconfig.cjs.json inherited incremental builds with outDir dist/cjs, so tsc wrote its 532 kB tsconfig.cjs.tsbuildinfo into dist/ and every npm tarball shipped it. Write it next to tsconfig.cjs.json instead, where the clean script and .gitignore already expect it. --- tsconfig.cjs.json | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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" } } From 3caea2b4d4522700c2abe658e656dc2825879001 Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:26:42 -0600 Subject: [PATCH 2/8] chore: stop tracking .DS_Store --- .DS_Store | Bin 6148 -> 0 bytes .gitignore | 1 + 2 files changed, 1 insertion(+) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 1ad899dbcdc748036dd701eacb0ec11e243703d4..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKyJ`bL3>+mc4$`I(2Sbbi#2M3J zT*oXyY@Q(Y!ZDE|1kgGlC+ZoQs7@HV6)|Fx!@~RZ=JlH_u58Z)4k@C?#6Xc7@{2$qaAbO f?f5y0vab1>=e=-D3_9~cC+cUwb&*MdzgFN1-fR_w 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 From 83b8db602dc20e7189ef8a93ac3961c03e411d69 Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:26:42 -0600 Subject: [PATCH 3/8] chore: use a git+https repository URL in package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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", From f44a6feeced1d18a6cdcb18bb929bdcc3af71217 Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:28:01 -0600 Subject: [PATCH 4/8] ci: run the tests before releasing, and against Valkey The release workflow published to npm without running anything, so a red main could ship. It now calls the test workflow and only versions or publishes once that passes; write and OIDC permissions are scoped to the release job, and the test workflow runs with read-only contents. The README says the Redis store is tested against Valkey 8, but CI only ran Redis 8; run the Redis store tests against Valkey too. Also typecheck examples/pg, which nothing checked. --- .github/workflows/coverage.yml | 20 ++++++++++++++++++-- .github/workflows/release.yml | 17 +++++++++++++---- 2 files changed, 31 insertions(+), 6 deletions(-) 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 From 5e7ed74f3e464ad95b5711ca6673e8beb964e40a Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:30:03 -0600 Subject: [PATCH 5/8] fix: explain a missing defer_until column on Postgres tables created before 0.6 migrate() creates missing tables but doesn't add columns, so upgrading from 0.5 without the documented ALTER TABLE failed every publish and claim with a bare 'column "defer_until" does not exist'. Name the table, the column and the statement to run, and point at MIGRATING.md. --- src/pg/store.ts | 86 ++++++++++++++++++++++++++++++++++--------------- test/pg.test.ts | 42 ++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 26 deletions(-) diff --git a/src/pg/store.ts b/src/pg/store.ts index 66091d9..1bc6494 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, @@ -328,23 +356,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/pg.test.ts b/test/pg.test.ts index d88b010..a2840ae 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. @@ -95,6 +97,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(); From b30f7645a81efa9618c7d413cf2e9613c7a6604e Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:30:03 -0600 Subject: [PATCH 6/8] fix: recognize txob errors thrown from the other build in instanceof checks When the ESM and CommonJS builds both load in one process, each has its own error classes. A handler throwing the CommonJS ErrorUnprocessableEventHandler into an ESM processor was retried until maxAttempts instead of being dead-lettered at once, and a TxOBError's backoffUntil was ignored. Brand the classes with registered symbols so instanceof matches instances from either copy. --- src/error.test.ts | 28 ++++++++++++++++++++++++++++ src/error.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) 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"); From 21a70149c0ec5ca74801a6c78b6a971e3114c0a4 Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:31:07 -0600 Subject: [PATCH 7/8] fix: read txob's MongoDB collections from the primary The collections inherited the client's read preference, so with secondaryPreferred the claim's counts and its read-back of leased deliveries could hit a lagging secondary: per-key and handler limits could be exceeded and claimed deliveries could be missing from the result until their lease expired. --- src/mongodb/store.ts | 4 +++- test/mongodb.test.ts | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/mongodb/store.ts b/src/mongodb/store.ts index 217fb45..6209778 100644 --- a/src/mongodb/store.ts +++ b/src/mongodb/store.ts @@ -61,7 +61,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/test/mongodb.test.ts b/test/mongodb.test.ts index bd56d4e..2548a5a 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"; /** @@ -53,6 +54,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(); From c55c144aeb0d1065fed82a6ed53f085412534ece Mon Sep 17 00:00:00 2001 From: dillonstreator Date: Sat, 28 Nov 2026 13:32:33 -0600 Subject: [PATCH 8/8] docs: warn about non-transaction handles, hung handlers and saturated Redis keys - publish type-checks with a pool, Prisma's root client or a MongoDB session outside a transaction; say plainly what happens then. - A handler that ignores its timeout signal keeps its lease and slot until the process exits. - Fan-out is idempotent rather than fenced by the lease token. - Each Redis claim walks every key at its per-key limit; give measured numbers. - Point the README banner at the 0.6 column migration and fix the types badge link. --- .changeset/hardening-and-packaging.md | 9 +++++++++ README.md | 11 +++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) create mode 100644 .changeset/hardening-and-packaging.md 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/README.md b/README.md index 2da02ed..6aaea0b 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 registered handler and marks the events fanned out. 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. @@ -254,7 +256,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. -- **`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 @@ -543,6 +545,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. ## DynamoDB