@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
ts 1,810 lines 65.9 KB
Raw
1 import * as cloudfront from "@distilled.cloud/aws/cloudfront";
2 import { isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import * as Namespace from "alchemy/Namespace";
5 import * as Output from "alchemy/Output";
6 import * as Provider from "alchemy/Provider";
7 import { Resource, type ResourceBinding } from "alchemy/Resource";
8 import { createInternalTags, createTagsList, diffTags } from "alchemy/Tags";
9 import { toWireSeconds } from "alchemy/Util/Duration";
10 import * as Data from "effect/Data";
11 import type * as Duration from "effect/Duration";
12 import * as Effect from "effect/Effect";
13 import * as FetchHttpClient from "effect/http/FetchHttpClient";
14 import * as HttpClient from "effect/http/HttpClient";
15 import * as Schedule from "effect/Schedule";
16 import * as Stream from "effect/Stream";
17 import { AWSEnvironment } from "../Environment.ts";
18 import {
19 WebFunctionPermission,
20 type WebFunctionEndpointRef,
21 } from "../Lambda/WebFunctionPermission.ts";
22 import type { Providers } from "../Providers.ts";
23 import {
24 MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_POLICY_ID,
25 MANAGED_CACHING_DISABLED_POLICY_ID,
26 } from "./ManagedPolicies.ts";
27 import { OriginAccessControl } from "./OriginAccessControl.ts";
28
29 export class DistributionConflict extends Data.TaggedError("DistributionConflict")<{
30 readonly message: string;
31 readonly cause?: unknown;
32 }> {}
33
34 export class DistributionUnexpectedResponse extends Data.TaggedError(
35 "DistributionUnexpectedResponse",
36 )<{
37 readonly message: string;
38 readonly cause?: unknown;
39 }> {}
40
41 const CLOUDFRONT_HOSTED_ZONE_ID = "Z2FDTNDATAQYW2" as const;
42
43 class DistributionFunctionAssociationPending extends Data.TaggedError(
44 "DistributionFunctionAssociationPending",
45 )<{
46 message: string;
47 }> {}
48
49 class DistributionPendingDeployment extends Data.TaggedError("DistributionPendingDeployment")<{
50 message: string;
51 }> {}
52
53 /**
54 * A Lambda Web Function endpoint to serve as an origin: an
55 * `AWS.Lambda.WebFunction` (its built-in endpoint), an
56 * `AWS.Lambda.WebFunctionEndpoint`, or a class declaration of either.
57 */
58 export interface WebFunctionOriginTarget extends WebFunctionEndpointRef {
59 domainName: string;
60 /** A `MultiRegion` endpoint's global domain needs SigV4A signatures. */
61 endpointType: string;
62 }
63
64 const signingProtocolFor = (endpointType: string) =>
65 endpointType === "MultiRegion" ? "sigv4a" : "sigv4";
66
67 export interface DistributionOrigin {
68 /**
69 * Unique origin identifier inside the distribution.
70 */
71 id: string;
72 /**
73 * Origin domain name. Required unless {@link webFunction} is set.
74 */
75 domainName?: Input<string>;
76 /**
77 * Serve a Lambda Web Function endpoint through this origin. Alchemy sets
78 * the origin's domain, sends HTTPS, creates an origin access control that
79 * signs every origin request, and grants this distribution (and only this
80 * distribution) permission to invoke the endpoint. The endpoint must use
81 * `authType: "IamAuth"`, so requests that bypass CloudFront are refused.
82 *
83 * Behaviors targeting this origin default to an API setup: no caching,
84 * the whole viewer request forwarded except `Host` (Lambda routes on
85 * it), and every HTTP method allowed. Set `cachePolicyId`,
86 * `originRequestPolicyId` or `allowedMethods` on the behavior to change
87 * that.
88 */
89 webFunction?: WebFunctionOriginTarget | Effect.Effect<WebFunctionOriginTarget, never, Providers>;
90 /**
91 * Optional origin path prefix.
92 */
93 originPath?: Input<string>;
94 /**
95 * CloudFront Origin Access Control identifier.
96 */
97 originAccessControlId?: Input<string>;
98 /**
99 * Whether the origin should be modeled as an S3 origin.
100 * @default false
101 */
102 s3Origin?: boolean;
103 /**
104 * Explicit S3 origin settings (legacy Origin Access Identity, read timeout).
105 * When set, the origin is treated as an S3 origin regardless of `s3Origin`.
106 */
107 s3OriginConfig?: {
108 originAccessIdentity?: string;
109 originReadTimeout?: Duration.Input;
110 };
111 /**
112 * Optional custom origin settings.
113 */
114 customOriginConfig?: {
115 httpPort?: number;
116 httpsPort?: number;
117 originProtocolPolicy?: cloudfront.OriginProtocolPolicy;
118 originReadTimeout?: Duration.Input;
119 originKeepaliveTimeout?: Duration.Input;
120 originSslProtocols?: cloudfront.SslProtocol[];
121 /**
122 * IP address type CloudFront uses to connect to the origin.
123 */
124 ipAddressType?: cloudfront.IpAddressType;
125 /**
126 * Mutual TLS configuration for the origin connection.
127 */
128 originMtlsConfig?: {
129 clientCertificateArn: string;
130 };
131 };
132 /**
133 * Route this origin through a VPC origin (private ALB/NLB/EC2). Mutually
134 * exclusive with `s3Origin`/`s3OriginConfig`/`customOriginConfig`.
135 */
136 vpcOriginConfig?: {
137 vpcOriginId: Input<string>;
138 originReadTimeout?: Duration.Input;
139 originKeepaliveTimeout?: Duration.Input;
140 ownerAccountId?: string;
141 };
142 /**
143 * Custom headers CloudFront adds to every request it sends to the origin.
144 */
145 customHeaders?: Record<string, string>;
146 /**
147 * Origin Shield configuration.
148 */
149 originShield?: {
150 enabled: boolean;
151 originShieldRegion?: string;
152 };
153 /**
154 * Number of times CloudFront attempts to connect to the origin (1-3).
155 */
156 connectionAttempts?: number;
157 /**
158 * How long CloudFront waits when trying to establish a connection (1-10
159 * seconds), e.g. `"5 seconds"` (a bare number is milliseconds).
160 */
161 connectionTimeout?: Duration.Input;
162 /**
163 * How long CloudFront waits for the origin to deliver a complete response,
164 * e.g. `"30 seconds"` (a bare number is milliseconds).
165 */
166 responseCompletionTimeout?: Duration.Input;
167 }
168
169 export interface DistributionBehavior {
170 /**
171 * ID of the origin (or origin group) this behavior routes requests to.
172 */
173 targetOriginId: string;
174 /**
175 * How viewers may connect (e.g. `redirect-to-https`, `https-only`).
176 */
177 viewerProtocolPolicy?: cloudfront.ViewerProtocolPolicy;
178 /**
179 * HTTP methods CloudFront accepts and forwards to the origin.
180 */
181 allowedMethods?: cloudfront.Method[];
182 /**
183 * HTTP methods whose responses CloudFront caches.
184 */
185 cachedMethods?: cloudfront.Method[];
186 /**
187 * Whether CloudFront automatically compresses eligible responses.
188 */
189 compress?: boolean;
190 /**
191 * Cache policy ID (a managed policy or a `CachePolicy`) controlling the
192 * cache key and TTLs.
193 */
194 cachePolicyId?: string;
195 /**
196 * Origin request policy ID controlling which viewer values CloudFront
197 * forwards to the origin.
198 */
199 originRequestPolicyId?: string;
200 /**
201 * Response headers policy ID applied to viewer responses.
202 */
203 responseHeadersPolicyId?: string;
204 /**
205 * Legacy forwarded-values settings. Prefer `cachePolicyId` /
206 * `originRequestPolicyId` for new configurations.
207 */
208 forwardedValues?: cloudfront.ForwardedValues;
209 /**
210 * Minimum time responses stay cached, e.g. `"1 hour"` (a bare number is
211 * milliseconds). Used with `forwardedValues`.
212 */
213 minTtl?: Duration.Input;
214 /**
215 * Default time responses stay cached when the origin sends no caching
216 * headers.
217 */
218 defaultTtl?: Duration.Input;
219 /**
220 * Maximum time responses stay cached.
221 */
222 maxTtl?: Duration.Input;
223 /**
224 * CloudFront Functions to run on viewer request/response events.
225 */
226 functionAssociations?: {
227 functionArn: string;
228 eventType: cloudfront.EventType;
229 }[];
230 /**
231 * Lambda@Edge functions to run on viewer/origin request/response events.
232 */
233 lambdaFunctionAssociations?: {
234 lambdaFunctionArn: string;
235 eventType: cloudfront.EventType;
236 includeBody?: boolean;
237 }[];
238 /**
239 * CloudFront KeyGroup IDs whose public keys gate signed URLs/cookies.
240 */
241 trustedKeyGroups?: Input<string[]>;
242 /**
243 * Legacy trusted signer AWS account numbers for signed URLs/cookies.
244 */
245 trustedSigners?: string[];
246 /**
247 * Field-level encryption configuration ID.
248 */
249 fieldLevelEncryptionId?: string;
250 /**
251 * ARN of a real-time log configuration to attach.
252 */
253 realtimeLogConfigArn?: string;
254 /**
255 * Whether Microsoft Smooth Streaming is enabled for this behavior.
256 */
257 smoothStreaming?: boolean;
258 /**
259 * gRPC configuration for this behavior.
260 */
261 grpcConfig?: {
262 enabled: boolean;
263 };
264 }
265
266 export interface DistributionViewerCertificate {
267 /**
268 * Serve HTTPS with the default `*.cloudfront.net` certificate (no custom
269 * domains).
270 */
271 cloudFrontDefaultCertificate?: boolean;
272 /**
273 * ARN of an ACM certificate (must live in `us-east-1`) covering the
274 * distribution's aliases.
275 */
276 acmCertificateArn?: string;
277 /**
278 * How CloudFront serves HTTPS to viewers (`sni-only` for modern clients).
279 */
280 sslSupportMethod?: cloudfront.SSLSupportMethod;
281 /**
282 * Minimum TLS protocol version viewers must support.
283 */
284 minimumProtocolVersion?: cloudfront.MinimumProtocolVersion;
285 /**
286 * Legacy IAM certificate ID.
287 */
288 iamCertificateId?: string;
289 /**
290 * Legacy certificate identifier (IAM/ACM raw value).
291 */
292 certificate?: string;
293 /**
294 * Source of the legacy certificate.
295 */
296 certificateSource?: cloudfront.CertificateSource;
297 }
298
299 export interface DistributionGeoRestriction {
300 /**
301 * Restriction mode. `none` disables geo restriction.
302 */
303 restrictionType: cloudfront.GeoRestrictionType;
304 /**
305 * Two-letter ISO 3166-1 country codes the restriction applies to.
306 */
307 locations?: string[];
308 }
309
310 export interface DistributionLogging {
311 /**
312 * Whether access logging is enabled.
313 * @default true
314 */
315 enabled?: boolean;
316 /**
317 * Whether cookies are included in access logs.
318 */
319 includeCookies?: boolean;
320 /**
321 * S3 bucket (domain name) that receives access logs.
322 */
323 bucket?: string;
324 /**
325 * Prefix applied to access log object keys.
326 */
327 prefix?: string;
328 }
329
330 export interface DistributionOriginGroup {
331 /**
332 * Origin group identifier (target it from a cache behavior).
333 */
334 id: string;
335 /**
336 * Member origin IDs in failover order (primary first, secondary second).
337 */
338 members: string[];
339 /**
340 * HTTP status codes that trigger failover to the next member.
341 */
342 failoverStatusCodes: number[];
343 /**
344 * How CloudFront selects the origin within the group.
345 */
346 selectionCriteria?: cloudfront.OriginGroupSelectionCriteria;
347 }
348
349 const isFunctionAssociationPending = (error: cloudfront.InvalidArgument) => {
350 const message = error.message ?? "";
351 return (
352 message.includes("FunctionAssociationArn") && message.includes("not found or is not published")
353 );
354 };
355
356 export interface DistributionProps {
357 /**
358 * Alternate domain names routed to this distribution.
359 */
360 aliases?: string[];
361 /**
362 * Default root object served for `/`.
363 */
364 defaultRootObject?: string;
365 /**
366 * CloudFront origin definitions.
367 */
368 origins: Input<DistributionOrigin[]>;
369 /**
370 * Default cache behavior.
371 */
372 defaultCacheBehavior: Input<DistributionBehavior>;
373 /**
374 * Ordered cache behaviors.
375 */
376 orderedCacheBehaviors?: Input<
377 Array<
378 DistributionBehavior & {
379 pathPattern: string;
380 }
381 >
382 >;
383 /**
384 * Custom error response rules.
385 */
386 customErrorResponses?: Input<cloudfront.CustomErrorResponse[]>;
387 /**
388 * Human-readable distribution comment.
389 * @default ""
390 */
391 comment?: string;
392 /**
393 * Whether the distribution should serve traffic.
394 * @default true
395 */
396 enabled?: boolean;
397 /**
398 * Viewer certificate configuration.
399 */
400 viewerCertificate?: Input<DistributionViewerCertificate>;
401 /**
402 * CloudFront price class.
403 */
404 priceClass?: cloudfront.PriceClass;
405 /**
406 * Optional AWS WAF web ACL association.
407 */
408 webAclId?: string;
409 /**
410 * Preferred HTTP version support.
411 */
412 httpVersion?: cloudfront.HttpVersion;
413 /**
414 * Whether IPv6 should be enabled.
415 * @default true
416 */
417 isIpv6Enabled?: boolean;
418 /**
419 * Geographic distribution restrictions. Defaults to no restriction.
420 */
421 geoRestriction?: DistributionGeoRestriction;
422 /**
423 * Standard access logging configuration.
424 */
425 logging?: DistributionLogging;
426 /**
427 * Origin failover groups. Target a group id from a cache behavior's
428 * `targetOriginId`.
429 */
430 originGroups?: Input<DistributionOriginGroup[]>;
431 /**
432 * Continuous deployment policy ID for blue/green deployments.
433 */
434 continuousDeploymentPolicyId?: string;
435 /**
436 * Whether this is a staging distribution for blue/green deployments.
437 * Create-only — changing it forces a replacement.
438 */
439 staging?: boolean;
440 /**
441 * Anycast static IP list ID to associate with the distribution.
442 */
443 anycastIpListId?: string;
444 /**
445 * User-defined tags to apply to the distribution.
446 */
447 tags?: Record<string, string>;
448 }
449
450 /**
451 * Binding contract of {@link Distribution}: composites contribute additional
452 * alternate domain names without a circular input prop (e.g. a site attached
453 * to an `AWS.Website.Router` binds its hostnames onto the Router's
454 * distribution). Bound aliases are merged with the declared `aliases` prop
455 * at reconcile time; the viewer certificate must cover them.
456 */
457 export type DistributionBinding = {
458 /**
459 * Additional alternate domain names (CNAMEs) attached to the
460 * distribution.
461 */
462 aliases?: string[];
463 };
464
465 /**
466 * Union of declared and bound aliases (see {@link DistributionBinding}),
467 * deduped, preserving declared order first. Tolerates both `{ sid, data }`
468 * rows (provider lifecycle) and bare binding payloads.
469 * @internal
470 */
471 const resolveEffectiveAliases = (
472 declared: string[] | undefined,
473 bindings: ReadonlyArray<DistributionBinding | ResourceBinding<DistributionBinding>> | undefined,
474 ): string[] | undefined => {
475 const bound = (bindings ?? []).flatMap((binding) =>
476 "data" in binding && binding.data !== undefined
477 ? ((binding as ResourceBinding<DistributionBinding>).data.aliases ?? [])
478 : ((binding as DistributionBinding).aliases ?? []),
479 );
480 if (bound.length === 0) {
481 return declared;
482 }
483 return [...new Set([...(declared ?? []), ...bound])];
484 };
485
486 export interface Distribution extends Resource<
487 "AWS.CloudFront.Distribution",
488 DistributionProps,
489 {
490 /**
491 * CloudFront distribution identifier.
492 */
493 distributionId: string;
494 /**
495 * ARN of the distribution.
496 */
497 distributionArn: string;
498 /**
499 * CloudFront-assigned domain name.
500 */
501 domainName: string;
502 /**
503 * The distribution's own URL — what a viewer opens.
504 *
505 * `https://{domainName}` on AWS. Under `alchemy dev` the emulator has no
506 * such hostname to offer (`*.cloudfront.net` resolves to nothing on a
507 * developer's machine), so it serves the distribution's edge on a local
508 * port and this is `http://localhost:{port}`. Reading `url` instead of
509 * building one from {@link domainName} is what makes a consumer work
510 * unchanged in both modes.
511 */
512 url: string;
513 /**
514 * Route 53 hosted zone ID for CloudFront aliases.
515 */
516 hostedZoneId: string;
517 /**
518 * Current deployment status.
519 */
520 status: string;
521 /**
522 * Configured alternate domain names.
523 */
524 aliases: string[];
525 /**
526 * Current comment.
527 */
528 comment: string;
529 /**
530 * Whether the distribution is enabled.
531 */
532 enabled: boolean;
533 /**
534 * Most recent entity tag for update/delete operations.
535 */
536 etag: string | undefined;
537 /**
538 * Number of invalidation batches still in progress.
539 */
540 inProgressInvalidationBatches: number;
541 /**
542 * Last CloudFront modification timestamp.
543 */
544 lastModifiedTime: Date | undefined;
545 /**
546 * Current tags on the distribution.
547 */
548 tags: Record<string, string>;
549 },
550 DistributionBinding,
551 Providers
552 > {}
553
554 const DistributionResource = Resource<Distribution>("AWS.CloudFront.Distribution");
555
556 /** CloudFront's managed `AllViewer` origin request policy: forwards `Host`. */
557 const MANAGED_ALL_VIEWER_ORIGIN_REQUEST_POLICY_ID = "216adef6-5c7f-47e4-b989-5492eafa07d3";
558
559 const ALL_METHODS: cloudfront.Method[] = [
560 "GET",
561 "HEAD",
562 "OPTIONS",
563 "PUT",
564 "PATCH",
565 "POST",
566 "DELETE",
567 ];
568
569 /** A behavior targeting a `webFunction` origin forwards the viewer's `Host`. */
570 export class WebFunctionOriginForwardsHost extends Data.TaggedError(
571 "WebFunctionOriginForwardsHost",
572 )<{ distributionId: string; targetOriginId: string; message: string }> {}
573
574 /**
575 * Behaviors that target a Lambda Web Function origin serve an API, not
576 * static files: unless the behavior says otherwise, don't cache, forward
577 * the whole viewer request except `Host` (Lambda routes on it), and allow
578 * every method. CloudFront's own defaults (cache GETs for a day, drop query
579 * strings, cookies and headers, GET/HEAD only) would break the server.
580 */
581 const apiBehaviorDefaults = <B extends DistributionBehavior>(
582 distributionId: string,
583 webOriginIds: ReadonlySet<string>,
584 behavior: B,
585 ): Effect.Effect<B> => {
586 if (!webOriginIds.has(behavior.targetOriginId)) return Effect.succeed(behavior);
587 if (behavior.originRequestPolicyId === MANAGED_ALL_VIEWER_ORIGIN_REQUEST_POLICY_ID) {
588 return Effect.die(
589 new WebFunctionOriginForwardsHost({
590 distributionId,
591 targetOriginId: behavior.targetOriginId,
592 message: `AWS.CloudFront.Distribution "${distributionId}": the behavior for Lambda Web Function origin "${behavior.targetOriginId}" uses the AllViewer origin request policy, which forwards the viewer's Host header. Lambda routes on Host and would answer 404. Omit originRequestPolicyId to use AllViewerExceptHostHeader.`,
593 }),
594 );
595 }
596 const legacy = behavior.forwardedValues !== undefined;
597 return Effect.succeed({
598 ...behavior,
599 ...(behavior.allowedMethods === undefined
600 ? { allowedMethods: ALL_METHODS, cachedMethods: behavior.cachedMethods ?? ["GET", "HEAD"] }
601 : {}),
602 ...(behavior.cachePolicyId === undefined && !legacy
603 ? { cachePolicyId: MANAGED_CACHING_DISABLED_POLICY_ID }
604 : {}),
605 ...(behavior.originRequestPolicyId === undefined && !legacy
606 ? { originRequestPolicyId: MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_POLICY_ID }
607 : {}),
608 });
609 };
610
611 /**
612 * Compose the children a `webFunction` origin needs: an origin access
613 * control before the distribution, and an invoke grant scoped to the
614 * distribution after it (the grant needs the distribution's ARN, which is
615 * why it is its own resource rather than part of the function).
616 */
617 const withWebFunctionOrigins = (
618 id: string,
619 props: DistributionProps | Effect.Effect<DistributionProps, never, Providers>,
620 ): Effect.Effect<Distribution, never, Providers> =>
621 Effect.gen(function* () {
622 const resolved = Effect.isEffect(props) ? yield* props : props;
623 const origins: unknown = resolved.origins;
624 if (
625 globalThis.__ALCHEMY_RUNTIME__ ||
626 !Array.isArray(origins) ||
627 !origins.some((origin: DistributionOrigin) => origin.webFunction !== undefined)
628 ) {
629 return yield* DistributionResource(id, resolved);
630 }
631 const targets: { originId: string; target: WebFunctionOriginTarget }[] = [];
632 const nextOrigins = yield* Effect.forEach(origins as DistributionOrigin[], (origin) =>
633 Effect.gen(function* () {
634 if (origin.webFunction === undefined) return origin;
635 const target = Effect.isEffect(origin.webFunction)
636 ? yield* origin.webFunction
637 : origin.webFunction;
638 targets.push({ originId: origin.id, target });
639 const access = yield* OriginAccessControl(`${origin.id}OriginAccess`, {
640 description: `Signs requests from ${id} to Lambda Web Function origin ${origin.id}`,
641 originType: "lambda",
642 signingBehavior: "always-amz-auth",
643 signingProtocol: Output.isOutput(target.endpointType)
644 ? Output.map(target.endpointType as Output.Output<string>, signingProtocolFor)
645 : signingProtocolFor(target.endpointType),
646 });
647 const { webFunction: _webFunction, ...rest } = origin;
648 return {
649 ...rest,
650 domainName: target.domainName,
651 originAccessControlId: access.originAccessControlId,
652 customOriginConfig: {
653 originProtocolPolicy: "https-only" as const,
654 ...rest.customOriginConfig,
655 },
656 } satisfies DistributionOrigin;
657 }),
658 ).pipe(Namespace.push(id));
659 const webOriginIds = new Set(targets.map((t) => t.originId));
660 const forWebFunction = <B extends DistributionBehavior>(behavior: B) =>
661 apiBehaviorDefaults(id, webOriginIds, behavior);
662 const defaultCacheBehavior = Output.isOutput(resolved.defaultCacheBehavior)
663 ? resolved.defaultCacheBehavior
664 : yield* forWebFunction(resolved.defaultCacheBehavior as DistributionBehavior);
665 const orderedCacheBehaviors =
666 resolved.orderedCacheBehaviors === undefined ||
667 Output.isOutput(resolved.orderedCacheBehaviors)
668 ? resolved.orderedCacheBehaviors
669 : yield* Effect.forEach(
670 resolved.orderedCacheBehaviors as (DistributionBehavior & { pathPattern: string })[],
671 forWebFunction,
672 );
673 const distribution = yield* DistributionResource(id, {
674 ...resolved,
675 origins: nextOrigins,
676 defaultCacheBehavior,
677 orderedCacheBehaviors,
678 });
679 yield* Effect.forEach(targets, ({ originId, target }) =>
680 WebFunctionPermission(`${originId}Invoke`, {
681 endpoint: target,
682 principal: "cloudfront.amazonaws.com",
683 sourceArn: distribution.distributionArn,
684 }),
685 ).pipe(Namespace.push(id));
686 return distribution;
687 });
688
689 /**
690 * A CloudFront distribution.
691 *
692 * `Distribution` manages the CDN layer for static sites and HTTP origins such
693 * as Lambda Function URLs and ALBs. It exposes the distribution domain and
694 * hosted zone ID needed for Route 53 alias records.
695 * ### Creating Distributions
696 * **Example:** CDN in Front of an HTTP Origin
697 * ```typescript
698 * import * as AWS from "@alchemy.run/aws";
699 *
700 * const distribution = yield* AWS.CloudFront.Distribution("ApiCdn", {
701 * origins: [
702 * {
703 * id: "api",
704 * domainName: "abc123.lambda-url.us-west-2.on.aws",
705 * customOriginConfig: { originProtocolPolicy: "https-only" },
706 * },
707 * ],
708 * defaultCacheBehavior: {
709 * targetOriginId: "api",
710 * viewerProtocolPolicy: "redirect-to-https",
711 * cachePolicyId: AWS.CloudFront.MANAGED_CACHING_DISABLED_POLICY_ID,
712 * originRequestPolicyId:
713 * AWS.CloudFront.MANAGED_ALL_VIEWER_EXCEPT_HOST_HEADER_POLICY_ID,
714 * },
715 * });
716 * ```
717 *
718 * **Example:** Private S3 Origin
719 * ```typescript
720 * const distribution = yield* Distribution("WebsiteCdn", {
721 * aliases: ["www.example.com"],
722 * origins: [
723 * {
724 * id: "site",
725 * domainName: bucket.bucketRegionalDomainName,
726 * s3Origin: true,
727 * originAccessControlId: oac.originAccessControlId,
728 * },
729 * ],
730 * defaultCacheBehavior: {
731 * targetOriginId: "site",
732 * viewerProtocolPolicy: "redirect-to-https",
733 * compress: true,
734 * },
735 * viewerCertificate: {
736 * acmCertificateArn: certificate.certificateArn,
737 * sslSupportMethod: "sni-only",
738 * minimumProtocolVersion: "TLSv1.2_2021",
739 * },
740 * });
741 * ```
742 *
743 * ### Lambda Web Function Origins
744 * Set `webFunction` on an origin to serve an `AWS.Lambda.WebFunction` (or a
745 * `WebFunctionEndpoint`) through CloudFront. Alchemy creates the origin
746 * access control that signs each origin request and grants only this
747 * distribution permission to invoke the endpoint. The endpoint must use
748 * `authType: "IamAuth"`, so requests that skip CloudFront are refused.
749 *
750 * **Example:** CloudFront in front of a Web Function
751 * ```typescript
752 * const api = yield* AWS.Lambda.WebFunction("Api", {
753 * main: "./src/server.ts",
754 * authType: "IamAuth",
755 * });
756 *
757 * const cdn = yield* AWS.CloudFront.Distribution("Cdn", {
758 * origins: [{ id: "api", webFunction: api }],
759 * defaultCacheBehavior: { targetOriginId: "api" },
760 * });
761 * ```
762 *
763 * Behaviors that target the origin don't cache, forward the whole viewer
764 * request except `Host`, and allow every method. Override any of that on
765 * the behavior, e.g. cache static assets under a path:
766 *
767 * **Example:** Cache one path, pass everything else through
768 * ```typescript
769 * const cdn = yield* AWS.CloudFront.Distribution("Cdn", {
770 * origins: [{ id: "api", webFunction: api }],
771 * defaultCacheBehavior: { targetOriginId: "api" },
772 * orderedCacheBehaviors: [
773 * {
774 * pathPattern: "/assets/*",
775 * targetOriginId: "api",
776 * cachePolicyId: AWS.CloudFront.MANAGED_CACHING_OPTIMIZED_POLICY_ID,
777 * },
778 * ],
779 * });
780 * ```
781 *
782 * ### Invalidating the Cache
783 * **Example:** Purge Paths on Deploy
784 * ```typescript
785 * // declaratively, whenever `version` changes:
786 * yield* AWS.CloudFront.Invalidation("PurgeBlog", {
787 * distributionId: distribution.distributionId,
788 * paths: ["/blog/*"],
789 * version: buildId,
790 * });
791 * ```
792 *
793 * To purge at runtime from a Lambda Function, bind
794 * `CloudFront.CreateInvalidation(distribution)` instead.
795 *
796 * @resource
797 */
798 export const Distribution: typeof DistributionResource = Object.assign(
799 (id: string, props: DistributionProps | Effect.Effect<DistributionProps, never, Providers>) =>
800 withWebFunctionOrigins(id, props),
801 DistributionResource,
802 ) as unknown as typeof DistributionResource;
803
804 export const DistributionProvider = () =>
805 Provider.effect(
806 Distribution,
807 Effect.gen(function* () {
808 const waitForDeployment = Effect.fn(function* (distributionId: string) {
809 yield* Effect.logInfo(
810 `CloudFront Distribution wait: polling deployment for ${distributionId}`,
811 );
812 return yield* cloudfront.getDistribution({ Id: distributionId }).pipe(
813 // Bound each poll — a wedged read must count as "not deployed
814 // yet" and retry, never hang the deploy (see the delete-wait).
815 Effect.timeoutOrElse({
816 duration: 30_000,
817 orElse: () =>
818 Effect.fail(
819 new DistributionPendingDeployment({
820 message: `Timed out reading distribution ${distributionId} while polling deployment`,
821 }),
822 ),
823 }),
824 Effect.map((response) => response.Distribution),
825 Effect.flatMap((distribution) =>
826 distribution?.Status === "Deployed"
827 ? Effect.gen(function* () {
828 yield* Effect.logInfo(`CloudFront Distribution wait: ${distributionId} deployed`);
829 return distribution;
830 })
831 : Effect.gen(function* () {
832 yield* Effect.logInfo(
833 `CloudFront Distribution wait: ${distributionId} status=${distribution?.Status ?? "unknown"}`,
834 );
835 return yield* new DistributionPendingDeployment({
836 message: `Distribution ${distributionId} is not yet deployed`,
837 });
838 }),
839 ),
840 Effect.retry({
841 while: (error) => error._tag === "DistributionPendingDeployment",
842 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]),
843 }),
844 );
845 });
846
847 const getCurrent = Effect.fn(function* (distributionId: string) {
848 yield* Effect.logInfo(
849 `CloudFront Distribution read: loading distribution ${distributionId}`,
850 );
851 const distribution = yield* cloudfront.getDistribution({ Id: distributionId }).pipe(
852 Effect.map((response) => response.Distribution),
853 Effect.catchTag("NoSuchDistribution", () => Effect.undefined),
854 );
855
856 if (!distribution?.Id) {
857 yield* Effect.logInfo(
858 `CloudFront Distribution read: distribution ${distributionId} not found`,
859 );
860 return undefined;
861 }
862
863 yield* Effect.logInfo(
864 `CloudFront Distribution read: loading config and tags for ${distributionId}`,
865 );
866 const config = yield* cloudfront.getDistributionConfig({
867 Id: distributionId,
868 });
869 const tags = yield* cloudfront
870 .listTagsForResource({
871 Resource: distribution.ARN,
872 })
873 .pipe(Effect.map((response) => toTagsRecord(response.Tags.Items)));
874
875 yield* Effect.logInfo(
876 `CloudFront Distribution read: loaded ${distributionId} status=${distribution.Status} enabled=${config.DistributionConfig?.Enabled ?? "unknown"} etag=${config.ETag ?? "missing"} tags=${Object.keys(tags).length}`,
877 );
878 return {
879 distribution,
880 config: config.DistributionConfig!,
881 etag: config.ETag,
882 tags,
883 };
884 });
885
886 const getByCallerReference = Effect.fn(function* (callerReference: string) {
887 yield* Effect.logInfo(
888 `CloudFront Distribution read: searching for callerReference=${callerReference}`,
889 );
890 let marker: string | undefined;
891
892 do {
893 const listed = yield* cloudfront.listDistributions({
894 Marker: marker,
895 });
896
897 for (const item of listed.DistributionList?.Items ?? []) {
898 if (!item.Id) continue;
899
900 const config = yield* cloudfront
901 .getDistributionConfig({
902 Id: item.Id,
903 })
904 .pipe(Effect.catchTag("NoSuchDistribution", () => Effect.undefined));
905
906 if (config?.DistributionConfig?.CallerReference === callerReference) {
907 yield* Effect.logInfo(
908 `CloudFront Distribution read: recovered ${item.Id} for callerReference=${callerReference}`,
909 );
910 return yield* getCurrent(item.Id);
911 }
912 }
913
914 marker = listed.DistributionList?.IsTruncated
915 ? listed.DistributionList.NextMarker
916 : undefined;
917 } while (marker);
918
919 yield* Effect.logInfo(
920 `CloudFront Distribution read: no distribution found for callerReference=${callerReference}`,
921 );
922 return undefined;
923 });
924
925 const waitForDeletionReady = Effect.fn(function* (distributionId: string) {
926 class DistributionPendingDeletionReadiness extends Data.TaggedError(
927 "DistributionPendingDeletionReadiness",
928 )<{
929 message: string;
930 }> {}
931
932 yield* Effect.logInfo(
933 `CloudFront Distribution delete: waiting for ${distributionId} to become disabled and deployed`,
934 );
935 return yield* Effect.logInfo(
936 `CloudFront Distribution delete: waiting for ${distributionId} to become disabled and deployed`,
937 ).pipe(
938 // Bound each poll: a single wedged HTTP read (stale keep-alive
939 // socket) otherwise hangs the whole destroy — observed as a
940 // disable-wait that logged one poll and then sat silent past a
941 // 60-minute test budget. Timeout counts as "not ready yet" and
942 // rides the same bounded retry.
943 Effect.andThen(() =>
944 getCurrent(distributionId).pipe(
945 Effect.timeoutOrElse({
946 duration: 30_000,
947 orElse: () =>
948 Effect.fail(
949 new DistributionPendingDeletionReadiness({
950 message: `Timed out reading distribution ${distributionId} while waiting for deletion readiness`,
951 }),
952 ),
953 }),
954 ),
955 ),
956 Effect.flatMap(
957 Effect.fn(function* (current) {
958 if (!current) {
959 yield* Effect.logInfo(
960 `CloudFront Distribution delete: ${distributionId} already absent while waiting`,
961 );
962 return undefined;
963 }
964
965 if (current.config.Enabled || current.distribution.Status !== "Deployed") {
966 yield* Effect.logInfo(
967 `CloudFront Distribution delete: ${distributionId} not ready enabled=${current.config.Enabled} status=${current.distribution.Status}`,
968 );
969 return yield* new DistributionPendingDeletionReadiness({
970 message: `Distribution ${distributionId} is not yet ready for deletion`,
971 });
972 }
973
974 yield* Effect.logInfo(
975 `CloudFront Distribution delete: ${distributionId} ready for delete with etag=${current.etag ?? "missing"}`,
976 );
977 return current;
978 }),
979 ),
980 Effect.retry({
981 while: (error) => error._tag === "DistributionPendingDeletionReadiness",
982 schedule: Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]),
983 }),
984 );
985 });
986
987 return {
988 stables: ["distributionId", "distributionArn", "domainName", "hostedZoneId"],
989 // `Staging` is create-only at the CloudFront API level; toggling it
990 // requires a fresh distribution. Everything else updates in place via
991 // the whole-config `updateDistribution` PUT.
992 diff: Effect.fn(function* ({ olds, news: _news }) {
993 if (!isResolved(_news)) return undefined;
994 const news = _news as DistributionProps;
995 if ((olds?.staging ?? false) !== (news.staging ?? false)) {
996 return { action: "replace" } as const;
997 }
998 }),
999 read: Effect.fn(function* ({ instanceId, output }) {
1000 // Without cached attributes, fall back to the deterministic
1001 // caller reference (= instanceId). A create interrupted during
1002 // its multi-minute deployment wait leaves a `creating` row with
1003 // no attributes; the engine asks `read` to recover it before
1004 // deleting, so returning `undefined` here would drop the row and
1005 // orphan the (already created) distribution.
1006 const current = output?.distributionId
1007 ? yield* getCurrent(output.distributionId)
1008 : yield* getByCallerReference(instanceId);
1009 if (!current) {
1010 return undefined;
1011 }
1012
1013 return toAttrs(
1014 current.distribution,
1015 current.etag,
1016 current.tags,
1017 yield* resolveUrl(current.distribution),
1018 );
1019 }),
1020 // CloudFront is a global service (no region). Enumerate every
1021 // distribution in the account via the paginated `listDistributions`
1022 // op, then resolve each summary to the full `read`-shaped Attributes
1023 // (distribution + config + tags) so callers get a `delete`-ready item.
1024 list: () =>
1025 Effect.gen(function* () {
1026 const summaries = yield* cloudfront.listDistributions.pages({}).pipe(
1027 Stream.runCollect,
1028 Effect.map((chunk) =>
1029 Array.from(chunk).flatMap((page) => page.DistributionList?.Items ?? []),
1030 ),
1031 );
1032
1033 const rows = yield* Effect.forEach(
1034 summaries,
1035 (summary) =>
1036 getCurrent(summary.Id).pipe(
1037 // Hydrating every distribution fires three read calls each
1038 // (getDistribution + getDistributionConfig +
1039 // listTagsForResource). Across a busy account that trips
1040 // CloudFront's low read throttle, so ride it out.
1041 Effect.retry({
1042 while: (error) => error._tag === "ThrottlingException",
1043 // Steady, capped backoff: CloudFront's read throttle
1044 // resets quickly, so a fixed cadence drains far faster
1045 // than an exponential whose tail delay can balloon past
1046 // the test budget on a busy account.
1047 schedule: Schedule.max([
1048 Schedule.spaced("1 second").pipe(Schedule.jittered),
1049 Schedule.recurs(30),
1050 ]),
1051 }),
1052 Effect.flatMap((current) =>
1053 current
1054 ? Effect.map(
1055 resolveUrl(current.distribution),
1056 (url) =>
1057 toAttrs(current.distribution, current.etag, current.tags, url) as
1058 | Distribution["Attributes"]
1059 | undefined,
1060 )
1061 : Effect.undefined,
1062 ),
1063 ),
1064 { concurrency: 10 },
1065 );
1066
1067 return rows.filter((row): row is Distribution["Attributes"] => row !== undefined);
1068 }),
1069 reconcile: Effect.fn(function* ({
1070 id,
1071 instanceId,
1072 news: _news,
1073 output,
1074 session,
1075 bindings,
1076 }) {
1077 // Fold bound aliases (see `DistributionBinding`) into the desired
1078 // props up front so both the create and update paths (`toConfig`)
1079 // attach them uniformly.
1080 const news: typeof _news = {
1081 ..._news,
1082 aliases: resolveEffectiveAliases(_news.aliases, bindings),
1083 };
1084 const desiredTags = {
1085 ...(yield* createInternalTags(id)),
1086 ...news.tags,
1087 };
1088 const callerReference = instanceId;
1089
1090 // Observe — locate an existing distribution by id (cached on
1091 // `output`) or by caller reference, which lets us recover from a
1092 // create that succeeded in the cloud but failed to persist its
1093 // attributes locally.
1094 let observed = output?.distributionId
1095 ? yield* getCurrent(output.distributionId)
1096 : undefined;
1097 if (!observed) {
1098 observed = yield* getByCallerReference(callerReference);
1099 }
1100
1101 // Ensure — create the distribution if it's missing. Tolerate
1102 // `DistributionAlreadyExists` (race with a peer reconciler) by
1103 // re-reading via caller reference. Tags are applied at create
1104 // time when permissions allow; otherwise we fall back to
1105 // create-then-tag and the sync path below converges them.
1106 if (!observed) {
1107 const config = toConfig(callerReference, news);
1108 yield* Effect.logInfo(
1109 `CloudFront Distribution reconcile: callerReference=${callerReference} aliases=${news.aliases?.length ?? 0} origins=${(news.origins as DistributionOrigin[]).length} tags=${Object.keys(desiredTags).length}`,
1110 );
1111 const created = yield* cloudfront
1112 .createDistributionWithTags({
1113 DistributionConfigWithTags: {
1114 DistributionConfig: config,
1115 Tags: {
1116 Items: createTagsList(desiredTags),
1117 },
1118 },
1119 })
1120 .pipe(
1121 Effect.catch((error) =>
1122 isAccessDenied(error)
1123 ? Effect.gen(function* () {
1124 yield* Effect.logInfo(
1125 `CloudFront Distribution reconcile: createDistributionWithTags denied, retrying without tags for callerReference=${callerReference}`,
1126 );
1127 const created = yield* cloudfront.createDistribution({
1128 DistributionConfig: config,
1129 });
1130 if (created.Distribution?.ARN && Object.keys(desiredTags).length > 0) {
1131 yield* Effect.logInfo(
1132 `CloudFront Distribution reconcile: tagging distribution ${created.Distribution.Id} after fallback`,
1133 );
1134 yield* cloudfront.tagResource({
1135 Resource: created.Distribution.ARN,
1136 Tags: {
1137 Items: createTagsList(desiredTags),
1138 },
1139 });
1140 }
1141 return created;
1142 })
1143 : Effect.gen(function* () {
1144 yield* Effect.logInfo(
1145 `CloudFront Distribution reconcile: createDistributionWithTags failed for callerReference=${callerReference} error=${String(error)}`,
1146 );
1147 return yield* error;
1148 }),
1149 ),
1150 Effect.map((created) => ({
1151 distributionId: created.Distribution?.Id,
1152 etag: created.ETag,
1153 tags: desiredTags,
1154 })),
1155 Effect.catchTags({
1156 DistributionAlreadyExists: () =>
1157 Effect.gen(function* () {
1158 yield* Effect.logInfo(
1159 `CloudFront Distribution reconcile: callerReference=${callerReference} already exists, attempting recovery`,
1160 );
1161 const recovered = yield* getByCallerReference(callerReference);
1162 if (!recovered?.distribution.Id) {
1163 return yield* new DistributionConflict({
1164 message: `CloudFront distribution with caller reference '${callerReference}' already exists but could not be recovered`,
1165 });
1166 }
1167 return {
1168 distributionId: recovered.distribution.Id,
1169 etag: recovered.etag,
1170 tags: recovered.tags,
1171 };
1172 }),
1173 InvalidArgument: (
1174 error,
1175 ): Effect.Effect<
1176 never,
1177 cloudfront.InvalidArgument | DistributionFunctionAssociationPending
1178 > =>
1179 isFunctionAssociationPending(error)
1180 ? Effect.logInfo(
1181 "CloudFront Distribution reconcile: function association not yet ready, retrying",
1182 ).pipe(
1183 Effect.andThen(
1184 Effect.fail(
1185 new DistributionFunctionAssociationPending({
1186 message: error.message ?? "CloudFront function association pending",
1187 }),
1188 ),
1189 ),
1190 )
1191 : Effect.fail(error),
1192 }),
1193 Effect.retry({
1194 while: (error) => error instanceof DistributionFunctionAssociationPending,
1195 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(24)]),
1196 }),
1197 );
1198
1199 if (!created.distributionId) {
1200 return yield* new DistributionUnexpectedResponse({
1201 message: "createDistribution returned no distribution",
1202 });
1203 }
1204
1205 yield* Effect.logInfo(
1206 `CloudFront Distribution reconcile: created ${created.distributionId} etag=${created.etag ?? "missing"}, waiting for deployment`,
1207 );
1208 const deployed = yield* waitForDeployment(created.distributionId);
1209 yield* Effect.logInfo(
1210 `CloudFront Distribution reconcile: deployed ${created.distributionId} domain=${deployed.DomainName}`,
1211 );
1212 yield* session.note(created.distributionId);
1213 return toAttrs(deployed, created.etag, created.tags, yield* resolveUrl(deployed));
1214 }
1215
1216 // Sync config — diff observed config against desired and patch
1217 // via `updateDistribution` with the freshly observed ETag. We
1218 // keep the observed `CallerReference` because CloudFront does
1219 // not allow it to change, and fill every member the props don't
1220 // express from the observed config: UpdateDistribution replaces
1221 // the whole config and rejects requests with missing members
1222 // (see `mergeWithObservedConfig`).
1223 yield* Effect.logInfo(
1224 `CloudFront Distribution reconcile: updating config for ${observed.distribution.Id} with etag=${observed.etag ?? "missing"}`,
1225 );
1226 const updated = yield* cloudfront
1227 .updateDistribution({
1228 Id: observed.distribution.Id,
1229 IfMatch: observed.etag,
1230 DistributionConfig: mergeWithObservedConfig(
1231 toConfig(observed.config.CallerReference, news),
1232 observed.config,
1233 ),
1234 })
1235 .pipe(
1236 Effect.catchTag(
1237 "InvalidArgument",
1238 (
1239 error,
1240 ): Effect.Effect<
1241 never,
1242 cloudfront.InvalidArgument | DistributionFunctionAssociationPending
1243 > =>
1244 isFunctionAssociationPending(error)
1245 ? Effect.logInfo(
1246 "CloudFront Distribution reconcile: function association not yet ready, retrying",
1247 ).pipe(
1248 Effect.andThen(
1249 Effect.fail(
1250 new DistributionFunctionAssociationPending({
1251 message: error.message ?? "CloudFront function association pending",
1252 }),
1253 ),
1254 ),
1255 )
1256 : Effect.fail(error),
1257 ),
1258 Effect.retry({
1259 while: (error) => error instanceof DistributionFunctionAssociationPending,
1260 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(24)]),
1261 }),
1262 );
1263
1264 if (!updated.Distribution?.Id) {
1265 return yield* new DistributionUnexpectedResponse({
1266 message: "updateDistribution returned no distribution",
1267 });
1268 }
1269
1270 // Sync tags — diff observed cloud tags against desired and apply
1271 // only the delta. `observed.tags` is fetched fresh, so we don't
1272 // rely on stale `olds.tags`.
1273 const { removed, upsert } = diffTags(observed.tags, desiredTags);
1274 yield* Effect.logInfo(
1275 `CloudFront Distribution reconcile: distribution=${observed.distribution.Id} upsertTags=${upsert.length} removedTags=${removed.length}`,
1276 );
1277
1278 if (upsert.length > 0) {
1279 yield* Effect.logInfo(
1280 `CloudFront Distribution reconcile: tagging ${observed.distribution.Id} with ${upsert.length} tag(s)`,
1281 );
1282 yield* cloudfront.tagResource({
1283 Resource: observed.distribution.ARN,
1284 Tags: {
1285 Items: upsert,
1286 },
1287 });
1288 }
1289
1290 if (removed.length > 0) {
1291 yield* Effect.logInfo(
1292 `CloudFront Distribution reconcile: removing ${removed.length} tag(s) from ${observed.distribution.Id}`,
1293 );
1294 yield* cloudfront.untagResource({
1295 Resource: observed.distribution.ARN,
1296 TagKeys: {
1297 Items: removed,
1298 },
1299 });
1300 }
1301
1302 yield* Effect.logInfo(
1303 `CloudFront Distribution reconcile: updated ${observed.distribution.Id} etag=${updated.ETag ?? "missing"}, waiting for deployment`,
1304 );
1305 const deployed = yield* waitForDeployment(updated.Distribution.Id);
1306 yield* Effect.logInfo(
1307 `CloudFront Distribution reconcile: deployed ${observed.distribution.Id} domain=${deployed.DomainName}`,
1308 );
1309 yield* session.note(observed.distribution.Id);
1310 return toAttrs(deployed, updated.ETag, desiredTags, yield* resolveUrl(deployed));
1311 }),
1312 delete: Effect.fn(function* ({ output }) {
1313 yield* Effect.logInfo(
1314 `CloudFront Distribution delete: distribution=${output.distributionId}`,
1315 );
1316 const current = yield* getCurrent(output.distributionId);
1317 if (!current) {
1318 yield* Effect.logInfo(
1319 `CloudFront Distribution delete: ${output.distributionId} already absent`,
1320 );
1321 return;
1322 }
1323
1324 if (current.config.Enabled) {
1325 yield* Effect.logInfo(
1326 `CloudFront Distribution delete: disabling ${output.distributionId} before delete`,
1327 );
1328 yield* cloudfront.updateDistribution({
1329 Id: output.distributionId,
1330 IfMatch: current.etag,
1331 DistributionConfig: {
1332 ...current.config,
1333 Enabled: false,
1334 },
1335 });
1336 }
1337
1338 const latest = yield* waitForDeletionReady(output.distributionId);
1339 if (!latest) {
1340 yield* Effect.logInfo(
1341 `CloudFront Distribution delete: ${output.distributionId} disappeared before delete`,
1342 );
1343 return;
1344 }
1345
1346 yield* Effect.logInfo(
1347 `CloudFront Distribution delete: deleting ${output.distributionId} with etag=${latest.etag ?? "missing"}`,
1348 );
1349 yield* cloudfront
1350 .deleteDistribution({
1351 Id: output.distributionId,
1352 IfMatch: latest.etag,
1353 })
1354 .pipe(Effect.catchTag("NoSuchDistribution", () => Effect.void));
1355 }),
1356 };
1357 }),
1358 );
1359
1360 const toTagsRecord = (tags: cloudfront.Tag[] | undefined) =>
1361 Object.fromEntries(
1362 (tags ?? [])
1363 .filter(
1364 (tag): tag is { Key: string; Value: string } =>
1365 typeof tag.Key === "string" && typeof tag.Value === "string",
1366 )
1367 .map((tag) => [tag.Key, tag.Value]),
1368 );
1369
1370 const isAccessDenied = (error: unknown) => {
1371 const tag = (error as { _tag?: string; name?: string })?._tag;
1372 const name = (error as { _tag?: string; name?: string })?.name;
1373 const text = String(error);
1374 return (
1375 tag === "AccessDenied" ||
1376 tag === "AccessDeniedException" ||
1377 name === "AccessDenied" ||
1378 name === "AccessDeniedException" ||
1379 text.includes("AccessDenied")
1380 );
1381 };
1382
1383 const toBehavior = (
1384 behavior: DistributionBehavior & {
1385 pathPattern?: string;
1386 },
1387 ): cloudfront.CacheBehavior | cloudfront.DefaultCacheBehavior => ({
1388 ...(behavior.pathPattern ? { PathPattern: behavior.pathPattern } : undefined),
1389 TargetOriginId: behavior.targetOriginId,
1390 ViewerProtocolPolicy: behavior.viewerProtocolPolicy ?? "redirect-to-https",
1391 AllowedMethods: behavior.allowedMethods
1392 ? {
1393 Quantity: behavior.allowedMethods.length,
1394 Items: behavior.allowedMethods,
1395 CachedMethods: behavior.cachedMethods
1396 ? {
1397 Quantity: behavior.cachedMethods.length,
1398 Items: behavior.cachedMethods,
1399 }
1400 : undefined,
1401 }
1402 : undefined,
1403 Compress: behavior.compress ?? true,
1404 CachePolicyId: behavior.cachePolicyId,
1405 OriginRequestPolicyId: behavior.originRequestPolicyId,
1406 ResponseHeadersPolicyId: behavior.responseHeadersPolicyId,
1407 // Without a cache policy, CloudFront is in legacy mode and rejects the
1408 // request unless both ForwardedValues and MinTTL are present.
1409 ForwardedValues:
1410 behavior.forwardedValues ??
1411 (behavior.cachePolicyId === undefined
1412 ? { QueryString: false, Cookies: { Forward: "none" } }
1413 : undefined),
1414 MinTTL: toWireSeconds(behavior.minTtl) ?? (behavior.cachePolicyId === undefined ? 0 : undefined),
1415 DefaultTTL: toWireSeconds(behavior.defaultTtl),
1416 MaxTTL: toWireSeconds(behavior.maxTtl),
1417 TrustedKeyGroups: behavior.trustedKeyGroups
1418 ? {
1419 Enabled: (behavior.trustedKeyGroups as string[]).length > 0,
1420 Quantity: (behavior.trustedKeyGroups as string[]).length,
1421 Items: behavior.trustedKeyGroups as string[],
1422 }
1423 : undefined,
1424 TrustedSigners: behavior.trustedSigners
1425 ? {
1426 Enabled: behavior.trustedSigners.length > 0,
1427 Quantity: behavior.trustedSigners.length,
1428 Items: behavior.trustedSigners,
1429 }
1430 : undefined,
1431 FieldLevelEncryptionId: behavior.fieldLevelEncryptionId,
1432 RealtimeLogConfigArn: behavior.realtimeLogConfigArn,
1433 SmoothStreaming: behavior.smoothStreaming,
1434 GrpcConfig: behavior.grpcConfig ? { Enabled: behavior.grpcConfig.enabled } : undefined,
1435 FunctionAssociations: behavior.functionAssociations
1436 ? {
1437 Quantity: behavior.functionAssociations.length,
1438 Items: behavior.functionAssociations.map((association) => ({
1439 FunctionARN: association.functionArn,
1440 EventType: association.eventType,
1441 })),
1442 }
1443 : undefined,
1444 LambdaFunctionAssociations: behavior.lambdaFunctionAssociations
1445 ? {
1446 Quantity: behavior.lambdaFunctionAssociations.length,
1447 Items: behavior.lambdaFunctionAssociations.map((association) => ({
1448 LambdaFunctionARN: association.lambdaFunctionArn,
1449 EventType: association.eventType,
1450 IncludeBody: association.includeBody,
1451 })),
1452 }
1453 : undefined,
1454 });
1455
1456 const toOrigin = (origin: DistributionOrigin): cloudfront.Origin => {
1457 // Exactly one of the three origin-config shapes may be set. A VPC origin
1458 // wins, then an explicit/legacy S3 origin, otherwise a custom origin.
1459 const isVpcOrigin = origin.vpcOriginConfig !== undefined;
1460 const isS3Origin =
1461 !isVpcOrigin && (origin.s3Origin === true || origin.s3OriginConfig !== undefined);
1462
1463 return {
1464 Id: origin.id,
1465 DomainName: origin.domainName as string,
1466 OriginPath: origin.originPath as string | undefined,
1467 OriginAccessControlId: origin.originAccessControlId as string | undefined,
1468 CustomHeaders: origin.customHeaders
1469 ? {
1470 Quantity: Object.keys(origin.customHeaders).length,
1471 Items: Object.entries(origin.customHeaders).map(([name, value]) => ({
1472 HeaderName: name,
1473 HeaderValue: value,
1474 })),
1475 }
1476 : undefined,
1477 OriginShield: origin.originShield
1478 ? {
1479 Enabled: origin.originShield.enabled,
1480 OriginShieldRegion: origin.originShield.originShieldRegion,
1481 }
1482 : undefined,
1483 ConnectionAttempts: origin.connectionAttempts,
1484 ConnectionTimeout: toWireSeconds(origin.connectionTimeout),
1485 ResponseCompletionTimeout: toWireSeconds(origin.responseCompletionTimeout),
1486 VpcOriginConfig: isVpcOrigin
1487 ? {
1488 VpcOriginId: origin.vpcOriginConfig!.vpcOriginId as string,
1489 OwnerAccountId: origin.vpcOriginConfig!.ownerAccountId,
1490 OriginReadTimeout: toWireSeconds(origin.vpcOriginConfig!.originReadTimeout),
1491 OriginKeepaliveTimeout: toWireSeconds(origin.vpcOriginConfig!.originKeepaliveTimeout),
1492 }
1493 : undefined,
1494 S3OriginConfig: isS3Origin
1495 ? {
1496 OriginAccessIdentity: origin.s3OriginConfig?.originAccessIdentity ?? "",
1497 OriginReadTimeout: toWireSeconds(origin.s3OriginConfig?.originReadTimeout),
1498 }
1499 : undefined,
1500 CustomOriginConfig:
1501 isVpcOrigin || isS3Origin
1502 ? undefined
1503 : {
1504 HTTPPort: origin.customOriginConfig?.httpPort ?? 80,
1505 HTTPSPort: origin.customOriginConfig?.httpsPort ?? 443,
1506 OriginProtocolPolicy: origin.customOriginConfig?.originProtocolPolicy ?? "https-only",
1507 OriginSslProtocols: {
1508 Quantity: (origin.customOriginConfig?.originSslProtocols ?? ["TLSv1.2"]).length,
1509 Items: origin.customOriginConfig?.originSslProtocols ?? ["TLSv1.2"],
1510 },
1511 OriginReadTimeout: toWireSeconds(origin.customOriginConfig?.originReadTimeout),
1512 OriginKeepaliveTimeout: toWireSeconds(
1513 origin.customOriginConfig?.originKeepaliveTimeout,
1514 ),
1515 IpAddressType: origin.customOriginConfig?.ipAddressType,
1516 OriginMtlsConfig: origin.customOriginConfig?.originMtlsConfig
1517 ? {
1518 ClientCertificateArn:
1519 origin.customOriginConfig.originMtlsConfig.clientCertificateArn,
1520 }
1521 : undefined,
1522 },
1523 };
1524 };
1525
1526 /**
1527 * Recursively fills `undefined` members of `desired` from `observed`.
1528 * Defined values in `desired` always win; arrays are taken from `desired`
1529 * wholesale (item-level merging is the caller's concern).
1530 */
1531 const fillUndefined = <T>(desired: T, observed: T): T => {
1532 if (desired === undefined) return observed;
1533 if (
1534 desired === null ||
1535 typeof desired !== "object" ||
1536 Array.isArray(desired) ||
1537 observed === null ||
1538 typeof observed !== "object" ||
1539 Array.isArray(observed)
1540 ) {
1541 return desired;
1542 }
1543 const out: Record<string, unknown> = {
1544 ...(desired as Record<string, unknown>),
1545 };
1546 const desiredObj = desired as Record<string, unknown>;
1547 for (const key of Object.keys(observed as Record<string, unknown>)) {
1548 // CloudFront list shapes pair `Quantity` with `Items`. A desired node
1549 // that declares a `Quantity` but no `Items` (e.g. a geo restriction of
1550 // `{ RestrictionType: "none", Quantity: 0 }`) is fully specified —
1551 // filling `Items` from the observed config would desynchronize the two
1552 // and CloudFront rejects the update with `InconsistentQuantities`.
1553 if (
1554 key === "Items" &&
1555 typeof desiredObj.Quantity === "number" &&
1556 desiredObj.Items === undefined
1557 ) {
1558 continue;
1559 }
1560 out[key] = fillUndefined(desiredObj[key], (observed as Record<string, unknown>)[key]);
1561 }
1562 return out as T;
1563 };
1564
1565 /**
1566 * Completes a desired `DistributionConfig` with the freshly observed live
1567 * config before an `updateDistribution` call.
1568 *
1569 * CloudFront's `UpdateDistribution` replaces the ENTIRE distribution config:
1570 * any member missing from the request is rejected with `IllegalUpdate`
1571 * (observed in practice: "Default root object is missing for the resource",
1572 * "The 'OriginCustomHeaders' field is missing"). `toConfig` emits only the
1573 * members the props express, so updating a live distribution fails on every
1574 * member the props don't model — some of which (e.g. per-origin
1575 * `CustomHeaders`, per-behavior `TrustedSigners`) are nested inside
1576 * collections and not expressible as props at all.
1577 *
1578 * The standard CloudFront update pattern is read-modify-write, which the
1579 * delete path here already uses (`{ ...current.config, Enabled: false }`).
1580 * This applies the same idea to updates: desired values always win — the
1581 * declared props still fully control drift — and only `undefined` members
1582 * are carried over from the observed config. `Origins` and `CacheBehaviors`
1583 * items are additionally merged by identity (`Id` / `PathPattern`) so their
1584 * nested unexpressed members carry over too.
1585 *
1586 * Exported for unit tests.
1587 */
1588 const originKind = (origin: cloudfront.Origin) =>
1589 origin.VpcOriginConfig ? "vpc" : origin.S3OriginConfig ? "s3" : "custom";
1590
1591 export const mergeWithObservedConfig = (
1592 desired: cloudfront.DistributionConfig,
1593 observed: cloudfront.DistributionConfig,
1594 ): cloudfront.DistributionConfig => {
1595 const merged = fillUndefined(desired, observed);
1596 if (merged.Origins?.Items && observed.Origins?.Items) {
1597 const observedOrigins = observed.Origins.Items;
1598 merged.Origins = {
1599 ...merged.Origins,
1600 Items: merged.Origins.Items.map((item) => {
1601 const current = observedOrigins.find((origin) => origin.Id === item.Id) ?? item;
1602 if (originKind(current) === originKind(item)) return fillUndefined(item, current);
1603 // An origin that changes kind (custom <-> S3 <-> VPC) under the same
1604 // id must not inherit the old kind's config or access control:
1605 // CloudFront rejects an origin carrying both.
1606 const {
1607 S3OriginConfig: _s3,
1608 CustomOriginConfig: _custom,
1609 VpcOriginConfig: _vpc,
1610 OriginAccessControlId: _oac,
1611 ...shared
1612 } = current;
1613 return fillUndefined(item, shared as cloudfront.Origin);
1614 }),
1615 };
1616 }
1617 if (merged.CacheBehaviors?.Items && observed.CacheBehaviors?.Items) {
1618 const observedBehaviors = observed.CacheBehaviors.Items;
1619 merged.CacheBehaviors = {
1620 ...merged.CacheBehaviors,
1621 Items: merged.CacheBehaviors.Items.map((item) =>
1622 fillUndefined(
1623 item,
1624 observedBehaviors.find((behavior) => behavior.PathPattern === item.PathPattern) ?? item,
1625 ),
1626 ),
1627 };
1628 }
1629 return merged;
1630 };
1631
1632 const toConfig = (
1633 callerReference: string,
1634 props: DistributionProps,
1635 ): cloudfront.DistributionConfig => ({
1636 CallerReference: callerReference,
1637 Aliases: props.aliases
1638 ? {
1639 Quantity: props.aliases.length,
1640 Items: props.aliases,
1641 }
1642 : undefined,
1643 DefaultRootObject: props.defaultRootObject,
1644 Origins: {
1645 Quantity: (props.origins as DistributionOrigin[]).length,
1646 Items: (props.origins as DistributionOrigin[]).map(toOrigin),
1647 },
1648 DefaultCacheBehavior: toBehavior(
1649 props.defaultCacheBehavior as DistributionBehavior,
1650 ) as cloudfront.DefaultCacheBehavior,
1651 CacheBehaviors: props.orderedCacheBehaviors
1652 ? {
1653 Quantity: (
1654 props.orderedCacheBehaviors as Array<DistributionBehavior & { pathPattern: string }>
1655 ).length,
1656 Items: (
1657 props.orderedCacheBehaviors as Array<DistributionBehavior & { pathPattern: string }>
1658 ).map((behavior) =>
1659 toBehavior(behavior as DistributionBehavior & { pathPattern: string }),
1660 ) as cloudfront.CacheBehavior[],
1661 }
1662 : undefined,
1663 OriginGroups: props.originGroups
1664 ? {
1665 Quantity: (props.originGroups as DistributionOriginGroup[]).length,
1666 Items: (props.originGroups as DistributionOriginGroup[]).map((group) => ({
1667 Id: group.id,
1668 FailoverCriteria: {
1669 StatusCodes: {
1670 Quantity: group.failoverStatusCodes.length,
1671 Items: group.failoverStatusCodes,
1672 },
1673 },
1674 Members: {
1675 Quantity: group.members.length,
1676 Items: group.members.map((originId) => ({ OriginId: originId })),
1677 },
1678 SelectionCriteria: group.selectionCriteria,
1679 })),
1680 }
1681 : undefined,
1682 CustomErrorResponses: props.customErrorResponses
1683 ? {
1684 Quantity: (props.customErrorResponses as cloudfront.CustomErrorResponse[]).length,
1685 Items: props.customErrorResponses as cloudfront.CustomErrorResponse[],
1686 }
1687 : undefined,
1688 Comment: props.comment ?? "",
1689 Logging: props.logging
1690 ? {
1691 Enabled: props.logging.enabled ?? true,
1692 IncludeCookies: props.logging.includeCookies ?? false,
1693 Bucket: props.logging.bucket ?? "",
1694 Prefix: props.logging.prefix ?? "",
1695 }
1696 : undefined,
1697 Enabled: props.enabled ?? true,
1698 ViewerCertificate: props.viewerCertificate
1699 ? {
1700 CloudFrontDefaultCertificate: (props.viewerCertificate as DistributionViewerCertificate)
1701 .cloudFrontDefaultCertificate,
1702 IAMCertificateId: (props.viewerCertificate as DistributionViewerCertificate)
1703 .iamCertificateId,
1704 ACMCertificateArn: (props.viewerCertificate as DistributionViewerCertificate)
1705 .acmCertificateArn,
1706 SSLSupportMethod: (props.viewerCertificate as DistributionViewerCertificate)
1707 .sslSupportMethod,
1708 MinimumProtocolVersion: (props.viewerCertificate as DistributionViewerCertificate)
1709 .minimumProtocolVersion,
1710 Certificate: (props.viewerCertificate as DistributionViewerCertificate).certificate,
1711 CertificateSource: (props.viewerCertificate as DistributionViewerCertificate)
1712 .certificateSource,
1713 }
1714 : props.aliases && props.aliases.length > 0
1715 ? undefined
1716 : {
1717 CloudFrontDefaultCertificate: true,
1718 },
1719 Restrictions: props.geoRestriction
1720 ? {
1721 GeoRestriction: {
1722 RestrictionType: props.geoRestriction.restrictionType,
1723 Quantity: props.geoRestriction.locations?.length ?? 0,
1724 Items: props.geoRestriction.locations,
1725 },
1726 }
1727 : {
1728 GeoRestriction: {
1729 RestrictionType: "none",
1730 Quantity: 0,
1731 },
1732 },
1733 PriceClass: props.priceClass,
1734 WebACLId: props.webAclId,
1735 HttpVersion: props.httpVersion ?? "http2",
1736 IsIPV6Enabled: props.isIpv6Enabled ?? true,
1737 ContinuousDeploymentPolicyId: props.continuousDeploymentPolicyId,
1738 Staging: props.staging,
1739 AnycastIpListId: props.anycastIpListId,
1740 });
1741
1742 /**
1743 * The distribution's own URL.
1744 *
1745 * On AWS this is `https://` + the CloudFront domain name. The local emulator
1746 * has no such hostname — `*.cloudfront.net` resolves to nothing on a
1747 * developer's machine — so it serves each distribution's edge on a plain-HTTP
1748 * port of its own and reports which one. Asking it here (rather than having
1749 * every consumer interpolate a URL from `domainName`) is what keeps `url`
1750 * openable in both modes. Anything unexpected falls back to the AWS-shaped
1751 * URL: a missing edge port must never fail a reconcile.
1752 */
1753 const resolveUrl = Effect.fn("AWS.CloudFront.Distribution.url")(function* (
1754 distribution: cloudfront.Distribution,
1755 ) {
1756 const awsUrl = `https://${distribution.DomainName}`;
1757 const env = yield* AWSEnvironment.current;
1758 const endpoint = env.endpoint;
1759 if (endpoint === undefined || !(yield* AWSEnvironment.isLocalEmulator)) {
1760 return awsUrl;
1761 }
1762 return yield* Effect.gen(function* () {
1763 const client = yield* HttpClient.HttpClient;
1764 const response = yield* client.get(`${endpoint}/_floci/cloudfront-edge/${distribution.Id}`);
1765 // A distribution legitimately has no edge port: the emulator binds one
1766 // opportunistically and stays Host-addressable when it can't, and the
1767 // endpoint 404s (with a JSON error body) for one it doesn't know yet.
1768 // `client.get` does not fail on 404, so every shape lands here — `null`,
1769 // an error object, or a port-less entry. Anything that isn't a numeric
1770 // `Port` means "no local edge", which is the AWS URL.
1771 const edge = (yield* response.json) as { Port?: number } | null;
1772 if (edge === null || typeof edge !== "object" || typeof edge.Port !== "number") {
1773 return awsUrl;
1774 }
1775 const host = yield* Effect.sync(() => new URL(endpoint).hostname);
1776 return `http://${host}:${edge.Port}`;
1777 }).pipe(
1778 Effect.timeout("10 seconds"),
1779 Effect.provide(FetchHttpClient.layer),
1780 // `orElseSucceed` alone only covers the error channel. A malformed body
1781 // throws inside the generator, which Effect surfaces as a DEFECT — that
1782 // escaped the fallback and killed a reconcile with a raw TypeError.
1783 // Resolving a convenience URL must never be able to fail a deploy.
1784 Effect.catchCause(() => Effect.succeed(awsUrl)),
1785 );
1786 });
1787
1788 const toAttrs = (
1789 distribution: cloudfront.Distribution,
1790 etag: string | undefined,
1791 tags: Record<string, string>,
1792 url: string,
1793 ): Distribution["Attributes"] => ({
1794 distributionId: distribution.Id,
1795 distributionArn: distribution.ARN,
1796 domainName: distribution.DomainName,
1797 url,
1798 hostedZoneId: CLOUDFRONT_HOSTED_ZONE_ID,
1799 status: distribution.Status,
1800 aliases: distribution.DistributionConfig.Aliases?.Items ?? [],
1801 comment:
1802 typeof distribution.DistributionConfig.Comment === "string"
1803 ? distribution.DistributionConfig.Comment
1804 : "",
1805 enabled: distribution.DistributionConfig.Enabled,
1806 etag,
1807 inProgressInvalidationBatches: distribution.InProgressInvalidationBatches,
1808 lastModifiedTime: distribution.LastModifiedTime,
1809 tags,
1810 });