Unique values
Usernames must be unique across all customers, but each customer is its own aggregate and can’t see the others. Give the rule an aggregate of its own, keyed by the value it protects, and decide the registration across both.
Make the username an aggregate
Section titled “Make the username an aggregate”Each username is one instance, and it holds who has it. Every registration that asks for a name reads the same instance, so two can’t both find it free.
import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { CustomerId } from "./Customer.id.ts";import { UsernameClaimed } from "./RegisterCustomer.command.ts";import { Username } from "./Username.ts";
/** * One username, and who holds it. Uniqueness spans every customer, so the * invariant has an aggregate of its own, keyed by the username: every * registration that asks for a name reads this one instance. */export class UsernameClaim extends Domain.Aggregate("UsernameClaim", { id: Username, state: Schema.Union([ Schema.TaggedStruct("Free", {}), Schema.TaggedStruct("Claimed", { customerId: CustomerId }), ]), initial: { _tag: "Free" }, events: [UsernameClaimed], evolve: { UsernameClaimed: (_, e) => ({ _tag: "Claimed" as const, customerId: e.customerId }), },}) {}It has no commands of its own. It only folds UsernameClaimed, which the registration records on it.
Declare the registration
Section titled “Declare the registration”Registering involves two instances, the customer and the username. The command’s input names both.
import * as Domain from "@alchemy.run/domain";import * as Schema from "effect/Schema";import { Session } from "../Session.middleware.ts";import { CustomerId } from "./Customer.id.ts";import { Username } from "./Username.ts";
/** The customer is already registered. */export class AlreadyRegistered extends Domain.Rejection("AlreadyRegistered") {}
/** A customer may only register themselves. */export class NotTheCustomer extends Domain.Rejection("NotTheCustomer") {}
/** Someone else holds this username. */export class UsernameTaken extends Domain.Rejection("UsernameTaken") {}
export class CustomerRegistered extends Domain.Event("CustomerRegistered", { name: Schema.String, username: Username,}) {}
export class UsernameClaimed extends Domain.Event("UsernameClaimed", { customerId: CustomerId }) {}
/** * Sign up as a customer under a unique username. It involves the customer * and the username, so `Registration` decides it across both; * `MainAccountProvisioning` then opens the customer's main account. */export class RegisterCustomer extends Domain.Command("RegisterCustomer", { middleware: [Session], input: { customerId: CustomerId, name: Schema.String, username: Username }, events: [CustomerRegistered, UsernameClaimed], rejects: [AlreadyRegistered, NotTheCustomer, UsernameTaken],}) {}Decide the claim with the registration
Section titled “Decide the claim with the registration”A decision reads the customer and the username together. It records the registration on one and the claim on the other, or it refuses and records nothing.
import * as Domain from "@alchemy.run/domain";import * as Effect from "effect/Effect";import { CurrentActor } from "../CurrentActor.context.ts";import { Customer } from "./Customer.aggregate.ts";import { AlreadyRegistered, CustomerRegistered, NotTheCustomer, RegisterCustomer, UsernameClaimed, UsernameTaken,} from "./RegisterCustomer.command.ts";import { UsernameClaim } from "./UsernameClaim.aggregate.ts";
/** * Register a customer and claim their username together. Both are recorded, * or neither is: a taken username rejects the registration, and two * customers who ask for one name at the same moment can't both get it. */export class Registration extends Domain.Decision(RegisterCustomer, { reads: { customer: Customer, claim: UsernameClaim }, keyOf: (cmd) => ({ customer: cmd.customerId, claim: cmd.username }), decide: Effect.fn(function* ({ customer, claim }, cmd) { const actor = yield* CurrentActor; if (actor._tag === "Customer" && actor.customerId !== customer.id) { return yield* new NotTheCustomer(); } if (customer.state._tag === "Registered") return yield* new AlreadyRegistered(); if (claim.state._tag === "Claimed") return yield* new UsernameTaken(); return [ customer.record(new CustomerRegistered({ name: cmd.name, username: cmd.username })), claim.record(new UsernameClaimed({ customerId: customer.id })), ]; }),}) {}The caller learns at once. A taken name fails the command with UsernameTaken, and the customer is never left half registered.
Two customers who ask for sam at the same moment both read UsernameClaim/sam. One commits first. The other finds the username changed since it read it, decides again, and is refused.
Test it
Section titled “Test it”import { it } from "@effect/vitest";import { Story } from "@alchemy.run/domain/Story";import * as Layer from "effect/Layer";import { Account } from "../src/Account/Account.aggregate.ts";import { mainAccountId } from "../src/Account/Account.id.ts";import { AccountOpened } from "../src/Account/OpenAccount.command.ts";import { customer } from "../src/Actor.ts";import { Bank, BankHandlers } from "../src/Bank.model.ts";import { CurrentActor } from "../src/CurrentActor.context.ts";import { Customer } from "../src/Customer/Customer.aggregate.ts";import { CustomerId } from "../src/Customer/Customer.id.ts";import { CustomerRegistered, RegisterCustomer, UsernameClaimed, UsernameTaken,} from "../src/Customer/RegisterCustomer.command.ts";import { Registration } from "../src/Customer/Registration.decision.ts";import { Username } from "../src/Customer/Username.ts";import { UsernameClaim } from "../src/Customer/UsernameClaim.aggregate.ts";import { FraudCheck } from "../src/Fraud/FraudCheck.external.ts";import { MemoryLedgerStore } from "../src/Ledger/LedgerStore.ts";import { Payments } from "../src/Settlement/Payments.external.ts";
const story = Story.make(Bank, { layer: BankHandlers.pipe(Layer.provide(MemoryLedgerStore)), stub: [FraudCheck, Payments],});const sam = Username.make("sam");const c1 = CustomerId.make("c-1");const c2 = CustomerId.make("c-2");
it.effect("registering claims the username with it, then opens a main account", () => story( Story.provide(CurrentActor, customer("c-1")), Story.when(new RegisterCustomer({ customerId: Registration.id, customerId: c1, name: "sam", username: sam })), Story.then(Customer.ref("c-1"), new CustomerRegistered({ name: "sam", username: sam })), Story.then(UsernameClaim.ref("sam"), new UsernameClaimed({ customerId: c1 })), Story.then(Account.ref(mainAccountId(c1)), new AccountOpened({ customerId: c1, owner: "sam" })), ),);
it.effect("a taken username rejects the registration, and nothing is recorded", () => story( Story.given(UsernameClaim.ref("sam"), new UsernameClaimed({ customerId: c1 })), Story.provide(CurrentActor, customer("c-2")), Story.when(new RegisterCustomer({ customerId: Registration.id, customerId: c2, name: "alex", username: sam })), Story.rejected(new UsernameTaken()), Story.then(Customer.ref("c-2")), ),);A registration that commits opens the customer’s main account, through a policy on CustomerRegistered. A rejected one records nothing, so nothing follows it.