@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, 06:00 UTC

main
mdx 289 lines 9.33 KB
Raw
1 ---
2 title: What is Alchemy?
3 description: Alchemy is a TypeScript framework for building cloud applications with Effects and Layers. Your infrastructure and the code that runs on it are written, type-checked, and deployed together.
4 prev:
5 link: /getting-started
6 label: Getting started
7 next:
8 link: /infrastructure-as-effects/runtime
9 label: Runtime
10 ---
11
12 import DeployTerminal from "../../components/marketing-islands/DeployTerminal.tsx";
13 import ProviderIcons from "../../components/ProviderIcons.astro";
14
15 Alchemy is a TypeScript framework for building cloud applications
16 with [Effects](https://effect.website) and Layers. Your infrastructure
17 and the code that runs on it are written together, type-checked
18 together, and deployed together.
19
20 Here is an R2 Bucket and a Worker that serves files from it:
21
22 ```typescript
23 // src/api.ts
24 import * as Cloudflare from "@alchemy.run/cloudflare";
25 import * as Effect from "effect/Effect";
26 import * as HttpServerResponse from "effect/http/HttpServerResponse";
27
28 export const Uploads = Cloudflare.R2.Bucket("Uploads");
29
30 export default Cloudflare.Worker(
31 "Api",
32 { main: import.meta.url },
33 Effect.gen(function* () {
34 const bucket = yield* Cloudflare.R2.ReadWriteBucket(Uploads);
35
36 return {
37 fetch: Effect.gen(function* () {
38 const obj = yield* bucket.get("hello.txt");
39 return obj
40 ? HttpServerResponse.text(yield* obj.text())
41 : HttpServerResponse.text("Not found", { status: 404 });
42 }),
43 };
44 }).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)),
45 );
46 ```
47
48 The Bucket is declared next to the Worker that uses it, and the Worker
49 asks for it in its own code. `Cloudflare.R2.ReadWriteBucket(Uploads)`
50 does two jobs. When you deploy, it gives the Worker access to the
51 Bucket. When the Worker runs, it returns a typed client, so
52 `bucket.get` is checked like any other function call.
53
54 On AWS the same kind of line writes the IAM policy and the environment
55 variable for you:
56
57 ```typescript
58 const getItem = yield* AWS.DynamoDB.GetItem(Jobs);
59 // → { Action: ["dynamodb:GetItem"], Resource: [Jobs.tableArn] }
60 // → Jobs_tableName=Jobs-a1b2c3
61 ```
62
63 ## More than just Infrastructure as Code
64
65 Infrastructure as Code tools like Terraform, Pulumi, and the CDK only
66 cover the first half of that file: the Bucket and the Worker. The
67 Worker's code is a separate program that finds the Bucket through an
68 environment variable. Alchemy can be used that way too:
69
70 ```typescript
71 // alchemy.run.ts
72 import * as Cloudflare from "@alchemy.run/cloudflare";
73
74 export const Uploads = Cloudflare.R2.Bucket("Uploads");
75
76 export const Api = Cloudflare.Worker("Api", {
77 main: "./src/api.ts",
78 env: { Uploads },
79 });
80
81 export type ApiEnv = Cloudflare.InferEnv<typeof Api>;
82 ```
83
84 ```typescript
85 // src/api.ts
86 import type { ApiEnv } from "../alchemy.run.ts";
87
88 export default {
89 async fetch(request: Request, env: ApiEnv) {
90 const obj = await env.Uploads.get("hello.txt");
91 return obj
92 ? new Response(await obj.text())
93 : new Response("Not found", { status: 404 });
94 },
95 };
96 ```
97
98 The two halves meet at one name, `Uploads`. The handler can't see how
99 the Bucket got there, and the infrastructure can't see what the handler
100 does with it. Every feature you build crosses that line. A new upload
101 route needs a Bucket, permission to use it, and the code that calls it,
102 in two places that have to agree.
103
104 Alchemy is built on Infrastructure as Code, but it doesn't stop there.
105 When the Worker's code is an Effect that asks for the Bucket itself,
106 there is no name to keep in sync, no policy to write, and no client to
107 set up.
108
109 ## Infrastructure as Effects
110
111 We call this **Infrastructure as Effects**. Your app is built from
112 Effects and Layers, and the infrastructure it needs is part of them.
113 Their types record the resources it uses
114 and the access it needs, so a missing piece is a compile error, not a
115 failed deploy.
116
117 A Worker, Lambda Function, or Container is a **Runtime**: a resource
118 that carries the code it runs. Its code always has the same shape. Ask
119 for what you need, then return what you expose:
120
121 ```typescript
122 Effect.gen(function* () {
123 // ask for what you need
124 const bucket = yield* Cloudflare.R2.ReadWriteBucket(Uploads);
125
126 // return what you expose
127 return { fetch: /* ... */ };
128 });
129 ```
130
131 The outer Effect runs when you deploy and again when the Worker starts.
132 This is the Construction phase. The `fetch` it returns runs once per
133 request. This is the Runtime phase.
134
135 `ReadWriteBucket` is a **Binding**: it connects a resource to the
136 Runtime that uses it. `ReadWriteBucketBinding` is the Layer that
137 decides how. Swap it to reach the Bucket over HTTP instead, and the
138 handler doesn't change:
139
140 ```diff lang="typescript"
141 Effect.gen(function* () {
142 const bucket = yield* Cloudflare.R2.ReadWriteBucket(Uploads);
143 // ...
144 -}).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketBinding)); // native Worker binding
145 +}).pipe(Effect.provide(Cloudflare.R2.ReadWriteBucketHttp)); // HTTP with a scoped token
146 ```
147
148 ## Underneath, it's Infrastructure as Code
149
150 Deploying works like Terraform or Pulumi. A **Stack** is the unit you
151 deploy. It creates resources and returns the outputs you want printed:
152
153 ```typescript
154 // alchemy.run.ts
155 import * as Alchemy from "alchemy";
156 import * as Cloudflare from "@alchemy.run/cloudflare";
157 import * as Effect from "effect/Effect";
158 import Api from "./src/api.ts";
159
160 export default Alchemy.Stack(
161 "MyApp",
162 { providers: Cloudflare.providers(), state: Cloudflare.state() },
163 Effect.gen(function* () {
164 const api = yield* Api;
165 return { url: api.url };
166 }),
167 );
168 ```
169
170 Deploy it:
171
172 ```sh
173 alchemy deploy # dev_$USER by default
174 alchemy deploy --stage prod
175 ```
176
177 Alchemy creates the Bucket, bundles the Worker, gives it access to the
178 Bucket, and prints the URL. Each stage is a separate copy of every
179 resource, so `dev` and `prod` never touch each other.
180
181 Every deploy reads the last result from **state**, compares it with
182 your program, shows a plan, and applies only what changed:
183
184 <DeployTerminal client:visible />
185
186 A **Resource** is anything in your cloud that Alchemy manages: a
187 Bucket, a database, a queue, a Worker, a DNS record. Its outputs are
188 typed values you can pass to other resources:
189
190 ```typescript
191 const bucket = yield* Cloudflare.R2.Bucket("Uploads");
192
193 yield* Cloudflare.Worker("Api", {
194 main: "./src/api.ts",
195 env: { BUCKET_NAME: bucket.bucketName },
196 });
197 ```
198
199 A **Provider** teaches Alchemy how to manage one kind of resource. Each
200 cloud ships its providers as one Layer, and a Stack takes as many as it
201 needs:
202
203 ```typescript
204 providers: Layer.mergeAll(Cloudflare.providers(), AWS.providers()),
205 ```
206
207 ## Your services own their infrastructure
208
209 Because infrastructure is created inside Effects, a service's Layer
210 can create what it needs. Here is a `JobService` that stores
211 jobs in a KV Namespace:
212
213 ```typescript
214 export const JobServiceKV = Layer.effect(
215 JobService,
216 Effect.gen(function* () {
217 const Jobs = yield* Cloudflare.KV.Namespace("Jobs");
218 const kv = yield* Cloudflare.KV.ReadWriteNamespace(Jobs);
219 return { getJob: (id: string) => kv.get<Job>(id, "json") };
220 }),
221 );
222 ```
223
224 The KV Namespace, the access to it, and the code that reads it ship
225 together. Any Runtime that provides `JobServiceKV` gets all three. Your
226 business logic only sees `JobService`, so moving to DynamoDB is one
227 line:
228
229 ```diff lang="typescript"
230 Effect.gen(function* () {
231 const jobs = yield* JobService;
232 // ...
233 -}).pipe(Effect.provide(JobServiceKV)); // a KV Namespace, created and bound
234 +}).pipe(Effect.provide(JobServiceDynamo)); // a DynamoDB Table instead
235 ```
236
237 This is why Alchemy reaches past infrastructure into your application.
238 Things you would normally run as separate systems become Layers. A durable workflow is plain `effect/workflow` code, and
239 the Layer you provide picks where it runs:
240
241 ```diff lang="typescript"
242 Effect.gen(function* () {
243 const greet = yield* Workflows.RunWorkflow(Greet);
244 // ...
245 }).pipe(
246 - Effect.provide(GreetLive.pipe(Layer.provideMerge(Cloudflare.Workflows.layerDurableObjectEngine()))),
247 + Effect.provide(GreetLive.pipe(Layer.provideMerge(Cloudflare.Workflows.NativeEngine))),
248 );
249 ```
250
251 The same idea runs through the rest of the docs.
252 [APIs](/apis) are typed RPC and HTTP services between your Runtimes.
253 [Domain](/domain) models your business as commands, events, and views
254 and runs them on Durable Objects.
255 [Telemetry](/infrastructure-as-effects/telemetry) traces every request,
256 and its dashboards and alerts are resources you deploy with it.
257 [Tests](/testing) deploy your app to a stage of its own, run
258 against it, and tear it down.
259
260 ## Where next
261
262 <div class="next-steps">
263
264 <a href="/infrastructure-as-effects/runtime" class="next-card next-card--recommended">
265 <strong>Runtime</strong>
266 <span>How a Worker or Lambda Function carries its code: asking for what it needs and returning what it exposes.</span>
267 </a>
268
269 <a href="/infrastructure-as-effects/layers" class="next-card">
270 <strong>Layers</strong>
271 <span>Build services that bring their own infrastructure and swap them per cloud.</span>
272 </a>
273
274 <a href="/cloudflare" class="next-card">
275 <strong>Cloudflare</strong>
276 <span>Workers, Durable Objects, R2, KV, D1, Queues, Workflows, and Containers, with a tutorial and a guide for each.</span>
277 </a>
278
279 <a href="/aws" class="next-card">
280 <strong>AWS</strong>
281 <span>Lambda, S3, SQS, DynamoDB, EC2, ECS, and EKS, with a tutorial and a guide for each.</span>
282 </a>
283
284 <a href="/providers" class="next-card">
285 <strong>More providers</strong>
286 <ProviderIcons />
287 </a>
288
289 </div>