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 | --- |
| 2 | title: Cloudflare Durable Objects |
| 3 | description: Host a domain model on Durable Objects behind a Worker, with live reads over WebSockets. |
| 4 | --- |
| 5 | |
| 6 | Host your model on Cloudflare, and every aggregate instance, view key and policy gets its own Durable Object. You declare none of them yourself. |
| 7 | |
| 8 | ## Host the model in a Worker |
| 9 | |
| 10 | Provide `DomainCloudflare.layerDurableObjects()` as the platform, and serve your Apis from the Worker. |
| 11 | |
| 12 | ```typescript |
| 13 | // packages/server/src/BankWorker.ts |
| 14 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 15 | import * as DomainCloudflare from "@alchemy.run/cloudflare/Domain"; |
| 16 | import * as Stripe from "@alchemy.run/stripe"; |
| 17 | import { Account } from "@bank/domain/Account/Account.aggregate"; |
| 18 | import { AccountSummary } from "@bank/domain/Account/AccountSummary.view"; |
| 19 | import { Bank, BankHandlers } from "@bank/domain/Bank.model"; |
| 20 | import { CustomerApi } from "@bank/domain/CustomerApi.api"; |
| 21 | import { LedgerStore } from "@bank/domain/Ledger/LedgerStore"; |
| 22 | import { SupportApi } from "@bank/domain/SupportApi.api"; |
| 23 | import * as Telemetry from "alchemy/Telemetry"; |
| 24 | import * as Effect from "effect/Effect"; |
| 25 | import { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 26 | import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 27 | import * as Layer from "effect/Layer"; |
| 28 | import * as Option from "effect/Option"; |
| 29 | import { SiftFraudCheck } from "./Fraud/SiftFraudCheck.ts"; |
| 30 | import { D1LedgerStore } from "./Ledger/D1LedgerStore.ts"; |
| 31 | import { MfaChallengeLive } from "./MfaChallenge.ts"; |
| 32 | import { Observability } from "./Observability.ts"; |
| 33 | import { actorOf, SessionKey, SessionKeyLive, SessionLive, sessionRoute } from "./Session.ts"; |
| 34 | import { StripePayments } from "./Settlement/StripePayments.ts"; |
| 35 | import { StripeSettlements } from "./Settlement/StripeSettlements.ts"; |
| 36 | |
| 37 | /** |
| 38 | * Everything the Worker serves: the middleware both Apis declare, and the |
| 39 | * Bank hosted on Durable Objects, with the ledger in D1. Swap |
| 40 | * `DomainCloudflare.layerDurableObjects()` for `Domain.InMemory` and nothing else changes. |
| 41 | */ |
| 42 | const BankLive = Layer.mergeAll( |
| 43 | SessionLive, |
| 44 | MfaChallengeLive, |
| 45 | Stripe.ConsumeEventsLive, |
| 46 | Observability, |
| 47 | ).pipe( |
| 48 | Layer.provideMerge(SessionKeyLive), |
| 49 | Layer.provideMerge(Bank.layer(BankHandlers)), |
| 50 | Layer.provideMerge(D1LedgerStore), |
| 51 | Layer.provide( |
| 52 | Layer.mergeAll( |
| 53 | DomainCloudflare.layerDurableObjects(), |
| 54 | SiftFraudCheck, |
| 55 | StripePayments, |
| 56 | Cloudflare.D1.QueryDatabaseBinding, |
| 57 | ), |
| 58 | ), |
| 59 | ); |
| 60 | |
| 61 | /** `/api/ledger/<account>`: the ledger is a store the bank owns, so it is served by a plain route. */ |
| 62 | const LEDGER = /^\/api\/ledger\/([^/]+)$/; |
| 63 | |
| 64 | export default class BankWorker extends Cloudflare.Worker<BankWorker>()( |
| 65 | "BankWorker", |
| 66 | { main: import.meta.url }, |
| 67 | Effect.gen(function* () { |
| 68 | const customerApi = yield* CustomerApi; |
| 69 | const supportApi = yield* SupportApi; |
| 70 | const ledger = yield* LedgerStore; |
| 71 | const summaries = yield* AccountSummary; |
| 72 | const sessionKey = yield* SessionKey; |
| 73 | const signedIn = (request: HttpServerRequest) => |
| 74 | actorOf(request.headers).pipe(Effect.provideService(SessionKey, sessionKey)); |
| 75 | const ledgerRoute = (accountId: string) => |
| 76 | Effect.gen(function* () { |
| 77 | const request = yield* HttpServerRequest; |
| 78 | const actor = yield* signedIn(request); |
| 79 | if (Option.isNone(actor)) return HttpServerResponse.empty({ status: 401 }); |
| 80 | const summary = yield* summaries.query(Account.ref(accountId)).pipe(Effect.orDie); |
| 81 | const owner = Option.getOrNull(summary)?.customerId; |
| 82 | if (actor.value._tag === "Customer" && owner !== actor.value.customerId) { |
| 83 | return HttpServerResponse.empty({ status: 404 }); |
| 84 | } |
| 85 | return yield* HttpServerResponse.json(yield* ledger.forAccount(accountId)); |
| 86 | }); |
| 87 | // The app's own telemetry, collected here and forwarded with the bank's |
| 88 | // credentials, so no ingest token reaches a browser. Signed-in users only. |
| 89 | const telemetry = Telemetry.relay({ |
| 90 | authorize: HttpServerRequest.pipe(Effect.flatMap(signedIn), Effect.map(Option.isSome)), |
| 91 | }); |
| 92 | // Claims POST /webhooks/stripe and provisions the Stripe webhook endpoint. |
| 93 | yield* StripeSettlements; |
| 94 | return { |
| 95 | // The foldkit app reaches /api through its own Worker, on its own origin, |
| 96 | // so the session cookie needs no cross-origin allowances. |
| 97 | fetch: Effect.gen(function* () { |
| 98 | const request = yield* HttpServerRequest; |
| 99 | const path = new URL(request.url, "http://localhost").pathname; |
| 100 | if (path === "/api/session") { |
| 101 | return yield* sessionRoute.pipe(Effect.provideService(SessionKey, sessionKey)); |
| 102 | } |
| 103 | const ledgerPath = LEDGER.exec(path); |
| 104 | if (ledgerPath) return yield* ledgerRoute(decodeURIComponent(ledgerPath[1]!)); |
| 105 | if (path.startsWith("/api/telemetry/")) return yield* telemetry; |
| 106 | if (path.startsWith("/api")) return yield* customerApi.fetch; |
| 107 | if (path.startsWith("/support")) return yield* supportApi.fetch; |
| 108 | return HttpServerResponse.text("Not Found", { status: 404 }); |
| 109 | }), |
| 110 | }; |
| 111 | }).pipe(Effect.provide(BankLive)), |
| 112 | ) {} |
| 113 | ``` |
| 114 | |
| 115 | Each aggregate, view and policy becomes a Durable Object class on this Worker while it starts, so there are no bindings or classes to write. |
| 116 | |
| 117 | ## Deploy it |
| 118 | |
| 119 | ```typescript |
| 120 | // alchemy.run.ts |
| 121 | import BankWorker from "@bank/server/BankWorker"; |
| 122 | import * as Alchemy from "alchemy"; |
| 123 | import * as Axiom from "@alchemy.run/axiom"; |
| 124 | import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 125 | import * as Stripe from "@alchemy.run/stripe"; |
| 126 | import * as Effect from "effect/Effect"; |
| 127 | import * as Layer from "effect/Layer"; |
| 128 | |
| 129 | export default Alchemy.Stack( |
| 130 | "CloudflareDomainExample", |
| 131 | { |
| 132 | providers: Layer.mergeAll(Cloudflare.providers(), Stripe.providers(), Axiom.providers()), |
| 133 | state: Alchemy.localState(), |
| 134 | }, |
| 135 | Effect.gen(function* () { |
| 136 | const bank = yield* BankWorker; |
| 137 | // The foldkit app, built with Vite. Its Worker serves the build and |
| 138 | // forwards /api to the bank, so the app and the Api share one origin. |
| 139 | const app = yield* Cloudflare.Website.Foldkit("BankApp", { |
| 140 | rootDir: "packages/web", |
| 141 | main: "src/worker.ts", |
| 142 | env: { BANK: bank }, |
| 143 | assets: { runWorkerFirst: ["/api", "/api/*"] }, |
| 144 | }); |
| 145 | return { url: bank.url.as<string>(), app: app.url.as<string>() }; |
| 146 | }), |
| 147 | ); |
| 148 | ``` |
| 149 | |
| 150 | ```sh |
| 151 | bun alchemy deploy |
| 152 | ``` |
| 153 | |
| 154 | `bun alchemy dev` runs the same Worker and Durable Objects on your machine. |
| 155 | |
| 156 | ## Know what runs where |
| 157 | |
| 158 | | Your model | On Cloudflare | |
| 159 | | --- | --- | |
| 160 | | An aggregate instance, like account `a-1` | One Durable Object, named by its id | |
| 161 | | A view key, like the summary of `a-1` | One Durable Object per view and key | |
| 162 | | A policy | One Durable Object per policy and key (by default, per source instance) | |
| 163 | | A projection | One Durable Object per projection and key, with the key's input log | |
| 164 | | A stream key, like the card of `a-1` | One Durable Object per stream and key | |
| 165 | | A saga run, like transfer `t-1` | One Durable Object per saga and run, holding its steps' results | |
| 166 | |
| 167 | Sagas run on `Cloudflare.Workflows.layerDurableObjectEngine()`, the same engine you can use for plain Effect workflows. See [Effect workflows](/cloudflare/compute/effect-workflows). |
| 168 | |
| 169 | ## Keep the model in a jurisdiction |
| 170 | |
| 171 | Pass a `jurisdiction` to `DomainCloudflare.layerDurableObjects` in `BankLive` to create and store every Durable Object of the model, saga runs included, only inside a jurisdiction, for example the EU for personal data: |
| 172 | |
| 173 | ```typescript |
| 174 | Layer.provide( |
| 175 | Layer.mergeAll( |
| 176 | DomainCloudflare.layerDurableObjects({ jurisdiction: "eu" }), |
| 177 | SiftFraudCheck, |
| 178 | StripePayments, |
| 179 | Cloudflare.D1.QueryDatabaseBinding, |
| 180 | ), |
| 181 | ), |
| 182 | ``` |
| 183 | |
| 184 | A Durable Object in a jurisdiction is a different object from the one with the same name outside it. A model that already has data starts empty when you add a jurisdiction, and its old objects stay where they were. Other resources the Worker uses, like the ledger's D1 database, take their own `jurisdiction`. `alchemy dev` doesn't emulate jurisdictions: local workerd runs the model unrestricted. |
| 185 | |
| 186 | ## Host several models in one Worker |
| 187 | |
| 188 | Each model's Durable Object classes are named after the model: `Billing.AccountAggregate` and `Audit.AccountAggregate` when both list `Account`, and `Billing.OpenAccountWorkflow` for a saga. Their data never mixes, so several models can share one Worker and one `layerDurableObjects()`. Two different models with the same name in one Worker fail its deploy. |
| 189 | |
| 190 | Renaming a model renames its classes, and the model starts empty under the new names. |
| 191 | |
| 192 | ## Upgrade without losing data |
| 193 | |
| 194 | Each Worker records the Domain version it was deployed with. When a later Alchemy release lays models out differently, the next deploy moves the deployed data to the new layout: it renames classes in place, so every aggregate, view row and running saga carries over. |
| 195 | |
| 196 | Models deployed before versions existed named classes after the definition alone, like `AccountAggregate`. If two models in one Worker listed the same aggregate, they shared that class and its data, and only one can keep it. The deploy fails until you choose: |
| 197 | |
| 198 | ```typescript |
| 199 | import * as DomainCloudflare from "@alchemy.run/cloudflare/Domain"; |
| 200 | import * as Layer from "effect/Layer"; |
| 201 | import { Audit, AuditHandlers } from "./Audit.ts"; |
| 202 | import { Billing, BillingHandlers } from "./Billing.ts"; |
| 203 | |
| 204 | const Platform = DomainCloudflare.layerDurableObjects(); |
| 205 | // Billing keeps the accounts both models wrote; Audit starts empty. |
| 206 | export const BillingLive = Billing.layer(BillingHandlers, { legacyData: true }).pipe( |
| 207 | Layer.provide(Platform), |
| 208 | ); |
| 209 | export const AuditLive = Audit.layer(AuditHandlers).pipe(Layer.provide(Platform)); |
| 210 | ``` |
| 211 | |
| 212 | ## Count on these guarantees |
| 213 | |
| 214 | Commands to one aggregate instance run one at a time. Its events, new state and reply commit together, or not at all. |
| 215 | |
| 216 | Every event reaches the views, projections and policies that consume it, at least once and in order for each source, even if a Durable Object restarts in between. A projection key whose handler fails keeps its inputs and retries them. Scheduled commands fire when they're due, even after a restart. |
| 217 | |
| 218 | ## Watch without polling |
| 219 | |
| 220 | With `Domain.protocolWebSocket`, each `watch` or `events` read is a WebSocket to the Durable Object that owns the key. Every change is pushed down it as it commits. Between changes the object hibernates, so a quiet watch doesn't keep it running. |
| 221 | |
| 222 | `get`, `list` and commands go over plain HTTP. See [Api](/domain/api#choose-a-protocol). |
| 223 | |
| 224 | ## Deploy without dropping requests |
| 225 | |
| 226 | During a deploy, some Durable Objects still run the previous version for a moment. Calls between them are retried for about a minute until the new version answers, and a client's live read reconnects and carries on from its last change. |
| 227 | |
| 228 | ## Add consumers to a running Domain |
| 229 | |
| 230 | A deploy that adds a view or a projection, or bumps a version, fills it from the history before it finishes. See [History at scale](/domain/backfill). |
| 231 | |
| 232 | :::note |
| 233 | The same model runs [in memory](/domain/in-memory) for tests. The full Worker, with Stripe and a support Api, is in the [bank example](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-domain). |
| 234 | ::: |