The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Domain from "@alchemy.run/domain"; |
| 2 | import { InMemory } from "@alchemy.run/domain/InMemory"; |
| 3 | import { describe, expect, it } from "@alchemy.run/test"; |
| 4 | import * as Cause from "effect/Cause"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Exit from "effect/Exit"; |
| 7 | import * as HttpApi from "effect/http-api/HttpApi"; |
| 8 | import * as HttpApiEndpoint from "effect/http-api/HttpApiEndpoint"; |
| 9 | import * as HttpApiError from "effect/http-api/HttpApiError"; |
| 10 | import * as HttpApiGroup from "effect/http-api/HttpApiGroup"; |
| 11 | import * as OpenApi from "effect/http-api/OpenApi"; |
| 12 | import * as Headers from "effect/http/Headers"; |
| 13 | import * as Layer from "effect/Layer"; |
| 14 | import * as Option from "effect/Option"; |
| 15 | import * as RpcMiddleware from "effect/rpc/RpcMiddleware"; |
| 16 | import * as Schema from "effect/Schema"; |
| 17 | |
| 18 | class Deposited extends Domain.Event("Deposited", { amount: Schema.Number }) {} |
| 19 | class Withdrawn extends Domain.Event("Withdrawn", { amount: Schema.Number }) {} |
| 20 | class Closed extends Domain.Event("Closed") {} |
| 21 | |
| 22 | class InsufficientFunds extends Domain.Rejection("InsufficientFunds", { |
| 23 | balance: Schema.Number, |
| 24 | requested: Schema.Number, |
| 25 | }) {} |
| 26 | class AccountClosed extends Domain.Rejection("AccountClosed") {} |
| 27 | |
| 28 | class Deposit extends Domain.Command("Deposit", { |
| 29 | target: Schema.String, |
| 30 | input: { amount: Schema.Number }, |
| 31 | events: [Deposited], |
| 32 | rejects: [AccountClosed], |
| 33 | }) {} |
| 34 | class Withdraw extends Domain.Command("Withdraw", { |
| 35 | target: Schema.String, |
| 36 | input: { amount: Schema.Number }, |
| 37 | events: [Withdrawn], |
| 38 | rejects: [InsufficientFunds, AccountClosed], |
| 39 | }) {} |
| 40 | class Close extends Domain.Command("Close", { target: Schema.String, events: [Closed] }) {} |
| 41 | |
| 42 | class Account extends Domain.Aggregate("Account", { |
| 43 | id: Schema.String, |
| 44 | state: Schema.Struct({ balance: Schema.Number, closed: Schema.Boolean }), |
| 45 | initial: { balance: 0, closed: false }, |
| 46 | commands: [Deposit, Withdraw, Close], |
| 47 | decide: { |
| 48 | Deposit: (s, { amount }) => (s.closed ? new AccountClosed() : [new Deposited({ amount })]), |
| 49 | Withdraw: (s, { amount }) => |
| 50 | s.closed |
| 51 | ? new AccountClosed() |
| 52 | : amount > s.balance |
| 53 | ? new InsufficientFunds({ balance: s.balance, requested: amount }) |
| 54 | : [new Withdrawn({ amount })], |
| 55 | Close: (s) => (s.closed ? [] : [new Closed()]), |
| 56 | }, |
| 57 | evolve: { |
| 58 | Deposited: (s, e) => ({ ...s, balance: s.balance + e.amount }), |
| 59 | Withdrawn: (s, e) => ({ ...s, balance: s.balance - e.amount }), |
| 60 | Closed: (s) => ({ ...s, closed: true }), |
| 61 | }, |
| 62 | read: {}, |
| 63 | }) {} |
| 64 | |
| 65 | class Bank extends Domain.Model("Bank", { aggregates: [Account] }) {} |
| 66 | |
| 67 | class BankApi extends Domain.Api("BankApi", { |
| 68 | model: Bank, |
| 69 | commands: ["Deposit", "Withdraw"], |
| 70 | aggregates: ["Account"], |
| 71 | }) {} |
| 72 | class CloseApi extends Domain.Api("CloseApi", { |
| 73 | model: Bank, |
| 74 | commands: ["Close"], |
| 75 | aggregates: ["Account"], |
| 76 | }) {} |
| 77 | |
| 78 | /** A helper written once for every Api: the tags of its commands. */ |
| 79 | const tagsOf = <A extends Domain.Api.Any>(api: A): ReadonlyArray<Domain.Api.CommandsOf<A>["tag"]> => |
| 80 | api.commands.map((command) => command.tag); |
| 81 | |
| 82 | describe("Domain Api", { tags: ["unit", "local"] }, () => { |
| 83 | it.effect("a concrete Api is an Api.Any", () => |
| 84 | Effect.sync(() => { |
| 85 | const any: Domain.Api.Any = BankApi; |
| 86 | const tags: ReadonlyArray<"Deposit" | "Withdraw"> = tagsOf(BankApi); |
| 87 | expect(any.apiName).toBe("BankApi"); |
| 88 | expect(tags).toEqual(["Deposit", "Withdraw"]); |
| 89 | }), |
| 90 | ); |
| 91 | |
| 92 | it.effect("commands are the command classes, in the order the Api lists them", () => |
| 93 | Effect.sync(() => { |
| 94 | expect(BankApi.commands).toEqual([Deposit, Withdraw]); |
| 95 | expect(CloseApi.commands).toEqual([Close]); |
| 96 | }), |
| 97 | ); |
| 98 | |
| 99 | it.effect("rejections decodes every declared rejection to its class", () => |
| 100 | Effect.sync(() => { |
| 101 | const Rejection = BankApi.rejections; |
| 102 | const decoded = Schema.decodeUnknownSync(Rejection)({ |
| 103 | _tag: "InsufficientFunds", |
| 104 | balance: 1, |
| 105 | requested: 5, |
| 106 | }); |
| 107 | const typed: InsufficientFunds | AccountClosed = decoded; |
| 108 | // @ts-expect-error a union member is not one rejection |
| 109 | const narrow: InsufficientFunds = decoded; |
| 110 | expect(narrow).toBe(typed); |
| 111 | expect(decoded).toBeInstanceOf(InsufficientFunds); |
| 112 | expect(decoded).toMatchObject({ balance: 1, requested: 5 }); |
| 113 | expect(Schema.decodeUnknownSync(Rejection)({ _tag: "AccountClosed" })).toBeInstanceOf( |
| 114 | AccountClosed, |
| 115 | ); |
| 116 | // AccountClosed is declared by two commands, and is in the union once. |
| 117 | expect((Rejection as unknown as Schema.Union<ReadonlyArray<Schema.Top>>).members).toEqual([ |
| 118 | AccountClosed, |
| 119 | InsufficientFunds, |
| 120 | ]); |
| 121 | expect(() => Schema.decodeUnknownSync(Rejection)({ _tag: "Closed" })).toThrow(); |
| 122 | }), |
| 123 | ); |
| 124 | |
| 125 | it.effect("an Api whose commands never reject has Schema.Never rejections", () => |
| 126 | Effect.sync(() => { |
| 127 | const Rejection: typeof Schema.Never = CloseApi.rejections; |
| 128 | expect(Rejection).toBe(Schema.Never); |
| 129 | }), |
| 130 | ); |
| 131 | |
| 132 | it.live("a rejection from the client is a member of the schema", () => |
| 133 | Effect.gen(function* () { |
| 134 | const bank: Domain.Api.ClientOf<typeof BankApi> = yield* BankApi.Client; |
| 135 | const isRejection = Schema.is(BankApi.rejections); |
| 136 | const refused = yield* bank.Withdraw("a-1", { amount: 5 }).pipe(Effect.flip); |
| 137 | expect(isRejection(refused)).toBe(true); |
| 138 | expect(refused).toBeInstanceOf(InsufficientFunds); |
| 139 | }).pipe( |
| 140 | Effect.scoped, |
| 141 | Effect.provide( |
| 142 | BankApi.layerClientInProcess.pipe( |
| 143 | Layer.provide(Bank.layer(Layer.empty).pipe(Layer.provide(InMemory))), |
| 144 | ), |
| 145 | ), |
| 146 | ), |
| 147 | ); |
| 148 | |
| 149 | it.effect("an Api serves everything of a kind it does not list", () => |
| 150 | Effect.sync(() => { |
| 151 | class Everything extends Domain.Api("Everything", { model: Bank }) {} |
| 152 | expect(Bank.commands).toEqual([Deposit, Withdraw, Close]); |
| 153 | expect(Everything.commands).toEqual([Deposit, Withdraw, Close]); |
| 154 | expect(Everything.serves).toEqual([Deposit, Withdraw, Close, Account]); |
| 155 | }), |
| 156 | ); |
| 157 | |
| 158 | it.effect("by default an Api serves only the aggregates that declare read", () => |
| 159 | Effect.sync(() => { |
| 160 | // Vault declares no `read`, so the Api serves its commands and not its state. |
| 161 | class VaultsApi extends Domain.Api("VaultsApi", { model: Vaults }) {} |
| 162 | expect(VaultsApi.serves).toEqual([Store]); |
| 163 | }), |
| 164 | ); |
| 165 | |
| 166 | it.effect("naming an aggregate without read is a type error", () => |
| 167 | Effect.sync(() => { |
| 168 | // @ts-expect-error Vault declares no `read`, so it is not a name `aggregates` takes. |
| 169 | Domain.Api("VaultReads", { model: Vaults, aggregates: ["Vault"] }); |
| 170 | // Account declares one. |
| 171 | Domain.Api("AccountReads", { model: Bank, aggregates: ["Account"] }); |
| 172 | }), |
| 173 | ); |
| 174 | |
| 175 | it.effect("an Api serves none of a kind it lists as empty", () => |
| 176 | Effect.sync(() => { |
| 177 | class Reads extends Domain.Api("Reads", { |
| 178 | model: Bank, |
| 179 | commands: [], |
| 180 | aggregates: ["Account"], |
| 181 | }) {} |
| 182 | expect(Reads.commands).toEqual([]); |
| 183 | expect(Reads.serves).toEqual([Account]); |
| 184 | }), |
| 185 | ); |
| 186 | |
| 187 | it.effect("naming something its model does not hold is a type error", () => |
| 188 | Effect.sync(() => { |
| 189 | class Vaulted extends Domain.Model("Vaulted", { aggregates: [Vault] }) {} |
| 190 | // @ts-expect-error Deposit is not a command of the Vaulted model |
| 191 | const api = Domain.Api("Wrong", { model: Vaulted, commands: ["Deposit"] }); |
| 192 | expect(api.serves).toEqual([]); |
| 193 | // @ts-expect-error Account is an aggregate, not a command |
| 194 | Domain.Api("Mixed", { model: Bank, commands: ["Account"] }); |
| 195 | }), |
| 196 | ); |
| 197 | |
| 198 | it.live("naming something its model does not hold dies with a DefinitionError", () => |
| 199 | Effect.gen(function* () { |
| 200 | // Typed as any model, so only serving it can tell. |
| 201 | const model: Domain.Model.Any = Vaults; |
| 202 | class LooseApi extends Domain.Api("LooseApi", { model, commands: ["Deposit"] }) {} |
| 203 | const exit = yield* LooseApi.clientInProcess.pipe(Effect.scoped, Effect.exit); |
| 204 | expect(exit._tag).toBe("Failure"); |
| 205 | if (exit._tag !== "Failure") return; |
| 206 | expect(Cause.squash(exit.cause)).toMatchObject({ |
| 207 | _tag: "DefinitionError", |
| 208 | message: "Deposit is not part of the Vaults model", |
| 209 | }); |
| 210 | }).pipe(Effect.provide(Bank.layer(Layer.empty).pipe(Layer.provide(InMemory)))), |
| 211 | ); |
| 212 | }); |
| 213 | |
| 214 | // ---------------------------------------------------------------- rejections |
| 215 | |
| 216 | /** A plain Effect tagged error, and a Domain shorthand with Effect's annotations. */ |
| 217 | class Frozen extends Schema.TaggedError<Frozen>()("Frozen", { until: Schema.String }) {} |
| 218 | class NotOwner extends Domain.Rejection( |
| 219 | "NotOwner", |
| 220 | {}, |
| 221 | { httpApiStatus: 403, description: "Only the vault's owner may do this." }, |
| 222 | ) {} |
| 223 | |
| 224 | class Stored extends Domain.Event("Stored", { item: Schema.String }) {} |
| 225 | class Store extends Domain.Command("Store", { |
| 226 | target: Schema.String, |
| 227 | input: { item: Schema.String }, |
| 228 | events: [Stored], |
| 229 | // Any tagged error class can be a rejection, Effect's own HttpApiError included. |
| 230 | rejects: [Frozen, NotOwner, HttpApiError.Forbidden], |
| 231 | }) {} |
| 232 | class Vault extends Domain.Aggregate("Vault", { |
| 233 | id: Schema.String, |
| 234 | state: Schema.Struct({ items: Schema.Array(Schema.String) }), |
| 235 | initial: { items: [] }, |
| 236 | commands: [Store], |
| 237 | decide: { |
| 238 | Store: (_, { item }) => |
| 239 | item === "ice" |
| 240 | ? new Frozen({ until: "spring" }) |
| 241 | : item === "gold" |
| 242 | ? new HttpApiError.Forbidden() |
| 243 | : item === "keys" |
| 244 | ? new NotOwner() |
| 245 | : [new Stored({ item })], |
| 246 | }, |
| 247 | evolve: { Stored: (s, e) => ({ items: [...s.items, e.item] }) }, |
| 248 | }) {} |
| 249 | class Vaults extends Domain.Model("Vaults", { aggregates: [Vault] }) {} |
| 250 | class VaultApi extends Domain.Api("VaultApi", { model: Vaults, commands: ["Store"] }) {} |
| 251 | // Vault declares no `read`, so its state is not for clients: naming it is a |
| 252 | // type error, and serving it anyway dies. |
| 253 | // @ts-expect-error Vault declares no `read`, so it is not a name `aggregates` takes. |
| 254 | class VaultStateApi extends Domain.Api("VaultStateApi", { model: Vaults, aggregates: ["Vault"] }) {} |
| 255 | |
| 256 | describe("Domain Rejection", { tags: ["unit", "local"] }, () => { |
| 257 | it.live("a command rejects with any tagged error class, and the client gets it typed", () => |
| 258 | Effect.gen(function* () { |
| 259 | const vaults = yield* VaultApi.clientInProcess; |
| 260 | const frozen = yield* vaults.Store("v-1", { item: "ice" }).pipe(Effect.flip); |
| 261 | expect(frozen).toBeInstanceOf(Frozen); |
| 262 | expect(frozen).toMatchObject({ until: "spring" }); |
| 263 | const forbidden = yield* vaults.Store("v-1", { item: "gold" }).pipe(Effect.flip); |
| 264 | expect(forbidden).toBeInstanceOf(HttpApiError.Forbidden); |
| 265 | expect((yield* vaults.Store("v-1", { item: "keys" }).pipe(Effect.flip))._tag).toBe( |
| 266 | "NotOwner", |
| 267 | ); |
| 268 | const { reply } = yield* vaults.Store("v-1", { item: "coat" }); |
| 269 | expect(reply).toBeUndefined(); |
| 270 | // The Api's rejections decode every one of them. |
| 271 | expect(Schema.decodeUnknownSync(VaultApi.rejections)({ _tag: "Forbidden" })).toBeInstanceOf( |
| 272 | HttpApiError.Forbidden, |
| 273 | ); |
| 274 | }).pipe( |
| 275 | Effect.scoped, |
| 276 | Effect.provide(Vaults.layer(Layer.empty).pipe(Layer.provideMerge(InMemory))), |
| 277 | ), |
| 278 | ); |
| 279 | |
| 280 | it.effect( |
| 281 | "a Domain.Rejection takes Schema.TaggedError's annotations, read as Effect reads them", |
| 282 | () => |
| 283 | Effect.sync(() => { |
| 284 | // An Effect HttpApi endpoint that declares the rejection gives it its status and description. |
| 285 | const api = HttpApi.make("Vaults").add( |
| 286 | HttpApiGroup.make("vaults").add( |
| 287 | HttpApiEndpoint.post("store", "/store", { error: [NotOwner, Frozen] }), |
| 288 | ), |
| 289 | ); |
| 290 | const responses = OpenApi.fromApi(api).paths["/store"]!.post!.responses; |
| 291 | expect(Object.keys(responses).sort()).toEqual(["204", "403", "500"]); |
| 292 | expect(responses["403"]!.description).toBe("Only the vault's owner may do this."); |
| 293 | }), |
| 294 | ); |
| 295 | }); |
| 296 | |
| 297 | // ---------------------------------------------------------------- calling in process |
| 298 | |
| 299 | // ---------------------------------------------------------------- a notes domain |
| 300 | |
| 301 | /** Who sent the request. The middleware provides it; `decide` and `validate` read it. */ |
| 302 | class Author extends Domain.RequestContext<Author>()("Test/Author", Schema.String) {} |
| 303 | class Unauthenticated extends Domain.Rejection("Unauthenticated") {} |
| 304 | class NotYours extends Domain.Rejection("NotYours") {} |
| 305 | |
| 306 | /** Authenticates every call from an `x-author` header. */ |
| 307 | class AuthorSession extends RpcMiddleware.Service<AuthorSession, { provides: Author }>()( |
| 308 | "Test/AuthorSession", |
| 309 | { error: Unauthenticated }, |
| 310 | ) {} |
| 311 | const AuthorSessionLive = Layer.succeed(AuthorSession, (effect, { headers }) => |
| 312 | Option.match(Headers.get(headers, "x-author"), { |
| 313 | onNone: () => Effect.fail(new Unauthenticated()), |
| 314 | onSome: (name) => Effect.provideService(effect, Author, name), |
| 315 | }), |
| 316 | ); |
| 317 | /** Code that already knows who the caller is: provide it without checking a header. */ |
| 318 | const trustedAuthor = (name: string) => |
| 319 | Layer.succeed(AuthorSession, (effect) => Effect.provideService(effect, Author, name)); |
| 320 | |
| 321 | class Written extends Domain.Event("Written", { text: Schema.String, by: Schema.String }) {} |
| 322 | class Write extends Domain.Command("Write", { |
| 323 | target: Schema.String, |
| 324 | middleware: [AuthorSession], |
| 325 | input: { text: Schema.String }, |
| 326 | events: [Written], |
| 327 | reply: { by: Schema.String }, |
| 328 | }) {} |
| 329 | class Note extends Domain.Aggregate("Note", { |
| 330 | id: Schema.String, |
| 331 | state: Schema.Struct({ text: Schema.String, by: Schema.NullOr(Schema.String) }), |
| 332 | initial: { text: "", by: null }, |
| 333 | commands: [Write], |
| 334 | decide: { |
| 335 | Write: Effect.fn(function* (_, cmd) { |
| 336 | return [new Written({ text: cmd.text, by: yield* Author })]; |
| 337 | }), |
| 338 | }, |
| 339 | evolve: { Written: (_, e) => ({ text: e.text, by: e.by }) }, |
| 340 | reply: { Write: (s) => ({ by: s.by ?? "" }) }, |
| 341 | read: { |
| 342 | middleware: [AuthorSession], |
| 343 | rejects: [NotYours], |
| 344 | validate: Effect.fn(function* (_request, s) { |
| 345 | if (s.by !== null && s.by !== (yield* Author)) return yield* new NotYours(); |
| 346 | }), |
| 347 | }, |
| 348 | }) {} |
| 349 | |
| 350 | class Notes extends Domain.Model("Notes", { aggregates: [Note] }) {} |
| 351 | class NotesApi extends Domain.Api("NotesApi", { |
| 352 | model: Notes, |
| 353 | commands: ["Write"], |
| 354 | aggregates: ["Note"], |
| 355 | }) {} |
| 356 | |
| 357 | const World = Notes.layer(Layer.empty).pipe(Layer.provideMerge(InMemory)); |
| 358 | |
| 359 | describe("Domain Api in process", { tags: ["unit", "local"] }, () => { |
| 360 | it.live("clientInProcess calls an Api in process, through every entry's middleware", () => |
| 361 | Effect.gen(function* () { |
| 362 | const notes = yield* NotesApi.clientInProcess; |
| 363 | const asSam = { headers: { "x-author": "sam" } }; |
| 364 | |
| 365 | const refused = yield* notes.Write("n-1", { text: "hi" }).pipe(Effect.flip); |
| 366 | expect(refused._tag).toBe("Unauthenticated"); |
| 367 | |
| 368 | const { reply } = yield* notes.Write("n-1", { text: "hi" }, asSam); |
| 369 | expect(reply).toEqual({ by: "sam" }); |
| 370 | expect(yield* notes.Note.get("n-1", asSam)).toEqual({ text: "hi", by: "sam" }); |
| 371 | |
| 372 | const notYours = yield* notes.Note.get("n-1", { headers: { "x-author": "kim" } }).pipe( |
| 373 | Effect.flip, |
| 374 | ); |
| 375 | expect(notYours._tag).toBe("NotYours"); |
| 376 | }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(World, AuthorSessionLive))), |
| 377 | ); |
| 378 | |
| 379 | it.live("a trusted caller provides its principal with its own middleware Layer", () => |
| 380 | Effect.gen(function* () { |
| 381 | // The served Api keeps checking headers; only this client trusts its caller. |
| 382 | const asKim = yield* NotesApi.clientInProcess.pipe(Effect.provide(trustedAuthor("kim"))); |
| 383 | const { reply } = yield* asKim.Write("n-2", { text: "from a webhook" }); |
| 384 | expect(reply).toEqual({ by: "kim" }); |
| 385 | |
| 386 | const anonymous = yield* NotesApi.clientInProcess; |
| 387 | const refused = yield* anonymous.Note.get("n-2").pipe(Effect.flip); |
| 388 | expect(refused._tag).toBe("Unauthenticated"); |
| 389 | }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(World, AuthorSessionLive))), |
| 390 | ); |
| 391 | |
| 392 | it.live("layerClientInProcess provides the Api's Client in process", () => { |
| 393 | // Written against `NotesApi.Client`, so it runs remotely (layerClient) or in process (layerClientInProcess). |
| 394 | const writeAs = Effect.fn(function* (author: string) { |
| 395 | const notes = yield* NotesApi.Client; |
| 396 | return yield* notes.Write( |
| 397 | "n-3", |
| 398 | { text: "shared code" }, |
| 399 | { headers: { "x-author": author } }, |
| 400 | ); |
| 401 | }); |
| 402 | return writeAs("sam").pipe( |
| 403 | Effect.map(({ reply }) => expect(reply).toEqual({ by: "sam" })), |
| 404 | Effect.provide( |
| 405 | NotesApi.layerClientInProcess.pipe( |
| 406 | Layer.provideMerge(Layer.mergeAll(World, AuthorSessionLive)), |
| 407 | ), |
| 408 | ), |
| 409 | ); |
| 410 | }); |
| 411 | |
| 412 | it.live("client runs over Domain.protocolInProcess", () => |
| 413 | Effect.gen(function* () { |
| 414 | const notes = yield* NotesApi.client; |
| 415 | const asSam = { headers: { "x-author": "sam" } }; |
| 416 | const { reply } = yield* notes.Write("n-4", { text: "over a protocol" }, asSam); |
| 417 | expect(reply).toEqual({ by: "sam" }); |
| 418 | expect(yield* notes.Note.get("n-4", asSam)).toEqual({ text: "over a protocol", by: "sam" }); |
| 419 | }).pipe( |
| 420 | Effect.scoped, |
| 421 | Effect.provide( |
| 422 | Domain.protocolInProcess(NotesApi).pipe( |
| 423 | Layer.provideMerge(Layer.mergeAll(World, AuthorSessionLive)), |
| 424 | ), |
| 425 | ), |
| 426 | ), |
| 427 | ); |
| 428 | }); |
| 429 | |
| 430 | describe("Domain Api exposing an aggregate", () => { |
| 431 | it.live("an aggregate without a read contract is never served", () => |
| 432 | Effect.gen(function* () { |
| 433 | const exit = yield* Effect.exit(VaultStateApi.clientInProcess); |
| 434 | expect(Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined).toMatchObject({ |
| 435 | _tag: "DefinitionError", |
| 436 | reason: { _tag: "Unreadable", aggregate: "Vault" }, |
| 437 | }); |
| 438 | }).pipe( |
| 439 | Effect.scoped, |
| 440 | Effect.provide(Vaults.layer(Layer.empty).pipe(Layer.provideMerge(InMemory))), |
| 441 | ), |
| 442 | ); |
| 443 | }); |