@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 07:15 UTC

main
md 375 lines 19.2 KB
Rendered Raw
1 # Building blocks
2
3 Templates for every block, taken from `examples/cloudflare-domain`. Every class is a `Domain.<Noun>(name, definition)`; extend it as `class X extends Domain.<Noun>(...) {}`.
4
5 ## Id and values
6
7 ```ts
8 // Account/Account.id.ts
9 import * as Schema from "effect/Schema";
10 export const AccountId = Schema.String.pipe(Schema.brand("AccountId"));
11 export type AccountId = typeof AccountId.Type;
12
13 // Money.ts
14 export const Cents = Schema.Int;
15 ```
16
17 More: [Aggregate: Give it an identity](https://alchemy.run/domain/aggregate#give-it-an-identity).
18
19 ## Command, its events and its rejections
20
21 ```ts
22 // Account/WithdrawMoney.command.ts
23 import * as Domain from "@alchemy.run/domain";
24 import { MfaChallenge } from "../MfaChallenge.middleware.ts";
25 import { Cents } from "../Money.ts";
26 import { Session } from "../Session.middleware.ts";
27 import { AccountId } from "./Account.id.ts";
28 import { NotOpen } from "./NotOpen.rejection.ts";
29
30 export class DailyLimitExceeded extends Domain.Rejection("DailyLimitExceeded", { remaining: Cents }) {}
31
32 export class MoneyWithdrawn extends Domain.Event("MoneyWithdrawn", {
33 amount: Cents,
34 balanceAfter: Cents,
35 }) {}
36
37 /** Take money out of an account, within the balance and the daily limit. */
38 export class WithdrawMoney extends Domain.Command("WithdrawMoney", {
39 target: AccountId, // the id schema of its aggregate, exactly
40 middleware: [Session, MfaChallenge], // authenticate; provide context to decide
41 input: { amount: Cents },
42 events: [MoneyWithdrawn], // every event it may record
43 rejects: [NotOpen, DailyLimitExceeded], // every way it can be refused
44 reply: { balance: Cents }, // optional typed reply
45 attributes: (cmd) => ({ "bank.amount": cmd.amount }), // optional: what its spans record
46 }) {}
47 ```
48
49 A rejection with no fields: `class NotOpen extends Domain.Rejection("NotOpen") {}` in `NotOpen.rejection.ts`. Events and rejections take `attributes` as a third argument: `Domain.Event("MoneyWithdrawn", { ... }, { attributes: (e) => ({ ... }) })`. Nothing from a payload is traced unless `attributes` returns it, and `Redacted` values record as `<redacted>`.
50
51 `Domain.Rejection(tag, fields, annotations)` is `Schema.TaggedError` with its type filled in: the third argument takes the same annotations (`httpApiStatus`, `description`, ...) plus `attributes`. `rejects` takes any tagged error class, `HttpApiError.Forbidden` included.
52
53 More: [Command: Annotate a rejection](https://alchemy.run/domain/command#annotate-a-rejection).
54
55 More: [Command](https://alchemy.run/domain/command), [Event](https://alchemy.run/domain/event).
56
57 ## Aggregate
58
59 ```ts
60 // Account/Account.aggregate.ts
61 type Open = Extract<AccountState, { _tag: "Open" }>;
62
63 // A shared rule: the narrowed state, or the rejection. Every decide handler starts from it.
64 const openFor = (s: AccountState): Open | NotOpen => (s._tag === "Open" ? s : new NotOpen());
65
66 export class Account extends Domain.Aggregate("Account", {
67 id: AccountId,
68 state: AccountState, // a Schema, usually a TaggedStruct union
69 initial: { _tag: "Unopened" },
70 commands: [OpenAccount, DepositMoney, WithdrawMoney], // events derive from the commands
71 decide: {
72 OpenAccount: (s, cmd) =>
73 s._tag !== "Unopened" ? new AlreadyOpen() : [new AccountOpened({ owner: cmd.owner })],
74 DepositMoney: (s, cmd) => {
75 const o = openFor(s);
76 if (o._tag !== "Open") return o;
77 return [new MoneyDeposited({ amount: cmd.amount, balanceAfter: o.balance + cmd.amount })];
78 },
79 // Effect.fn when decide reads middleware context; fail with `return yield* rejection`
80 WithdrawMoney: Effect.fn(function* (s, cmd, { now }) {
81 const o = openFor(s);
82 if (o._tag !== "Open") return yield* o;
83 if (o.owner !== (yield* CurrentActor).customerId) return yield* new NotOwner();
84 if (cmd.amount > o.balance) return yield* new InsufficientFunds({ balance: o.balance });
85 return [new MoneyWithdrawn({ amount: cmd.amount, balanceAfter: o.balance - cmd.amount })];
86 }),
87 },
88 evolve: {
89 AccountOpened: (_, e) => ({ _tag: "Open" as const, owner: e.owner, balance: 0 }),
90 // decide already refused a closed account: keep any state the event can't follow
91 MoneyDeposited: (s, e) => (s._tag === "Open" ? { ...s, balance: e.balanceAfter } : s),
92 MoneyWithdrawn: (s, e) => (s._tag === "Open" ? { ...s, balance: e.balanceAfter } : s),
93 },
94 reply: { WithdrawMoney: (s) => ({ balance: s._tag === "Open" ? s.balance : 0 }) },
95 // optional: let clients read/watch the aggregate through an Api
96 read: { middleware: [Session], rejects: [NotOwner], validate: Effect.fn(function* (_req, s) { /* authorize */ }) },
97 }) {}
98 ```
99
100 `Aggregate.ref(id)` builds a reference for stories and views.
101
102 More: [Aggregate](https://alchemy.run/domain/aggregate).
103
104 ### Patterns for decide, evolve and reply
105
106 - **decide answers one of three ways.** Events when the command changes something; `[]` when the state already is what it asks for (freezing a frozen account); a declared rejection when it can't be done.
107 - **Name shared rules as pure guards** that return the narrowed state or the rejection (`openFor`), and start each handler from one. In an `Effect.fn` handler, fail with `return yield* o`.
108 - **Events carry the outcome**, not just the request (`balanceAfter`), so `evolve` copies it and never repeats a rule. Views and policies see the same numbers.
109 - **decide reads time from `now`** (its third argument) and the actor from middleware context. Never `Date.now()`, `Clock` or randomness.
110 - **evolve and reply are total and never fail.** decide already refused the command, so a handler keeps any state its event can't follow: `s._tag === "Open" ? { ...s, balance: e.balanceAfter } : s`. An event that changes the stage returns the new state whole.
111 - **Optics are an opt-in shorthand** for many handlers that repeat the same check. `const balance = Optic.id<State>().tag("Open").key("balance")` focuses on the Open state; `Optic.replace(s, balance, e.balanceAfter)` sets one field and `open.modify((o) => ({ ...o, ... }))(s)` several, leaving other states unchanged. The example bank uses them.
112 - **A compensation never refuses.** A command that undoes another process's step (`RefundTransfer`) records a fact for every state (`TransferRefunded`, or `RefundStranded` when the account closed), so the saga that sent it has no refusal to handle.
113
114 More: [Aggregate: Focus on a state with optics](https://alchemy.run/domain/aggregate#focus-on-a-state-with-optics), [Aggregate: Never refuse a compensation](https://alchemy.run/domain/aggregate#never-refuse-a-compensation).
115
116 ## Request context and middleware
117
118 ```ts
119 // CurrentActor.context.ts: the key must be unique across every request context
120 export class CurrentActor extends Domain.RequestContext<CurrentActor>()("Bank/CurrentActor", Actor) {}
121
122 // Session.middleware.ts (domain): the declaration, its error, and a client helper
123 export class Unauthorized extends Schema.TaggedError<Unauthorized>()("Unauthorized", {}) {}
124 export class Session extends RpcMiddleware.Service<Session, { provides: CurrentActor }>()(
125 "Bank/Session",
126 { error: Unauthorized },
127 ) {}
128
129 // server/src/Session.ts: the implementation
130 export const SessionLive = Layer.succeed(Session, (effect, { headers }) =>
131 Option.match(actorOf(headers), {
132 onNone: () => Effect.fail(new Unauthorized()),
133 onSome: (actor) => Effect.provideService(effect, CurrentActor, actor),
134 }),
135 );
136 ```
137
138 A `RequestContext` has a schema, so its value travels with the command to the aggregate's Durable Object. A `decide` that reads `CurrentActor` won't type-check for a command without the middleware that provides it.
139
140 The middleware's server half asks your auth library who is signed in, such as better-auth's `auth.getSession(headers)`. See [Sign in with better-auth](https://alchemy.run/domain/better-auth) and `examples/cloudflare-domain-better-auth`.
141
142 More: [Sessions and middleware](https://alchemy.run/domain/sessions), [Sign in with better-auth](https://alchemy.run/domain/better-auth).
143
144 ## View
145
146 ```ts
147 // Account/AccountSummary.view.ts
148 export class AccountSummary extends Domain.View("AccountSummary", {
149 from: [Account], // aggregates or other views
150 key: Account, // what one row is about
151 middleware: [Session],
152 rejects: [NotOwner],
153 state: Schema.Struct({ customerId: Schema.NullOr(CustomerId), balance: Cents }),
154 initial: { customerId: null, balance: 0 },
155 evolve: {
156 AccountOpened: (v, e) => ({ ...v, customerId: e.customerId }),
157 MoneyWithdrawn: (v, e) => ({ ...v, balance: e.balanceAfter }),
158 },
159 // judged on every get, list, and every change while watched
160 validate: Effect.fn(function* (_request, summary) {
161 yield* mustOwn(summary?.customerId ?? null);
162 }),
163 }) {}
164 ```
165
166 Emit derived events with `events: [StatementLine]` and `emit: { MoneyDeposited: (e) => new StatementLine({...}) }`. Each emitted event carries the view's state after it. Route one event to several keys with named routes:
167
168 ```ts
169 keyOf: {
170 TransferRequested: {
171 out: ({ event }) => Account.ref(event.from),
172 in: ({ event }) => Account.ref(event.to),
173 },
174 },
175 emit: { TransferRequested: { out: moved("out"), in: moved("in") } },
176 ```
177
178 A view keyed by a different aggregate than its source uses `keyOf`, returning `undefined` to skip. A view about something with no aggregate of its own (an org) takes a string Schema as `key` (`key: OrgId`); its `keyOf` returns the value, and reads take the value (`watch(orgId)`). Policies, projections and streams take a Schema `key` the same way (`Domain.Key.Any` is either). Don't declare an empty aggregate only to key something. Add derived fields with `computed: { total: (v) => ... }`.
179
180 When you change what a deployed view computes (`evolve`, `emit`, `keyOf`, `state`, the events or sources it reads), bump its `version` in the declaration (`version: 1`), and only ever increase it. The deploy recomputes it from the events: in place for a view keyed by the one aggregate it reads, from the history otherwise, and rebuilds whatever reads it.
181
182 More: [View](https://alchemy.run/domain/view), [Views as security boundaries](https://alchemy.run/domain/view-security), [Change a view: bump its version](https://alchemy.run/domain/model#change-a-view-bump-its-version).
183
184 ## Policy
185
186 ```ts
187 // Customer/MainAccountProvisioning.policy.ts
188 export class MainAccountProvisioning extends Domain.Policy("MainAccountProvisioning", {
189 from: Customer,
190 on: [CustomerRegistered],
191 }) {}
192
193 export const MainAccountProvisioningLive = MainAccountProvisioning.toLayer(
194 Effect.gen(function* () {
195 const accounts = yield* Account; // resolve clients once
196 return Effect.fn(function* ({ source, event }) {
197 yield* accounts
198 .send(mainAccountId(source.id), new OpenAccount({ customerId: source.id, owner: event.name }))
199 .pipe(Effect.catchTag("AlreadyOpen", () => Effect.void)); // handle every rejection
200 });
201 }),
202 );
203 ```
204
205 The handler receives `{ key, source, event, envelope, state }` (`state` for a view source). It must handle every rejection. A policy has no session, so it provides context itself: `.pipe(Effect.provideService(CurrentActor, system("FraudReview")))`. To send a command later, durably, use `transfers.schedule(ref, new ExpireTransfer(), { after: "24 hours" })`. Only commands that never reject can be scheduled. `schedule` returns a `ScheduleReceipt` (`{ commandId, at }`). To cancel one that no longer applies, call `transfers.unschedule(ref, commandId)` with a known `commandId` or the receipt's. Both fail with `AlreadyExecuted` when the instance already handled a command with that id; `unschedule` also fails with `AlreadyCancelled` (cancelled before) or `NotScheduled` (never scheduled). A policy catches the ones it expects with `Effect.catchTag([...], ...)`, since a redelivery finds its expiry already cancelled. A policy cancels after the event is recorded, so the command can still fire first: keep the guard in `decide`.
206
207 More: [Policy](https://alchemy.run/domain/policy).
208
209 ## Saga
210
211 ```ts
212 // Transfer/ExecuteTransfer.saga.ts
213 export const Decision = DurableDeferred.make("decision", { success: Schema.Literals(["approved", "expired"]) });
214
215 export class ExecuteTransfer extends Domain.Saga("ExecuteTransfer", {
216 key: TransferId,
217 input: { from: AccountId, to: AccountId, amount: Cents, requestedBy: Actor, needsApproval: Schema.Boolean },
218 rejects: [NotOpen, InsufficientFunds, DestinationClosed],
219 }) {}
220
221 export const ExecuteTransferLive = ExecuteTransfer.toLayer(
222 Effect.gen(function* () {
223 const accounts = yield* Account;
224 const transfers = yield* Transfer;
225 return Effect.fn(function* ({ key, from, to, amount, requestedBy, needsApproval }) {
226 if (needsApproval && (yield* DurableDeferred.await(Decision)) === "expired") return;
227 yield* Activity.make({
228 name: "debit",
229 error: Schema.Union([NotOpen, InsufficientFunds]),
230 execute: accounts.send(from, new DebitTransfer({ transferId: key, amount, requestedBy })),
231 }).pipe(
232 ExecuteTransfer.withCompensation(() =>
233 Activity.make({ name: "refund", execute: accounts.send(from, new RefundTransfer({ transferId: key, amount })) }),
234 ),
235 );
236 yield* Activity.make({ name: "credit", error: DestinationClosed, execute: /* ... */ });
237 yield* Activity.make({ name: "complete", execute: transfers.send(key, new CompleteTransfer()) });
238 });
239 }),
240 );
241 ```
242
243 Start and signal it from a policy, keyed by the aggregate:
244
245 ```ts
246 const executions = yield* ExecuteTransfer;
247 yield* executions.start(source, { from, to, amount, requestedBy, needsApproval }); // returns a run handle at once
248 yield* executions.get(source).signal(Decision, "approved");
249 // run handle: executionId, status, result, signal(deferred, value), interrupt
250 ```
251
252 Rules:
253 - One command per step. Commands inside a step get stable ids, so a retried step doesn't apply twice.
254 - Report each outcome to an aggregate (`CompleteTransfer`, `FailTransfer` in a `Workflow.addFinalizer`), so views can follow the process.
255 - `DurableClock.sleep` waits durably.
256
257 More: [Saga](https://alchemy.run/domain/saga).
258
259 ## External system
260
261 ```ts
262 // Fraud/FraudCheck.external.ts (domain)
263 export class FraudCheck extends Domain.ExternalSystem("FraudCheck", {
264 score: { args: { accountId: AccountId, amount: Cents }, success: { risk: Schema.Number } },
265 }) {}
266
267 // server/src/Fraud/SiftFraudCheck.ts
268 export const SiftFraudCheck = FraudCheck.toLayer(
269 Effect.succeed({ score: ({ amount }) => Effect.succeed({ risk: amount >= 80_000 ? 0.95 : 0.05 }) }),
270 );
271 ```
272
273 Use it with `const fraud = yield* FraudCheck` in a policy or saga `toLayer`, then call `fraud.score({...})`. Declare typed errors per operation with `error:`: one schema, or a list (`error: [RefundDeclined, CardFrozen]`) when the vendor can refuse in several ways. Every call through a `toLayer` adapter is checked against the operation's schemas (args before, success or error after); a value a schema rejects dies with an `ExternalSystemSchemaError` naming the system and operation. `toLayer(build, { validate: false })` turns the check off. In a story, systems in `stub` are faked and the story answers their calls; the others run for real from a Layer you provide, and the story asserts what each call sent and returned. See [testing.md](testing.md).
274
275 More: [External System](https://alchemy.run/domain/external-system).
276
277 ## Projection and its port
278
279 ```ts
280 // Ledger/LedgerStore.ts (domain): the port, plus a memory implementation for stories
281 export class LedgerStore extends Context.Service<LedgerStore, {
282 readonly record: (rows: ReadonlyArray<LedgerRow>) => Effect.Effect<void, never, RuntimeContext>;
283 }>()("Bank/LedgerStore") {}
284
285 // Ledger/Ledger.projection.ts
286 export class Ledger extends Domain.Projection("Ledger", {
287 from: [Account],
288 key: Account,
289 on: [MoneyDeposited, MoneyWithdrawn],
290 }) {}
291
292 export const LedgerLive = Ledger.toLayer(
293 Effect.gen(function* () {
294 const store = yield* LedgerStore;
295 return Effect.fn(function* (batch) {
296 yield* store.record(batch.map(({ key, event, envelope }) => ({
297 id: `${envelope.stream}:${envelope.seq}`, // idempotent: a replay upserts the same row
298 accountId: key.id, kind: event._tag, amount: event.amount,
299 })));
300 });
301 }),
302 { batch: { size: 100, wait: "1 second" } }, // tuning lives on the Layer
303 );
304 ```
305
306 The server provides `LedgerStore` with D1; a story provides it with memory.
307
308 More: [Projection](https://alchemy.run/domain/projection).
309
310 ## Stream
311
312 ```ts
313 // Account/AccountCard.stream.ts
314 export class CardChanged extends Domain.Event("CardChanged", { balance: Cents, frozen: Schema.Boolean }) {}
315
316 export class AccountCard extends Domain.Stream("AccountCard", {
317 key: Account,
318 entries: [CardChanged],
319 middleware: [Session],
320 rejects: [NotOwner],
321 validate: Effect.fn(function* (_request, latest) { /* authorize on the latest entry */ }),
322 }) {}
323 ```
324
325 A projection with `writes: [AccountCard]` appends entries with `yield* cards.append(input, new CardChanged({...}))`. Clients `peek`, `watch`, `list` and read `events`.
326
327 More: [Stream](https://alchemy.run/domain/stream).
328
329 ## Api
330
331 ```ts
332 // CustomerApi.api.ts
333 export class CustomerApi extends Domain.Api("CustomerApi", {
334 model: Bank, // names must be part of it
335 commands: ["RegisterCustomer", "DepositMoney", "WithdrawMoney"], // client methods
336 views: ["AccountSummary", "Statement"],
337 streams: ["AccountCard"],
338 aggregates: ["Account"], // read directly, through their `read` contract
339 }) {}
340 // A kind left out is served whole (aggregates: those with `read`); `[]` serves none.
341 ```
342
343 Clients call commands as methods (`bank.WithdrawMoney(accountId, { amount }, { commandId, headers })`) and reads as namespaces. A view or aggregate has `get(id)` and `watch(id)` for its state, and `events(id)` and `list(id, { take, after })` for what it emitted. A view also has `snapshot(id)`: its state and the cursor to pass as `events(id, { after })`. A stream has `peek`, `watch`, `events` and `list`. What an Api serves authorizes itself, through its own middleware and `validate`.
344
345 More: [Api](https://alchemy.run/domain/api).
346
347 `toHttpApi(CustomerApi)` from `@alchemy.run/domain/Http` publishes every call of the Api as a plain HTTP JSON API with an OpenAPI document. See [hosting.md](hosting.md#plain-http-and-openapi).
348
349 `toMcp(CustomerApi)` from `@alchemy.run/domain/Ai` gives an agent each call that returns once as an MCP tool; `toToolkit` gives the same tools to an in-app agent. See [hosting.md](hosting.md#mcp).
350
351 `toCli(CustomerApi)` from `@alchemy.run/domain/Cli` runs each call that returns once from a terminal, over the deployed Api's HTTP protocol. See [hosting.md](hosting.md#cli).
352
353 ## Model
354
355 ```ts
356 // Bank.model.ts
357 export class Bank extends Domain.Model("Bank", {
358 aggregates: [Customer, UsernameClaim, Account, Transfer],
359 views: [AccountSummary, Statement, CustomerDashboard],
360 policies: [UsernameReservation, MainAccountProvisioning, TransferExecution],
361 projections: [Ledger, AccountCards],
362 streams: [AccountCard],
363 sagas: [ExecuteTransfer],
364 }) {}
365
366 /** Every policy, saga and projection implementation, as one Layer. */
367 export const BankHandlers = Layer.mergeAll(
368 UsernameReservationLive, MainAccountProvisioningLive, TransferExecutionLive,
369 ExecuteTransferLive, LedgerLive, AccountCardsLive,
370 );
371 ```
372
373 `Bank.layer(BankHandlers)` hosts the model on whatever platform is provided: `Domain.InMemory` or `DomainCloudflare.layerDurableObjects()`.
374
375 More: [Domain Model: Declare the model](https://alchemy.run/domain/model#declare-the-model).