@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 227 lines 8.01 KB
Raw
1 import * as cloudfront from "@distilled.cloud/aws/cloudfront";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import type { Providers } from "../Providers.ts";
9
10 export class InvalidationUnexpectedResponse extends Data.TaggedError(
11 "InvalidationUnexpectedResponse",
12 )<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export interface InvalidationProps {
18 /**
19 * Distribution to invalidate.
20 */
21 distributionId: string;
22 /**
23 * Version string used as the invalidation caller reference. Change this value
24 * to trigger a new invalidation.
25 */
26 version: string;
27 /**
28 * Paths to invalidate.
29 * @default ["/*"]
30 */
31 paths?: string[];
32 /**
33 * Wait for the invalidation to complete.
34 * @default false
35 */
36 wait?: boolean;
37 }
38
39 export interface Invalidation extends Resource<
40 "AWS.CloudFront.Invalidation",
41 InvalidationProps,
42 {
43 /**
44 * The identifier of the invalidation batch.
45 */
46 invalidationId: string;
47 /**
48 * The distribution the invalidation ran against.
49 */
50 distributionId: string;
51 /**
52 * The version prop that triggered this invalidation batch.
53 */
54 version: string;
55 /**
56 * Current status of the invalidation (`InProgress` or `Completed`).
57 */
58 status: string;
59 /**
60 * The path patterns that were invalidated.
61 */
62 paths: string[];
63 /**
64 * When the invalidation batch was created.
65 */
66 createTime: Date | undefined;
67 },
68 never,
69 Providers
70 > {}
71
72 /**
73 * A CloudFront cache invalidation request.
74 *
75 * `Invalidation` is a helper resource for website deployments that need to
76 * clear selected CloudFront cache paths after asset updates.
77 * ### Creating Invalidations
78 * **Example:** Invalidate The Entire Distribution
79 * ```typescript
80 * const invalidation = yield* Invalidation("WebsiteInvalidation", {
81 * distributionId: distribution.distributionId,
82 * version: files.version,
83 * });
84 * ```
85 *
86 * @resource
87 */
88 export const Invalidation = Resource<Invalidation>("AWS.CloudFront.Invalidation");
89
90 const defaultPaths = ["/*"];
91
92 class InvalidationInProgress extends Data.TaggedError("InvalidationInProgress")<{
93 message: string;
94 }> {}
95
96 export const InvalidationProvider = () =>
97 Provider.effect(
98 Invalidation,
99 Effect.gen(function* () {
100 const waitForCompletion = Effect.fn(function* (
101 distributionId: string,
102 invalidationId: string,
103 ) {
104 yield* Effect.logInfo(
105 `CloudFront Invalidation wait: polling ${invalidationId} for distribution ${distributionId}`,
106 );
107 return yield* cloudfront
108 .getInvalidation({
109 DistributionId: distributionId,
110 Id: invalidationId,
111 })
112 .pipe(
113 Effect.map((response) => response.Invalidation),
114 Effect.flatMap((invalidation) =>
115 invalidation?.Status === "Completed"
116 ? Effect.gen(function* () {
117 yield* Effect.logInfo(
118 `CloudFront Invalidation wait: ${invalidationId} completed`,
119 );
120 return invalidation;
121 })
122 : Effect.gen(function* () {
123 yield* Effect.logInfo(
124 `CloudFront Invalidation wait: ${invalidationId} status=${invalidation?.Status ?? "unknown"}`,
125 );
126 return yield* new InvalidationInProgress({
127 message: `Invalidation ${invalidationId} is still in progress`,
128 });
129 }),
130 ),
131 Effect.retry({
132 while: (error) => error._tag === "InvalidationInProgress",
133 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(120)]),
134 }),
135 );
136 });
137
138 const createInvalidation = Effect.fn(function* (props: InvalidationProps) {
139 yield* Effect.logInfo(
140 `CloudFront Invalidation create: distribution=${props.distributionId} version=${props.version} paths=${(props.paths ?? defaultPaths).length} wait=${props.wait ?? false}`,
141 );
142 const response = yield* cloudfront.createInvalidation({
143 DistributionId: props.distributionId,
144 InvalidationBatch: {
145 CallerReference: props.version,
146 Paths: {
147 Quantity: (props.paths ?? defaultPaths).length,
148 Items: props.paths ?? defaultPaths,
149 },
150 },
151 });
152
153 yield* Effect.logInfo(
154 `CloudFront Invalidation create: created ${response.Invalidation?.Id ?? "missing"} status=${response.Invalidation?.Status ?? "unknown"}`,
155 );
156 const invalidation = props.wait
157 ? yield* waitForCompletion(props.distributionId, response.Invalidation?.Id!)
158 : response.Invalidation;
159
160 if (!invalidation?.Id) {
161 return yield* new InvalidationUnexpectedResponse({
162 message: "createInvalidation returned no invalidation",
163 });
164 }
165
166 return invalidation;
167 });
168
169 return {
170 stables: ["distributionId", "version"],
171 // Non-listable: an Invalidation is an ephemeral, immutable ledger entry
172 // keyed by {distributionId, invalidationId}. It completes on its own and
173 // cannot be deleted (`delete` is a no-op), so there is no persistent
174 // "current resource" to enumerate for nuke. `listInvalidations` only
175 // exposes historical, undeletable entries per distribution.
176 list: () => Effect.succeed([]),
177 diff: Effect.fn(function* ({ olds, news: _news }) {
178 if (!isResolved(_news)) return undefined;
179 const news = _news as typeof olds;
180 yield* Effect.logInfo(
181 `CloudFront Invalidation diff: oldDistribution=${olds.distributionId} newDistribution=${news.distributionId} oldVersion=${olds.version} newVersion=${news.version}`,
182 );
183 if (olds.distributionId !== news.distributionId || olds.version !== news.version) {
184 yield* Effect.logInfo(
185 `CloudFront Invalidation diff: replacing invalidation for distribution=${news.distributionId}`,
186 );
187 return { action: "replace" } as const;
188 }
189 }),
190 reconcile: Effect.fn(function* ({ news, output, session }) {
191 // An invalidation is an immutable ledger entry, not a mutable
192 // resource. If we already issued one for this distribution and
193 // version, return its attributes unchanged. `diff` only sees a
194 // version change when it is resolved at plan time; a version taken
195 // from an upstream output (e.g. `AssetDeployment.version`) is
196 // unresolved whenever that upstream changes, so the engine plans an
197 // update instead of a replace and lands here with the old output.
198 if (
199 output?.invalidationId &&
200 output.distributionId === news.distributionId &&
201 output.version === news.version
202 ) {
203 yield* session.note(output.invalidationId);
204 return output;
205 }
206
207 // Ensure — issue the invalidation. CloudFront uses
208 // `CallerReference` (= `version`) for idempotency: the same
209 // version submitted twice returns the same invalidation.
210 const invalidation = yield* createInvalidation(news);
211 yield* Effect.logInfo(
212 `CloudFront Invalidation reconcile: storing ${invalidation.Id} for distribution=${news.distributionId}`,
213 );
214 yield* session.note(invalidation.Id);
215 return {
216 invalidationId: invalidation.Id,
217 distributionId: news.distributionId,
218 version: news.version,
219 status: invalidation.Status ?? "InProgress",
220 paths: news.paths ?? defaultPaths,
221 createTime: invalidation.CreateTime,
222 };
223 }),
224 delete: Effect.fn(function* () {}),
225 };
226 }),
227 );