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

main
mdx 415 lines 12.9 KB
Raw
1 ---
2 title: "Part 2: Add a Lambda"
3 description: Create an AWS Lambda Function with a public URL, bind the S3 Bucket, and implement GET/PUT routes.
4 sidebar:
5 order: 2
6 ---
7
8 import Terminal from "../../../../components/Terminal.astro";
9 import PackageManagers from "../../../../components/PackageManagers.astro";
10
11 In [Part 1](/aws/tutorial/part-1) you deployed an S3 Bucket. Now
12 you'll create a Lambda Function with a public URL that reads and
13 writes objects in that bucket over HTTP.
14
15 ## Create the function file
16
17 A Lambda Function in Alchemy is a class — it has both an
18 infrastructure definition and a runtime implementation expressed as
19 an Effect. Create `src/api.ts` with the smallest possible
20 declaration:
21
22 ```typescript
23 // src/api.ts
24 import * as AWS from "@alchemy.run/aws";
25 import * as Effect from "effect/Effect";
26
27 export default class Api extends AWS.Lambda.Function<Api>()(
28 "Api",
29 { main: import.meta.url },
30 Effect.gen(function* () {
31 return {};
32 }),
33 ) {}
34 ```
35
36 The `<Api>` type argument plus the empty `()` is a one-time bit of
37 ceremony — it lets TypeScript reason about `Api` as a typed handle
38 that other resources can later bind against. `main: import.meta.url`
39 tells Alchemy this same file is the bundle entrypoint: at deploy time
40 it's bundled with Rolldown into a zip and uploaded as the function's
41 code.
42
43 ## Serve HTTP with `fetch`
44
45 The empty function compiles, but it doesn't do anything yet. Add a
46 `fetch` field — Alchemy treats anything returned from the
47 `Effect.gen` block as the runtime API, and `fetch` specifically is
48 wired up to handle incoming HTTP requests:
49
50 ```diff lang="typescript"
51 // src/api.ts
52 import * as AWS from "@alchemy.run/aws";
53 import * as Effect from "effect/Effect";
54 +import * as HttpServerResponse from "effect/http/HttpServerResponse";
55
56 export default class Api extends AWS.Lambda.Function<Api>()(
57 "Api",
58 { main: import.meta.url },
59 Effect.gen(function* () {
60 - return {};
61 + return {
62 + fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
63 + };
64 }),
65 ) {}
66 ```
67
68 `HttpServerResponse.text(...)` is the same `effect/http` API
69 used everywhere else in Effect — Alchemy adapts it to the Lambda
70 event envelope under the hood, so your handler never sees the raw
71 `APIGatewayProxyEvent` shape.
72
73 :::note
74 Notice the "Effect returning an Effect" pattern. The outer generator
75 is the **Construction phase** — it runs at both plan time and runtime. The
76 inner `fetch` generator is the **Runtime phase** — it runs only when
77 handling a request.
78 :::
79
80 ## Expose a public URL
81
82 Every Lambda Function gets a public **Function URL** by default:
83 `functionUrl` defaults to `true`, which creates an unauthenticated HTTPS
84 endpoint (`authType: "NONE"`) and lets anyone invoke it. Spell it out
85 so the access level is visible in the code:
86
87 ```diff lang="typescript"
88 export default class Api extends AWS.Lambda.Function<Api>()(
89 "Api",
90 - { main: import.meta.url },
91 + { main: import.meta.url, functionUrl: true },
92 Effect.gen(function* () {
93 return {
94 fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
95 };
96 }),
97 ) {}
98 ```
99
100 The resolved `Api` resource exposes a `functionUrl` field
101 carrying that endpoint — we'll surface it from the Stack in a moment.
102
103 `functionUrl` takes three access choices. `false` creates no URL,
104 `true` creates a public one, and `{ authType: "AWS_IAM" }` requires
105 SigV4-signed requests.
106
107 :::caution
108 Omitting `functionUrl` gives you a public URL. A Function that only
109 consumes events (SQS, SNS, EventBridge, Kinesis, S3) should set
110 `functionUrl: false`.
111 :::
112
113 ## Move the Bucket into the function
114
115 In Part 1 the Bucket lived in `alchemy.run.ts`, but resources can be
116 declared inside any Effect the Stack runs — including a function's
117 Construction phase. Declaring the bucket next to the code that uses it keeps
118 everything about the function in one file. Add it to the constructor:
119
120 ```diff lang="typescript"
121 // src/api.ts
122 import * as AWS from "@alchemy.run/aws";
123 +import * as S3 from "@alchemy.run/aws/S3";
124 import * as Effect from "effect/Effect";
125 import * as HttpServerResponse from "effect/http/HttpServerResponse";
126
127 export default class Api extends AWS.Lambda.Function<Api>()(
128 "Api",
129 { main: import.meta.url, functionUrl: true },
130 Effect.gen(function* () {
131 + const bucket = yield* S3.Bucket("Bucket");
132
133 return {
134 fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
135 };
136 }),
137 ) {}
138 ```
139
140 The logical id is still `Bucket`, so Alchemy recognizes it as the
141 same resource you deployed in Part 1 — moving a declaration between
142 files doesn't recreate anything.
143
144 ## Bind PutObject and GetObject
145
146 S3 operations like `s3:PutObject` and `s3:GetObject` are exposed as
147 **bindings** — a typed runtime function you call from your handler,
148 plus an IAM policy statement that gets attached to the function role
149 automatically, scoped to the exact bucket ARN. Bind them in the outer
150 constructor, alongside the bucket:
151
152 ```diff lang="typescript"
153 Effect.gen(function* () {
154 const bucket = yield* S3.Bucket("Bucket");
155 + const putObject = yield* S3.PutObject(bucket);
156 + const getObject = yield* S3.GetObject(bucket);
157
158 return {
159 fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
160 };
161 }),
162 ```
163
164 Both capability calls return a callable Effect: `putObject` takes a
165 `PutObjectRequest` (the AWS SDK shape, minus the `Bucket` field
166 Alchemy fills in for you) and `getObject` takes a `GetObjectRequest`.
167 Each call is 1:1 with an IAM statement on the execution role — delete
168 a capability call and the matching statement disappears next deploy.
169 See [S3 → One binding, one IAM statement](/aws/data/s3#one-binding-one-iam-statement)
170 for the exact mapping.
171
172 ## Write objects with `PUT /:key`
173
174 Replace the static handler with one that takes the URL path as the
175 object key and writes the request body to the bucket:
176
177 ```diff lang="typescript"
178 // src/api.ts
179 import * as AWS from "@alchemy.run/aws";
180 import * as S3 from "@alchemy.run/aws/S3";
181 import * as Effect from "effect/Effect";
182 +import { HttpServerRequest } from "effect/http/HttpServerRequest";
183 import * as HttpServerResponse from "effect/http/HttpServerResponse";
184
185 // ...
186 return {
187 - fetch: Effect.succeed(HttpServerResponse.text("Hello from Lambda!")),
188 + fetch: Effect.gen(function* () {
189 + const request = yield* HttpServerRequest;
190 + const key = new URL(request.url).pathname.slice(1);
191 +
192 + if (request.method === "PUT") {
193 + const body = yield* request.text;
194 + yield* putObject({ Key: key, Body: body });
195 + return HttpServerResponse.empty({ status: 204 });
196 + }
197 +
198 + return HttpServerResponse.text("Method not allowed", { status: 405 });
199 + }),
200 };
201 ```
202
203 `putObject({ Key, Body })` is the same shape as `s3:PutObject` in the
204 AWS SDK, minus the `Bucket` field — Alchemy fills that in from the
205 bucket you bound, so the call site stays focused on what's actually
206 variable.
207
208 ## Read objects with `GET /:key`
209
210 Add a `GET` branch that fetches the object and pipes it back to the
211 client:
212
213 ```diff lang="typescript"
214 if (request.method === "PUT") {
215 const body = yield* request.text;
216 yield* putObject({ Key: key, Body: body });
217 return HttpServerResponse.empty({ status: 204 });
218 }
219
220 +if (request.method === "GET") {
221 + const result = yield* getObject({ Key: key });
222 + return HttpServerResponse.stream(result.Body!);
223 +}
224
225 return HttpServerResponse.text("Method not allowed", { status: 405 });
226 ```
227
228 `result.Body` is an Effect `Stream<Uint8Array>`, not a buffered
229 `Buffer`. `HttpServerResponse.stream` flushes each chunk to the HTTP
230 response as it arrives, so even a multi-gigabyte object moves through
231 the function without ever being held in memory.
232
233 ## Handle missing objects
234
235 If the key doesn't exist, S3 responds with `NoSuchKey`. The binding
236 surfaces that as a typed error tag on the Effect, so
237 `Effect.catchTag` recovers from it without inspecting strings:
238
239 ```diff lang="typescript"
240 if (request.method === "GET") {
241 - const result = yield* getObject({ Key: key });
242 + const result = yield* getObject({ Key: key }).pipe(
243 + Effect.catchTag("NoSuchKey", () => Effect.succeed(undefined)),
244 + );
245 + if (!result?.Body) {
246 + return HttpServerResponse.text("Not found", { status: 404 });
247 + }
248 return HttpServerResponse.stream(result.Body!);
249 }
250 ```
251
252 Every binding's failure channel is enumerated this way: the AWS SDK
253 error names become Effect tags, so the type-checker tells you which
254 failures the call site needs to handle.
255
256 ## Convert unhandled errors to 500s
257
258 Any failure you didn't `catchTag` is a programmer error — a missing
259 IAM grant, a transient AWS outage, a bug. Surface those as 500s by
260 applying `Effect.orDie` once at the request boundary, rather than per
261 call:
262
263 ```diff lang="typescript"
264 fetch: Effect.gen(function* () {
265 // ... PUT and GET branches ...
266 return HttpServerResponse.text("Method not allowed", { status: 405 });
267 -}),
268 +}).pipe(Effect.orDie),
269 ```
270
271 Applying `orDie` once at the outer layer keeps the inner code free of
272 repetitive error plumbing — the only errors you handle explicitly are
273 the ones you actually have a recovery for (`NoSuchKey`, in this
274 case).
275
276 ## Provide the runtime layers
277
278 Bindings declare a capability; **runtime layers** implement it. For
279 S3 those are `S3.PutObjectHttp` and `S3.GetObjectHttp` — both ship in
280 `@alchemy.run/aws/S3` and depend only on the AWS SDK and the ambient
281 credentials. Provide them at the bottom of the function:
282
283 ```diff lang="typescript"
284 // src/api.ts
285 +import * as Layer from "effect/Layer";
286 // ...
287 export default class Api extends AWS.Lambda.Function<Api>()(
288 "Api",
289 { main: import.meta.url, functionUrl: true },
290 Effect.gen(function* () {
291 /* ... bucket + bindings + fetch ... */
292 - }),
293 + }).pipe(
294 + Effect.provide(Layer.mergeAll(S3.PutObjectHttp, S3.GetObjectHttp)),
295 + ),
296 ) {}
297 ```
298
299 `Layer.mergeAll` unions multiple layers into one — no order required
300 — and `Effect.provide` satisfies the binding requirements declared by
301 `PutObject` and `GetObject`.
302
303 ## Wire the function into the Stack
304
305 The `Api` class is just a typed identifier — yielding it inside the
306 Stack's Effect is what registers the resource and starts the deploy:
307
308 ```diff lang="typescript"
309 // alchemy.run.ts
310 import * as Alchemy from "alchemy";
311 import * as AWS from "@alchemy.run/aws";
312 import * as Effect from "effect/Effect";
313 +import Api from "./src/api.ts";
314
315 export default Alchemy.Stack(
316 "MyApp",
317 {
318 providers: AWS.providers(),
319 state: AWS.state(),
320 },
321 Effect.gen(function* () {
322 const bucket = yield* AWS.S3.Bucket("Bucket");
323 + const api = yield* Api;
324
325 return {
326 bucketName: bucket.bucketName,
327 + url: api.functionUrl,
328 };
329 }),
330 );
331 ```
332
333 Yielding `Api` returns the resolved Lambda outputs — the function
334 ARN, role ARN, and the public Function URL we asked for with
335 `functionUrl: true`. We surface `functionUrl` as the Stack's `url` output.
336
337 ## Retire the inline Bucket
338
339 The Bucket is now declared inside `Api`'s constructor, so the copy in
340 `alchemy.run.ts` is redundant — remove it:
341
342 ```diff lang="typescript"
343 Effect.gen(function* () {
344 - const bucket = yield* AWS.S3.Bucket("Bucket");
345 const api = yield* Api;
346
347 return {
348 - bucketName: bucket.bucketName,
349 url: api.functionUrl,
350 };
351 }),
352 ```
353
354 The bucket is still part of the Stack — it's registered when `Api`'s
355 Construction phase runs — it just isn't surfaced as a stack output anymore.
356
357 ## Deploy
358
359 Deploy again. Alchemy detects the new function and the unchanged
360 bucket:
361
362 <PackageManagers run="alchemy deploy" />
363
364 <Terminal content={`[u]Plan[/u]: [g]1 to create[/g]
365
366 [g]+[/g] [b]Api[/b] [d](AWS.Lambda.Function)[/d]
367 [d]•[/d] [b]Bucket[/b] [d](AWS.S3.Bucket)[/d]
368
369 Proceed?
370 ◉ Yes ○ No
371 [d]•[/d] [b]Bucket[/b] [d](AWS.S3.Bucket)[/d] [d]no change[/d]
372 [g]✓[/g] [b]Api[/b] [d](AWS.Lambda.Function)[/d] [g]created[/g]
373 {
374 [s2]url: "https://abc123xyz.lambda-url.us-east-1.on.aws",
375 }`} />
376
377 Alchemy bundles `src/api.ts` with Rolldown, packages it into a zip,
378 creates the IAM execution role with the two S3 statements, uploads
379 the function, and provisions the Function URL. The first deploy takes
380 a moment because of role propagation; subsequent deploys are seconds.
381
382 ## Try it out
383
384 Use `curl` to write and read an object:
385
386 ```sh
387 # Store an object
388 curl -X PUT https://abc123xyz.lambda-url.us-east-1.on.aws/hello.txt \
389 -d 'Hello, world!'
390
391 # Retrieve it
392 curl https://abc123xyz.lambda-url.us-east-1.on.aws/hello.txt
393 # → Hello, world!
394 ```
395
396 ## Recap
397
398 You now have:
399
400 - A Lambda Function with GET and PUT routes served over a public
401 Function URL
402 - An S3 Bucket bound to the function, with the IAM policy generated
403 from the bindings you actually use — no policy JSON in sight
404 - Stack outputs showing the function URL
405
406 In [Part 3](/aws/tutorial/part-3), you'll write integration tests
407 that deploy the stack and drive it over HTTP.
408
409 :::tip[Want to start building now?]
410 You have a deployed function — that's enough to skip ahead to
411 [DynamoDB](/aws/data/dynamodb), [SQS](/aws/messaging/sqs), or
412 [Kinesis](/aws/messaging/kinesis) if you'd rather build something interesting
413 first and circle back to testing, stages, and CI/CD when you need
414 them.
415 :::