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

main
mdx 247 lines 6.94 KB
Raw
1 ---
2 title: Effect RPC on Cloud Run
3 description: Build a typed RPC API with Effect's Rpc module, deploy it to Cloud Run, and call its procedures from a typed client.
4 sidebar:
5 order: 3
6 ---
7
8 Effect RPC gives you procedures instead of URLs, and a typed client
9 with no codegen. Every request is checked against a schema, so use it
10 where a web app or another service calls into yours. The concept lives
11 at [Effect RPC](/apis/effect-rpc). This page wires it onto Cloud Run.
12
13 ## Define the schemas
14
15 ```typescript
16 // src/Job.ts
17 import * as Schema from "effect/Schema";
18
19 export const JobId = Schema.String;
20
21 export class Job extends Schema.Class<Job>("Job")({
22 id: JobId,
23 content: Schema.String,
24 }) {}
25
26 export class JobNotFound extends Schema.TaggedClass<JobNotFound>()(
27 "JobNotFound",
28 { jobId: JobId },
29 ) {}
30
31 export class PutJobFailed extends Schema.TaggedClass<PutJobFailed>()(
32 "PutJobFailed",
33 { reason: Schema.String },
34 ) {}
35 ```
36
37 The client receives these errors as typed values it can `catchTag`.
38
39 ## Declare the procedures
40
41 ```typescript
42 // src/JobRpcs.ts
43 import * as Schema from "effect/Schema";
44 import { Rpc, RpcGroup } from "effect/rpc";
45 import { Job, JobId, JobNotFound, PutJobFailed } from "./Job.ts";
46
47 const getJob = Rpc.make("getJob", {
48 success: Job,
49 error: JobNotFound,
50 payload: { jobId: JobId },
51 });
52
53 const createJob = Rpc.make("createJob", {
54 success: JobId,
55 error: PutJobFailed,
56 payload: { content: Schema.String },
57 });
58
59 export class JobRpcs extends RpcGroup.make(getJob, createJob) {}
60 ```
61
62 ## Implement it on Cloud Run
63
64 `GCP.Run.ServeRpc` turns the group into a `fetch` handler. It serves
65 NDJSON, so streaming procedures work, and builds the server once per
66 instance:
67
68 ```typescript
69 // src/JobService.ts
70 import * as GCP from "@alchemy.run/gcp";
71 import * as Effect from "effect/Effect";
72 import { Job, JobNotFound, PutJobFailed } from "./Job.ts";
73 import { JobRpcs } from "./JobRpcs.ts";
74
75 export default class JobService extends GCP.Function<JobService>()(
76 "JobService",
77 { main: import.meta.url, invokerIamDisabled: true },
78 Effect.gen(function* () {
79 const jobs = yield* GCP.Firestore.Database("Jobs", {
80 type: "FIRESTORE_NATIVE",
81 });
82 const db = yield* GCP.Firestore.ReadWriteDatabase(jobs);
83
84 const handlersLayer = JobRpcs.toLayer({
85 getJob: ({ jobId }) =>
86 db.get(`jobs/${jobId}`).pipe(
87 Effect.orDie,
88 Effect.flatMap((doc) =>
89 doc
90 ? Effect.succeed(
91 new Job({ id: jobId, content: String(doc.fields.content ?? "") }),
92 )
93 : Effect.fail(new JobNotFound({ jobId })),
94 ),
95 ),
96 createJob: ({ content }) =>
97 Effect.gen(function* () {
98 const jobId = crypto.randomUUID();
99 yield* db.set(`jobs/${jobId}`, { content });
100 return jobId;
101 }).pipe(
102 Effect.mapError((error) => new PutJobFailed({ reason: error._tag })),
103 ),
104 });
105
106 return {
107 fetch: GCP.Run.ServeRpc(JobRpcs, handlersLayer),
108 };
109 }).pipe(Effect.provide(GCP.Firestore.ReadWriteDatabaseHttp)),
110 ) {}
111 ```
112
113 `getJob` turns Firestore failures into 500s and keeps `JobNotFound`
114 for the client. `createJob` maps them to the declared `PutJobFailed`.
115
116 ## Add it to the Stack
117
118 ```typescript
119 // alchemy.run.ts
120 import * as Alchemy from "alchemy";
121 import * as GCP from "@alchemy.run/gcp";
122 import * as Effect from "effect/Effect";
123 import JobService from "./src/JobService.ts";
124
125 export default Alchemy.Stack(
126 "JobRpc",
127 { providers: GCP.providers(), state: GCP.state() },
128 Effect.gen(function* () {
129 const service = yield* JobService;
130 return { url: service.uri };
131 }),
132 );
133 ```
134
135 ```sh
136 bun alchemy deploy
137 ```
138
139 ## Call it from a typed client
140
141 ```typescript
142 // scripts/client.ts
143 import * as Effect from "effect/Effect";
144 import * as Layer from "effect/Layer";
145 import * as FetchHttpClient from "effect/http/FetchHttpClient";
146 import { RpcClient, RpcSerialization } from "effect/rpc";
147 import { JobRpcs } from "../src/JobRpcs.ts";
148
149 const program = Effect.gen(function* () {
150 const client = yield* RpcClient.make(JobRpcs);
151
152 const jobId = yield* client.createJob({ content: "Ship the docs" });
153 const job = yield* client.getJob({ jobId });
154 yield* Effect.log(job.content);
155 });
156
157 Effect.runPromise(
158 program.pipe(
159 Effect.scoped,
160 Effect.provide(
161 RpcClient.layerProtocolHttp({ url: process.env.JOB_RPC_URL! }).pipe(
162 Layer.provide(FetchHttpClient.layer),
163 Layer.provide(RpcSerialization.layerNdjson),
164 ),
165 ),
166 ),
167 );
168 ```
169
170 ```sh
171 JOB_RPC_URL=https://<service>.run.app bun scripts/client.ts
172 ```
173
174 ## Call it from another service
175
176 Keep the RPC service private (drop `invokerIamDisabled`) and call it
177 from another Cloud Run service. `GCP.Run.InvokeService` with
178 `schema` grants `roles/run.invoker`, signs each call with an ID token,
179 and returns the typed client:
180
181 ```typescript
182 // src/Gateway.ts
183 import * as GCP from "@alchemy.run/gcp";
184 import * as Effect from "effect/Effect";
185 import * as HttpServerResponse from "effect/http/HttpServerResponse";
186 import JobService from "./JobService.ts";
187 import { JobRpcs } from "./JobRpcs.ts";
188
189 export default class Gateway extends GCP.Run.Service<Gateway>()(
190 "Gateway",
191 { main: import.meta.url, invokerIamDisabled: true },
192 Effect.gen(function* () {
193 const jobs = yield* GCP.Run.InvokeService(JobService, { schema: JobRpcs });
194 return {
195 fetch: Effect.gen(function* () {
196 const jobId = yield* jobs.createJob({ content: "Ship the docs" });
197 return yield* HttpServerResponse.json(yield* jobs.getJob({ jobId }));
198 }).pipe(Effect.orDie),
199 };
200 }).pipe(Effect.provide(GCP.Run.InvokeServiceHttp)),
201 ) {}
202 ```
203
204 The client speaks NDJSON, the serialization `GCP.Run.ServeRpc` serves.
205
206 ## Run it as a sidecar
207
208 The same group can run next to the caller in one instance. Declare it
209 as a `GCP.Run.Container` and bind it with `GCP.Run.bindContainer`:
210
211 ```typescript
212 // src/JobSidecar.ts
213 import * as GCP from "@alchemy.run/gcp";
214 import * as Effect from "effect/Effect";
215 import { JobRpcs } from "./JobRpcs.ts";
216 import { handlersLayer } from "./handlers.ts";
217
218 export default class JobSidecar extends GCP.Run.Container<JobSidecar>()(
219 "JobSidecar",
220 { main: import.meta.url, port: 3000, startupProbe: { tcpSocket: {} } },
221 Effect.gen(function* () {
222 return { fetch: GCP.Run.ServeRpc(JobRpcs, handlersLayer) };
223 }),
224 ) {}
225 ```
226
227 ```typescript
228 // inside the calling service's Effect
229 const jobs = yield* GCP.Run.bindContainer(JobSidecar, { schema: JobRpcs });
230 const job = yield* jobs.getJob({ jobId });
231 ```
232
233 Calls go over `localhost` and never leave the instance. Streaming
234 procedures return a `Stream` on both clients.
235
236 ## Choosing an API style
237
238 Use Effect RPC when every caller is Effect. Use
239 [Effect HTTP](/gcp/apis/effect-http-api) when callers want plain
240 REST. The [RPC overview](/apis) has the full decision.
241
242 ## Where next
243
244 - [Effect RPC](/apis/effect-rpc) — procedures, streaming, and clients
245 in depth.
246 - [Private services](/gcp/networking/private-services) — keep the RPC
247 service private and call it from another service.