diff --git a/.changeset/event-data-round-trip.md b/.changeset/event-data-round-trip.md new file mode 100644 index 0000000..8351dd9 --- /dev/null +++ b/.changeset/event-data-round-trip.md @@ -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. diff --git a/MIGRATING.md b/MIGRATING.md index 5e902df..745b46e 100644 --- a/MIGRATING.md +++ b/MIGRATING.md @@ -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`. diff --git a/README.md b/README.md index 4d8565a..2da02ed 100644 --- a/README.md +++ b/README.md @@ -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:** @@ -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 @@ -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"; @@ -654,6 +659,8 @@ A store implements `TxOBStore`, 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 diff --git a/src/dynamodb/store.ts b/src/dynamodb/store.ts index f2d86bd..a4b7646 100644 --- a/src/dynamodb/store.ts +++ b/src/dynamodb/store.ts @@ -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 { @@ -551,6 +552,8 @@ export const createDynamoStore = ( }; return { + roundTripData: jsonRoundTrip, + insertEvent: async (tx, event) => { tx.push({ Put: { diff --git a/src/error.ts b/src/error.ts index b5c1738..000973c 100644 --- a/src/error.ts +++ b/src/error.ts @@ -52,11 +52,16 @@ export class TxOBValidationError extends Error { constructor( eventType: string, issues: ReadonlyArray, + 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; diff --git a/src/json.ts b/src/json.ts new file mode 100644 index 0000000..5974e53 --- /dev/null +++ b/src/json.ts @@ -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)); diff --git a/src/memory/store.ts b/src/memory/store.ts index 5bdfb3e..13f1591 100644 --- a/src/memory/store.ts +++ b/src/memory/store.ts @@ -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, @@ -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 }) => { diff --git a/src/mongodb/store.ts b/src/mongodb/store.ts index d634604..217fb45 100644 --- a/src/mongodb/store.ts +++ b/src/mongodb/store.ts @@ -1,5 +1,6 @@ import { randomUUID } from "node:crypto"; import { + BSON, MongoBulkWriteError, MongoServerError, type ClientSession, @@ -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( { diff --git a/src/outbox.ts b/src/outbox.ts index 9c0e779..d52980d 100644 --- a/src/outbox.ts +++ b/src/outbox.ts @@ -6,6 +6,7 @@ import type { TxOBStore } from "./store.js"; import type { TxOBDefer, TxOBEvent, + TxOBEventData, TxOBEventSchemaMap, TxOBEventTypeOf, TxOBSchemaInput, @@ -58,10 +59,41 @@ export const validateEventData = async ( 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 ( + eventType: string, + schema: TSchema, + data: unknown, + stored: unknown, +): Promise> => { + 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 }); @@ -76,7 +108,7 @@ export const createOutbox = < TTx, >(opts: { eventSchemas: TEventSchemas; - store: Pick, "insertEvent">; + store: Pick, "insertEvent" | "roundTripData">; }): TxOBOutbox => { const { eventSchemas, store } = opts; @@ -91,15 +123,19 @@ 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 > = { 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, correlation_id: publishOpts?.correlation_id ?? null, created_at, defer_until: resolveDefer( @@ -107,7 +143,10 @@ export const createOutbox = < { 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; }; diff --git a/src/pg/store.ts b/src/pg/store.ts index d89cdf5..66091d9 100644 --- a/src/pg/store.ts +++ b/src/pg/store.ts @@ -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"; @@ -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, diff --git a/src/processor.ts b/src/processor.ts index 744b316..7cc0308 100644 --- a/src/processor.ts +++ b/src/processor.ts @@ -44,6 +44,7 @@ import { import type { Logger, TxOBDelivery, + TxOBEvent, TxOBEventFromSchemas, TxOBEventSchemaMap, TxOBSerializedError, @@ -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 @@ -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}`, @@ -504,7 +531,7 @@ export class EventProcessor< event.defer_until ?? resolveDefer( normalizeDefer( - handler.defer(event), + handler.defer(parsed), `${event.type}.${handler.name}.defer`, ), event, @@ -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 = { diff --git a/src/redis/store.ts b/src/redis/store.ts index 92d2644..58c18c7 100644 --- a/src/redis/store.ts +++ b/src/redis/store.ts @@ -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 { @@ -141,6 +142,8 @@ export const createRedisStore = ( ]; 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, [ diff --git a/src/store.ts b/src/store.ts index 358261e..55a2f41 100644 --- a/src/store.ts +++ b/src/store.ts @@ -56,6 +56,15 @@ export interface TxOBStore { /** Insert an event using the caller's transaction. */ insertEvent(tx: TTx, event: TxOBEvent): Promise; + /** + * 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 }, diff --git a/test/contract.ts b/test/contract.ts index 9535693..6c39c41 100644 --- a/test/contract.ts +++ b/test/contract.ts @@ -11,7 +11,16 @@ import { type TxOBStore, type WakeupEmitter, } from "../src/index.js"; -import { delay, schema, silentLogger, waitFor } from "./helpers.js"; +import { + centsSchema, + coercedDateSchema, + dateSchema, + delay, + schema, + shoutSchema, + silentLogger, + waitFor, +} from "./helpers.js"; export type ContractDelivery = { event_id: string; @@ -40,6 +49,11 @@ const eventSchemas = { OrderPlaced: schema<{ orderId: string; accountId: string }>(), DeliveryDead: schema<{ eventId: string; handler: string }>(), Unhandled: schema<{ n: number }>(), + // Schemas whose output differs from their input + Reminder: dateSchema, + Scheduled: coercedDateSchema, + Greeted: shoutSchema, + Charged: centsSchema, }; type Schemas = typeof eventSchemas; @@ -91,6 +105,10 @@ export const runStoreContract = ( OrderPlaced: {}, DeliveryDead: {}, Unhandled: {}, + Reminder: {}, + Scheduled: {}, + Greeted: {}, + Charged: {}, }; const publishUsers = (count: number) => @@ -141,6 +159,132 @@ export const runStoreContract = ( }); }); + describe("event data", () => { + it("gives handlers and fan-out functions the schema's output, with transforms applied once", async () => { + const seen: Record = {}; + const see = (name: string, value: unknown) => + void (seen[name] ??= []).push(value); + const at = new Date(Date.now() - 1_000); + startProcessor({ + handlerMap: { + ...baseHandlers, + Greeted: { + greet: { + priority: (event) => { + see("priority", event.data.name); + return 0; + }, + concurrency: { + perKey: { + key: (event) => { + see("key", event.data.name); + return event.data.name; + }, + limit: 1, + }, + }, + handler: async (event) => see("greet", event.data), + }, + }, + Scheduled: { + remind: { + defer: (event) => { + see("defer", event.data.at); + return { until: event.data.at }; + }, + handler: async (event) => see("remind", event.data.at), + }, + }, + Charged: { bill: async (event) => see("bill", event.data) }, + }, + }); + const published = await h.transaction(async (tx) => [ + await outbox.publish(tx, "Greeted", { name: "bob" }), + await outbox.publish(tx, "Scheduled", { at }), + await outbox.publish(tx, "Charged", { cents: "250" }), + ]); + expect(published.map((e) => e.data)).toEqual([ + { name: "bob!" }, + { at }, + { cents: 250 }, + ]); + await waitFor( + async () => (await deliveriesBy("completed")).length === 3, + ); + expect(seen.greet).toEqual([{ name: "bob!" }]); + expect(seen.priority).toEqual(["bob!"]); + expect(seen.key).toEqual(["bob!"]); + expect(seen.bill).toEqual([{ cents: 250 }]); + expect(seen.defer).toEqual([at]); + expect(seen.remind).toEqual([at]); + expect(seen.defer[0]).toBeInstanceOf(Date); + expect(seen.remind[0]).toBeInstanceOf(Date); + }); + + it("rejects at publish data the store can't hand back in a form the schema accepts", async () => { + const at = new Date(); + const stored = h.store.roundTripData + ? h.store.roundTripData({ at }) + : { at }; + const keepsDates = (stored as { at: unknown }).at instanceof Date; + const seen: unknown[] = []; + startProcessor({ + handlerMap: { + ...baseHandlers, + Reminder: { + remind: async (event) => void seen.push(event.data.at), + }, + }, + }); + const published = h.transaction((tx) => + outbox.publish(tx, "Reminder", { at }), + ); + if (keepsDates) { + await published; + await waitFor( + async () => (await deliveriesBy("completed")).length === 1, + ); + expect(seen).toEqual([at]); + } else { + // A JSON store gives the date back as a string, which `z.date()` would reject at + // delivery; failing the publish surfaces that in the caller's transaction instead + await expect(published).rejects.toThrow( + /'Reminder' as stored: expected date\..*z\.coerce\.date\(\)/, + ); + expect(await h.getEvents()).toHaveLength(0); + } + expect(await deliveriesBy("dead")).toHaveLength(0); + }); + + it("delivers events stored by 0.6.0, which hold the schema's output", async () => { + const at = new Date(Date.now() - 1_000); + const seen: unknown[] = []; + startProcessor({ + handlerMap: { + ...baseHandlers, + Scheduled: { + remind: async (event) => void seen.push(event.data.at), + }, + }, + }); + // 0.6.0 passed the output, { at: Date }, to insertEvent + await h.transaction((tx) => + h.store.insertEvent(tx, { + id: "stored-by-0.6.0", + type: "Scheduled", + data: { at }, + correlation_id: null, + created_at: new Date(), + defer_until: null, + }), + ); + await waitFor( + async () => (await deliveriesBy("completed")).length === 1, + ); + expect(seen).toEqual([at]); + }); + }); + describe("leases", () => { it("hides claimed events from other fan-out claims until the lease expires", async () => { await publishUsers(3); diff --git a/test/helpers.ts b/test/helpers.ts index d3dccba..ea4df6f 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -19,6 +19,53 @@ export const schema = >( }, }); +/** Standard Schema whose output differs from its input, like zod's `.transform()`. */ +export const transformSchema = ( + parse: (value: Record) => TOutput | string, +): StandardSchemaV1 => ({ + "~standard": { + version: 1, + vendor: "test", + validate: (value) => { + if (typeof value !== "object" || value === null) { + return { issues: [{ message: "expected object" }] }; + } + const result = parse(value as Record); + return typeof result === "string" + ? { issues: [{ message: result }] } + : { value: result }; + }, + }, +}); + +/** Like `z.object({ at: z.date() })`: only a `Date` passes. */ +export const dateSchema = transformSchema<{ at: Date }, { at: Date }>((v) => + v.at instanceof Date ? { at: v.at } : "expected date", +); + +/** Like `z.object({ at: z.coerce.date() })`: an ISO string or a `Date` becomes a `Date`. */ +export const coercedDateSchema = transformSchema< + { at: Date | string }, + { at: Date } +>((v) => { + const at = new Date(v.at as string); + return Number.isNaN(at.getTime()) ? "expected date" : { at }; +}); + +/** Like `z.object({ name: z.string().transform((s) => `${s}!`) })`. */ +export const shoutSchema = transformSchema<{ name: string }, { name: string }>( + (v) => + typeof v.name === "string" ? { name: `${v.name}!` } : "expected name", +); + +/** Like `z.object({ cents: z.string().transform(Number) })`: the output isn't valid input. */ +export const centsSchema = transformSchema< + { cents: string }, + { cents: number } +>((v) => + typeof v.cents === "string" ? { cents: Number(v.cents) } : "expected cents", +); + export const waitFor = async ( predicate: () => boolean | Promise, { timeoutMs = 5_000, intervalMs = 10 } = {},