@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, 04:45 UTC

main
mdx 172 lines 6.69 KB
Raw
1 ---
2 title: Unique values
3 description: Keep a value unique across every customer by making the value itself an aggregate.
4 ---
5
6 Usernames must be unique across all customers, but each customer is its own aggregate and can't see the others. Make the rule its own aggregate, keyed by the value it protects.
7
8 ## Make the username an aggregate
9
10 Each username is one instance. Two customers claiming the same name send commands to the same instance, which handles one at a time, so one of them wins.
11
12 ```typescript
13 // packages/domain/src/Customer/UsernameClaim.aggregate.ts
14 import * as Domain from "@alchemy.run/domain";
15 import * as Schema from "effect/Schema";
16 import { ClaimUsername, UsernameClaimed, UsernameTaken } from "./ClaimUsername.command.ts";
17 import { CustomerId } from "./Customer.id.ts";
18 import { Username } from "./Username.ts";
19
20 /**
21 * One username, and who holds it. Uniqueness spans every customer, so the
22 * invariant is its own aggregate, keyed by the username: two customers
23 * claiming the same name race on this one instance, and one of them wins.
24 */
25 export class UsernameClaim extends Domain.Aggregate("UsernameClaim", {
26 id: Username,
27 state: Schema.Union([
28 Schema.TaggedStruct("Free", {}),
29 Schema.TaggedStruct("Claimed", { customerId: CustomerId }),
30 ]),
31 initial: { _tag: "Free" },
32 commands: [ClaimUsername],
33 decide: {
34 ClaimUsername: (s, cmd) =>
35 s._tag === "Free"
36 ? [new UsernameClaimed({ customerId: cmd.customerId })]
37 : s.customerId === cmd.customerId
38 ? []
39 : new UsernameTaken(),
40 },
41 evolve: {
42 UsernameClaimed: (_, e) => ({ _tag: "Claimed" as const, customerId: e.customerId }),
43 },
44 }) {}
45 ```
46
47 Claiming a name you already hold records nothing, so a repeated claim is harmless.
48
49 ## Declare the claim
50
51 ```typescript
52 // packages/domain/src/Customer/ClaimUsername.command.ts
53 import * as Domain from "@alchemy.run/domain";
54 import { CustomerId } from "./Customer.id.ts";
55 import { Username } from "./Username.ts";
56
57 /** Someone else holds this username. */
58 export class UsernameTaken extends Domain.Rejection("UsernameTaken") {}
59
60 export class UsernameClaimed extends Domain.Event("UsernameClaimed", { customerId: CustomerId }) {}
61
62 /**
63 * Reserve a username for a customer. Sent by `UsernameReservation`; claiming
64 * a username the customer already holds records nothing.
65 */
66 export class ClaimUsername extends Domain.Command("ClaimUsername", {
67 target: Username,
68 input: { customerId: CustomerId },
69 events: [UsernameClaimed],
70 rejects: [UsernameTaken],
71 }) {}
72 ```
73
74 ## Claim it before registering
75
76 Registration records a request, and a policy claims the username before the customer counts as registered. A taken name rejects the registration, and nothing that follows a registration happens.
77
78 ```typescript
79 // packages/domain/src/Customer/UsernameReservation.policy.ts
80 import * as Domain from "@alchemy.run/domain";
81 import * as Effect from "effect/Effect";
82 import { ClaimUsername } from "./ClaimUsername.command.ts";
83 import { ConfirmRegistration } from "./ConfirmRegistration.command.ts";
84 import { Customer } from "./Customer.aggregate.ts";
85 import { RegistrationRequested } from "./RegisterCustomer.command.ts";
86 import { RejectRegistration } from "./RejectRegistration.command.ts";
87 import { UsernameClaim } from "./UsernameClaim.aggregate.ts";
88
89 /**
90 * Reserve first, then commit: claim the username, and only then register the
91 * customer. Nothing downstream (the main account) happens for a registration
92 * whose username is taken.
93 */
94 export class UsernameReservation extends Domain.Policy("UsernameReservation", {
95 from: Customer,
96 on: [RegistrationRequested],
97 }) {}
98
99 export const UsernameReservationLive = UsernameReservation.toLayer(
100 Effect.gen(function* () {
101 const claims = yield* UsernameClaim;
102 const customers = yield* Customer;
103 return Effect.fn(function* ({ source, event }) {
104 yield* claims.send(event.username, new ClaimUsername({ customerId: source.id })).pipe(
105 Effect.andThen(customers.send(source, new ConfirmRegistration())),
106 Effect.catchTag("UsernameTaken", () =>
107 customers.send(source, new RejectRegistration({ reason: "username taken" })),
108 ),
109 );
110 });
111 }),
112 );
113 ```
114
115 See [Saga](/domain/saga#take-the-step-you-cant-undo-first) for why the claim comes first.
116
117 ## Test it
118
119 ```typescript
120 // packages/domain/test/usernames.test.ts
121 import { it } from "@effect/vitest";
122 import { Story } from "@alchemy.run/domain/Story";
123 import { customer } from "../src/Actor.ts";
124 import * as Layer from "effect/Layer";
125 import { Bank, BankHandlers } from "../src/Bank.model.ts";
126 import { MemoryLedgerStore } from "../src/Ledger/LedgerStore.ts";
127 import { CurrentActor } from "../src/CurrentActor.context.ts";
128 import { ClaimUsername, UsernameClaimed, UsernameTaken } from "../src/Customer/ClaimUsername.command.ts";
129 import { CustomerId } from "../src/Customer/Customer.id.ts";
130 import { Customer } from "../src/Customer/Customer.aggregate.ts";
131 import { RegisterCustomer, RegistrationRequested } from "../src/Customer/RegisterCustomer.command.ts";
132 import { RegistrationRejected } from "../src/Customer/RejectRegistration.command.ts";
133 import { UsernameClaim } from "../src/Customer/UsernameClaim.aggregate.ts";
134 import { Username } from "../src/Customer/Username.ts";
135 import { FraudCheck } from "../src/Fraud/FraudCheck.external.ts";
136 import { Payments } from "../src/Settlement/Payments.external.ts";
137
138 const story = Story.make(Bank, {
139 layer: BankHandlers.pipe(Layer.provide(MemoryLedgerStore)),
140 stub: [FraudCheck, Payments],
141 });
142 const sam = Username.make("sam");
143 const samsClaim = UsernameClaim.ref("sam");
144
145 it.effect("a username can only be claimed once", () =>
146 story(
147 Story.when(samsClaim, new ClaimUsername({ customerId: CustomerId.make("c-1") })),
148 Story.then(samsClaim, new UsernameClaimed({ customerId: CustomerId.make("c-1") })),
149 Story.when(samsClaim, new ClaimUsername({ customerId: CustomerId.make("c-2") })),
150 Story.rejected(new UsernameTaken()),
151 ),
152 );
153
154 it.effect("registering with a taken username is rejected", () =>
155 story(
156 Story.given(samsClaim, new UsernameClaimed({ customerId: CustomerId.make("c-1") })),
157 Story.provide(CurrentActor, customer("c-2")),
158 Story.when(Customer.ref("c-2"), new RegisterCustomer({ name: "alex", username: sam })),
159 Story.then(
160 Customer.ref("c-2"),
161 new RegistrationRequested({ name: "alex", username: sam }),
162 new RegistrationRejected({ username: sam, reason: "username taken" }),
163 ),
164 ),
165 );
166 ```
167
168 The second customer's registration is requested, the policy finds the name taken, and the registration is rejected. No account is opened for it.
169
170 :::note
171 The full registration flow is in the [bank example](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-domain/packages/domain/src/Customer).
172 :::