@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
mdx 937 lines 31.2 KB
Raw
1 ---
2 title: Effect RPC
3 description: Build a typed RPC API with Effect's Rpc module and deploy it as a Cloudflare Worker.
4 sidebar:
5 order: 4
6 ---
7
8 Effect RPC exposes a typed, schema-validated surface across a
9 **trust boundary** — a web app or an external service calling into
10 your Worker. For internal Worker-to-Worker or Worker-to-DO calls,
11 use [Schemaless RPC](/apis/schemaless) instead; for choosing between
12 the modalities, see [RPC](/apis).
13
14 The [HTTP API guide](/cloudflare/apis/effect-http-api) showed how to build
15 REST-style endpoints with schema validation. Effect RPC takes a
16 different angle — you define **procedures** instead of HTTP
17 endpoints, and you get a fully typed client for free with no URL
18 construction or manual serialization.
19
20 The transport is still HTTP under the hood, and both patterns
21 produce the same `HttpEffect` type, so the wiring story is
22 identical to the HTTP API guide:
23
24 1. **Define schemas outside.** Domain types and tagged errors,
25 importable by both server and client.
26 2. **Construct the service inside the Worker's Construction phase.**
27 `RpcGroup.toLayer` is pure construction — safe to call at plan
28 time. Don't `yield*` the running server; it can't run without a
29 request.
30 3. **Return `{ fetch }`** where `fetch` is the `HttpEffect`
31 produced by `RpcServer.toHttpEffect`.
32 4. **Bonus:** deploy and call the procedures from a typed client
33 that shares the exact same `RpcGroup` value.
34
35 ## 1. Define the schemas
36
37 Domain model and error types — pure schemas, no runtime concerns:
38
39 ```typescript
40 // src/task.ts
41 import * as Schema from "effect/Schema";
42
43 export class Task extends Schema.Class<Task>("Task")({
44 id: Schema.String,
45 title: Schema.String,
46 completed: Schema.Boolean,
47 }) {}
48
49 export class TaskNotFound extends Schema.TaggedClass<TaskNotFound>()(
50 "TaskNotFound",
51 { id: Schema.String },
52 ) {}
53
54 export class CreateTaskFailed extends Schema.TaggedClass<CreateTaskFailed>()(
55 "CreateTaskFailed",
56 { message: Schema.String },
57 ) {}
58 ```
59
60 RPC errors are schema-backed tagged classes. The client receives
61 them as typed values you can `match` on — not raw HTTP status codes.
62
63 ## 2. Declare the RPCs
64
65 Each `Rpc.make` declares one procedure: a name, a payload schema,
66 a success schema, and an error schema. `RpcGroup.make` collects them
67 into a single value that both the server and the client will share.
68
69 ```typescript
70 // src/rpcs.ts
71 import * as Schema from "effect/Schema";
72 import { Rpc, RpcGroup } from "effect/rpc";
73 import { Task, TaskNotFound, CreateTaskFailed } from "./task.ts";
74
75 const getTask = Rpc.make("getTask", {
76 success: Task,
77 error: TaskNotFound,
78 payload: { id: Schema.String },
79 });
80
81 const createTask = Rpc.make("createTask", {
82 success: Task,
83 error: CreateTaskFailed,
84 payload: { title: Schema.String },
85 });
86
87 export class TaskRpcs extends RpcGroup.make(getTask, createTask) {}
88 ```
89
90 `TaskRpcs` is just a value-level description. Nothing executes yet.
91
92 ## 3. Build the Worker
93
94 Create `src/worker.ts` with an empty Construction phase:
95
96 ```typescript
97 // src/worker.ts
98 import * as Cloudflare from "@alchemy.run/cloudflare";
99 import * as Effect from "effect/Effect";
100
101 export default Cloudflare.Worker(
102 "Worker",
103 { main: import.meta.url },
104 Effect.gen(function* () {
105 return {};
106 }),
107 );
108 ```
109
110 The generator inside `Cloudflare.Worker` is the **Construction phase** — it
111 runs both at *plan time* and at *runtime*. Only do pure construction
112 or resource-binding factories here; never `yield*` work that needs
113 an incoming request.
114
115 ### 3a. Bind an R2 bucket for storage
116
117 Tasks need durable storage. Declare a `Bucket` resource and bind
118 it inside the constructor — `Cloudflare.R2.ReadWriteBucket(Tasks)`
119 returns a typed handle whose `get` / `put` / `delete` / `list` methods
120 we'll call from the handlers below.
121
122 ```typescript
123 // src/bucket.ts
124 import * as Cloudflare from "@alchemy.run/cloudflare";
125
126 export const Tasks = Cloudflare.R2.Bucket("Tasks");
127 ```
128
129 ```diff lang="typescript"
130 +import { Tasks } from "./bucket.ts";
131
132 export default Cloudflare.Worker(
133 "Worker",
134 { main: import.meta.url },
135 Effect.gen(function* () {
136 + const tasks = yield* Cloudflare.R2.ReadWriteBucket(Tasks);
137
138 return {};
139 }),
140 );
141 ```
142
143 We'll provide the runtime side of this binding
144 (`Cloudflare.R2.ReadWriteBucketBinding`) in step 3c when we wire up the
145 `fetch` handler.
146
147 ### 3b. Construct the handlers inside the constructor
148
149 `TaskRpcs.toLayer` takes an `Effect` that returns one handler per
150 procedure and produces a `Layer`. Like `HttpApiBuilder.group`, this
151 is pure construction — it builds a value, it doesn't run the server.
152
153 > Don't `yield* TaskRpcs.toLayer(...)` here. Building a layer is
154 > fine, but actually executing the procedures requires an incoming
155 > request. The constructor only constructs; the work happens later, on each
156 > `fetch` call.
157
158 ```diff lang="typescript"
159 Effect.gen(function* () {
160 const tasks = yield* Cloudflare.R2.ReadWriteBucket(Tasks);
161
162 + const handlersLayer = TaskRpcs.toLayer({
163 + getTask: ({ id }) =>
164 + Effect.gen(function* () {
165 + const object = yield* tasks.get(id).pipe(Effect.orDie);
166 + if (!object) {
167 + return yield* Effect.fail(new TaskNotFound({ id }));
168 + }
169 + return Schema.decodeUnknownSync(Task)(
170 + JSON.parse(yield* object.text().pipe(Effect.orDie)),
171 + );
172 + }),
173 + createTask: ({ title }) =>
174 + Effect.gen(function* () {
175 + const task = new Task({
176 + id: crypto.randomUUID(),
177 + title,
178 + completed: false,
179 + });
180 + yield* tasks.put(task.id, JSON.stringify(task));
181 + return task;
182 + }).pipe(
183 + Effect.catchTag("R2Error", (error) =>
184 + Effect.fail(new CreateTaskFailed({ message: error.message })),
185 + ),
186 + ),
187 + });
188
189 return {};
190 }),
191 ```
192
193 Each handler receives the typed payload and returns an `Effect`
194 that either succeeds with the declared success schema or fails with
195 the declared error schema. `getTask` uses `Effect.orDie` to turn
196 unexpected R2 failures into 500s — `TaskNotFound` is the only
197 client-visible error. `createTask` maps R2 failures into the
198 declared `CreateTaskFailed` error so the client can match on it.
199
200 ### 3c. Return `{ fetch }`
201
202 `RpcServer.toHttpEffect` converts the `RpcGroup` into an
203 `HttpEffect` — exactly the type Workers expect for `fetch`. We
204 provide two layers to it via `Layer.mergeAll`:
205
206 - The `handlersLayer` we just built.
207 - `RpcSerialization.layerNdjson` — one frame per line, so streaming
208 procedures work out of the box and the wire format matches what
209 `Cloudflare.RpcWorker.bind` clients speak. When nothing streams
210 and no bound consumer is involved, the buffered
211 `RpcSerialization.layerJson` is also an option.
212
213 Unlike the HTTP API approach, RPC doesn't need `HttpPlatform.layer`
214 or `Etag.layer` — the RPC server handles message framing internally.
215
216 ```diff lang="typescript"
217 return {
218 + fetch: RpcServer.toHttpEffect(TaskRpcs).pipe(
219 + Effect.provide(
220 + Layer.mergeAll(handlersLayer, RpcSerialization.layerNdjson),
221 + ),
222 + ),
223 };
224 ```
225
226 ### Putting it together
227
228 ```typescript
229 // src/worker.ts
230 import * as Cloudflare from "@alchemy.run/cloudflare";
231 import * as Effect from "effect/Effect";
232 import * as Layer from "effect/Layer";
233 import * as Schema from "effect/Schema";
234 import { RpcSerialization, RpcServer } from "effect/rpc";
235 import { Tasks } from "./bucket.ts";
236 import { CreateTaskFailed, Task, TaskNotFound } from "./task.ts";
237 import { TaskRpcs } from "./rpcs.ts";
238
239 export default Cloudflare.Worker(
240 "Worker",
241 { main: import.meta.url },
242 Effect.gen(function* () {
243 const tasks = yield* Cloudflare.R2.ReadWriteBucket(Tasks);
244
245 const handlersLayer = TaskRpcs.toLayer({
246 getTask: ({ id }) =>
247 Effect.gen(function* () {
248 const object = yield* tasks.get(id).pipe(Effect.orDie);
249 if (!object) {
250 return yield* Effect.fail(new TaskNotFound({ id }));
251 }
252 return Schema.decodeUnknownSync(Task)(
253 JSON.parse(yield* object.text().pipe(Effect.orDie)),
254 );
255 }),
256 createTask: ({ title }) =>
257 Effect.gen(function* () {
258 const task = new Task({
259 id: crypto.randomUUID(),
260 title,
261 completed: false,
262 });
263 yield* tasks.put(task.id, JSON.stringify(task));
264 return task;
265 }).pipe(
266 Effect.catchTag("R2Error", (error) =>
267 Effect.fail(new CreateTaskFailed({ message: error.message })),
268 ),
269 ),
270 });
271
272 return {
273 fetch: RpcServer.toHttpEffect(TaskRpcs).pipe(
274 Effect.provide(
275 Layer.mergeAll(handlersLayer, RpcSerialization.layerNdjson),
276 ),
277 ),
278 };
279 }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
280 );
281 ```
282
283 ## 4. Add to the Stack
284
285 ```typescript
286 // alchemy.run.ts
287 import * as Alchemy from "alchemy";
288 import * as Cloudflare from "@alchemy.run/cloudflare";
289 import * as Effect from "effect/Effect";
290 import Worker from "./src/worker.ts";
291
292 export default Alchemy.Stack(
293 "TaskRpc",
294 { providers: Cloudflare.providers(), state: Cloudflare.state() },
295 Effect.gen(function* () {
296 const worker = yield* Worker;
297 return { url: worker.url };
298 }),
299 );
300 ```
301
302 ## 5. Deploy
303
304 ```sh
305 alchemy deploy
306 ```
307
308 ## Bonus: call it from a typed client
309
310 Because `TaskRpcs` is just a value, the same group drives a fully
311 typed client — no codegen. `client.createTask` accepts
312 `{ title: string }` and returns `Effect<Task, CreateTaskFailed>`.
313
314 ```typescript
315 // scripts/client.ts
316 import * as Effect from "effect/Effect";
317 import * as Layer from "effect/Layer";
318 import * as FetchHttpClient from "effect/http/FetchHttpClient";
319 import { RpcClient, RpcSerialization } from "effect/rpc";
320 import { TaskRpcs } from "../src/rpcs.ts";
321
322 const program = Effect.gen(function* () {
323 const client = yield* RpcClient.make(TaskRpcs);
324
325 const task = yield* client.createTask({ title: "Write docs" });
326 console.log("Created:", task.id);
327
328 const fetched = yield* client.getTask({ id: task.id });
329 console.log("Fetched:", fetched.title);
330 });
331
332 Effect.runPromise(
333 program.pipe(
334 Effect.scoped,
335 Effect.provide(
336 RpcClient.layerProtocolHttp({ url: process.env.TASK_RPC_URL! }).pipe(
337 Layer.provide(FetchHttpClient.layer),
338 Layer.provide(RpcSerialization.layerNdjson),
339 ),
340 ),
341 ),
342 );
343 ```
344
345 Get the URL from the deploy output and run it:
346
347 ```sh
348 TASK_RPC_URL=https://your-worker.workers.dev bun scripts/client.ts
349 ```
350
351 The errors are typed values: `client.getTask` returns
352 `Effect<Task, TaskNotFound>`, and you can `Effect.catchTag(
353 "TaskNotFound", ...)` to handle the missing case explicitly.
354
355 ## Bonus: streaming responses
356
357 An RPC's `success` doesn't have to be a single value. Wrapping it in
358 `RpcSchema.Stream(item, error)` produces a procedure whose handler
359 returns a `Stream` and whose client method also returns a `Stream`.
360 The wire format is one frame per item — exactly what the
361 `RpcSerialization.layerNdjson` layer we're already on emits, so the
362 `fetch` wiring doesn't change.
363
364 ```typescript
365 // src/rpcs.ts
366 import * as RpcSchema from "effect/rpc/RpcSchema";
367
368 const countTasks = Rpc.make("countTasks", {
369 payload: { upto: Schema.Number },
370 success: RpcSchema.Stream(Schema.Number, Schema.Never),
371 });
372
373 export class TaskRpcs extends RpcGroup.make(getTask, createTask, countTasks) {}
374 ```
375
376 The handler returns a `Stream<number>` directly:
377
378 ```diff lang="typescript"
379 +import * as Stream from "effect/Stream";
380
381 const handlersLayer = TaskRpcs.toLayer({
382 getTask: /* ... */,
383 createTask: /* ... */,
384 + countTasks: ({ upto }) =>
385 + Stream.fromIterable(Array.from({ length: upto }, (_, i) => i + 1)),
386 });
387 ```
388
389 On the client, `client.countTasks({ upto: 5 })` is a `Stream<number>`
390 you consume with `Stream.runCollect`, `Stream.runForEach`, etc. Each
391 emitted item arrives as soon as the server flushes its frame.
392
393 ## Recap
394
395 - **Schemas** (`Task`, `TaskNotFound`, `CreateTaskFailed`) and the
396 **RPC group** (`TaskRpcs`) live outside the Worker — pure
397 descriptions, importable by clients.
398 - The **handlers** are constructed inside the Worker's Construction phase
399 closure via `TaskRpcs.toLayer`. We build a `Layer` but never
400 `yield*` the running server.
401 - The Worker's surface is `{ fetch }`, where `fetch` is the
402 `HttpEffect` produced by `RpcServer.toHttpEffect`.
403 - The same `TaskRpcs` value drives a fully typed client via
404 `RpcClient.make`, with errors as typed values rather than HTTP
405 status codes.
406
407 ## Sugar: `Cloudflare.RpcWorker`
408
409 The `Cloudflare.Worker(...)` + `RpcServer.toHttpEffect(...)` recipe is
410 identical for every RPC Worker, so Alchemy ships a thin wrapper that
411 takes the `RpcGroup` directly in props and removes the `{ fetch }`
412 wrapper:
413
414 ```typescript
415 import * as Cloudflare from "@alchemy.run/cloudflare";
416 import * as Effect from "effect/Effect";
417 import * as Layer from "effect/Layer";
418 import { RpcSerialization, RpcServer } from "effect/rpc";
419 import { TaskRpcs } from "./rpcs.ts";
420
421 export default class Worker extends Cloudflare.RpcWorker<Worker>()(
422 "Worker",
423 { main: import.meta.url, schema: TaskRpcs },
424 Effect.gen(function* () {
425 const handlers = TaskRpcs.toLayer({ getTask: /* ... */ });
426 return RpcServer.toHttpEffect(TaskRpcs).pipe(
427 Effect.provide(Layer.mergeAll(handlers, RpcSerialization.layerNdjson)),
428 );
429 }),
430 ) {}
431 ```
432
433 Functionally identical to the long form above — yielding the class
434 returns the same `Worker` resource — but `props.schema` lets a second
435 Worker bind a typed client without re-importing `RpcClient`:
436
437 ```typescript
438 // INIT: register the binding, get the typed client
439 const tasks = yield* Cloudflare.RpcWorker.bind(TaskWorker);
440
441 // PER-REQUEST: just call methods directly
442 proxyGetTask: ({ id }) => tasks.getTask({ id }),
443 ```
444
445 The bind goes over the in-account service binding (not the public
446 internet) and the client is typed by `TaskWorker`'s declared schema.
447 A `Proxy` defers each call's underlying `RpcClient` construction so
448 Cloudflare's "no cross-request I/O" rule is satisfied transparently.
449 For internal Worker-to-Worker calls that don't need a schema at all,
450 see [Schemaless RPC on Workers](/cloudflare/compute/workers#call-another-worker).
451
452 `RpcWorker` also supports a **modular form** that separates the
453 class declaration from its runtime — useful when a consumer Worker
454 should be able to import the class for binding without pulling in
455 the host's runtime:
456
457 ```typescript
458 // Modular: class declaration carries no impl — just the schema.
459 export class TaskWorker extends Cloudflare.RpcWorker<TaskWorker>()(
460 "TaskWorker",
461 { schema: TaskRpcs },
462 ) {}
463
464 // Runtime lives in a separate Layer — only the host script imports it.
465 // `make` takes the Worker props (main, etc.) plus the impl.
466 export default TaskWorker.make(
467 { main: import.meta.url },
468 Effect.gen(function* () {
469 const handlers = TaskRpcs.toLayer({ /* ... */ });
470 return RpcServer.toHttpEffect(TaskRpcs).pipe(
471 Effect.provide(Layer.mergeAll(handlers, RpcSerialization.layerNdjson)),
472 );
473 }),
474 );
475 ```
476
477 The class can also declare DOs it publishes via the second type
478 argument — `RpcWorker<Self, Deps>()` mirrors
479 `Cloudflare.Worker<Self, Bindings, Deps>` so cross-script
480 `Counter.from(TaskWorker)` type-checks.
481
482 ## Sugar: `Cloudflare.RpcDurableObject`
483
484 The same shape applies to Durable Objects.
485 `Cloudflare.RpcDurableObject<Self>()(...)` mirrors the
486 regular DO class. Return the RPC handler Layer from the inner Effect;
487 Alchemy supplies the server and serialization. This example uses a shared
488 `CounterRpcs` group:
489
490 ```typescript
491 // rpcs.ts
492 import * as Schema from "effect/Schema";
493 import { Rpc, RpcGroup } from "effect/rpc";
494
495 export class CounterRpcs extends RpcGroup.make(
496 Rpc.make("setTitle", {
497 payload: { title: Schema.String },
498 success: Schema.Void,
499 }),
500 Rpc.make("getTitle", { payload: {}, success: Schema.String }),
501 ) {}
502 ```
503
504 Return its handler Layer from the per-instance Effect:
505
506 ```typescript
507 // counter.ts
508 import * as Cloudflare from "@alchemy.run/cloudflare";
509 import * as Effect from "effect/Effect";
510 import { CounterRpcs } from "./rpcs.ts";
511
512 export default class Counter extends Cloudflare.RpcDurableObject<Counter>()(
513 "Counter",
514 { schema: CounterRpcs },
515 Effect.gen(function* () {
516 const state = yield* Cloudflare.DurableObjectState;
517 return Effect.gen(function* () {
518 return CounterRpcs.toLayer({
519 setTitle: ({ title }) => state.storage.put("title", title),
520 getTitle: () => state.storage.get<string>("title").pipe(
521 Effect.map((title) => title ?? ""),
522 ),
523 });
524 });
525 }),
526 ) {}
527 ```
528
529 `counters.getByName(id)` returns an `Effect<RpcClient<CounterRpcs>>`
530 (yield it inside a per-request scope) rather than alchemy's built-in
531 DO method bridge. Reach for this when an external client connects to
532 the DO and speaks RPC over a WebSocket connection, or whenever DO
533 method return values cross a `Schema.Class` boundary — the built-in bridge
534 `JSON.stringify`s each value and loses class identity, while the RPC
535 namespace round-trips through the shared `RpcSerialization` codec.
536 The concept home for this trade-off is
537 [Effect RPC](/apis/effect-rpc).
538
539 Like `RpcWorker`, the RPC DO supports a **modular form** that
540 separates the class from its runtime so consumer Workers can bind
541 to it cross-script:
542
543 ```typescript
544 // counter.ts — class declaration carries no impl.
545 export class Counter extends Cloudflare.RpcDurableObject<Counter>()(
546 "Counter",
547 { schema: CounterRpcs },
548 ) {}
549
550 // Runtime lives in a separate Layer — only the host Worker imports it.
551 export default Counter.make(
552 Effect.gen(function* () {
553 const state = yield* Cloudflare.DurableObjectState;
554 return Effect.gen(function* () {
555 return CounterRpcs.toLayer({
556 setTitle: ({ title }) => state.storage.put("title", title),
557 getTitle: () => state.storage.get<string>("title").pipe(
558 Effect.map((title) => title ?? ""),
559 ),
560 });
561 });
562 }),
563 );
564 ```
565
566 From a consumer Worker, `Counter.from(HostWorker)` produces a
567 typed namespace bound to the host's running DO instances:
568
569 ```typescript
570 const counters = yield* Counter.from(HostWorker);
571 const stub = yield* counters.getByName("shared");
572 yield* stub.setTitle({ title: "hi" });
573 ```
574
575 For internal DO calls that don't need a schema, see
576 [Schemaless RPC on Durable Objects](/cloudflare/compute/durable-objects#schemaless-rpc).
577
578 ## HTTP and WebSocket RPC
579
580 Returning a handler Layer enables both HTTP and hibernating WebSocket RPC
581 automatically. Keep the declaration as `{ schema: CounterRpcs }`; the
582 incoming request selects the transport.
583
584 WebSocket upgrades use Effect RPC's JSON protocol. Ordinary HTTP requests
585 and existing `getByName` clients continue to use NDJSON. A WebSocket is
586 opened only when a client connects over one.
587
588 Existing implementations returning `RpcServer.toHttpEffect(...)` remain
589 HTTP-only. Return the handler Layer instead to let Alchemy provide both
590 transports.
591
592 ## Forward browser connections
593
594 The hosting Worker maps a URL to a named Durable Object. This Worker
595 forwards `/counters/alice` to `"alice"` and `/counters/bob` to `"bob"`:
596
597 ```typescript
598 // worker.ts
599 import * as Cloudflare from "@alchemy.run/cloudflare";
600 import * as Effect from "effect/Effect";
601 import { HttpServerRequest } from "effect/http/HttpServerRequest";
602 import * as HttpServerResponse from "effect/http/HttpServerResponse";
603 import Counter from "./counter.ts";
604
605 export default class CounterWorker extends Cloudflare.Worker<CounterWorker>()(
606 "CounterWorker",
607 { main: import.meta.url },
608 Effect.gen(function* () {
609 const counters = yield* Counter;
610 return {
611 fetch: Effect.gen(function* () {
612 const request = yield* HttpServerRequest;
613 const path = new URL(request.url, "https://worker").pathname;
614 const name = /^\/counters\/([a-zA-Z0-9_-]+)$/.exec(path)?.[1];
615 if (!name) return HttpServerResponse.empty({ status: 404 });
616 return yield* counters.fetch(name, request);
617 }),
618 };
619 }),
620 ) {}
621 ```
622
623 `counters.fetch(name, request)` selects that name in the `Counter` namespace
624 and forwards the HTTP request or WebSocket upgrade. It is not an application
625 RPC method, and `/counters/:name` is an application route, not a built-in
626 Alchemy endpoint.
627
628 Once upgraded, every RPC on that socket goes to the selected object; method
629 payloads do not need an object ID. Connections to the same name in the same
630 namespace share the object's state. Different names select different objects.
631 A socket cannot switch objects: open another connection to target another name.
632
633 This routing-only example accepts any name matching the route. For a private
634 API, authenticate the request and authorize access to the selected name before
635 calling `fetch`, or derive the name from the authenticated user or tenant.
636 Knowing an object's URL must not grant access by itself.
637
638 ## Connect over a WebSocket
639
640 Connect to the Worker's `/counters/alice` route and create the browser's
641 Effect RPC client in a Layer. This client talks only to the `"alice"` object:
642
643 ```typescript
644 import * as RpcWebSocketClient from "@alchemy.run/cloudflare/Workers/RpcWebSocketClient";
645 import * as Context from "effect/Context";
646 import * as Effect from "effect/Effect";
647 import * as Layer from "effect/Layer";
648 import * as RpcClient from "effect/rpc/RpcClient";
649 import type { RpcClientError } from "effect/rpc/RpcClientError";
650 import * as Socket from "effect/socket/Socket";
651 import { CounterRpcs } from "./rpcs.ts";
652
653 class CounterClient extends Context.Service<
654 CounterClient,
655 RpcClient.FromGroup<typeof CounterRpcs, RpcClientError>
656 >()("CounterClient") {}
657
658 const CounterClientLive = RpcWebSocketClient.layer(
659 CounterClient,
660 CounterRpcs,
661 "wss://example.com/counters/alice",
662 ).pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal));
663
664 const program = Effect.gen(function* () {
665 const counter = yield* CounterClient;
666 yield* counter.setTitle({ title: "Hello over WebSockets" });
667 return yield* counter.getTitle({});
668 }).pipe(Effect.provide(CounterClientLive));
669 ```
670
671 The dedicated `@alchemy.run/cloudflare/Workers/RpcWebSocketClient` entrypoint imports only
672 Effect modules and is safe to bundle for browsers. The wrapper is optional;
673 it composes Effect's RPC client, socket protocol, WebSocket, and JSON serializer.
674 Client middleware remains an explicit Layer dependency. Its `socket`, `protocol`,
675 and `client` options pass through to Effect; `serialization` defaults to JSON
676 and must match the server. See the
677 [`RpcWebSocketClient.layer` API reference](/providers/cloudflare/workers/layer).
678
679 The Layer owns the client and connection lifetime, so ordinary calls do not need
680 an explicit `Effect.scoped`. It closes the connection when the provided program
681 finishes, fails, or is interrupted. Provide it around the whole application or
682 component program that shares the client, rather than constructing it for each
683 call. Concurrent calls and streams share the socket; Effect handles typed errors,
684 backpressure, and cancellation.
685
686 ### Keep a client for a browser session
687
688 For a UI driven by callbacks, keep one managed runtime for the session:
689
690 ```typescript
691 import * as ManagedRuntime from "effect/ManagedRuntime";
692
693 const runtime = ManagedRuntime.make(CounterClientLive);
694
695 const getTitle = () => runtime.runPromise(
696 Effect.gen(function* () {
697 const counter = yield* CounterClient;
698 return yield* counter.getTitle({});
699 }),
700 );
701 ```
702
703 On application or component teardown, release that runtime:
704
705 ```typescript
706 await runtime.dispose();
707 ```
708
709 Your application wires teardown to its UI lifecycle; the Layer does not detect
710 component unmounts. Keeping the browser connection open does not prevent
711 Cloudflare from hibernating an idle Durable Object. When calling from another
712 Cloudflare Worker rather than a browser, provide the client Layer inside each
713 request; Worker sockets cannot be shared across request contexts.
714
715 ### Subscription scopes
716
717 Ordinary streaming RPCs return an Effect `Stream`; consume them with stream
718 operators while the client Layer is alive. Requesting `{ asQueue: true }`
719 returns a queue acquisition that still requires a consumer `Scope`. The Layer
720 owns the shared connection, not the lifetime of each subscription. Scope those
721 queue consumers separately so ending one subscription does not close the client.
722
723 ### Compose the built-in Effect layers directly
724
725 The convenience wrapper is equivalent to this composition, using the same
726 `CounterClient` service and RPC group:
727
728 ```typescript
729 import * as RpcSerialization from "effect/rpc/RpcSerialization";
730
731 const CounterClientLive = Layer.effect(
732 CounterClient,
733 RpcClient.make(CounterRpcs),
734 ).pipe(
735 Layer.provide(
736 RpcClient.layerProtocolSocket().pipe(
737 Layer.provide([
738 Socket.layerWebSocket("wss://example.com/counters/alice"),
739 RpcSerialization.layerJson,
740 ]),
741 Layer.provide(Socket.layerWebSocketConstructorGlobal),
742 ),
743 ),
744 );
745 ```
746
747 ## WebSocket RPC and hibernation
748
749 Idle connections can survive Durable Object hibernation and accept new
750 calls after the instance wakes. Alchemy restores connection metadata
751 from socket attachments and handles protocol heartbeats internally. A restored
752 socket with a different recorded serializer content type is reset. This is not
753 a schema-version check: changes that keep the same content type are not detected,
754 so coordinate incompatible schema or codec changes with clients.
755
756 In-flight calls and streams are not replayed. If the instance is
757 reconstructed with unfinished work, the affected socket closes with
758 code `1012`; clients must handle the interruption. A platform reset can
759 close the connection before Alchemy restores it, so other transport errors
760 are also possible. Durable checkpoints and resumable subscriptions are
761 not part of this API. Application RPC methods do not need acknowledgment
762 or lifecycle methods.
763
764 ## Under the hood: the manual DO bridge
765
766 `RpcDurableObject.getByName(id)` above returns a wired `RpcClient`
767 directly — you rarely need more. This section shows what it does
768 internally, and doubles as the escape hatch when the `RpcServer`
769 runs inside a plain `Cloudflare.DurableObject` and you build the
770 bridge yourself: `Cloudflare.toHttpClient(stub)` turns the DO stub
771 into an `HttpClient` that plugs into `RpcClient.layerProtocolHttp`.
772
773 ### Split the RPCs into two groups
774
775 Put the procedures the DO implements into one group, and the
776 Worker-only proxies into another. `merge` produces the public group
777 the Worker exposes:
778
779 ```typescript
780 // src/rpcs.ts
781 export const InnerRpcs = RpcGroup.make(getTask, createTask, countTasks);
782
783 export const DoRpcs = RpcGroup.make(
784 Rpc.make("getTaskDO", {
785 payload: { id: Schema.String },
786 success: Task,
787 error: TaskNotFound,
788 }),
789 Rpc.make("createTaskDO", {
790 payload: { title: Schema.String },
791 success: Task,
792 error: CreateTaskFailed,
793 }),
794 );
795
796 export class TaskRpcs extends InnerRpcs.merge(DoRpcs) {}
797 ```
798
799 ### Implement the DO
800
801 The DO's constructor returns `{ fetch }` produced by
802 `RpcServer.toHttpEffect(InnerRpcs)`. State lives in
803 `state.storage` instead of R2:
804
805 ```typescript
806 // src/object.ts
807 import * as Cloudflare from "@alchemy.run/cloudflare";
808 import * as Effect from "effect/Effect";
809 import * as Layer from "effect/Layer";
810 import * as Stream from "effect/Stream";
811 import * as RpcSerialization from "effect/rpc/RpcSerialization";
812 import * as RpcServer from "effect/rpc/RpcServer";
813 import { InnerRpcs } from "./rpcs.ts";
814 import { Task, TaskNotFound } from "./task.ts";
815
816 export default class TasksObject extends Cloudflare.DurableObject<TasksObject>()(
817 "TasksObject",
818 Effect.gen(function* () {
819 const state = yield* Cloudflare.DurableObjectState;
820 return Effect.gen(function* () {
821 const handlersLayer = InnerRpcs.toLayer({
822 getTask: ({ id }) =>
823 state.storage.get<Task>(id).pipe(
824 Effect.flatMap((task) =>
825 task ? Effect.succeed(task) : Effect.fail(new TaskNotFound({ id })),
826 ),
827 ),
828 createTask: ({ title }) =>
829 Effect.sync(() => new Task({ id: crypto.randomUUID(), title, completed: false }))
830 .pipe(Effect.tap((task) => state.storage.put(task.id, task))),
831 countTasks: ({ upto }) =>
832 Stream.fromIterable(Array.from({ length: upto }, (_, i) => i + 1)),
833 });
834
835 return {
836 fetch: RpcServer.toHttpEffect(InnerRpcs).pipe(
837 Effect.provide(Layer.mergeAll(handlersLayer, RpcSerialization.layerNdjson)),
838 ),
839 };
840 });
841 }),
842 ) {}
843 ```
844
845 ### Bridge the DO into the Worker
846
847 `Cloudflare.toHttpClient(stub)` produces an `HttpClient` whose
848 `execute` calls into the DO's `fetch`. Plug it into
849 `RpcClient.layerProtocolHttp` to get a typed `RpcClient<InnerRpcs>`
850 — the group the DO actually serves — then the `*DO` handlers just
851 forward the typed call. Here's the
852 whole Worker — the R2-backed handlers are unchanged, the new
853 `makeDOClient` and `getTaskDO` / `createTaskDO` proxies are added:
854
855 ```typescript
856 // src/worker.ts
857 import * as Cloudflare from "@alchemy.run/cloudflare";
858 import * as Effect from "effect/Effect";
859 import * as Layer from "effect/Layer";
860 import * as HttpClient from "effect/http/HttpClient";
861 import { RpcClient, RpcSerialization, RpcServer } from "effect/rpc";
862 import { Tasks } from "./bucket.ts";
863 import { InnerRpcs, TaskRpcs } from "./rpcs.ts";
864 import TasksObject from "./object.ts";
865
866 export default Cloudflare.Worker(
867 "Worker",
868 { main: import.meta.url },
869 Effect.gen(function* () {
870 const tasks = yield* Cloudflare.R2.ReadWriteBucket(Tasks);
871 const tasksDO = yield* TasksObject;
872
873 // A per-request typed RpcClient that short-circuits to the DO's
874 // `fetch`. The `url` is a placeholder — the request never hits the
875 // network; it routes straight to `tasksDO.getByName(id).fetch`.
876 const makeDOClient = (id: string = "default") =>
877 RpcClient.make(InnerRpcs).pipe(
878 Effect.provide(
879 RpcClient.layerProtocolHttp({ url: "http://localhost" }).pipe(
880 Layer.provide(
881 Layer.succeed(
882 HttpClient.HttpClient,
883 Cloudflare.toHttpClient(tasksDO.getByName(id)),
884 ),
885 ),
886 Layer.provide(RpcSerialization.layerNdjson),
887 ),
888 ),
889 );
890
891 const handlersLayer = TaskRpcs.toLayer({
892 // R2-backed handlers — unchanged
893 getTask: /* ... R2 implementation ... */,
894 createTask: /* ... R2 implementation ... */,
895 // DO-backed proxies — forward the typed call to the DO
896 getTaskDO: (payload) =>
897 makeDOClient().pipe(Effect.flatMap((client) => client.getTask(payload))),
898 createTaskDO: (payload) =>
899 makeDOClient().pipe(Effect.flatMap((client) => client.createTask(payload))),
900 });
901
902 return {
903 fetch: RpcServer.toHttpEffect(TaskRpcs).pipe(
904 Effect.provide(
905 Layer.mergeAll(handlersLayer, RpcSerialization.layerNdjson),
906 ),
907 ),
908 };
909 }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
910 );
911 ```
912
913 For streaming RPCs the same proxy pattern works with `Stream.unwrap` —
914 declare a streaming `countTasksDO` in `DoRpcs` (same shape as
915 `countTasks`, with `stream: true`) and forward:
916
917 ```typescript
918 countTasksDO: (payload) =>
919 Stream.unwrap(
920 makeDOClient().pipe(Effect.map((client) => client.countTasks(payload))),
921 ),
922 ```
923
924 `getTaskDO` / `createTaskDO` now hit the DO; `getTask` / `createTask`
925 still hit R2. One `TaskRpcs` value, one client, two storage backends.
926
927 ## Choosing a modality
928
929 - **Internal calls** (Worker-to-Worker, Worker-to-DO) —
930 [Schemaless RPC](/apis/schemaless): typed clients with no schema
931 and no per-request validation cost.
932 - **External Effect/TypeScript consumers** — this page.
933 - **External plain-HTTP consumers** —
934 [Effect HTTP](/cloudflare/apis/effect-http-api): the same typed
935 interface over real REST endpoints.
936
937 The full decision guide lives at [RPC](/apis).