@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
ts 373 lines 14.4 KB
Raw
1 import { createHash } from "node:crypto";
2 import * as ag from "@distilled.cloud/aws/api-gateway";
3 import { deepEqual, isResolved } from "alchemy/Diff";
4 import type { Input } from "alchemy/Input";
5 import * as Output from "alchemy/Output";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { Stack } from "alchemy/Stack";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import { retryOnApiStatusUpdating } from "./common.ts";
13 import type { RestApi, RestApiBinding } from "./RestApi.ts";
14
15 export interface DeploymentProps {
16 /**
17 * The `RestApi` to deploy. When supplied, the Deployment reads every
18 * `RestApiBinding` already registered on the API (each `Method`,
19 * `Resource`, etc. that was declared with `restApi: api`) and pulls
20 * those into its dependency graph. Adding a new `Method` automatically
21 * causes the next apply to produce a fresh deployment — no user-authored
22 * `DependsOn` or `triggers` hash required.
23 */
24 restApi?: RestApi;
25 /**
26 * ID of the REST API. Usually derived from `restApi.restApiId`; supply
27 * explicitly only when not using `restApi`.
28 */
29 restApiId?: Input<string>;
30 /** Description of the deployment. */
31 description?: string;
32 /** Name of a stage API Gateway creates alongside the deployment (legacy pattern — prefer a separate `Stage`). */
33 stageName?: string;
34 /** Description of the stage created via `stageName`. */
35 stageDescription?: string;
36 /** Enable a cache cluster on the stage created via `stageName`. */
37 cacheClusterEnabled?: boolean;
38 /** Cache cluster size for the stage created via `stageName`. */
39 cacheClusterSize?: ag.CacheClusterSize;
40 /** Stage variables for the stage created via `stageName`. */
41 variables?: { [key: string]: string | undefined };
42 /** Canary settings applied to the deployment. */
43 canarySettings?: ag.DeploymentCanarySettings;
44 /** Enable X-Ray tracing on the stage created via `stageName`. */
45 tracingEnabled?: boolean;
46 /**
47 * Opaque key/value map; when any value changes, a replacement deployment
48 * is planned. Each value may be a literal string or an `Input<string>`
49 * (such as a resource output) — output references create real dependency
50 * edges, which is how Alchemy ensures a new deployment runs after the
51 * resources it references are updated.
52 *
53 * You rarely need to set this manually: when you pass `restApi`, the
54 * deployment already depends on every bound `Method` and redeploys
55 * automatically when any of them change. Reach for `triggers` only when
56 * you want to force a redeploy on some other signal (e.g. a config hash,
57 * a manual version bump).
58 */
59 triggers?: Record<string, Input<string>>;
60 }
61
62 export interface DeploymentType extends Resource<
63 "AWS.ApiGateway.Deployment",
64 DeploymentProps,
65 {
66 deploymentId: string;
67 restApiId: string;
68 description: string | undefined;
69 },
70 never,
71 Providers
72 > {}
73
74 /**
75 * A point-in-time snapshot of a REST API, ready to be served through a
76 * `Stage`.
77 * ### Creating a deployment
78 * A Deployment captures whatever methods, integrations, resources, and
79 * authorizers currently exist on the REST API and produces an immutable
80 * `deploymentId` that a `Stage` can point at. Pass the `RestApi` value on
81 * `restApi` and Alchemy handles all the ordering for you — the deployment
82 * will run after every method bound to the API.
83 *
84 * **Example:** Deployment of a REST API
85 * ```typescript
86 * const api = yield* ApiGateway.RestApi("Api", {
87 * endpointConfiguration: { types: ["REGIONAL"] },
88 * });
89 *
90 * yield* ApiGateway.Method("GetRoot", {
91 * restApi: api,
92 * httpMethod: "GET",
93 * authorizationType: "NONE",
94 * integration: { type: "MOCK" },
95 * });
96 *
97 * const deployment = yield* ApiGateway.Deployment("Release", {
98 * restApi: api,
99 * description: "v1",
100 * });
101 * ```
102 *
103 * ### Forcing a redeploy
104 * Usually you do not have to: `restApi` already makes the Deployment
105 * depend on every method, so any change to a method re-plans a new
106 * deployment. Use `triggers` when you want to couple the deployment to a
107 * signal Alchemy cannot see — for example, a manual version bump or a
108 * hash of configuration computed outside the stack.
109 *
110 * **Example:** Force redeploy on a version bump
111 * ```typescript
112 * const deployment = yield* ApiGateway.Deployment("Release", {
113 * restApi: api,
114 * triggers: { version: "2026-05-01" },
115 * });
116 * ```
117 *
118 * ### Why no DependsOn?
119 * CloudFormation's `AWS::ApiGateway::Deployment` famously requires a
120 * hand-written `DependsOn: [Method1, Method2, ...]` listing every method.
121 * Alchemy derives that list automatically from the bindings registered on
122 * the `RestApi`, so adding a method never requires editing the deployment.
123 *
124 * @resource
125 */
126 export const DeploymentResource = Resource<DeploymentType>("AWS.ApiGateway.Deployment");
127
128 interface DeploymentInputProps {
129 restApi?: RestApi;
130 restApiId?: Input<string>;
131 description?: Input<string>;
132 stageName?: Input<string>;
133 stageDescription?: Input<string>;
134 cacheClusterEnabled?: Input<boolean>;
135 cacheClusterSize?: Input<ag.CacheClusterSize>;
136 variables?: Input<{ [key: string]: string | undefined }>;
137 canarySettings?: Input<ag.DeploymentCanarySettings>;
138 tracingEnabled?: Input<boolean>;
139 triggers?: Record<string, Input<string>>;
140 }
141
142 /**
143 * User-facing wrapper that adds a dependency edge from the Deployment to
144 * every resource bound to the supplied `restApi`. Implementation detail:
145 * each binding's output references get copied into the deployment's
146 * `triggers` map so `resolveUpstream` sees them as real upstream dependencies.
147 */
148 export const Deployment = (id: string, props: DeploymentInputProps) =>
149 Effect.gen(function* () {
150 const { restApi, ...rest } = props;
151 const restApiId = rest.restApiId ?? restApi?.restApiId;
152 if (!restApiId) {
153 return yield* Effect.die(
154 "Deployment requires either `restApi` (preferred) or explicit " + "`restApiId`.",
155 );
156 }
157 let triggers: Record<string, Input<string>> | undefined = rest.triggers;
158 if (restApi) {
159 const stack = yield* Stack;
160 const bindings = stack.bindings[restApi.FQN] ?? [];
161 const autoTriggers: Record<string, Input<string>> = {};
162 for (const b of bindings) {
163 autoTriggers[`@alchemy:binding:${b.sid}`] = bindingDigest(b.data);
164 }
165 triggers = { ...autoTriggers, ...triggers };
166 }
167 return yield* DeploymentResource(id, {
168 ...rest,
169 restApiId,
170 triggers,
171 } as any);
172 });
173
174 /**
175 * Serializes a binding payload down to a deterministic `Input<string>` so
176 * it can ride along as a trigger value. The inner `Output.all` is what
177 * surfaces the underlying resource FQNs to the dependency resolver.
178 */
179 const bindingDigest = (data: RestApiBinding): Input<string> => {
180 const entries = Object.entries(data as Record<string, unknown>).filter(([k]) => k !== "kind");
181 const values = entries.map(([, v]) => Output.asOutput(v as string | Output.Output<string>));
182 return Output.map(Output.all(...values), (parts) =>
183 [data.kind, ...(parts as unknown as unknown[]).map(String)].join("|"),
184 );
185 };
186
187 const embedTriggers = (description: string | undefined, triggers?: Record<string, string>) =>
188 Effect.gen(function* () {
189 if (!triggers || Object.keys(triggers).length === 0) {
190 return description;
191 }
192 const fp = yield* Effect.sync(() =>
193 createHash("sha256").update(JSON.stringify(triggers)).digest("hex").slice(0, 24),
194 );
195 const suffix = `@alchemy:triggers:${fp}`;
196 return description ? `${description}\n${suffix}` : suffix;
197 });
198
199 export const DeploymentProvider = () =>
200 Provider.effect(
201 DeploymentResource,
202 Effect.gen(function* () {
203 return {
204 stables: ["deploymentId", "restApiId"] as const,
205 // Deployments are sub-resources keyed by `restApiId`. Enumerate every
206 // RestApi in the account/region, then page every deployment under each
207 // one and flatten — yielding the same Attributes shape `read` returns.
208 list: () =>
209 Effect.gen(function* () {
210 const restApiIds = yield* ag.getRestApis.pages({}).pipe(
211 Stream.runCollect,
212 Effect.map((chunk) =>
213 Array.from(chunk).flatMap((page) =>
214 (page.items ?? []).map((api) => api.id).filter((id): id is string => id != null),
215 ),
216 ),
217 );
218 const rows = yield* Effect.forEach(
219 restApiIds,
220 (restApiId) =>
221 ag.getDeployments.pages({ restApiId }).pipe(
222 Stream.runCollect,
223 Effect.map((chunk) =>
224 Array.from(chunk).flatMap((page) =>
225 (page.items ?? [])
226 .filter((d): d is ag.Deployment & { id: string } => d.id != null)
227 .map((d) => ({
228 deploymentId: d.id,
229 restApiId,
230 description: d.description,
231 })),
232 ),
233 ),
234 ),
235 { concurrency: 10 },
236 );
237 return rows.flat();
238 }),
239 diff: Effect.fn(function* ({ news: newsIn, olds }) {
240 if (!isResolved(newsIn)) return;
241 const news = newsIn as Input.ResolveProps<DeploymentProps>;
242 const oldsP = olds as Input.ResolveProps<DeploymentProps>;
243 if (news.restApiId !== oldsP.restApiId) {
244 return { action: "replace" } as const;
245 }
246 if (!deepEqual(news.triggers, oldsP.triggers)) {
247 return { action: "replace" } as const;
248 }
249 if (
250 news.stageName !== oldsP.stageName ||
251 news.stageDescription !== oldsP.stageDescription ||
252 news.cacheClusterEnabled !== oldsP.cacheClusterEnabled ||
253 news.cacheClusterSize !== oldsP.cacheClusterSize ||
254 !deepEqual(news.variables, oldsP.variables) ||
255 !deepEqual(news.canarySettings, oldsP.canarySettings) ||
256 news.tracingEnabled !== oldsP.tracingEnabled
257 ) {
258 return { action: "replace" } as const;
259 }
260 if (news.description !== oldsP.description) {
261 return { action: "update" } as const;
262 }
263 }),
264 read: Effect.fn(function* ({ output }) {
265 if (!output?.deploymentId) return undefined;
266 const d = yield* ag
267 .getDeployment({
268 restApiId: output.restApiId,
269 deploymentId: output.deploymentId,
270 })
271 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
272 if (!d?.id) return undefined;
273 return {
274 deploymentId: d.id,
275 restApiId: output.restApiId,
276 description: d.description,
277 };
278 }),
279 reconcile: Effect.fn(function* ({ news: newsIn, output, session }) {
280 if (!isResolved(newsIn)) {
281 return yield* Effect.die("Deployment props were not resolved");
282 }
283 const news = newsIn as Input.ResolveProps<DeploymentProps>;
284 const description = yield* embedTriggers(
285 news.description,
286 news.triggers as Record<string, string> | undefined,
287 );
288 const restApiId = (output?.restApiId ?? news.restApiId) as string;
289
290 // Observe — fetch the live deployment if we have a cached id.
291 // A Deployment is immutable apart from `description`, so we never
292 // trust a stale `output.description` for diffing.
293 let observed = output?.deploymentId
294 ? yield* ag
295 .getDeployment({
296 restApiId,
297 deploymentId: output.deploymentId,
298 })
299 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined))
300 : undefined;
301
302 // Ensure — create a new deployment if there isn't one yet.
303 // `createDeployment` always produces a fresh deploymentId, so we
304 // only call it when missing; any change that should produce a new
305 // deployment is modeled as `replace` in `diff`.
306 if (!observed?.id) {
307 const created = yield* retryOnApiStatusUpdating(
308 ag.createDeployment({
309 restApiId: news.restApiId as string,
310 stageName: news.stageName,
311 stageDescription: news.stageDescription,
312 description,
313 cacheClusterEnabled: news.cacheClusterEnabled,
314 cacheClusterSize: news.cacheClusterSize,
315 variables: news.variables,
316 canarySettings: news.canarySettings,
317 tracingEnabled: news.tracingEnabled,
318 }),
319 );
320 if (!created.id) return yield* Effect.die("createDeployment missing id");
321 yield* session.note(`Created deployment ${created.id}`);
322 observed = yield* ag.getDeployment({
323 restApiId: news.restApiId as string,
324 deploymentId: created.id,
325 });
326 }
327
328 const deploymentId = observed.id!;
329
330 // Sync description — observed ↔ desired.
331 if (description !== observed.description) {
332 yield* retryOnApiStatusUpdating(
333 ag.updateDeployment({
334 restApiId,
335 deploymentId,
336 patchOperations: description
337 ? [
338 {
339 op: "replace",
340 path: "/description",
341 value: description,
342 },
343 ]
344 : [{ op: "remove", path: "/description" }],
345 }),
346 );
347 }
348
349 yield* session.note(`Reconciled deployment ${deploymentId}`);
350 const final = yield* ag.getDeployment({
351 restApiId,
352 deploymentId,
353 });
354 return {
355 deploymentId,
356 restApiId,
357 description: final?.description,
358 };
359 }),
360 delete: Effect.fn(function* ({ output, session }) {
361 yield* retryOnApiStatusUpdating(
362 ag
363 .deleteDeployment({
364 restApiId: output.restApiId,
365 deploymentId: output.deploymentId,
366 })
367 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
368 );
369 yield* session.note(`Deleted deployment ${output.deploymentId}`);
370 }),
371 };
372 }),
373 );