Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed .DS_Store
Binary file not shown.
9 changes: 9 additions & 0 deletions .changeset/hardening-and-packaging.md
Original file line number Diff line number Diff line change
@@ -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.
20 changes: 18 additions & 2 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand All @@ -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:
Expand Down
17 changes: 13 additions & 4 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ coverage
*.tsbuildinfo
tsconfig.tsbuildinfo
test/prisma/generated
.DS_Store
11 changes: 7 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@
<a aria-label="License" href="https://github.com/osbytes/txob/blob/main/LICENSE">
<img alt="" src="https://badgen.net/npm/license/txob">
</a>
<a aria-label="Typescript" href="https://github.com/osbytes/txob/blob/main/src/cache.ts">
<a aria-label="Typescript" href="https://github.com/osbytes/txob/blob/main/src/index.ts">
<img alt="" src="https://badgen.net/npm/types/txob">
</a>
<a aria-label="CodeFactor" href="https://www.codefactor.io/repository/github/osbytes/txob">
<img alt="" src="https://www.codefactor.io/repository/github/osbytes/txob/badge">
</a>
</p>

> **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

Expand Down Expand Up @@ -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`.
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
28 changes: 28 additions & 0 deletions src/error.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});
30 changes: 30 additions & 0 deletions src/error.ts
Original file line number Diff line number Diff line change
@@ -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<symbol, unknown>)[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.
Expand Down Expand Up @@ -77,3 +102,8 @@ export class TxOBTimeoutError extends Error {
this.name = "TxOBTimeoutError";
}
}

brand(TxOBError, "TxOBError");
brand(ErrorUnprocessableEventHandler, "ErrorUnprocessableEventHandler");
brand(TxOBValidationError, "TxOBValidationError");
brand(TxOBTimeoutError, "TxOBTimeoutError");
4 changes: 3 additions & 1 deletion src/mongodb/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand Down
Loading
Loading