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 | import * as Domain from "@alchemy.run/domain"; |
| 2 | import * as 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 Context from "effect/Context"; |
| 6 | import * as DateTime from "effect/DateTime"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Layer from "effect/Layer"; |
| 9 | import * as Option from "effect/Option"; |
| 10 | import * as RpcMiddleware from "effect/rpc/RpcMiddleware"; |
| 11 | import * as Schema from "effect/Schema"; |
| 12 | |
| 13 | // Who operates the bank: what a session middleware would provide. |
| 14 | class Operator extends Domain.RequestContext<Operator>()("Test/Operator", Schema.String) {} |
| 15 | class Unauthenticated extends Domain.Rejection("Unauthenticated") {} |
| 16 | class OperatorSession extends RpcMiddleware.Service<OperatorSession, { provides: Operator }>()( |
| 17 | "Test/OperatorSession", |
| 18 | { error: Unauthenticated }, |
| 19 | ) {} |
| 20 | |
| 21 | class Opened extends Domain.Event("Opened", { owner: Schema.String, at: Schema.Number }) {} |
| 22 | class Deposited extends Domain.Event("Deposited", { amount: Schema.Number }) {} |
| 23 | class Withdrawn extends Domain.Event("Withdrawn", { amount: Schema.Number }) {} |
| 24 | class Frozen extends Domain.Event("Frozen", { by: Schema.String }) {} |
| 25 | class Stamped extends Domain.Event("Stamped", { |
| 26 | commandId: Schema.String, |
| 27 | stream: Schema.String, |
| 28 | version: Schema.Number, |
| 29 | }) {} |
| 30 | |
| 31 | class InsufficientFunds extends Domain.Rejection("InsufficientFunds", { |
| 32 | balance: Schema.Number, |
| 33 | requested: Schema.Number, |
| 34 | }) {} |
| 35 | class NotAnOperator extends Domain.Rejection("NotAnOperator") {} |
| 36 | |
| 37 | class Open extends Domain.Command("Open", { |
| 38 | target: Schema.String, |
| 39 | input: { owner: Schema.String }, |
| 40 | events: [Opened], |
| 41 | }) {} |
| 42 | class Deposit extends Domain.Command("Deposit", { |
| 43 | target: Schema.String, |
| 44 | input: { amount: Schema.Number }, |
| 45 | events: [Deposited], |
| 46 | }) {} |
| 47 | class Withdraw extends Domain.Command("Withdraw", { |
| 48 | target: Schema.String, |
| 49 | input: { amount: Schema.Number }, |
| 50 | events: [Withdrawn], |
| 51 | rejects: [InsufficientFunds], |
| 52 | }) {} |
| 53 | // Reads the operator, so a client predicts it only with the operator in context. |
| 54 | class Freeze extends Domain.Command("Freeze", { |
| 55 | target: Schema.String, |
| 56 | events: [Frozen], |
| 57 | rejects: [NotAnOperator], |
| 58 | middleware: [OperatorSession], |
| 59 | }) {} |
| 60 | // Records what decide is told about the command and the stream. |
| 61 | class Stamp extends Domain.Command("Stamp", { target: Schema.String, events: [Stamped] }) {} |
| 62 | |
| 63 | const AccountState = Schema.Struct({ |
| 64 | owner: Schema.String, |
| 65 | balance: Schema.Number, |
| 66 | frozen: Schema.Boolean, |
| 67 | }); |
| 68 | |
| 69 | class Account extends Domain.Aggregate("Account", { |
| 70 | id: Schema.String, |
| 71 | state: AccountState, |
| 72 | initial: { owner: "", balance: 0, frozen: false }, |
| 73 | commands: [Open, Deposit, Withdraw, Freeze, Stamp], |
| 74 | decide: { |
| 75 | Open: (_, { owner }, { now }) => [new Opened({ owner, at: DateTime.toEpochMillis(now) })], |
| 76 | Deposit: (_, { amount }) => [new Deposited({ amount })], |
| 77 | Withdraw: (s, { amount }) => |
| 78 | amount > s.balance |
| 79 | ? new InsufficientFunds({ balance: s.balance, requested: amount }) |
| 80 | : [new Withdrawn({ amount })], |
| 81 | Freeze: Effect.fn(function* () { |
| 82 | const operator = yield* Operator; |
| 83 | if (operator === "guest") return yield* new NotAnOperator(); |
| 84 | return [new Frozen({ by: operator })]; |
| 85 | }), |
| 86 | Stamp: (_, __, { commandId, stream, version }) => [new Stamped({ commandId, stream, version })], |
| 87 | }, |
| 88 | evolve: { |
| 89 | Opened: (s, e) => ({ ...s, owner: e.owner }), |
| 90 | Deposited: (s, e) => ({ ...s, balance: s.balance + e.amount }), |
| 91 | Withdrawn: (s, e) => ({ ...s, balance: s.balance - e.amount }), |
| 92 | Frozen: (s) => ({ ...s, frozen: true }), |
| 93 | Stamped: (s) => s, |
| 94 | }, |
| 95 | }) {} |
| 96 | |
| 97 | class Moved extends Domain.Event("Moved", { |
| 98 | from: Schema.String, |
| 99 | to: Schema.String, |
| 100 | amount: Schema.Number, |
| 101 | }) {} |
| 102 | class Move extends Domain.Command("Move", { |
| 103 | target: Schema.String, |
| 104 | input: { from: Schema.String, to: Schema.String, amount: Schema.Number }, |
| 105 | events: [Moved], |
| 106 | }) {} |
| 107 | class Transfer extends Domain.Aggregate("Transfer", { |
| 108 | id: Schema.String, |
| 109 | state: Schema.Struct({}), |
| 110 | initial: {}, |
| 111 | commands: [Move], |
| 112 | decide: { Move: (_, { from, to, amount }) => [new Moved({ from, to, amount })] }, |
| 113 | evolve: { Moved: (s) => s }, |
| 114 | }) {} |
| 115 | |
| 116 | class Balance extends Domain.View("Balance", { |
| 117 | from: [Account], |
| 118 | key: Account, |
| 119 | state: Schema.Struct({ balance: Schema.Number, lines: Schema.Number }), |
| 120 | initial: { balance: 0, lines: 0 }, |
| 121 | evolve: { |
| 122 | Deposited: (s, e) => ({ balance: s.balance + e.amount, lines: s.lines + 1 }), |
| 123 | Withdrawn: (s, e) => ({ balance: s.balance - e.amount, lines: s.lines + 1 }), |
| 124 | }, |
| 125 | }) {} |
| 126 | |
| 127 | // One transfer updates two keys: the sender's as `out`, the recipient's as `in`. |
| 128 | class Flows extends Domain.View("Flows", { |
| 129 | from: [Transfer], |
| 130 | key: Account, |
| 131 | keyOf: { |
| 132 | Moved: { |
| 133 | out: ({ event }) => Account.ref(event.from), |
| 134 | in: ({ event }) => Account.ref(event.to), |
| 135 | }, |
| 136 | }, |
| 137 | state: Schema.Struct({ net: Schema.Number }), |
| 138 | initial: { net: 0 }, |
| 139 | evolve: { |
| 140 | Moved: { |
| 141 | out: (s, e) => ({ net: s.net - e.amount }), |
| 142 | in: (s, e) => ({ net: s.net + e.amount }), |
| 143 | }, |
| 144 | }, |
| 145 | }) {} |
| 146 | |
| 147 | // Keyed by the sender's id itself, a Schema key with no aggregate behind it. |
| 148 | class Sent extends Domain.View("Sent", { |
| 149 | from: [Transfer], |
| 150 | key: Schema.String, |
| 151 | keyOf: { Moved: ({ event }) => event.from }, |
| 152 | state: Schema.Struct({ total: Schema.Number }), |
| 153 | initial: { total: 0 }, |
| 154 | evolve: { Moved: (s, e) => ({ total: s.total + e.amount }) }, |
| 155 | }) {} |
| 156 | |
| 157 | class Bank extends Domain.Model("Bank", { |
| 158 | aggregates: [Account, Transfer], |
| 159 | views: [Balance, Flows, Sent], |
| 160 | }) {} |
| 161 | |
| 162 | // A decide that waits on something asynchronous, and one that breaks its declaration. |
| 163 | class Waited extends Domain.Event("Waited") {} |
| 164 | class Wait extends Domain.Command("Wait", { target: Schema.String, events: [Waited] }) {} |
| 165 | class Stray extends Domain.Command("Stray", { target: Schema.String, events: [Waited] }) {} |
| 166 | class Later extends Domain.Aggregate("Later", { |
| 167 | id: Schema.String, |
| 168 | state: Schema.Struct({}), |
| 169 | initial: {}, |
| 170 | commands: [Wait, Stray], |
| 171 | decide: { |
| 172 | Wait: () => Effect.promise(() => Promise.resolve([new Waited()])), |
| 173 | Stray: () => [new Frozen({ by: "nobody" })] as never, |
| 174 | }, |
| 175 | evolve: { Waited: (s) => s }, |
| 176 | }) {} |
| 177 | |
| 178 | class Strays extends Domain.Model("Strays", { aggregates: [Later] }) {} |
| 179 | |
| 180 | const NOW = 1_800_000_000_000; |
| 181 | const Hosted = Bank.layer(Layer.empty).pipe( |
| 182 | Layer.provide(Layer.suspend(() => InMemory.make({ now: () => NOW }).layer)), |
| 183 | ); |
| 184 | const now = DateTime.makeUnsafe(NOW); |
| 185 | const a1 = Account.ref("a-1"); |
| 186 | |
| 187 | /** The server's answer to a command: its events, or its rejection, and the state after it. */ |
| 188 | const serve = (command: Domain.Aggregate.CommandOf<typeof Account>, operator = "sam") => |
| 189 | Effect.gen(function* () { |
| 190 | const accounts = yield* Account; |
| 191 | const result = yield* accounts |
| 192 | .send(a1, command, { commandId: `c-${command._tag}` }) |
| 193 | .pipe(Effect.provideService(Operator, operator), Effect.result); |
| 194 | return { result, state: yield* accounts.state(a1) }; |
| 195 | }); |
| 196 | |
| 197 | describe("Domain Aggregate.predict", { tags: ["unit", "local"] }, () => { |
| 198 | it.live("an accepted command: the same events and state as the server", () => |
| 199 | Effect.gen(function* () { |
| 200 | const accounts = yield* Account; |
| 201 | yield* accounts.send(a1, new Open({ owner: "sam" })); |
| 202 | const before = yield* accounts.state(a1); |
| 203 | const command = new Deposit({ amount: 30 }); |
| 204 | const local = Account.predict(before, command, { id: "a-1", now, version: 1 }); |
| 205 | const remote = yield* serve(command); |
| 206 | |
| 207 | expect(local._tag).toBe("Accepted"); |
| 208 | if (local._tag !== "Accepted" || remote.result._tag !== "Success") return; |
| 209 | expect(local.events).toEqual(remote.result.success.events); |
| 210 | expect(local.state).toEqual(remote.state); |
| 211 | expect(local.envelopes.map((e) => [e.stream, e.seq])).toEqual([["Account/a-1", 2]]); |
| 212 | }).pipe(Effect.provide(Hosted)), |
| 213 | ); |
| 214 | |
| 215 | it.live("a rejected command: the same rejection as the server", () => |
| 216 | Effect.gen(function* () { |
| 217 | const accounts = yield* Account; |
| 218 | const before = yield* accounts.state(a1); |
| 219 | const command = new Withdraw({ amount: 5 }); |
| 220 | const local = Account.predict(before, command, { id: "a-1", now }); |
| 221 | const remote = yield* serve(command); |
| 222 | |
| 223 | expect(local._tag).toBe("Rejected"); |
| 224 | expect(remote.result._tag).toBe("Failure"); |
| 225 | if (local._tag !== "Rejected" || remote.result._tag !== "Failure") return; |
| 226 | expect(local.rejection).toBeInstanceOf(InsufficientFunds); |
| 227 | expect(local.rejection).toEqual(remote.result.failure); |
| 228 | // The rejection is a value, typed by the command's `rejects`. |
| 229 | const typed: InsufficientFunds = local.rejection; |
| 230 | expect(typed.requested).toBe(5); |
| 231 | }).pipe(Effect.provide(Hosted)), |
| 232 | ); |
| 233 | |
| 234 | it.effect("decide sees the id and time the caller gives", () => |
| 235 | Effect.sync(() => { |
| 236 | const local = Account.predict(Account.definition.initial, new Open({ owner: "sam" }), { |
| 237 | id: "a-1", |
| 238 | now, |
| 239 | commandId: "c-1", |
| 240 | }); |
| 241 | expect(local).toMatchObject({ |
| 242 | _tag: "Accepted", |
| 243 | events: [new Opened({ owner: "sam", at: NOW })], |
| 244 | envelopes: [{ id: "a-1", seq: 1, commandId: "c-1", correlationId: "c-1" }], |
| 245 | }); |
| 246 | }), |
| 247 | ); |
| 248 | |
| 249 | it.live("the server's decide sees the command id, stream and version before it", () => |
| 250 | Effect.gen(function* () { |
| 251 | const accounts = yield* Account; |
| 252 | yield* accounts.send(a1, new Open({ owner: "sam" })); |
| 253 | const remote = yield* serve(new Stamp()); |
| 254 | |
| 255 | expect(remote.result._tag).toBe("Success"); |
| 256 | if (remote.result._tag !== "Success") return; |
| 257 | expect(remote.result.success.events).toEqual([ |
| 258 | new Stamped({ commandId: "c-Stamp", stream: "Account/a-1", version: 1 }), |
| 259 | ]); |
| 260 | }).pipe(Effect.provide(Hosted)), |
| 261 | ); |
| 262 | |
| 263 | it.effect("decide sees the command id and version the caller gives", () => |
| 264 | Effect.sync(() => { |
| 265 | const local = Account.predict(Account.definition.initial, new Stamp(), { |
| 266 | id: "a-1", |
| 267 | now, |
| 268 | version: 1, |
| 269 | commandId: "c-Stamp", |
| 270 | }); |
| 271 | expect(local).toMatchObject({ |
| 272 | _tag: "Accepted", |
| 273 | events: [new Stamped({ commandId: "c-Stamp", stream: "Account/a-1", version: 1 })], |
| 274 | }); |
| 275 | }), |
| 276 | ); |
| 277 | |
| 278 | it.effect("decide sees version 0 and an empty command id when the caller gives none", () => |
| 279 | Effect.sync(() => { |
| 280 | const local = Account.predict(Account.definition.initial, new Stamp(), { id: "a-1", now }); |
| 281 | expect(local).toMatchObject({ |
| 282 | _tag: "Accepted", |
| 283 | events: [new Stamped({ commandId: "", stream: "Account/a-1", version: 0 })], |
| 284 | }); |
| 285 | }), |
| 286 | ); |
| 287 | |
| 288 | it.effect("a command with middleware needs what its middleware provides", () => |
| 289 | Effect.sync(() => { |
| 290 | const state = Account.definition.initial; |
| 291 | // @ts-expect-error Freeze's middleware provides Operator: pass it as context |
| 292 | const unknown = Account.predict(state, new Freeze(), { id: "a-1", now }); |
| 293 | expect(unknown._tag).toBe("Unpredictable"); |
| 294 | |
| 295 | const operator = (name: string) => ({ |
| 296 | id: "a-1", |
| 297 | now, |
| 298 | context: Context.make(Operator, name), |
| 299 | }); |
| 300 | expect(Account.predict(state, new Freeze(), operator("sam"))).toMatchObject({ |
| 301 | _tag: "Accepted", |
| 302 | events: [new Frozen({ by: "sam" })], |
| 303 | }); |
| 304 | const refused = Account.predict(state, new Freeze(), operator("guest")); |
| 305 | expect(refused._tag).toBe("Rejected"); |
| 306 | if (refused._tag === "Rejected") expect(refused.rejection).toBeInstanceOf(NotAnOperator); |
| 307 | }), |
| 308 | ); |
| 309 | |
| 310 | it.effect("a decide that suspends cannot be predicted, and does not hang", () => |
| 311 | Effect.sync(() => { |
| 312 | const local = Later.predict({}, new Wait(), { id: "l-1", now }); |
| 313 | expect(local._tag).toBe("Unpredictable"); |
| 314 | }), |
| 315 | ); |
| 316 | |
| 317 | it.effect("an undeclared event cannot be predicted: the cause holds a DefinitionError", () => |
| 318 | Effect.sync(() => { |
| 319 | const local = Later.predict({}, new Stray(), { id: "l-1", now }); |
| 320 | expect(local._tag).toBe("Unpredictable"); |
| 321 | if (local._tag !== "Unpredictable") return; |
| 322 | expect(Cause.squash(local.cause)).toMatchObject({ |
| 323 | _tag: "DefinitionError", |
| 324 | message: "Later.decide.Stray returned 'Frozen', which Stray does not declare in events", |
| 325 | }); |
| 326 | }), |
| 327 | ); |
| 328 | |
| 329 | it.live("the server dies on the same undeclared event", () => |
| 330 | Effect.gen(function* () { |
| 331 | const later = yield* Later; |
| 332 | const exit = yield* later.send(Later.ref("l-1"), new Stray()).pipe(Effect.exit); |
| 333 | expect(exit._tag).toBe("Failure"); |
| 334 | if (exit._tag !== "Failure") return; |
| 335 | expect(Cause.hasDies(exit.cause)).toBe(true); |
| 336 | expect(Cause.squash(exit.cause)).toMatchObject({ |
| 337 | _tag: "DefinitionError", |
| 338 | message: "Later.decide.Stray returned 'Frozen', which Stray does not declare in events", |
| 339 | }); |
| 340 | }).pipe( |
| 341 | Effect.provide( |
| 342 | Strays.layer(Layer.empty).pipe( |
| 343 | Layer.provide(Layer.suspend(() => InMemory.make({ now: () => NOW }).layer)), |
| 344 | ), |
| 345 | ), |
| 346 | ), |
| 347 | ); |
| 348 | |
| 349 | it.effect("a client-side Layer provides the middleware's context", () => |
| 350 | Effect.gen(function* () { |
| 351 | // The server's OperatorSession reads a header; the client knows who it is. |
| 352 | const ClientSession = Layer.succeed(Operator, "sam"); |
| 353 | const context = yield* Layer.build(ClientSession); |
| 354 | const local = Account.predict(Account.definition.initial, new Freeze(), { |
| 355 | id: "a-1", |
| 356 | now, |
| 357 | context, |
| 358 | }); |
| 359 | expect(local).toMatchObject({ _tag: "Accepted", events: [new Frozen({ by: "sam" })] }); |
| 360 | }).pipe(Effect.scoped), |
| 361 | ); |
| 362 | }); |
| 363 | |
| 364 | describe("Domain View.evolve", { tags: ["unit", "local"] }, () => { |
| 365 | it.live("predicted events folded by the view give the server's view state", () => |
| 366 | Effect.gen(function* () { |
| 367 | const accounts = yield* Account; |
| 368 | const balances = yield* Balance; |
| 369 | yield* accounts.send(a1, new Deposit({ amount: 50 })); |
| 370 | const before = yield* accounts.state(a1); |
| 371 | const view = yield* balances.query(a1, { atLeast: { stream: "Account/a-1", version: 1 } }); |
| 372 | |
| 373 | const local = Account.predict(before, new Withdraw({ amount: 20 }), { |
| 374 | id: "a-1", |
| 375 | now, |
| 376 | version: 1, |
| 377 | }); |
| 378 | if (local._tag !== "Accepted") return expect(local._tag).toBe("Accepted"); |
| 379 | const predicted = local.events.reduce( |
| 380 | (state, event, index) => |
| 381 | Balance.evolve(state, { |
| 382 | name: "Account", |
| 383 | event, |
| 384 | source: a1, |
| 385 | envelope: local.envelopes[index]!, |
| 386 | }), |
| 387 | Option.getOrNull(view), |
| 388 | ); |
| 389 | |
| 390 | const receipt = yield* accounts.send(a1, new Withdraw({ amount: 20 })); |
| 391 | const server = yield* balances.query(a1, { |
| 392 | atLeast: { stream: receipt.stream, version: receipt.version }, |
| 393 | }); |
| 394 | expect(predicted).toEqual({ balance: 30, lines: 2 }); |
| 395 | expect(Option.getOrNull(server)).toEqual(predicted); |
| 396 | }).pipe(Effect.provide(Hosted)), |
| 397 | ); |
| 398 | |
| 399 | it.live("a routed view applies each route that reaches the key", () => |
| 400 | Effect.gen(function* () { |
| 401 | const transfers = yield* Transfer; |
| 402 | const flows = yield* Flows; |
| 403 | const command = new Move({ from: "a-1", to: "a-2", amount: 7 }); |
| 404 | const local = Transfer.predict(Transfer.definition.initial, command, { id: "t-1", now }); |
| 405 | if (local._tag !== "Accepted") return expect(local._tag).toBe("Accepted"); |
| 406 | const fold = (key: string) => |
| 407 | Flows.evolve(null, { |
| 408 | name: "Transfer", |
| 409 | event: local.events[0]!, |
| 410 | source: Transfer.ref("t-1"), |
| 411 | envelope: local.envelopes[0]!, |
| 412 | key: Account.ref(key), |
| 413 | }); |
| 414 | |
| 415 | const receipt = yield* transfers.send(Transfer.ref("t-1"), command); |
| 416 | const atLeast = { stream: receipt.stream, version: receipt.version }; |
| 417 | expect(fold("a-1")).toEqual({ net: -7 }); |
| 418 | expect(fold("a-2")).toEqual({ net: 7 }); |
| 419 | // A key no route reaches keeps its state. |
| 420 | expect(fold("a-3")).toBeNull(); |
| 421 | const server = (key: string) => |
| 422 | flows.query(Account.ref(key), { atLeast }).pipe(Effect.map(Option.getOrNull)); |
| 423 | expect(yield* server("a-1")).toEqual(fold("a-1")); |
| 424 | expect(yield* server("a-2")).toEqual(fold("a-2")); |
| 425 | }).pipe(Effect.provide(Hosted)), |
| 426 | ); |
| 427 | |
| 428 | it.live("a view keyed by a Schema value applies only the key keyOf returns", () => |
| 429 | Effect.gen(function* () { |
| 430 | const transfers = yield* Transfer; |
| 431 | const sent = yield* Sent; |
| 432 | const command = new Move({ from: "a-1", to: "a-2", amount: 5 }); |
| 433 | const local = Transfer.predict(Transfer.definition.initial, command, { id: "t-2", now }); |
| 434 | if (local._tag !== "Accepted") return expect(local._tag).toBe("Accepted"); |
| 435 | const fold = (key: string) => |
| 436 | Sent.evolve(null, { |
| 437 | name: "Transfer", |
| 438 | event: local.events[0]!, |
| 439 | source: Transfer.ref("t-2"), |
| 440 | envelope: local.envelopes[0]!, |
| 441 | key, |
| 442 | }); |
| 443 | |
| 444 | const receipt = yield* transfers.send(Transfer.ref("t-2"), command); |
| 445 | const atLeast = { stream: receipt.stream, version: receipt.version }; |
| 446 | expect(fold("a-1")).toEqual({ total: 5 }); |
| 447 | expect(fold("a-2")).toBeNull(); |
| 448 | expect(Option.getOrNull(yield* sent.query("a-1", { atLeast }))).toEqual(fold("a-1")); |
| 449 | }).pipe(Effect.provide(Hosted)), |
| 450 | ); |
| 451 | }); |