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
11 changes: 11 additions & 0 deletions .changeset/event-data-round-trip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"txob": minor
---

Store event data as published and parse it once at delivery. `publish` used to store the schema's output and the processor parsed that again as input, so `z.date()` fields were dead-lettered on their first claim on Postgres, Redis and DynamoDB (while passing on the memory store), transforms ran twice, and transforms whose output isn't valid input never delivered. Now:

- the event keeps the data passed to `publish` (the schema's input), and handlers and `priority`/`perKey`/`defer` functions get the parsed output, with transforms applied once;
- `publish` validates the data in the form the store hands it back (new optional `TxOBStore.roundTripData`), so data a store can't keep, like a `Date` under `z.date()` in a JSON store, throws `TxOBValidationError` at publish with a hint to use `z.coerce.date()`;
- the memory store keeps event data as JSON like the Postgres, Redis and DynamoDB stores.

**Behavior change:** publishes that used to be dead-lettered at delivery now throw, and new rows in `txob_events.data` hold the input shape. Events stored by 0.6.0 deliver as before. See MIGRATING.md.
8 changes: 8 additions & 0 deletions MIGRATING.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
# Migrating from 0.6 to 0.7

- **Event data is stored as published.** 0.6 stored the schema's _output_ and parsed it again at delivery, which applied transforms twice and dead-lettered events whose output isn't valid input (e.g. `z.string().transform(Number)`). 0.7 stores the data you pass to `publish` (the schema's _input_) and parses it once per delivery; `priority`, `perKey` and `defer` functions now get the parsed output too, as their types always said. Events already stored by 0.6 keep the output and are parsed exactly as 0.6 parsed them, so they deliver as before. If you read `txob_events.data` directly (SQL, dashboards), new rows hold the input shape.
- **`publish` rejects data the store can't round-trip.** It validates the data in the form the store hands back (JSON for Postgres, Redis, DynamoDB and the memory store; BSON for MongoDB). A `Date` under `z.date()` used to be dead-lettered on its first delivery on Postgres, Redis and DynamoDB; now `publish` throws `TxOBValidationError`. Use `z.coerce.date()` (or another schema that accepts an ISO string) for dates.
- **Defaults and transforms run at delivery**, once per delivery. Make them deterministic: compute IDs and timestamps before publishing instead of in `.default()` or `.transform()`.
- **The memory store keeps event data as JSON**, like the Postgres, Redis and DynamoDB stores, so tests catch the cases above.
- **Custom stores:** optionally implement `roundTripData(data)` to return event data as the store will read it back. Without it, `publish` validates data as given, as before.

# Migrating from 0.5 to 0.6

0.6 adds deferred delivery (`defer` on handler definitions and `publish`). Events gain a `defer_until` timestamp, and new deliveries carry a `run_after`.
Expand Down
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,11 @@ 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.

**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`.
- **Defaults and transforms run again at delivery.** Keep them deterministic: generate IDs and timestamps before you publish rather than in `.default()` or `.transform()`, or each delivery sees a different value.

Options: `id` (default: a random UUID), `correlation_id`, and `defer` to hold every delivery of the event back, overriding the handlers' own `defer` (see [Deferred delivery](#deferred-delivery)).

**4. Process them:**
Expand Down Expand Up @@ -312,7 +317,7 @@ processor.getConfig(); // effective settings per handler, after overrides
| `new ErrorUnprocessableEventHandler(error)` | dead immediately; retrying won't help |
| `signal.reason` after `timeoutMs` (`TxOBTimeoutError`) | retry |

Events whose stored data no longer passes their schema are marked dead without running the handler.
Events whose stored data no longer passes their schema (for example, after a schema change) are marked dead without running the handler.

### Dead deliveries

Expand Down Expand Up @@ -624,7 +629,7 @@ await client.send(

## Testing

`txob/memory` provides an in-process store with the same semantics, so you can run your real handler map in unit tests without a database:
`txob/memory` provides an in-process store with the same semantics, so you can run your real handler map in unit tests without a database. Like the Postgres, Redis and DynamoDB stores, it keeps event data as JSON, so a schema that can't read its stored data back fails in your tests too:

```typescript
import { createMemoryStore } from "txob/memory";
Expand Down Expand Up @@ -654,6 +659,8 @@ A store implements `TxOBStore<TTx>`, where `TTx` is whatever handle your writes
2. **Compare-and-set**, for lease-fenced `completeDelivery`, `failDelivery`, `extendLeases` and `releaseDeliveries`.
3. **An ordered query on due time**, for `claimEventsForFanout` and `claimDeliveries`. `completeFanout` must honor each new delivery's `run_after`, and `insertEvent` must persist `event.defer_until` and hand it back on later reads.

If the store serializes event data (as JSON, say), implement `roundTripData` to return data the way the store will read it back, e.g. `(data) => JSON.parse(JSON.stringify(data))`. `publish` validates that form, so data the store can't keep fails at publish instead of at delivery.

The behavioral contract every store must satisfy lives in this repo at [`test/contract.ts`](./test/contract.ts) (it is not part of the npm package); copy it and run `runStoreContract(name, setup)` against your store. [`src/memory/store.ts`](./src/memory/store.ts) is a compact reference implementation.

## Telemetry
Expand Down
3 changes: 3 additions & 0 deletions src/dynamodb/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
type BatchGetCommandOutput,
type TransactWriteCommandInput,
} from "@aws-sdk/lib-dynamodb";
import { jsonRoundTrip } from "../json.js";
import type { TxOBHandlerSlot, TxOBNewDelivery, TxOBStore } from "../store.js";
import type { TxOBDelivery, TxOBEvent } from "../types.js";
import {
Expand Down Expand Up @@ -551,6 +552,8 @@ export const createDynamoStore = (
};

return {
roundTripData: jsonRoundTrip,

insertEvent: async (tx, event) => {
tx.push({
Put: {
Expand Down
11 changes: 8 additions & 3 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,16 @@ export class TxOBValidationError extends Error {
constructor(
eventType: string,
issues: ReadonlyArray<StandardSchemaV1.Issue>,
opts: {
/** The data passes the schema as given, but not in the form the store keeps it in. */
stored?: boolean;
} = {},
) {
const messages = issues.map((issue) => issue.message).join("; ");
super(
`invalid data for event type '${eventType}': ${issues
.map((issue) => issue.message)
.join("; ")}`,
opts.stored
? `invalid data for event type '${eventType}' as stored: ${messages}. The data passes the schema as given but not once the store has serialized it (e.g. a Date read back from JSON is a string); use a schema that also accepts the stored form, such as z.coerce.date()`
: `invalid data for event type '${eventType}': ${messages}`,
);
this.name = "TxOBValidationError";
this.issues = issues;
Expand Down
3 changes: 3 additions & 0 deletions src/json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/** Event data as a store that keeps it as JSON hands it back. */
export const jsonRoundTrip = (data: unknown): unknown =>
data === undefined ? undefined : JSON.parse(JSON.stringify(data));
10 changes: 9 additions & 1 deletion src/memory/store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
import { EventEmitter } from "node:events";
import { jsonRoundTrip } from "../json.js";
import { deliveryKey, type TxOBFanoutEvent, type TxOBStore } from "../store.js";
import type {
TxOBDelivery,
Expand Down Expand Up @@ -149,8 +150,15 @@ export const createMemoryStore = (): MemoryStore => {
}),
),

// Keeps event data as JSON, like the Postgres, Redis and DynamoDB stores, so tests against
// this store catch data those stores can't round-trip
roundTripData: jsonRoundTrip,

insertEvent: async (tx, event) => {
tx.events.push(event);
tx.events.push({
...event,
data: jsonRoundTrip(event.data) as TxOBEvent["data"],
});
},

claimEventsForFanout: async ({ types, limit, leaseMs }) => {
Expand Down
8 changes: 8 additions & 0 deletions src/mongodb/store.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { randomUUID } from "node:crypto";
import {
BSON,
MongoBulkWriteError,
MongoServerError,
type ClientSession,
Expand Down Expand Up @@ -256,6 +257,13 @@ export const createMongoStore = (
};

return {
// BSON keeps Dates (unlike JSON) but, by default, turns undefined into null
roundTripData: (data) =>
BSON.deserialize(
BSON.serialize({ data }, events.bsonOptions),
events.bsonOptions,
).data,

insertEvent: async (session, event) => {
await events.insertOne(
{
Expand Down
49 changes: 44 additions & 5 deletions src/outbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { TxOBStore } from "./store.js";
import type {
TxOBDefer,
TxOBEvent,
TxOBEventData,
TxOBEventSchemaMap,
TxOBEventTypeOf,
TxOBSchemaInput,
Expand Down Expand Up @@ -58,10 +59,41 @@ export const validateEventData = async <TSchema extends StandardSchemaV1>(
return result.value;
};

/**
* Validates data in the form the store will hand it back to the processor, so data that only
* fails once stored is rejected at publish rather than dead-lettered at delivery.
*/
const validateStoredEventData = async <TSchema extends StandardSchemaV1>(
eventType: string,
schema: TSchema,
data: unknown,
stored: unknown,
): Promise<StandardSchemaV1.InferOutput<TSchema>> => {
try {
return await validateEventData(eventType, schema, stored);
} catch (error) {
if (stored !== data && error instanceof TxOBValidationError) {
let asGiven = schema["~standard"].validate(data);
if (asGiven instanceof Promise) asGiven = await asGiven;
if (!asGiven.issues) {
throw new TxOBValidationError(eventType, error.issues, {
stored: true,
});
}
}
throw error;
}
};

/**
* Creates a typed outbox writer. `publish` validates the event data against its schema and
* inserts the event using the caller's transaction so it commits atomically with business data.
*
* The data is stored as given (the schema's input) and parsed again at delivery, so handlers
* get the schema's output and transforms run once per delivery. It is validated in the form the
* store keeps it in: data that doesn't survive storage (e.g. a `Date` under `z.date()` in a JSON
* store) is rejected here.
*
* @example
* ```typescript
* const outbox = createOutbox({ eventSchemas, store });
Expand All @@ -76,7 +108,7 @@ export const createOutbox = <
TTx,
>(opts: {
eventSchemas: TEventSchemas;
store: Pick<TxOBStore<TTx>, "insertEvent">;
store: Pick<TxOBStore<TTx>, "insertEvent" | "roundTripData">;
}): TxOBOutbox<TEventSchemas, TTx> => {
const { eventSchemas, store } = opts;

Expand All @@ -91,23 +123,30 @@ export const createOutbox = <
throw new Error(`unknown event type '${type}'`);
}
const created_at = new Date();
const stored = store.roundTripData ? store.roundTripData(data) : data;
const event: TxOBEvent<
typeof type,
TxOBSchemaOutput<TEventSchemas[typeof type]>
> = {
id: publishOpts?.id ?? randomUUID(),
type,
data: (await validateEventData(type, schema, data)) as TxOBSchemaOutput<
TEventSchemas[typeof type]
>,
data: (await validateStoredEventData(
type,
schema,
data,
stored,
)) as TxOBSchemaOutput<TEventSchemas[typeof type]>,
correlation_id: publishOpts?.correlation_id ?? null,
created_at,
defer_until: resolveDefer(
normalizeDefer(publishOpts?.defer ?? null, `publish('${type}')`),
{ created_at },
),
};
await store.insertEvent(tx, event);
// The input is stored, not the output: the processor parses it again at delivery, and
// parsing an output can fail (a transform's output needn't be valid input) or apply a
// transform twice
await store.insertEvent(tx, { ...event, data: stored as TxOBEventData });
return event;
};

Expand Down
3 changes: 3 additions & 0 deletions src/pg/store.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { jsonRoundTrip } from "../json.js";
import type { TxOBFanoutEvent, TxOBStore } from "../store.js";
import type { TxOBDelivery, TxOBEvent } from "../types.js";
import { resolveNames, type PgTableOpts } from "./schema.js";
Expand Down Expand Up @@ -236,6 +237,8 @@ WHERE event_id = $1 AND handler = $2 AND lease_token = $3::uuid
RETURNING 1`;

return {
roundTripData: jsonRoundTrip,

insertEvent: async (tx, event) => {
await db.queryIn(
tx,
Expand Down
37 changes: 33 additions & 4 deletions src/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
import type {
Logger,
TxOBDelivery,
TxOBEvent,
TxOBEventFromSchemas,
TxOBEventSchemaMap,
TxOBSerializedError,
Expand Down Expand Up @@ -482,9 +483,35 @@ export class EventProcessor<
let firstDue: Date | null = null;
for (const event of events) {
try {
// Priority, key and defer functions get the schema's output, like handlers do. If the
// data doesn't pass the schema, the deliveries get default settings and are marked
// dead when claimed, without running the handler.
let parsed: TxOBEvent | undefined;
try {
parsed = {
...event,
data: await validateEventData(
event.type,
this.eventSchemas[event.type],
event.data,
),
};
} catch (error) {
if (!(error instanceof TxOBValidationError)) throw error;
}
const eventDeliveries = (this.handlers.get(event.type) ?? []).map(
(handler): TxOBNewDelivery => {
const priority = handler.priority(event);
if (parsed === undefined) {
return {
event_id: event.id,
event_type: event.type,
handler: handler.name,
priority: 0,
concurrency_key: null,
run_after: event.defer_until,
};
}
const priority = handler.priority(parsed);
if (
!Number.isInteger(priority) ||
Math.abs(priority) > maxPriority
Expand All @@ -493,7 +520,7 @@ export class EventProcessor<
`${event.type}.${handler.name}: priority must be a 32-bit integer, got ${priority}`,
);
}
const key = handler.perKey ? handler.perKey.key(event) : null;
const key = handler.perKey ? handler.perKey.key(parsed) : null;
if (key !== null && typeof key !== "string") {
throw new Error(
`${event.type}.${handler.name}: concurrency key must be a string or null, got ${typeof key}`,
Expand All @@ -504,7 +531,7 @@ export class EventProcessor<
event.defer_until ??
resolveDefer(
normalizeDefer(
handler.defer(event),
handler.defer(parsed),
`${event.type}.${handler.name}.defer`,
),
event,
Expand Down Expand Up @@ -690,7 +717,9 @@ export class EventProcessor<
);
}

// Re-validate so handlers receive the schema's output type (e.g. coerced dates)
// The stored data is the schema's input, as published, so parsing it gives handlers the
// output with transforms applied once. (Events stored by 0.6.0 hold the output; those
// parse the same way they did then.)
const schema = this.eventSchemas[delivery.event_type];
try {
event = {
Expand Down
3 changes: 3 additions & 0 deletions src/redis/store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { randomUUID } from "node:crypto";
import { jsonRoundTrip } from "../json.js";
import type { TxOBStore } from "../store.js";
import type { TxOBDelivery, TxOBEvent } from "../types.js";
import {
Expand Down Expand Up @@ -141,6 +142,8 @@ export const createRedisStore = <TClient extends RedisClientLike>(
];

return {
roundTripData: jsonRoundTrip,

insertEvent: async (multi, event) => {
// Inside a MULTI, so the script is sent in full rather than by SHA
driver.queue(multi as object, [
Expand Down
9 changes: 9 additions & 0 deletions src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,15 @@ export interface TxOBStore<TTx = unknown> {
/** Insert an event using the caller's transaction. */
insertEvent(tx: TTx, event: TxOBEvent): Promise<void>;

/**
* Event data as this store hands it back after `insertEvent` wrote it, e.g.
* `JSON.parse(JSON.stringify(data))` for a store that keeps JSON. `publish` validates this
* form, so data the store can't keep as is (such as a `Date` where the schema requires one,
* in a JSON store) is rejected when it is published instead of when it is delivered.
* Omit it if the store keeps data exactly as given.
*/
roundTripData?(data: unknown): unknown;

/** Lease up to `limit` events of `types` that have not yet been fanned out. */
claimEventsForFanout(
opts: TxOBStoreOpts & { types: string[]; limit: number; leaseMs: number },
Expand Down
Loading
Loading