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, 04:45 UTC
| 1 | --- |
| 2 | title: Command |
| 3 | description: How a command names its target, carries its data, declares every outcome, and reaches its aggregate exactly once. |
| 4 | --- |
| 5 | |
| 6 | import DAG from "../../../components/DAG.astro"; |
| 7 | |
| 8 | A command asks one aggregate instance for a change. It's a request, so it can be refused, and it's named as an instruction: `OpenAccount`, `DepositMoney`, `WithdrawMoney`. |
| 9 | |
| 10 | A command is also a contract. Before you send one, its declaration tells you which instance it goes to, what data it carries, which events it may record, which refusals it may return, and what you get back. This chapter starts with how to find the commands in a business, then goes through the declaration one part at a time, and follows a command as it's sent. |
| 11 | |
| 12 | ## Find the commands in your business |
| 13 | |
| 14 | Commands come from the verbs people use when they describe their work. At a bank, for example, a customer *opens* an account, *deposits* money, *withdraws* cash, *requests* a transfer; a support agent *freezes* an account, *approves* a large transfer. Each of those sentences is a command, named the way the business says it. |
| 15 | |
| 16 | <DAG |
| 17 | nodes={[ |
| 18 | { id: "customer", label: "Customer", type: "who asks", kind: "client", layer: 0 }, |
| 19 | { id: "agent", label: "Support agent", type: "who asks", kind: "client", layer: 0 }, |
| 20 | { id: "withdraw", label: "WithdrawMoney", type: "a customer's intent", kind: "command", layer: 1 }, |
| 21 | { id: "freeze", label: "FreezeAccount", type: "an agent's intent", kind: "command", layer: 1 }, |
| 22 | { id: "account", label: "Account", type: "decides both", kind: "aggregate", layer: 2 }, |
| 23 | ]} |
| 24 | edges={[ |
| 25 | { from: "customer", to: "withdraw" }, |
| 26 | { from: "agent", to: "freeze" }, |
| 27 | { from: "withdraw", to: "account" }, |
| 28 | { from: "freeze", to: "account" }, |
| 29 | ]} |
| 30 | caption="Each command is one thing someone wants, in the words they'd use to ask for it." |
| 31 | /> |
| 32 | |
| 33 | The opposite is a command named after the data it touches: `UpdateAccount`, `SetBalance`, `PatchCustomer`. Those say what changes in storage, but not why. An `UpdateAccount` that sets `frozen: true` and one that sets `owner: "kim"` are different requests with different rules: who may make them, when they're refused, and what the history should say afterwards. Give each intent its own command, `FreezeAccount` and `ChangeOwner`, so each gets its own rules, its own refusals and its own event. |
| 34 | |
| 35 | A useful test: read the command's name aloud to someone who works in the business. If they'd say "yes, customers do that", it's a good command. If they'd ask "update it how?", split it. |
| 36 | |
| 37 | ## Carry the intent, not the outcome |
| 38 | |
| 39 | A command carries what the caller knows and wants. It doesn't carry what the aggregate will work out. A withdrawal says how much to withdraw; it doesn't say what the balance will be afterwards, because only the account knows its balance at the moment it decides. |
| 40 | |
| 41 | ```typescript |
| 42 | new WithdrawMoney({ amount: 30 }); // the intent |
| 43 | new MoneyWithdrawn({ amount: 30, balanceAfter: 70 }); // the outcome, decided by the account |
| 44 | ``` |
| 45 | |
| 46 | That split keeps every rule in the aggregate. A client can't send a balance it made up, and two clients that both read a balance of 100 can't both withdraw 80: the account decides each withdrawal against its own state, one at a time. |
| 47 | |
| 48 | ## Declare a command |
| 49 | |
| 50 | Here is a withdrawal from the bank in the [tutorial](/domain/tutorial/part-1). |
| 51 | |
| 52 | ```typescript title="src/WithdrawMoney.command.ts" |
| 53 | export class WithdrawMoney extends Domain.Command("WithdrawMoney", { |
| 54 | target: AccountId, |
| 55 | input: { amount: Schema.Int }, |
| 56 | events: [MoneyWithdrawn], |
| 57 | rejects: [NotOpen, InsufficientFunds], |
| 58 | reply: { balance: Schema.Int }, |
| 59 | }) {} |
| 60 | ``` |
| 61 | |
| 62 | The first argument is the command's name. It's how the command is identified on the wire and in the aggregate's handlers, so it must be unique within a model. |
| 63 | |
| 64 | ## Keep it with its events and rejections |
| 65 | |
| 66 | A command, the events it records and the rejections it returns are one unit: you read them together, and change them together. Put them in one file named after the command, with a `.command.ts` suffix, like `WithdrawMoney.command.ts`. See [Project layout](/domain/project-layout). |
| 67 | |
| 68 | ```typescript title="src/WithdrawMoney.command.ts" |
| 69 | export class MoneyWithdrawn extends Domain.Event("MoneyWithdrawn", { |
| 70 | amount: Schema.Int, |
| 71 | balanceAfter: Schema.Int, |
| 72 | }) {} |
| 73 | |
| 74 | export class InsufficientFunds extends Domain.Rejection("InsufficientFunds", { |
| 75 | balance: Schema.Int, |
| 76 | requested: Schema.Int, |
| 77 | }) {} |
| 78 | ``` |
| 79 | |
| 80 | When more than one command uses something, it moves to a file of its own. Deposits and withdrawals both refuse an account that isn't open, so `NotOpen` has its own file, `NotOpen.rejection.ts`, and both import it. |
| 81 | |
| 82 | ```typescript title="src/NotOpen.rejection.ts" |
| 83 | export class NotOpen extends Domain.Rejection("NotOpen") {} |
| 84 | ``` |
| 85 | |
| 86 | The aggregate's file then holds only its state and how it decides and evolves, and imports each command from its file. The same goes for ids, like `AccountId`, which the commands and the aggregate share. |
| 87 | |
| 88 | ## Address one instance |
| 89 | |
| 90 | `target` is the schema of the id the command is addressed to. A withdrawal goes to one account, so its target is an `AccountId`. |
| 91 | |
| 92 | ```typescript title="src/Account.id.ts" |
| 93 | export const AccountId = Schema.String.pipe(Schema.brand("AccountId")); |
| 94 | ``` |
| 95 | |
| 96 | The brand makes the id its own type. A `CustomerId` is a string too, but passing one where an `AccountId` is expected is a type error, so a command can't be sent to the wrong kind of instance. |
| 97 | |
| 98 | The target must be the id of the aggregate that lists the command. If `Account` lists a command whose target is a `CustomerId`, or a plain `Schema.String`, that entry in `Account`'s `commands` is a type error that names the command. |
| 99 | |
| 100 | The target isn't part of the command's data. You pass it alongside the command when you send it, and the model uses it to route the command to that one instance. |
| 101 | |
| 102 | ## Carry the request's data |
| 103 | |
| 104 | `input` lists the fields the caller provides, each as a schema. You create the command with them, and the aggregate reads them in `decide`. |
| 105 | |
| 106 | ```typescript title="src/Account.aggregate.ts" |
| 107 | WithdrawMoney: (s, cmd) => |
| 108 | s._tag !== "Open" |
| 109 | ? new NotOpen() |
| 110 | : cmd.amount > s.balance |
| 111 | ? new InsufficientFunds({ balance: s.balance, requested: cmd.amount }) |
| 112 | : [new MoneyWithdrawn({ amount: cmd.amount, balanceAfter: s.balance - cmd.amount })], |
| 113 | ``` |
| 114 | |
| 115 | The schemas also decode the command when it arrives from a client, so `decide` only ever sees well-formed input. A command with no input, like a request to close an account, leaves `input` out. |
| 116 | |
| 117 | ## Declare every outcome |
| 118 | |
| 119 | A command can end in one of two ways: the aggregate records events, or it refuses. `events` lists the events the command may record, and `rejects` lists the refusals it may return. |
| 120 | |
| 121 | A refusal is a `Domain.Rejection`, a typed error that can carry data about why. |
| 122 | |
| 123 | ```typescript title="src/WithdrawMoney.command.ts" |
| 124 | export class InsufficientFunds extends Domain.Rejection("InsufficientFunds", { |
| 125 | balance: Schema.Int, |
| 126 | requested: Schema.Int, |
| 127 | }) {} |
| 128 | ``` |
| 129 | |
| 130 | Both lists are enforced by the types. The aggregate's `decide` handler for `WithdrawMoney` can only return `MoneyWithdrawn` events or one of its two rejections. And whoever sends it gets exactly `NotOpen | InsufficientFunds` in the error channel, so they can handle each case by name. |
| 131 | |
| 132 | A rejection means nothing happened. No event is recorded and the state is unchanged, so the caller can safely try again with different input. |
| 133 | |
| 134 | Name a rejection after the business reason, the way you'd explain it to the customer: `InsufficientFunds`, `NotOpen`, `DailyLimitExceeded`. Give it the data the caller needs to do something about it. `InsufficientFunds` carries the balance and the amount requested, so an app can say "you have 50, you asked for 80" without a second read. |
| 135 | |
| 136 | ## Annotate a rejection |
| 137 | |
| 138 | `Domain.Rejection` is `Schema.TaggedError` with its own type filled in, so its third argument takes the same annotations. An HTTP API reads `httpApiStatus` from it, as it does for any Effect error: |
| 139 | |
| 140 | ```typescript title="src/NotOwner.rejection.ts" |
| 141 | export class NotOwner extends Domain.Rejection( |
| 142 | "NotOwner", |
| 143 | {}, |
| 144 | { httpApiStatus: 403, description: "Only the account's owner may do this." }, |
| 145 | ) {} |
| 146 | ``` |
| 147 | |
| 148 | `rejects` takes any tagged error class, so a `Schema.TaggedError` of your own, or one of Effect's `HttpApiError` classes, works as a rejection too: |
| 149 | |
| 150 | ```typescript |
| 151 | class WithdrawMoney extends Domain.Command("WithdrawMoney", { |
| 152 | target: AccountId, |
| 153 | input: { amount: Cents }, |
| 154 | events: [MoneyWithdrawn], |
| 155 | rejects: [InsufficientFunds, HttpApiError.Forbidden], |
| 156 | }) {} |
| 157 | ``` |
| 158 | |
| 159 | ## Report a fact that can't be refused |
| 160 | |
| 161 | Some commands don't ask permission. They tell the model about something that already happened outside it: a card payment settled at the payment processor, a deadline passed. The model can't refuse a fact, so these commands declare no `rejects`. Their aggregate records what the fact means for it instead, even when the news is bad. |
| 162 | |
| 163 | ```typescript title="packages/domain/src/Account/RecordSettlement.command.ts" |
| 164 | export class RecordSettlement extends Domain.Command("RecordSettlement", { |
| 165 | target: AccountId, |
| 166 | input: { settlementId: Schema.String, amount: Cents }, |
| 167 | events: [SettlementReceived, SettlementOnClosedAccount], |
| 168 | }) {} |
| 169 | ``` |
| 170 | |
| 171 | Money that settles on a closed account is still recorded, as `SettlementOnClosedAccount`, and a policy refunds it. See [External System](/domain/external-system#turn-outside-events-into-commands). |
| 172 | |
| 173 | ## Reply to the caller |
| 174 | |
| 175 | `reply` is what the caller gets back after the events commit. Here, the balance after the withdrawal. |
| 176 | |
| 177 | The aggregate computes it from its state after the events, in a `reply` handler named after the command. |
| 178 | |
| 179 | ```typescript title="src/Account.aggregate.ts" |
| 180 | reply: { |
| 181 | DepositMoney: (s) => ({ balance: s._tag === "Open" ? s.balance : 0 }), |
| 182 | WithdrawMoney: (s) => ({ balance: s._tag === "Open" ? s.balance : 0 }), |
| 183 | }, |
| 184 | ``` |
| 185 | |
| 186 | A command without a `reply` still tells the caller where it committed. See [the receipt](#send-it) below. |
| 187 | |
| 188 | ## Guard it with middleware |
| 189 | |
| 190 | Before a command reaches its aggregate, it can pass through middleware. In the full example bank, a withdrawal first authenticates the caller with `Session`, then asks for a second factor with `MfaChallenge`. |
| 191 | |
| 192 | ```typescript title="packages/domain/src/Account/WithdrawMoney.command.ts" |
| 193 | export class WithdrawMoney extends Domain.Command("WithdrawMoney", { |
| 194 | target: AccountId, |
| 195 | middleware: [Session, MfaChallenge], |
| 196 | input: { amount: Cents }, |
| 197 | events: [MoneyWithdrawn], |
| 198 | rejects: [NotOpen, NotOwner, Frozen, InsufficientFunds, DailyLimitExceeded], |
| 199 | reply: { balance: Cents }, |
| 200 | // Recorded on every span the withdrawal passes through; nothing else from it is. |
| 201 | attributes: (cmd) => ({ "bank.amount": cmd.amount }), |
| 202 | }) {} |
| 203 | ``` |
| 204 | |
| 205 | `attributes` chooses what its spans record; see [Observability](/domain/observability). |
| 206 | |
| 207 | Middleware runs in order, and any of it can stop the command with its own error, like `Unauthorized`. What it provides, such as who the caller is, travels with the command to the aggregate, where `decide` reads it to authorize the change. See [Sessions and middleware](/domain/sessions). |
| 208 | |
| 209 | A client can run the same `decide` with `Account.predict` when it provides what the middleware would, from a client-side Layer. See [Optimistic updates](/domain/optimistic-updates#bound-this-pattern). |
| 210 | |
| 211 | ## Send it |
| 212 | |
| 213 | Inside a hosted model, you send a command through the aggregate's client, with the target id first. |
| 214 | |
| 215 | ```typescript title="src/MainAccountProvisioning.policy.ts" |
| 216 | yield* accounts |
| 217 | .send(AccountId.make(`${source.id}-main`), new OpenAccount({ owner: source.id })) |
| 218 | .pipe(Effect.catchTag("AlreadyOpen", () => Effect.void)); |
| 219 | ``` |
| 220 | |
| 221 | From a client of an [Api](/domain/api), each command is a method that takes the target, the input, and optional call options: `bank.WithdrawMoney(accountId, { amount: 2_000 })`. |
| 222 | |
| 223 | Either way, `send` succeeds once the events have committed, with a receipt. It holds the stream and the version the instance committed at, the events it recorded, and the reply. |
| 224 | |
| 225 | ## Send it exactly once |
| 226 | |
| 227 | Networks fail after a command commits but before its receipt arrives. A client that retries could withdraw twice. |
| 228 | |
| 229 | Every command has an id to prevent that. The instance stores each receipt under its command's id, and when the same id arrives again, it returns the stored receipt without deciding again. Pass your own `commandId` when you might retry: |
| 230 | |
| 231 | ```typescript title="packages/server/test/withdrawOnce.ts" |
| 232 | const first = yield* bank.WithdrawMoney(accountId, { amount: 2_000 }, { commandId: requestId, ...mfa }); |
| 233 | const retry = yield* bank.WithdrawMoney(accountId, { amount: 2_000 }, { commandId: requestId, ...mfa }); |
| 234 | first.version === retry.version; // true |
| 235 | ``` |
| 236 | |
| 237 | Both calls return the same receipt, and the money leaves the account once. Without a `commandId`, each send gets a fresh one. |
| 238 | |
| 239 | Commands sent by a [policy](/domain/policy) get ids derived from the event that caused them, so a policy that runs twice for the same event sends the same commands, and each takes effect once. |
| 240 | |
| 241 | ## Send it later |
| 242 | |
| 243 | A command can also be scheduled to arrive at a later time, which is how deadlines work: "expire this transfer if nobody approves it within a day". Only commands that can't be refused can be scheduled, because there's no caller waiting to handle a rejection. See [Deadlines](/domain/deadlines). |
| 244 | |
| 245 | ```typescript title="packages/domain/src/Transfer/TransferApprovalDeadline.policy.ts" |
| 246 | yield* transfers.schedule(source, new ExpireTransfer(), { after: APPROVAL_WINDOW }).pipe( |
| 247 | Effect.catchTag("AlreadyExecuted", () => Effect.void), |
| 248 | ); |
| 249 | ``` |
| 250 | |
| 251 | Scheduling fails with `AlreadyExecuted` when the transfer already handled a command with that id. |
| 252 | |
| 253 | Next, [Event](/domain/event): what a command records when it succeeds. |