Skip to content
Closed
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
10 changes: 10 additions & 0 deletions .changeset/event-catalogue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"@bounda-dev/core": minor
"@bounda-dev/postgresql": minor
"@bounda-dev/cloudflare": minor
"@bounda-dev/react-router": minor
---

The store keeps a catalogue of every kind of event it holds, and the boot checks it against the code. `EventStore` gains `types()`, every `(aggregateType, type, schemaVersion)` of a committed event, each once; `append` records the ones it has not met in the same transaction, in a new `bounda_event_types` table on SQLite, PostgreSQL and the Durable Object, so a booted app writes nothing more for the types it already holds. `eventStoreContract` and `storageTransactionContract` pin it; an adapter of your own must add it. `createApp`, `boot()` and `bounda rebuild` refuse a store holding events the code cannot read, of an event type, aggregate or process it no longer has, or written with a schema version past the one it knows, with one `ConfigurationError` naming each. A store written before this version has no rows, and the catalogue fills as new events are appended.

An event that newer code wrote while a deploy rolls out is now the transient `SchemaAheadError` (`SCHEMA_AHEAD`, with `eventId`, `aggregateType`, `aggregateId`, `type`, `position`, `schemaVersion` and `known`) instead of a terminal `ConfigurationError`: a future schema version, or a type this code has no module for that the catalogue records. A command that loads such a stream fails with it. Reads of the global stream stop right before the event, so a read model waits there and backs off as a failing one does, shown by `getLag().failing`; a policy or process holds the event and retries with its back-off past `maxAttempts`, never dead-lettering it; a scheduled command waits `runtime.dispatcher.backoff.baseDelay` without counting an attempt; a dead-letter retry rejects with it and the letter stays `failed`. A non-system event of an aggregate the app does not have is no longer passed through: it is refused the same way. `failure()` of React Router and `createWorker` answer it with a 503.
1 change: 1 addition & 0 deletions docs/src/content/docs/adapters/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ On first use the adapter creates its tables, prefixed with `bounda_` by default:
| Table | Holds |
| --- | --- |
| `bounda_events` | Every event, with its stream version, a global position and the person it names, if any, which [`exportPersonalData`](/guides/personal-data/#exporting-a-persons-data) reads by |
| `bounda_event_types` | Every kind of event the store holds, by aggregate, type and schema version, which the runtime [checks against the code](/guides/deployment/#deploying-a-change-to-events) on boot |
| `bounda_checkpoints` | How far each projection, the policy runner, the process runner, the retention and the [forget ledger](/guides/personal-data/#backups)'s copy have read, where a paused rebuild stands, the time of the last ledger entry the database applied, when the last reconciliation ran and the wait of one that failed, and when the [key rotation](/guides/personal-data/#rotating-the-master-key) was last found complete for a set of master keys |
| `bounda_inbox` | Which handler already completed for which event, so a retry does not run it again |
| `bounda_scheduled_commands` | Scheduled commands, process deadlines and timeouts, and delayed policy runs |
Expand Down
11 changes: 7 additions & 4 deletions docs/src/content/docs/guides/changing-events.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,10 @@ reason, rather than deriving them from today's event.
handlers is always the current shape, stamped with the current version. Nothing is rewritten
in the store.
- An event written with a version this code does not know, because a newer deploy wrote it,
is refused with an error naming the event. Roll forward, never back, once new events exist.
is refused: at boot, which does not start, and while running, with the transient
`SCHEMA_AHEAD` until that deploy reaches every instance
([Deploying a change to events](/guides/deployment/#deploying-a-change-to-events)). Roll
forward, never back, once new events exist.

The types keep you honest in one direction: the last upcaster must return the current payload, so
a change to `payload` in the event module fails to compile until the upcast module catches up.
Expand All @@ -101,9 +104,9 @@ change to how its state is folded does.

## What is not covered yet

- **Renaming or removing an event type.** Upcasters change the payload, not the type. A stored
event whose module is gone still fails to fold; keep the module, even if its `evolve` changes
nothing (`() => ({})`).
- **Renaming or removing an event type.** Upcasters change the payload, not the type. A store
that holds events whose module is gone refuses to boot; keep the module, even if its `evolve`
changes nothing (`() => ({})`).
- **Process state.** A process keeps its state in its own lifecycle events. Changing that
state's shape has the same problem and no upcaster yet; a `state.upcast.ts` in the process
directory is the natural extension when it is needed.
27 changes: 27 additions & 0 deletions docs/src/content/docs/guides/deployment.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,33 @@ it needs on start, and a view that gains a field gains a column, or an index for
`unique()` needs the rebuild below ([what an adapter creates](/adapters/#what-an-adapter-creates)
and [evolving a read model](/adapters/#evolving-a-read-model)).

## Deploying a change to events

The store keeps a catalogue of every kind of event it holds, `bounda_event_types`: each aggregate,
event type and schema version, recorded the first time an append writes it. On boot, and before
`bounda rebuild`, the runtime checks it against the code. Events whose module is gone, of an
aggregate or a process the app no longer has, or written with a schema version past the one the
code knows ([upcasters](/guides/changing-events/)), refuse the boot with one
`INVALID_CONFIGURATION` error that names each of them. An app never starts on a store it cannot
read.

Roll forward, never back. While a deploy rolls out over several instances, old ones run beside
new ones, and an old instance can read an event the new code wrote: a new event type, or a new
upcaster's version. It never moves past it. It reads up to that event and refuses it with
`SCHEMA_AHEAD`, a transient error, until the new code runs everywhere:

- A read model stops right before the event and backs off as a [failing projection](#a-projection-that-keeps-failing)
does; `app.getLag()` shows it under `failing`.
- A policy or process holds the event and tries again with its back-off, however many attempts
that takes. It never gives up on it, so nothing reaches a dead letter.
- A scheduled command goes back to wait `runtime.dispatcher.backoff.baseDelay`, without counting
an attempt.
- A command fails to its caller, which `failure()` of React Router and the Cloudflare Worker
answer with a 503 ([errors](/reference/errors/#over-http)).

A rollback leaves the old code facing events it cannot read, and it does not start. A short deploy
is all the window there is; keep it short.

## Rebuilding a read model

A read model is derived data: when its projection had a bug, or its view lost a field or changed a
Expand Down
5 changes: 3 additions & 2 deletions docs/src/content/docs/guides/react-router.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,10 @@ when its handler rejects it, with the code in `rejected`. Return `failure(error)
| `ValidationError` | 400 | `{ error, issues }`, each issue with the `path` of the field and its `message` |
| `DomainError` | 409 | `{ error, issues: [], rejected }`, the code the command declares |
| `IdempotencyKeyConflictError` | 422 | `{ error, issues: [] }`, the request's `Idempotency-Key` came back with another payload |
| `SchemaAheadError` | 503 | `{ error, issues: [] }`, the command read an event newer code wrote while a [deploy rolls out](/guides/deployment/#deploying-a-change-to-events); trying again later goes through |

`failure` goes by the error's `code`, `VALIDATION_FAILED`, `DOMAIN_ERROR` or
`IDEMPOTENCY_KEY_CONFLICT`, so it answers the same for the refusals a Durable Object sends back on
`failure` goes by the error's `code`, `VALIDATION_FAILED`, `DOMAIN_ERROR`,
`IDEMPOTENCY_KEY_CONFLICT` or `SCHEMA_AHEAD`, so it answers the same for the refusals a Durable Object sends back on
Cloudflare, which arrive as plain errors.
Anything else is rethrown and reaches the route's `ErrorBoundary`. `Failure`, the shape of that
data, is exported from `@bounda-dev/react-router`.
Expand Down
16 changes: 15 additions & 1 deletion docs/src/content/docs/reference/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,20 @@ dead letter with `errorType: "retriable_exhausted"`.
registry entry that does not exist.
- **`INVALID_CONFIGURATION`** (`ConfigurationError`; terminal). `bounda.config.ts` or the registry
is malformed: an unknown key, a port with no implementation chosen, a module missing an export.
Thrown at boot, or when a handler reads a port a test left out.
Thrown at boot, or when a handler reads a port a test left out. Boot and `bounda rebuild` also
throw it for a store holding events the code cannot read: of a type, aggregate or process it no
longer has, or written with a schema version past the one it knows
([Deploying a change to events](/guides/deployment/#deploying-a-change-to-events)).
- **`SCHEMA_AHEAD`** (`SchemaAheadError`; held, never dead-lettered). An event newer code wrote,
while a deploy rolls out: its schema version is past the one this code knows, or its type is
one this code has no module for although the store's catalogue records it. `eventId`,
`aggregateType`, `aggregateId`, `type`, `position`, `schemaVersion`, and `known`, the version
this code reads up to, `null` for a type it lacks. A command that loads such a stream fails with
it. A policy or process holds the event and retries with its back-off past `maxAttempts`, never
giving up on it; each retry still counts as an attempt of its claim. A scheduled command waits
`runtime.dispatcher.backoff.baseDelay` without counting one, a read model stops right before the
event, and a dead-letter retry rejects with it, leaving the letter `failed`. It goes away once
that code runs on every instance; roll forward, never back.
- **`FORGET_LEDGER_UNRECONCILED`** (`ForgetLedgerUnreconciledError`; a start's answer). Thrown
by `createApp`, and so by `boot` and the CLI, when `runtime.personalData.forgetLedger.strict` is
set and the [forget ledger](/guides/personal-data/#the-forget-ledger) could not be read through:
Expand Down Expand Up @@ -119,6 +132,7 @@ The hosts map the codes a client can cause to a status:
| `FOREIGN_REJECTION` | 500, code `INTERNAL`, logged | rethrown |
| `NOT_FOUND` | 404 | rethrown |
| `PAYLOAD_TOO_LARGE` | 413, a body over `maxPayloadBytes` | — |
| `SCHEMA_AHEAD` | 503 | 503 |
| `HANDLER_TIMEOUT` | 504 | rethrown |
| anything else | 500, code `INTERNAL`, logged | rethrown, for the route's `ErrorBoundary` |

Expand Down
1 change: 1 addition & 0 deletions packages/cloudflare/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ const STATUS_BY_CODE: Readonly<Record<string, number>> = {
PROCESSING_RESTRICTED: 409,
CONCURRENCY_CONFLICT: 409,
CHAIN_DEPTH_EXCEEDED: 409,
SCHEMA_AHEAD: 503,
HANDLER_TIMEOUT: 504,
};

Expand Down
23 changes: 23 additions & 0 deletions packages/cloudflare/test/worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,29 @@ describe("createWorker", () => {
expect(errors).toEqual([["bounda worker has no such binding", { binding: "MISSING" }]]);
});

it("answers a 503 for an event newer code wrote, which a deploy rolling out leaves behind", async () => {
const worker = createWorker({
config: { storage: cloudflare({ binding: "SPY" }) },
tenantOf: () => {
throw Object.assign(new Error("written by newer code"), { code: "SCHEMA_AHEAD" });
},
});
const response = await worker.fetch?.(
new Request("https://bounda.test/queries/getOrder", {
method: "POST",
body: JSON.stringify({ orderId: "o-1" }),
}) as Request<unknown, IncomingRequestCfProperties>,
{
SPY: { idFromName: () => "id", get: () => recordingStub().stub },
} as unknown as Cloudflare.Env,
createExecutionContext(),
);
expect(response?.status).toBe(503);
expect(await response?.json()).toEqual({
error: { code: "SCHEMA_AHEAD", message: "written by newer code" },
});
});

it("answers a 500 and logs it when tenantOf throws", async () => {
const errors: unknown[][] = [];
const logger: Logger = {
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/adapter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export type {
ReadAllArgs,
ReadOneArgs,
ResealedEvent,
StoredEventType,
} from "./storage/event-store.ts";
export type {
ByForgetLedgerOrderFunction,
Expand Down
78 changes: 78 additions & 0 deletions packages/core/src/adapter/sql/event-types.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import { pendingEvent } from "../testing/fixtures.ts";
import { postgresqlDialect, sqliteDialect } from "./dialect.ts";
import { createKnownEventTypes, insertEventTypesStatements } from "./event-types.ts";

const placed = { aggregateType: "order", type: "OrderPlaced", schemaVersion: 1 };
const paid = { aggregateType: "order", type: "OrderPaid", schemaVersion: 1 };

describe("createKnownEventTypes", () => {
it("names each type of a batch once, until it is recorded", () => {
const known = createKnownEventTypes();
const events = [
pendingEvent({ aggregateId: "1", version: 1 }),
pendingEvent({ aggregateId: "1", version: 2 }),
pendingEvent({ aggregateId: "1", version: 3, type: "OrderPaid" }),
pendingEvent({ aggregateId: "1", version: 4, schemaVersion: 2 }),
];
expect(known.unseen(events)).toEqual([placed, paid, { ...placed, schemaVersion: 2 }]);
known.recorded([placed]);
expect(known.unseen(events)).toEqual([paid, { ...placed, schemaVersion: 2 }]);
known.recorded([paid, { ...placed, schemaVersion: 2 }]);
expect(known.unseen(events)).toEqual([]);
});

it("counts what a transaction's stores record only once it commits, and never when it does not", () => {
const known = createKnownEventTypes();
const events = [pendingEvent({ aggregateId: "1", version: 1 })];
const rolledBack = known.pending();
rolledBack.recorded(rolledBack.unseen(events));
expect(known.unseen(events)).toEqual([placed]);
const committed = known.pending();
committed.recorded(committed.unseen(events));
expect(committed.unseen(events)).toEqual([placed]);
committed.commit();
expect(known.unseen(events)).toEqual([]);
expect(committed.unseen(events)).toEqual([]);
committed.commit();
expect(known.unseen(events)).toEqual([]);
});
});

describe("insertEventTypesStatements", () => {
it("writes nothing for no types", () => {
expect(insertEventTypesStatements({ dialect: sqliteDialect, table: '"t"', types: [] })).toEqual(
[],
);
});

it("binds three numbered parameters a type, leaving types already there as they are", () => {
expect(
insertEventTypesStatements({
dialect: postgresqlDialect,
table: '"t"',
types: [placed, paid],
}),
).toEqual([
{
sql: 'INSERT INTO "t" ("aggregate_type", "type", "schema_version") VALUES ($1, $2, $3), ($4, $5, $6) ON CONFLICT DO NOTHING',
params: ["order", "OrderPlaced", 1, "order", "OrderPaid", 1],
},
]);
});

it("splits types over statements of at most a hundred parameters", () => {
const types = Array.from({ length: 34 }, (_, index) => ({ ...placed, schemaVersion: index }));
const statements = insertEventTypesStatements({
dialect: postgresqlDialect,
table: '"t"',
types,
});
expect(statements.map(({ params }) => params.length)).toEqual([99, 3]);
expect(statements[1]).toEqual({
sql: 'INSERT INTO "t" ("aggregate_type", "type", "schema_version") VALUES ($1, $2, $3) ON CONFLICT DO NOTHING',
params: ["order", "OrderPlaced", 33],
});
expect(statements[0]?.sql).toContain("($97, $98, $99) ON CONFLICT");
});
});
Loading
Loading