@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 305 lines 9.29 KB
Raw
1 ---
2 title: Bindings
3 description: A Binding connects a Resource to a Worker or Lambda. One line declares the capability and generates the permissions, the configuration, and a typed client.
4 ---
5
6 A **Binding** connects a [Resource](/infrastructure-as-code/resource)
7 to a Worker, Lambda Function, Container, or Server — any
8 [Runtime](/infrastructure-as-effects/runtime). Inside the Runtime's
9 constructor, you yield the resource and get back a typed client:
10
11 ```typescript
12 import * as AWS from "@alchemy.run/aws";
13 import * as Effect from "effect/Effect";
14 import * as HttpServerResponse from "effect/http/HttpServerResponse";
15
16 export const Jobs = AWS.DynamoDB.Table("Jobs", { partitionKey: "pk" });
17
18 export default AWS.Lambda.Function(
19 "Api",
20 { main: import.meta.url, functionUrl: true },
21 Effect.gen(function* () {
22 const getItem = yield* AWS.DynamoDB.GetItem(Jobs);
23
24 return {
25 fetch: Effect.gen(function* () {
26 const job = yield* getItem({ Key: { pk: { S: "job-1" } } });
27 return HttpServerResponse.json(job.Item);
28 }),
29 };
30 }).pipe(Effect.provide(AWS.DynamoDB.GetItemHttp)),
31 );
32 ```
33
34 `yield* GetItem(Jobs)` is the binding. `getItem` is the client.
35 `GetItemHttp` is the implementation.
36
37 A Function that reads a table needs three things: permission to call
38 the API, the table's name at runtime, and a client to call it with. In
39 traditional IaC those live in three places. A policy in the
40 infrastructure code, an environment variable wired between the two, and
41 an SDK call in the handler that reads it back:
42
43 ```typescript
44 // infrastructure: grant access and pass the name
45 policy: { Action: ["dynamodb:GetItem"], Resource: [table.arn] },
46 environment: { JOBS_TABLE: table.name },
47 ```
48
49 ```typescript
50 // handler: hope the two above agree
51 const client = new DynamoDBClient();
52 await client.send(
53 new GetItemCommand({ TableName: process.env.JOBS_TABLE, Key }),
54 );
55 ```
56
57 Nothing checks that they agree. Rename the table, widen the policy,
58 forget the env var, and you find out at runtime. The binding is all
59 three. Let's follow what that one line produces.
60
61 ## Permissions
62
63 At deploy time the binding attaches an IAM statement to the Function's
64 role. It grants the one action the client can make, on the one table
65 it was bound to:
66
67 ```json
68 {
69 "Effect": "Allow",
70 "Action": ["dynamodb:GetItem"],
71 "Resource": ["arn:aws:dynamodb:us-east-1:123456789012:table/Jobs-a1b2c3"]
72 }
73 ```
74
75 Least privilege falls out of the shape. Bind `PutItem` as well and the
76 role gains a second statement for `dynamodb:PutItem`, nothing more:
77
78 ```typescript
79 const getItem = yield* AWS.DynamoDB.GetItem(Jobs);
80 const putItem = yield* AWS.DynamoDB.PutItem(Jobs);
81 ```
82
83 Bind several tables at once and the statement lists each of their ARNs:
84
85 ```typescript
86 const batchGet = yield* AWS.DynamoDB.BatchGetItem(Jobs, Audit);
87 ```
88
89 ## Configuration
90
91 The client needs the table's physical name. The binding serializes the
92 `Jobs.tableName` [Output](/infrastructure-as-code/outputs) into the
93 Function's environment:
94
95 ```sh
96 Jobs_tableName=Jobs-a1b2c3
97 ```
98
99 `getItem` reads it back and fills in `TableName` on every request. You
100 never touch `process.env`, and the name can't drift from the policy.
101 Both come from the same `Jobs` declaration.
102
103 ## The client
104
105 `getItem` is the DynamoDB operation with the table already filled in.
106 It returns an `Effect` with a typed error channel, so retries, timeouts,
107 and error handling compose onto it:
108
109 ```typescript
110 const job = yield* getItem({ Key: { pk: { S: "job-1" } } }).pipe(
111 Effect.retry({ times: 3, schedule: Schedule.exponential("100 millis") }),
112 Effect.timeout("5 seconds"),
113 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)),
114 );
115 ```
116
117 ## A contract and a Layer
118
119 `GetItem` names the capability. `GetItemHttp` decides how it's
120 satisfied. Cloudflare shows why that split matters. A Worker binds an
121 R2 bucket with the same shape:
122
123 ```typescript
124 import * as Cloudflare from "@alchemy.run/cloudflare";
125
126 export const Uploads = Cloudflare.R2.Bucket("Uploads");
127
128 export default Cloudflare.Worker(
129 "Api",
130 { main: import.meta.url },
131 Effect.gen(function* () {
132 const bucket = yield* Cloudflare.R2.ReadWriteBucket(Uploads);
133
134 return {
135 fetch: Effect.gen(function* () {
136 yield* bucket.put("hello.txt", "world");
137 return HttpServerResponse.text("ok");
138 }),
139 };
140 }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
141 );
142 ```
143
144 There is no IAM on Cloudflare. `ReadWriteBucketBinding` registers a
145 native `r2_bucket` binding on the Worker instead, and the access level
146 is in the name: `ReadBucket`, `WriteBucket`, or `ReadWriteBucket`.
147
148 The contract is a `Binding.Service`. It names the capability and the
149 client it returns, and nothing about the platform:
150
151 ```typescript
152 export interface ReadWriteBucket extends Binding.Service<
153 ReadWriteBucket,
154 "Cloudflare.R2.ReadWriteBucket",
155 (bucket: Bucket) => Effect.Effect<ReadWriteBucketClient>
156 > {}
157 ```
158
159 So the same contract can be satisfied a different way. Swap the Layer
160 and `bucket` calls R2 over HTTP with a scoped API token minted at deploy
161 time:
162
163 ```diff lang="typescript"
164 - }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
165 + }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketHttp)),
166 ```
167
168 The handler doesn't change. And a Layer that needs a platform the host
169 can't supply is a compile error:
170
171 ```typescript
172 export default AWS.Lambda.Function(
173 "Api",
174 { main: import.meta.url },
175 handler.pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
176 // ✗ Type error: the Layer requires `WorkerEnvironment` and `Worker`,
177 // which a Lambda Function can't provide
178 );
179 ```
180
181 [Layers](/infrastructure-as-effects/layers) takes this split one level
182 up, so your own services can carry their bindings with them.
183
184 ## Plan-time invokes
185
186 A binding can also run before anything is deployed. Terraform calls
187 this a data source, Pulumi an invoke. Call it directly and you get back
188 an [Output](/infrastructure-as-code/outputs) to pass into resource
189 props:
190
191 ```typescript
192 // Output<ec2.Image | undefined>
193 const image = AWS.EC2.getAmi({ owners: ["amazon"], name: ["al2023-ami-2023.*"] });
194
195 // a helper built on it. Output<string>, fails when nothing matches
196 imageId: AWS.EC2.amazonLinux2023(),
197 ```
198
199 The same capability bound inside a Function with
200 `yield* AWS.EC2.GetAmi(...)` still grants its IAM and runs at runtime.
201 One contract, both phases.
202
203 ## Event Sources and Sinks
204
205 An [Event Source](/infrastructure-as-effects/event-sources) is a
206 Binding that runs an Effect or `Stream` in the background, whenever
207 something happens on the resource:
208
209 ```typescript
210 yield* AWS.SQS.consumeQueueMessages(
211 Inbound,
212 Effect.fn(function* (event) {
213 for (const record of event.Records) {
214 yield* Effect.log(record.body);
215 }
216 }),
217 );
218 ```
219
220 A [Sink](/infrastructure-as-effects/sinks) is the converse, a Binding
221 you sink a `Stream` into:
222
223 ```typescript
224 const sink = yield* AWS.SQS.QueueSink(Outbound);
225 ```
226
227 Both generate their permissions and configuration the same way.
228
229 ## How it works under the hood
230
231 A binding declaration says nothing about how it is implemented. The
232 Layer you provide decides that:
233
234 ```typescript
235 Effect.provide(Cloudflare.R2.ReadWriteBucketHttp)
236 ```
237
238 Inside that Layer, the deploy-time work sits behind a guard. The
239 **Construction phase** runs twice, and the guard is what tells the two
240 runs apart:
241
242 ```typescript
243 if (!globalThis.__ALCHEMY_RUNTIME__) {
244 // deploy time only: register IAM / native bindings / env on the host
245 yield* host.bind`${resource}`(/* … */);
246 }
247 // always: return the typed runtime client
248 ```
249
250 When Alchemy bundles the Runtime it defines that global as `true`, so
251 the bundler drops the whole branch. Only the client ships:
252
253 ```typescript
254 // folded into every bundle as a rolldown define
255 "globalThis.__ALCHEMY_RUNTIME__": "true"
256 ```
257
258 The Resource Provider, the code that actually creates the bucket or
259 the table, is never imported by the binding at all. Declaring a
260 resource only records a requirement for its Provider, and that
261 requirement is satisfied once, at the Stack:
262
263 ```typescript
264 export default Alchemy.Stack(
265 "MyApp",
266 { providers: Cloudflare.providers(), state: Cloudflare.state() },
267 Effect.gen(function* () {
268 yield* Api;
269 }),
270 );
271 ```
272
273 This is what lets you declare resources and bindings inside runtime
274 code with little to no effect on bundle size. The heavy infrastructure
275 code stays at the Stack, and the guard erases the rest.
276 [Phases](/infrastructure-as-effects/phases#the-__alchemy_runtime__-guard)
277 covers the guard in depth.
278
279 The granularity pays off twice. Every binding has its own Layer, and
280 each Layer carries exactly one client and registers exactly one grant.
281 Provide the two you use and you get two clients in the bundle and two
282 statements on the role, nothing more:
283
284 ```typescript
285 Effect.provide(
286 Layer.mergeAll(
287 AWS.DynamoDB.GetItemHttp, // ships getItem, grants dynamodb:GetItem
288 AWS.DynamoDB.PutItemHttp, // ships putItem, grants dynamodb:PutItem
289 ),
290 )
291 ```
292
293 The same choice that keeps the bundle small keeps the permissions and
294 environment minimal.
295
296 ## Where next
297
298 - [Layers](/infrastructure-as-effects/layers) — hide bindings behind a
299 service interface. Next page.
300 - [Event Sources](/infrastructure-as-effects/event-sources) — bindings
301 that trigger your Function.
302 - [Sinks](/infrastructure-as-effects/sinks) — bindings you write
303 Streams into.
304 - [Circular Bindings](/infrastructure-as-effects/circular-bindings) —
305 two Functions that bind each other.