The best way to control Claude Code, Codex and more from any computer or phone

main
md 241 lines 11.9 KB
Rendered Raw
1 # Hosting on Cloudflare with alchemy
2
3 The server package hosts the model in a Cloudflare Worker. `DomainCloudflare.layerDurableObjects()` declares one Durable Object class per aggregate, view, policy, projection and stream while the Worker builds. It also runs sagas on `Cloudflare.Workflows.layerDurableObjectEngine()`. Each aggregate instance is one Durable Object: one writer, which commits its events, state, idempotency receipt and outbox in a single transaction.
4
5 ```ts
6 // packages/server/src/BankWorker.ts
7 import { Bank, BankHandlers } from "@acme/domain/Bank.model";
8 import { CustomerApi } from "@acme/domain/CustomerApi.api";
9 import * as Cloudflare from "@alchemy.run/cloudflare";
10 import * as DomainCloudflare from "@alchemy.run/cloudflare/Domain";
11 import * as Effect from "effect/Effect";
12 import { HttpServerRequest } from "effect/http/HttpServerRequest";
13 import * as HttpServerResponse from "effect/http/HttpServerResponse";
14 import * as Layer from "effect/Layer";
15 import { SiftFraudCheck } from "./Fraud/SiftFraudCheck.ts";
16 import { D1LedgerStore } from "./Ledger/D1LedgerStore.ts";
17 import { MfaChallengeLive } from "./MfaChallenge.ts";
18 import { SessionLive, sessionRoute } from "./Session.ts";
19
20 /** One Layer: the middleware, the hosted model, and every adapter it needs. */
21 const BankLive = Layer.mergeAll(SessionLive, MfaChallengeLive).pipe(
22 Layer.provideMerge(Bank.layer(BankHandlers)),
23 Layer.provideMerge(D1LedgerStore),
24 Layer.provide(
25 Layer.mergeAll(DomainCloudflare.layerDurableObjects(), SiftFraudCheck, Cloudflare.D1.QueryDatabaseBinding),
26 ),
27 );
28
29 export default class BankWorker extends Cloudflare.Worker<BankWorker>()(
30 "BankWorker",
31 { main: import.meta.url },
32 Effect.gen(function* () {
33 const customerApi = yield* CustomerApi; // resolve once, at init
34 return {
35 fetch: Effect.gen(function* () {
36 const request = yield* HttpServerRequest;
37 const path = new URL(request.url, "http://localhost").pathname;
38 if (path === "/api/session") return yield* sessionRoute;
39 if (path.startsWith("/api")) return yield* customerApi.fetch;
40 return HttpServerResponse.text("Not Found", { status: 404 });
41 }),
42 };
43 }).pipe(Effect.provide(BankLive)), // provide one Layer, once
44 ) {}
45 ```
46
47 - Swap `DomainCloudflare.layerDurableObjects()` for `Domain.InMemory` and nothing else changes. That's how the Api tests host the model.
48 - Resources the adapters need, like a D1 database, are declared in the server package and bound through alchemy bindings (`Cloudflare.D1.QueryDatabase(db)` inside the adapter's Layer).
49 - Webhooks and event sources, like a Stripe webhook, are yielded in the Worker's init and send commands into the model.
50 - `alchemy dev` runs everything locally in workerd: Durable Objects, sagas and the foldkit app.
51
52 ## Calling the Api in process
53
54 Code in the Worker that is not a client of the Api (a webhook route, a scheduled job) calls it with `CustomerApi.clientInProcess`: the same typed client, wired to the handlers in process, with the middleware of everything it serves. When that code has already checked its caller (a webhook signature), it provides a middleware Layer that trusts the caller, to that client only:
55
56 ```ts
57 const asSystem = Layer.succeed(Session, (effect) =>
58 Effect.provideService(effect, CurrentActor, system("payments-webhook")),
59 );
60 const bank = yield* CustomerApi.clientInProcess.pipe(Effect.provide(asSystem)); // per request, in Effect.scoped
61 yield* bank.DepositMoney(accountId, { amount });
62 ```
63
64 - Build `clientInProcess` per request in a Worker. `layerClientInProcess` provides `CustomerApi.Client` in process, for long-lived processes and scripts.
65 - Do not send a request to the Worker's own URL, and do not pass a verified secret through a header to `clientInProcess` to be checked again.
66
67 More: [Api: Call it in process](https://alchemy.run/domain/api#call-it-in-process), [In memory](https://alchemy.run/domain/in-memory).
68
69 ## Live reads
70
71 Clients that `watch` or read `events` open a WebSocket per read, with `Domain.protocolWebSocket`. The Worker runs the read's middleware, then hands the socket to the Durable Object that owns the key. That object pushes each committed change, judged by `validate` again, and hibernates in between. Commands go over HTTP.
72
73 More: [Cloudflare: Watch without polling](https://alchemy.run/domain/cloudflare#watch-without-polling).
74
75 ## Plain HTTP and OpenAPI
76
77 For clients that are not Effect (a partner, a script, a public API), `toHttpApi` from `@alchemy.run/domain/Http` publishes an Api as an Effect `HttpApi` group, with its handlers Layer and an OpenAPI document from the same Api.
78
79 ```ts
80 import * as DomainHttp from "@alchemy.run/domain/Http";
81 import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
82 import * as Etag from "effect/http/Etag";
83 import * as HttpPlatform from "effect/http/HttpPlatform";
84 import * as HttpRouter from "effect/http/HttpRouter";
85
86 // every call the Api serves; a typed failure answers at its `httpApiStatus`, else 422
87 const BankHttp = DomainHttp.toHttpApi(CustomerApi);
88
89 // in the Worker's init, inside `.pipe(Effect.provide(BankLive))`
90 return {
91 fetch: HttpApiBuilder.layer(BankHttp.api, { openapiPath: "/openapi.json" }).pipe(
92 Layer.provide(BankHttp.layer),
93 Layer.provide([HttpPlatform.layer, Etag.layer]),
94 HttpRouter.toHttpEffect,
95 ),
96 };
97 ```
98
99 A command is a `POST` with the RPC payload as its JSON body, and answers with its receipt:
100
101 ```sh
102 curl -X POST /DepositMoney -H "cookie: $SESSION" \
103 -d '{ "target": "a-1", "commandId": "d-1", "input": { "amount": 1000 } }'
104 # { "reply": { "balance": 1000 }, "stream": "Account/a-1", "version": 3 }
105 ```
106
107 A read is a `GET` by key, and the receipt's `stream` and `version` make it wait for your own write:
108
109 ```sh
110 curl "/AccountSummary/a-1?stream=Account/a-1&version=3"
111 curl "/AccountSummary/a-1/snapshot"
112 curl "/AccountSummary/a-1/list?order=desc&take=20&after=118"
113 ```
114
115 `watch` and `events` answer with Server-Sent Events, one value per event:
116
117 ```ts
118 const summary = new EventSource(`/AccountSummary/${accountId}/events?after=${cursor}`);
119 summary.onmessage = (event) => render(JSON.parse(event.data));
120 ```
121
122 Every call runs through the Api's own handlers with the request's headers, so a rejection answers with the status its schema declares (422 if none):
123
124 ```ts
125 export class NotOwner extends Domain.Rejection("NotOwner", {}, { httpApiStatus: 403 }) {}
126 // GET /AccountSummary/a-2 as someone else -> 403 { "_tag": "NotOwner" }
127 ```
128
129 What the Api serves is what is published, so HTTP clients get their own Api:
130
131 ```ts
132 export class PartnerApi extends Domain.Api("PartnerApi", {
133 model: Bank,
134 commands: ["DepositMoney"],
135 views: ["AccountSummary"],
136 streams: [],
137 aggregates: [],
138 }) {}
139 const PartnerHttp = DomainHttp.toHttpApi(PartnerApi);
140 ```
141
142 To serve the group next to others or under a prefix, add it to your own `HttpApi`:
143
144 ```ts
145 const AppApi = HttpApi.make("App").add(BankHttp.group.prefix("/v1"));
146 const AppLive = HttpApiBuilder.layer(AppApi).pipe(Layer.provide(BankHttp.layerFor(AppApi)));
147 ```
148
149 More: [Plain HTTP and OpenAPI](https://alchemy.run/domain/http-api).
150
151 ## MCP
152
153 `toMcp` from `@alchemy.run/domain/Ai` serves each call of an Api that returns once as an MCP tool, named `<api>_<name>_<operation>`:
154
155 ```ts
156 import * as DomainAi from "@alchemy.run/domain/Ai";
157 import { McpProtocol, McpServer } from "effect/ai";
158
159 // packages/server/src/BankMcp.ts
160 export const BankMcp = DomainAi.toMcp(AgentApi).pipe(
161 Layer.provide(
162 McpServer.layerHttp({ name: "bank", version: "1.0.0", path: "/mcp", protocols: [McpProtocol.v2025_11_25] }),
163 ),
164 Layer.provide(BankLive),
165 );
166 ```
167
168 On a Worker, use `McpServer.layerHttpRequestScoped` with `McpProtocol.v2026_07_28`. Each call carries the MCP request's headers to the Api's middleware, so an MCP client signs in like any other client, and a rejection comes back as the tool's typed failure.
169
170 `toToolkit` gives the same tools to an agent in the app, acting for the headers you give it:
171
172 ```ts
173 const { toolkit, layer } = DomainAi.toToolkit(AgentApi, {
174 headers: Effect.map(CurrentSession, (s) => ({ authorization: `Bearer ${s.token}` })),
175 });
176 const answer = LanguageModel.generateText({ prompt, toolkit }).pipe(Effect.provide(layer));
177 ```
178
179 More: [MCP](https://alchemy.run/domain/mcp).
180
181 ## CLI
182
183 `toCli` from `@alchemy.run/domain/Cli` builds an Effect CLI command that calls the deployed Api over HTTP, one kebab-case subcommand per command, view, stream or aggregate:
184
185 ```ts
186 // packages/cli/src/bank.ts
187 const bank = toCli(CustomerApi, {
188 name: "bank",
189 headers: Config.redacted("BANK_TOKEN").pipe(
190 Effect.map((token) => ({ authorization: `Bearer ${Redacted.value(token)}` })),
191 ),
192 });
193 Command.run(bank, { version: "1.0.0" }).pipe(
194 Effect.provide(
195 Layer.mergeAll(
196 Domain.protocolHttp(url).pipe(Layer.provide(FetchHttpClient.layer)),
197 BunServices.layer,
198 ),
199 ),
200 BunRuntime.runMain,
201 );
202 ```
203
204 Fields are flags, and the result is JSON on stdout; a rejection is its wire JSON on stderr with exit code 1:
205
206 ```sh
207 $ bank deposit-money --target a-1 --amount 1000
208 $ bank account-summary get --key a-1
209 ```
210
211 More: [CLI](https://alchemy.run/domain/cli).
212
213 ## Deploying
214
215 The root `alchemy.run.ts` yields the server Worker and the foldkit website (see [layout.md](layout.md)). Deploy with `alchemy deploy`, develop with `alchemy dev`, and tear down with `alchemy destroy`.
216
217 More: [Cloudflare: Deploy it](https://alchemy.run/domain/cloudflare#deploy-it), [Cloudflare: Deploy without dropping requests](https://alchemy.run/domain/cloudflare#deploy-without-dropping-requests).
218
219 ## Observability
220
221 Every command, event and reaction is traced automatically:
222 - `Domain.send` and `Domain.decide` spans for commands, with a span event per committed event.
223 - `Domain.policy` and `Domain.view` spans that continue the trace of the commit they react to.
224 - `Domain.saga` and `Domain.projection` spans that start their own trace and link back to their cause.
225 - `Domain.external` spans for external system calls.
226
227 All of them carry `domain.correlation_id`, the first command of the flow, which finds a whole flow across traces. Export to an OpenTelemetry backend to see each flow as one connected trace: declare an `Axiom.Dataset` per signal and an `Axiom.ApiToken` that may ingest into them, and add `Axiom.Telemetry({ token, traces, logs })` to the Worker's single `Effect.provide` (or `Alchemy.Telemetry.layerOtlp` for any OTLP endpoint). Name datasets per stage. `Cloudflare.Telemetry()` shows spans in Cloudflare's dashboard instead, but Cloudflare starts a new trace per Worker or Durable Object event, so flows don't connect and browser spans can't be added.
228
229 Metrics: `domain.commands`, `domain.command.duration`, `domain.events`, `domain.lag` (commit to handling), `domain.runs`, `domain.projection.batch_size`, `domain.external.calls`. Turn off view spans with `Bank.layer(handlers, { telemetry: { views: false } })`.
230
231 More: [Observability](https://alchemy.run/domain/observability).
232
233 ## Pitfalls
234
235 - Durable Object calls right after a fresh deploy can briefly hit alchemy's placeholder script. The Domain platform retries its own calls, so make test readiness probes retry the first real request.
236 - Never keep per-request objects (sockets, promises) across events in a Durable Object or Worker. Resolve services at init, and do I/O per request.
237 - Handlers may require `RuntimeContext` (for bindings); every platform provides it when it runs them.
238 - Models never share data. Two models that list the same aggregate each get their own instances: on Cloudflare, Durable Object classes named after the model (`Billing.AccountAggregate`). Two models with the same name on one platform fail.
239 - Deploys keep data across Domain layout changes. Upgrading models that shared a class before Domain versions existed fails until one sets `legacyData: true` on its `layer`.
240
241 More: [Cloudflare: Know what runs where](https://alchemy.run/domain/cloudflare#know-what-runs-where), [Cloudflare: Host several models in one Worker](https://alchemy.run/domain/cloudflare#host-several-models-in-one-worker), [Cloudflare: Upgrade without losing data](https://alchemy.run/domain/cloudflare#upgrade-without-losing-data).