The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import type { RuntimeContext } from "alchemy"; |
| 2 | import * as Context from "effect/Context"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Layer from "effect/Layer"; |
| 5 | |
| 6 | /** One money movement on an account, as the ledger table stores it. */ |
| 7 | export interface LedgerRow { |
| 8 | /** `${stream}:${seq}`: the event it came from, so a replay upserts the same row. */ |
| 9 | readonly id: string; |
| 10 | readonly accountId: string; |
| 11 | readonly kind: string; |
| 12 | readonly amount: number; |
| 13 | readonly balanceAfter: number; |
| 14 | /** Epoch milliseconds. */ |
| 15 | readonly at: number; |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * Where the ledger lives. The projection depends on this port, not on a |
| 20 | * database, so a story runs it against memory and the server against D1. |
| 21 | */ |
| 22 | export class LedgerStore extends Context.Service< |
| 23 | LedgerStore, |
| 24 | { |
| 25 | readonly record: (rows: ReadonlyArray<LedgerRow>) => Effect.Effect<void, never, RuntimeContext>; |
| 26 | readonly forAccount: ( |
| 27 | accountId: string, |
| 28 | ) => Effect.Effect<ReadonlyArray<LedgerRow>, never, RuntimeContext>; |
| 29 | } |
| 30 | >()("Bank/LedgerStore") {} |
| 31 | |
| 32 | /** A ledger in memory, for stories and tests: its Layer, and a reader for assertions. */ |
| 33 | export const memoryLedger = () => { |
| 34 | const table = new Map<string, LedgerRow>(); |
| 35 | const forAccount = (accountId: string) => |
| 36 | Effect.sync(() => [...table.values()].filter((row) => row.accountId === accountId)); |
| 37 | return { |
| 38 | layer: Layer.succeed(LedgerStore, { |
| 39 | record: (rows) => |
| 40 | Effect.sync(() => { |
| 41 | for (const row of rows) if (!table.has(row.id)) table.set(row.id, row); |
| 42 | }), |
| 43 | forAccount, |
| 44 | }), |
| 45 | forAccount, |
| 46 | }; |
| 47 | }; |
| 48 | |
| 49 | /** A fresh ledger in memory each time it is built. */ |
| 50 | export const MemoryLedgerStore = Layer.suspend(() => memoryLedger().layer); |