@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 458 lines 16 KB
Raw
1 import * as cloudfront from "@distilled.cloud/aws/cloudfront";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, createTagsList, diffTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import type { Providers } from "../Providers.ts";
11
12 export class VpcOriginUnexpectedResponse extends Data.TaggedError("VpcOriginUnexpectedResponse")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 class VpcOriginPendingDeployment extends Data.TaggedError("VpcOriginPendingDeployment")<{
18 message: string;
19 }> {}
20
21 class VpcOriginStillInUse extends Data.TaggedError("VpcOriginStillInUse")<{
22 message: string;
23 }> {}
24
25 export interface VpcOriginProps {
26 /**
27 * Name of the VPC origin. If omitted, a deterministic name is generated.
28 */
29 name?: string;
30 /**
31 * ARN of the resource the VPC origin fronts (an Application/Network Load
32 * Balancer or an EC2 instance in a VPC). Changing the target ARN forces a
33 * replacement.
34 */
35 arn: string;
36 /**
37 * HTTP port CloudFront uses to connect to the origin.
38 * @default 80
39 */
40 httpPort?: number;
41 /**
42 * HTTPS port CloudFront uses to connect to the origin.
43 * @default 443
44 */
45 httpsPort?: number;
46 /**
47 * Origin protocol policy CloudFront uses to connect to the origin.
48 * @default "https-only"
49 */
50 originProtocolPolicy?: cloudfront.OriginProtocolPolicy;
51 /**
52 * SSL/TLS protocols CloudFront uses when establishing an HTTPS connection.
53 * @default ["TLSv1.2"]
54 */
55 originSslProtocols?: cloudfront.SslProtocol[];
56 /**
57 * User-defined tags to apply to the VPC origin.
58 */
59 tags?: Record<string, string>;
60 }
61
62 export interface VpcOrigin extends Resource<
63 "AWS.CloudFront.VpcOrigin",
64 VpcOriginProps,
65 {
66 /**
67 * CloudFront-assigned VPC origin identifier.
68 */
69 vpcOriginId: string;
70 /**
71 * ARN of the VPC origin.
72 */
73 vpcOriginArn: string;
74 /**
75 * Current deployment status of the VPC origin.
76 */
77 status: string;
78 /**
79 * Name of the VPC origin.
80 */
81 name: string;
82 /**
83 * ARN of the resource the VPC origin fronts.
84 */
85 arn: string;
86 /**
87 * Creation timestamp.
88 */
89 createdTime: Date | undefined;
90 /**
91 * Last CloudFront modification timestamp.
92 */
93 lastModifiedTime: Date | undefined;
94 /**
95 * Most recent entity tag for update/delete operations.
96 */
97 etag: string | undefined;
98 /**
99 * Current tags on the VPC origin.
100 */
101 tags: Record<string, string>;
102 },
103 never,
104 Providers
105 > {}
106
107 /**
108 * A CloudFront VPC origin.
109 *
110 * `VpcOrigin` lets a CloudFront distribution route to a private Application
111 * Load Balancer, Network Load Balancer, or EC2 instance inside a VPC without
112 * exposing it to the public internet. Reference the resulting `vpcOriginId`
113 * from a distribution origin's `vpcOriginConfig`.
114 * ### Creating VPC Origins
115 * **Example:** Private ALB Origin
116 * ```typescript
117 * const vpcOrigin = yield* VpcOrigin("AppOrigin", {
118 * arn: loadBalancer.arn,
119 * httpPort: 80,
120 * httpsPort: 443,
121 * originProtocolPolicy: "https-only",
122 * });
123 * ```
124 *
125 * **Example:** Attaching a VPC Origin to a Distribution
126 * ```typescript
127 * const distribution = yield* Distribution("AppCdn", {
128 * origins: [
129 * {
130 * id: "app",
131 * domainName: loadBalancer.dnsName,
132 * vpcOriginConfig: { vpcOriginId: vpcOrigin.vpcOriginId },
133 * },
134 * ],
135 * defaultCacheBehavior: {
136 * targetOriginId: "app",
137 * viewerProtocolPolicy: "redirect-to-https",
138 * },
139 * });
140 * ```
141 *
142 * @resource
143 */
144 export const VpcOrigin = Resource<VpcOrigin>("AWS.CloudFront.VpcOrigin");
145
146 export const VpcOriginProvider = () =>
147 Provider.effect(
148 VpcOrigin,
149 Effect.gen(function* () {
150 // Observe — locate the VPC origin by id, tolerating a concurrent delete.
151 const getById = Effect.fn(function* (id: string) {
152 const result = yield* cloudfront
153 .getVpcOrigin({ Id: id })
154 .pipe(Effect.catchTag("EntityNotFound", () => Effect.undefined));
155 if (!result?.VpcOrigin?.Id) {
156 return undefined;
157 }
158 return { vpcOrigin: result.VpcOrigin, etag: result.ETag };
159 });
160
161 // Crash recovery — a create can succeed in the cloud but fail to persist
162 // locally. Recover by listing and matching on the fronted ARN.
163 const getByArn = Effect.fn(function* (arn: string) {
164 let marker: string | undefined;
165 do {
166 const listed: cloudfront.ListVpcOriginsResult = yield* cloudfront.listVpcOrigins({
167 Marker: marker,
168 });
169 const summary = listed.VpcOriginList?.Items?.find(
170 (item) => item.OriginEndpointArn === arn,
171 );
172 if (summary?.Id) {
173 return yield* getById(summary.Id);
174 }
175 marker = listed.VpcOriginList?.IsTruncated ? listed.VpcOriginList.NextMarker : undefined;
176 } while (marker);
177 return undefined;
178 });
179
180 const fetchTags = Effect.fn(function* (arn: string) {
181 const response = yield* cloudfront.listTagsForResource({
182 Resource: arn,
183 });
184 return toTagsRecord(response.Tags.Items);
185 });
186
187 // Wait — poll until the VPC origin reaches the terminal `Deployed` state,
188 // mirroring the Distribution deployment wait.
189 const waitForDeployment = Effect.fn(function* (id: string) {
190 return yield* getById(id).pipe(
191 Effect.flatMap((current) =>
192 current?.vpcOrigin.Status === "Deployed"
193 ? Effect.succeed(current)
194 : Effect.fail(
195 new VpcOriginPendingDeployment({
196 message: `VPC origin ${id} is not yet deployed (status=${current?.vpcOrigin.Status ?? "unknown"})`,
197 }),
198 ),
199 ),
200 Effect.retry({
201 while: (error) => error._tag === "VpcOriginPendingDeployment",
202 // CloudFront VPC-origin deployment is slow (global propagation) and
203 // routinely exceeds 10 min; budget ~20 min (120 * 10s) so a real
204 // deploy doesn't fail spuriously.
205 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(120)]),
206 }),
207 );
208 });
209
210 const desiredEndpointConfig = (
211 name: string,
212 props: VpcOriginProps,
213 ): cloudfront.VpcOriginEndpointConfig => ({
214 Name: name,
215 Arn: props.arn,
216 HTTPPort: props.httpPort ?? 80,
217 HTTPSPort: props.httpsPort ?? 443,
218 OriginProtocolPolicy: props.originProtocolPolicy ?? "https-only",
219 OriginSslProtocols: {
220 Quantity: (props.originSslProtocols ?? ["TLSv1.2"]).length,
221 Items: props.originSslProtocols ?? ["TLSv1.2"],
222 },
223 });
224
225 const endpointConfigEquals = (
226 a: cloudfront.VpcOriginEndpointConfig | undefined,
227 b: cloudfront.VpcOriginEndpointConfig,
228 ) =>
229 !!a &&
230 a.Name === b.Name &&
231 a.Arn === b.Arn &&
232 a.HTTPPort === b.HTTPPort &&
233 a.HTTPSPort === b.HTTPSPort &&
234 a.OriginProtocolPolicy === b.OriginProtocolPolicy &&
235 (a.OriginSslProtocols?.Items ?? []).join(",") ===
236 (b.OriginSslProtocols?.Items ?? []).join(",");
237
238 const syncTags = Effect.fn(function* (
239 arn: string,
240 observedTags: Record<string, string>,
241 desiredTags: Record<string, string>,
242 ) {
243 const { removed, upsert } = diffTags(observedTags, desiredTags);
244 if (upsert.length > 0) {
245 yield* cloudfront.tagResource({
246 Resource: arn,
247 Tags: { Items: upsert },
248 });
249 }
250 if (removed.length > 0) {
251 yield* cloudfront.untagResource({
252 Resource: arn,
253 TagKeys: { Items: removed },
254 });
255 }
256 });
257
258 return {
259 stables: ["vpcOriginId", "vpcOriginArn"],
260 list: () =>
261 Effect.gen(function* () {
262 const items: VpcOrigin["Attributes"][] = [];
263 let marker: string | undefined;
264 do {
265 const listed: cloudfront.ListVpcOriginsResult = yield* cloudfront.listVpcOrigins({
266 Marker: marker,
267 });
268 for (const summary of listed.VpcOriginList?.Items ?? []) {
269 if (!summary.Id) continue;
270 const current = yield* getById(summary.Id);
271 if (!current) continue;
272 const tags = yield* fetchTags(current.vpcOrigin.Arn);
273 items.push(toAttrs(current.vpcOrigin, current.etag, tags));
274 }
275 marker = listed.VpcOriginList?.IsTruncated
276 ? listed.VpcOriginList.NextMarker
277 : undefined;
278 } while (marker);
279 return items;
280 }),
281 diff: Effect.fn(function* ({ id, olds, news: _news }) {
282 if (!isResolved(_news)) return undefined;
283 const news = _news as VpcOriginProps;
284 // `arn` is create-only — a changed target endpoint forces replace.
285 if (olds?.arn !== undefined && olds.arn !== news.arn) {
286 return { action: "replace" } as const;
287 }
288 // A changed name also forces replace (it is the immutable identity).
289 if (
290 (yield* createName(id, olds ?? ({} as VpcOriginProps))) !==
291 (yield* createName(id, news))
292 ) {
293 return { action: "replace" } as const;
294 }
295 }),
296 read: Effect.fn(function* ({ olds, output }) {
297 const existing = output?.vpcOriginId
298 ? yield* getById(output.vpcOriginId)
299 : yield* getByArn((olds ?? ({} as VpcOriginProps)).arn ?? "");
300 if (!existing?.vpcOrigin.Id) {
301 return undefined;
302 }
303 const tags = yield* fetchTags(existing.vpcOrigin.Arn);
304 return toAttrs(existing.vpcOrigin, existing.etag, tags);
305 }),
306 reconcile: Effect.fn(function* ({ id, news, output, session }) {
307 const name = yield* createName(id, news);
308 const desiredTags = {
309 ...(yield* createInternalTags(id)),
310 ...news.tags,
311 };
312
313 // Observe — locate by cached id or recover by fronted ARN.
314 let observed = output?.vpcOriginId ? yield* getById(output.vpcOriginId) : undefined;
315 if (!observed) {
316 observed = yield* getByArn(news.arn);
317 }
318
319 // Ensure — create the VPC origin if it's missing. Tolerate an
320 // `EntityAlreadyExists` race by recovering via the fronted ARN.
321 if (!observed) {
322 const created = yield* cloudfront
323 .createVpcOrigin({
324 VpcOriginEndpointConfig: desiredEndpointConfig(name, news),
325 Tags: { Items: createTagsList(desiredTags) },
326 })
327 .pipe(
328 Effect.map((result) =>
329 result.VpcOrigin?.Id
330 ? { vpcOrigin: result.VpcOrigin, etag: result.ETag }
331 : undefined,
332 ),
333 Effect.catchTag("EntityAlreadyExists", () => getByArn(news.arn)),
334 );
335
336 if (!created?.vpcOrigin.Id) {
337 return yield* new VpcOriginUnexpectedResponse({
338 message: "createVpcOrigin returned no identifier",
339 });
340 }
341
342 yield* session.note(created.vpcOrigin.Id);
343 const deployed = yield* waitForDeployment(created.vpcOrigin.Id);
344 const tags = yield* fetchTags(deployed.vpcOrigin.Arn);
345 return toAttrs(deployed.vpcOrigin, deployed.etag, tags);
346 }
347
348 // Sync endpoint config — patch only when the observed config differs
349 // from desired, using the freshly observed ETag for concurrency.
350 const desired = desiredEndpointConfig(name, news);
351 let current = observed;
352 if (!endpointConfigEquals(observed.vpcOrigin.VpcOriginEndpointConfig, desired)) {
353 yield* cloudfront.updateVpcOrigin({
354 Id: observed.vpcOrigin.Id,
355 IfMatch: observed.etag ?? "",
356 VpcOriginEndpointConfig: desired,
357 });
358 current = yield* waitForDeployment(observed.vpcOrigin.Id);
359 } else if (observed.vpcOrigin.Status !== "Deployed") {
360 current = yield* waitForDeployment(observed.vpcOrigin.Id);
361 }
362
363 // Sync tags — diff against observed cloud tags so adoption converges.
364 const observedTags = yield* fetchTags(current.vpcOrigin.Arn);
365 yield* syncTags(current.vpcOrigin.Arn, observedTags, desiredTags);
366
367 yield* session.note(current.vpcOrigin.Id);
368 return toAttrs(current.vpcOrigin, current.etag, desiredTags);
369 }),
370 delete: Effect.fn(function* ({ output }) {
371 if (!output.vpcOriginId) {
372 return;
373 }
374 // Observe current state. `deleteVpcOrigin` requires a terminal
375 // `Deployed` status and the *current* ETag — `output.etag` may be
376 // stale. If the origin is still `Deploying` (e.g. an interrupted
377 // create), CloudFront refuses the delete and leaves the origin — and
378 // its managed ENIs, which then block the VPC/ALB teardown —
379 // orphaned. Wait for it to settle so it becomes deletable.
380 const observed = yield* getById(output.vpcOriginId);
381 if (!observed) {
382 return; // already gone — idempotent
383 }
384 const current =
385 observed.vpcOrigin.Status === "Deployed"
386 ? observed
387 : yield* waitForDeployment(output.vpcOriginId).pipe(
388 Effect.orElseSucceed(() => observed),
389 );
390 yield* cloudfront
391 .deleteVpcOrigin({
392 Id: output.vpcOriginId,
393 IfMatch: current.etag ?? observed.etag ?? "",
394 })
395 .pipe(
396 Effect.catchTags({
397 EntityNotFound: () => Effect.void,
398 // The VPC origin may still be referenced by a distribution origin
399 // that is mid-removal; retry on the in-use signal.
400 CannotDeleteEntityWhileInUse: (error) =>
401 Effect.fail(
402 new VpcOriginStillInUse({
403 message: error.message ?? "VPC origin still in use",
404 }),
405 ),
406 }),
407 Effect.retry({
408 while: (error) => error._tag === "VpcOriginStillInUse",
409 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(30)]),
410 }),
411 );
412 // Block until the origin record is fully gone so dependents (the
413 // fronted ALB/VPC, held by CloudFront's ENIs) can be torn down.
414 yield* Effect.repeat(
415 getById(output.vpcOriginId).pipe(Effect.map((o) => o !== undefined)),
416 {
417 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(30)]),
418 until: (exists) => exists === false,
419 },
420 ).pipe(Effect.catch(() => Effect.void));
421 }),
422 };
423 }),
424 );
425
426 const createName = (id: string, props: VpcOriginProps) =>
427 props.name
428 ? Effect.succeed(props.name)
429 : createPhysicalName({
430 id,
431 maxLength: 64,
432 });
433
434 const toTagsRecord = (tags: cloudfront.Tag[] | undefined) =>
435 Object.fromEntries(
436 (tags ?? [])
437 .filter(
438 (tag): tag is { Key: string; Value: string } =>
439 typeof tag.Key === "string" && typeof tag.Value === "string",
440 )
441 .map((tag) => [tag.Key, tag.Value]),
442 );
443
444 const toAttrs = (
445 vpcOrigin: cloudfront.VpcOrigin,
446 etag: string | undefined,
447 tags: Record<string, string>,
448 ): VpcOrigin["Attributes"] => ({
449 vpcOriginId: vpcOrigin.Id,
450 vpcOriginArn: vpcOrigin.Arn,
451 status: vpcOrigin.Status,
452 name: vpcOrigin.VpcOriginEndpointConfig.Name,
453 arn: vpcOrigin.VpcOriginEndpointConfig.Arn,
454 createdTime: vpcOrigin.CreatedTime,
455 lastModifiedTime: vpcOrigin.LastModifiedTime,
456 etag,
457 tags,
458 });