@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 208 lines 11.1 KB
Raw
1 ---
2 title: Programmatic API
3 description: Run deploy, plan, destroy, drift, nuke, logs, and state from your own scripts with alchemy/Alchemist.
4 ---
5
6 Every stack command has a programmatic counterpart in `alchemy/Alchemist`. The CLI is built on the same functions. They take the stack value your `alchemy.run.ts` exports, return plain results, and never prompt. Approval, rendering and printing are up to you.
7
8 ```typescript
9 import * as Alchemist from "alchemy/Alchemist";
10 import * as Effect from "effect/Effect";
11 import stack from "./alchemy.run.ts";
12
13 const program = Effect.gen(function* () {
14 const plan = yield* Alchemist.plan({ stack, operation: "deploy", stage: "prod" });
15 return yield* Alchemist.apply(plan);
16 });
17
18 await Effect.runPromise(program.pipe(Effect.provide(Alchemist.layer()), Effect.scoped));
19 ```
20
21 `Alchemist.layer()` provides everything the operations need: platform services, HTTP, config from the environment, profiles and credentials. Each operation takes the stack module and builds only what it needs. Deploy and logs run your stack program. Destroy, drift and nuke only build its providers and state store, and nuke never reads state.
22
23 ## Plan, then apply
24
25 Deploy and destroy are a `plan` and an `apply`. Drift and nuke don't plan changes to a stack; they look at what is there, so they are a `scan` and an `execute`. Each takes one object with the `stack` and its options:
26
27 | CLI | Read | Change |
28 | ------------------------ | -------------------------------------------------------- | ------------------------- |
29 | `alchemy deploy` | `Alchemist.plan({ stack, operation: "deploy", ... })` | `Alchemist.apply` |
30 | `alchemy plan` | `Alchemist.plan({ stack, operation: "deploy", ... })` | — |
31 | `alchemy destroy` | `Alchemist.plan({ stack, operation: "destroy", ... })` | `Alchemist.apply` |
32 | `alchemy drift --repair` | `Alchemist.Drift.scan({ stack, ... })` | `Alchemist.Drift.execute` |
33 | `alchemy unsafe nuke` | `Alchemist.Nuke.scan({ stack, ... })` | `Alchemist.Nuke.execute` |
34
35 Alongside the operations, `Alchemist` holds what they share: `layer`, `importStack`, `hasChanges`, and `onEvent`.
36
37 `plan` and `scan` don't change your resources. They return everything the next step needs, so you can inspect the result, ask for approval, or drop it. The one write they can make is to the state store itself: creating it on first use, or upgrading an outdated one when you pass `updateStateStore: true`.
38
39 Plans report what they would change:
40
41 ```typescript
42 const plan = yield* Alchemist.plan({ stack, operation: "deploy", stage: "prod" });
43 if (Alchemist.hasChanges(plan)) {
44 for (const resource of plan.resources) console.log(resource.action, resource.fqn);
45 yield* Alchemist.apply(plan);
46 }
47 ```
48
49 ## Options
50
51 | CLI flag | Option |
52 | ------------------- | -------------------------------------------- |
53 | `deploy` / `destroy` | `operation: "deploy"` or `"destroy"` (required) |
54 | `--stage <name>` | `stage: "prod"` (required, no fallback) |
55 | `--profile <name>` | `profile: "ci"` |
56 | `--env-file <path>` | `envFile: ".env.prod"` |
57 | `--adopt` | `adopt: true` |
58 | `--yes` | `updateStateStore: true` upgrades an outdated state store without asking; approval is yours |
59 | `--force` | `force: true` |
60 | `--include` | `include: ["Api"]` (deploy only) |
61 | `--exclude` | `exclude: ["Legacy/**"]` (deploy only) |
62 | `--config <file>` | the stack you import, or `yield* Alchemist.importStack(path)` |
63
64 `apply` returns the stack's output for a deploy plan and `undefined` for a destroy plan, typed from the stack. A plan filtered with `include` or `exclude` applies to `undefined` and leaves the persisted output untouched.
65
66 ## Scopes
67
68 A plan or scan keeps what it built open until the surrounding `Effect.scoped` closes, so its `apply` or `execute` can run later in the same scope. That includes the stage's state-store lease: a remote state store lets one build per stage hold it. To run another operation on the same stage, close the first one's scope. This is how `alchemy deploy --detect-drift` checks drift before deploying:
69
70 ```typescript
71 yield* Effect.scoped(
72 Effect.gen(function* () {
73 const drift = yield* Alchemist.Drift.scan({ stack, stage: "prod" });
74 if (Alchemist.Drift.hasDrift(drift)) yield* Alchemist.Drift.execute(drift);
75 }),
76 );
77
78 yield* Alchemist.apply(yield* Alchemist.plan({ stack, operation: "deploy", stage: "prod" }));
79 ```
80
81 Running a second operation on a stage whose first build is still open fails with a `StateStoreError` saying this process holds the stage's lock.
82
83 A `destroy` plan and `Alchemist.Drift.scan` never run the stack program, so they work even when the program no longer does.
84
85 ## Drift
86
87 `Alchemist.Drift.scan` reads every resource the stage owns and compares it with state. Each row's `status` is `in-sync`, `drifted`, `missing`, or `skipped` when it could not be checked (its provider can't read it, or a deploy was interrupted); `reason` says which. `Alchemist.Drift.hasDrift(scan)` is true when any row is `drifted` or `missing`.
88
89 `Alchemist.Drift.execute(scan)` repairs only the rows the scan reported as drifted or missing, back to their last-deployed state. It reads each one again first, so a resource that is back in sync is left alone, and drift that appeared after the scan waits for the next scan.
90
91 ## Nuke
92
93 `Alchemist.Nuke.scan` lists everything the stack's providers can see in the account, and `Alchemist.Nuke.execute` deletes it. Like the CLI, it ignores the state store and is not scoped to a stage. Spare resources by filtering the scan:
94
95 ```typescript
96 const scan = yield* Alchemist.Nuke.scan({ stack, include: ["Cloudflare.*"] });
97 const result = yield* Alchemist.Nuke.execute({
98 scan,
99 resources: scan.resources.filter(
100 (resource) => !String(resource.attributes.workerName).startsWith("prod-"),
101 ),
102 });
103 ```
104
105 | CLI flag | Option |
106 | ----------------------------- | ---------------------------------------------------------- |
107 | `--local` | `dev: true` |
108 | `--include`/`--exclude` | `include`/`exclude` on `scan` |
109 | `--filter` | `resources` on `execute` |
110 | `--independent --retries <n>` | `strategy: { type: "independent", retries: n }` on `execute` |
111 | `--concurrency <n>` | `concurrency: n` |
112 | `--timeout <s>` | `providerTimeoutSeconds: s` |
113
114 ## Dev
115
116 `dev: true` plans with local providers, as `alchemy dev` does. Local processes the deploy starts, such as dev servers and workerd, run until the scope closes.
117
118 ```typescript
119 yield* Alchemist.apply(
120 yield* Alchemist.plan({ stack, operation: "deploy", stage: "dev_sam", dev: true }),
121 );
122 ```
123
124 This is one deploy, not a dev loop. The API doesn't watch files or reload. That loop needs the CLI: `alchemy dev` runs your stack in a child process with module loader hooks, so an edit re-imports it, and keeps local providers in a sidecar process that survives each reload. For a dev loop, run [`alchemy dev`](/cli/dev).
125
126 ## Logs
127
128 `Alchemist.Logs.entries` queries past entries, and `Alchemist.Logs.tail` returns a `Stream` of live ones. `Alchemist.Logs.resources` lists what can be queried. Each call closes its build when it finishes; `tail` closes its build when the stream ends.
129
130 ```typescript
131 const entries = yield* Alchemist.Logs.entries({
132 stack,
133 stage: "prod",
134 resources: ["Api"],
135 limit: 50,
136 });
137 ```
138
139 ## State
140
141 `Alchemist.State.store` returns the state store a command would use. The `type` picks it, like `--backend`: `configured` uses the entrypoint's store, `local` uses `.alchemy/state`, and `provider` reaches a provider's store from the profile alone.
142
143 ```typescript
144 const state = yield* Alchemist.State.store({ type: "configured", entrypoint: "alchemy.run.ts" });
145
146 yield* state.listStacks(); // state list
147 yield* state.get({ stack: "my-app", stage: "prod", fqn: "Api" }); // state read
148 yield* state.delete({ stack: "my-app", stage: "prod", fqn: "Api" }); // state delete
149
150 yield* Alchemist.State.bootstrap({ type: "provider", backend: "aws" }); // state bootstrap
151 ```
152
153 The `provider` source needs no stack file, so a script can manage state on its own. See [Use a store without a stack file](/state-store#use-a-store-without-a-stack-file).
154
155 ## Events
156
157 Operations report progress as typed events instead of rendering it. Events are log records: the CLI's run log and `--log-format json` carry them, and `Alchemist.onEvent` subscribes to the ones an effect emits. `Alchemist.Event` is one Schema union discriminated by `type`, so a reader can decode events with it:
158
159 ```typescript
160 yield* Alchemist.apply(plan).pipe(
161 Alchemist.onEvent((event) =>
162 event.type === "apply.resource.status"
163 ? Effect.log(`${event.fqn}: ${event.status}`)
164 : Effect.void,
165 ),
166 );
167 ```
168
169 Any Effect logger you install sees every event too, as a record whose message is the event. Events are logged at `info`, except failures: a resource that fails to apply at `error`, and a nuke deletion or provider scan that fails at `warn`.
170
171 A handler runs for each event in order, and the operation waits for every handler before it returns. Keep handlers quick: a slow one delays the operation's end, and one that dies fails the operation.
172
173 ## Terminal UI
174
175 `alchemy/Cli/SigilRenderer` reuses the CLI's terminal views in your own script: the Sigil UI on an interactive terminal, plain log lines everywhere else. Provide `SigilRenderer.layer()` after `Alchemist.layer()` and wrap each step:
176
177 ```typescript
178 import * as SigilRenderer from "alchemy/Cli/SigilRenderer";
179
180 const program = Effect.gen(function* () {
181 const plan = yield* Alchemist.plan({ stack, operation: "deploy", stage }).pipe(
182 SigilRenderer.planning({ operation: "Deploy", stage }),
183 );
184 if (!(yield* SigilRenderer.approve(plan, { stage }))) return;
185 const output = yield* Alchemist.apply(plan).pipe(SigilRenderer.apply(plan, { stage }));
186 yield* SigilRenderer.outputs(output);
187 });
188
189 await Effect.runPromise(
190 program.pipe(
191 Effect.provide([Alchemist.layer(), SigilRenderer.layer()]),
192 Effect.scoped,
193 ),
194 );
195 ```
196
197 | Step | Renderer |
198 | --- | --- |
199 | any `plan` or drift `scan` | `SigilRenderer.planning({ operation, stage })` |
200 | approval prompt | `SigilRenderer.approve(plan)`, or `SigilRenderer.display(plan)` to only show it |
201 | `apply`, or drift `execute` | `SigilRenderer.apply(plan)`, or `SigilRenderer.apply(scan)` for drift |
202 | stack outputs | `SigilRenderer.outputs(output)` |
203 | nuke | `SigilRenderer.Nuke.scan()`, `.review(resources, options)`, `.delete(resources, mode)` |
204
205 ## Where next
206
207 - [deploy](/cli/deploy), [destroy](/cli/destroy), [drift](/cli/drift), [unsafe nuke](/cli/nuke), [state](/cli/state) — what each command does
208 - [State Store](/state-store) — where plans read and applies write