@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 364 lines 12.4 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 * as Data from "effect/Data";
7 import * as Duration from "effect/Duration";
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 FunctionUnexpectedResponse extends Data.TaggedError("FunctionUnexpectedResponse")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export interface FunctionProps {
18 /**
19 * CloudFront Function name. If omitted, a deterministic name is generated.
20 */
21 name?: string;
22 /**
23 * CloudFront Function runtime.
24 * @default "cloudfront-js-2.0"
25 */
26 runtime?: cloudfront.FunctionRuntime;
27 /**
28 * Optional function comment.
29 */
30 comment?: string;
31 /**
32 * JavaScript source code for the function.
33 */
34 code: string;
35 /**
36 * Optional associated KeyValueStore ARNs.
37 */
38 keyValueStoreArns?: string[];
39 }
40
41 export interface Function extends Resource<
42 "AWS.CloudFront.Function",
43 FunctionProps,
44 {
45 /**
46 * CloudFront function ARN.
47 */
48 functionArn: string;
49 /**
50 * Function name.
51 */
52 functionName: string;
53 /**
54 * Runtime currently configured for the function.
55 */
56 runtime: cloudfront.FunctionRuntime;
57 /**
58 * Current comment.
59 */
60 comment: string;
61 /**
62 * Deployment stage for the function.
63 */
64 stage: cloudfront.FunctionStage;
65 /**
66 * Last modified time.
67 */
68 lastModifiedTime: Date | undefined;
69 /**
70 * Latest entity tag for update/delete operations.
71 */
72 etag: string | undefined;
73 /**
74 * Associated KeyValueStore ARNs.
75 */
76 keyValueStoreArns: string[];
77 },
78 never,
79 Providers
80 > {}
81
82 /**
83 * A CloudFront Function for viewer request and response customization.
84 *
85 * CloudFront Functions are lightweight JavaScript handlers that run at the
86 * edge and can be attached to distribution cache behaviors.
87 * ### Creating Functions
88 * **Example:** Viewer Request Function
89 * ```typescript
90 * const fn = yield* Function("RouterRequestFunction", {
91 * code: `
92 * async function handler(event) {
93 * event.request.headers["x-forwarded-host"] = {
94 * value: event.request.headers.host.value,
95 * };
96 * return event.request;
97 * }
98 * `,
99 * });
100 * ```
101 *
102 * @resource
103 */
104 export const Function = Resource<Function>("AWS.CloudFront.Function");
105
106 export const FunctionProvider = () =>
107 Provider.effect(
108 Function,
109 Effect.gen(function* () {
110 const describe = Effect.fn(function* (name: string, stage?: cloudfront.FunctionStage) {
111 return yield* cloudfront
112 .describeFunction({
113 Name: name,
114 Stage: stage,
115 })
116 .pipe(Effect.catchTag("NoSuchFunctionExists", () => Effect.undefined));
117 });
118
119 const getCurrent = Effect.fn(function* (name: string) {
120 const live = yield* describe(name, "LIVE");
121 if (live?.FunctionSummary) {
122 return live;
123 }
124 return yield* describe(name, "DEVELOPMENT");
125 });
126
127 const getDevelopmentEtag = Effect.fn(function* (name: string) {
128 const current = yield* describe(name, "DEVELOPMENT");
129 return current?.ETag;
130 });
131
132 const publish = Effect.fn(function* (name: string, etag: string | undefined) {
133 if (!etag) {
134 return yield* new FunctionUnexpectedResponse({
135 message: `CloudFront Function '${name}' is missing an ETag for publish`,
136 });
137 }
138 yield* cloudfront.publishFunction({
139 Name: name,
140 IfMatch: etag,
141 });
142 return yield* describe(name, "LIVE");
143 });
144
145 return {
146 stables: ["functionArn", "functionName"],
147 // CloudFront is global; listFunctions enumerates every function in the
148 // account. It is non-paginated in distilled but uses Marker/NextMarker,
149 // so we page manually until NextMarker is absent. All CloudFront
150 // functions are custom (no AWS-managed ones), so every item is ours.
151 list: () =>
152 Effect.gen(function* () {
153 const items: Function["Attributes"][] = [];
154 let marker: string | undefined = undefined;
155 do {
156 const listed: cloudfront.ListFunctionsResult = yield* cloudfront.listFunctions({
157 Marker: marker,
158 });
159 for (const summary of listed.FunctionList?.Items ?? []) {
160 items.push(toAttrs(summary, undefined, summary.Name ?? ""));
161 }
162 marker = listed.FunctionList?.NextMarker;
163 } while (marker);
164 return items;
165 }),
166 diff: Effect.fn(function* ({ id, olds, news: _news }) {
167 if (!isResolved(_news)) return undefined;
168 const news = _news as typeof olds;
169 if ((yield* createName(id, olds ?? {})) !== (yield* createName(id, news))) {
170 return { action: "replace" } as const;
171 }
172 }),
173 read: Effect.fn(function* ({ id, olds, output }) {
174 const name = output?.functionName ?? (yield* createName(id, olds ?? {}));
175 const current = yield* getCurrent(name);
176 if (!current?.FunctionSummary) {
177 return undefined;
178 }
179 return toAttrs(current.FunctionSummary, current.ETag, name);
180 }),
181 reconcile: Effect.fn(function* ({ id, news, output, session }) {
182 const name = output?.functionName ?? (yield* createName(id, news));
183
184 // Observe — describe the function (LIVE stage preferred,
185 // DEVELOPMENT fallback). We don't trust `output` because the
186 // function may have been deleted out-of-band.
187 const observedDevelopment = yield* describe(name, "DEVELOPMENT");
188
189 // Ensure — create the function if it's missing. Tolerate
190 // `FunctionAlreadyExists` as a race with a peer reconciler. The
191 // newly created function lives in DEVELOPMENT; we publish it to
192 // LIVE below, in the same flow that handles already-existing
193 // functions.
194 const createDevelopmentFunction = Effect.gen(function* () {
195 const created = yield* cloudfront
196 .createFunction({
197 Name: name,
198 FunctionConfig: {
199 Comment: news.comment ?? "",
200 Runtime: news.runtime ?? "cloudfront-js-2.0",
201 KeyValueStoreAssociations: toKvAssociations(news.keyValueStoreArns),
202 },
203 FunctionCode: new TextEncoder().encode(news.code),
204 })
205 .pipe(
206 Effect.catchTag("FunctionAlreadyExists", () =>
207 describe(name, "DEVELOPMENT").pipe(
208 Effect.flatMap((existing) =>
209 existing
210 ? Effect.succeed(existing)
211 : Effect.die(
212 `CloudFront Function '${name}' already exists but could not be recovered`,
213 ),
214 ),
215 ),
216 ),
217 Effect.retry({
218 while: (error) =>
219 error._tag === "InvalidArgument" && isKeyValueStoreAssociationPending(error),
220 schedule: cappedCloudFrontRetrySchedule,
221 }),
222 );
223 return created.ETag;
224 });
225 const developmentEtag = observedDevelopment
226 ? observedDevelopment.ETag
227 : yield* createDevelopmentFunction;
228
229 // Sync — push desired config/code to DEVELOPMENT when the
230 // function already existed. Skip when we just created it (the
231 // creation already used the desired config).
232 let etagToPublish = developmentEtag;
233 if (observedDevelopment) {
234 const updated = yield* cloudfront
235 .updateFunction({
236 Name: name,
237 IfMatch: observedDevelopment.ETag!,
238 FunctionConfig: {
239 Comment: news.comment ?? "",
240 Runtime:
241 news.runtime ??
242 observedDevelopment.FunctionSummary?.FunctionConfig.Runtime ??
243 "cloudfront-js-2.0",
244 KeyValueStoreAssociations: toKvAssociations(news.keyValueStoreArns),
245 },
246 FunctionCode: new TextEncoder().encode(news.code),
247 })
248 .pipe(
249 Effect.retry({
250 while: (error) =>
251 error._tag === "InvalidArgument" && isKeyValueStoreAssociationPending(error),
252 schedule: cappedCloudFrontRetrySchedule,
253 }),
254 );
255 etagToPublish = updated.ETag;
256 }
257
258 // Publish DEVELOPMENT → LIVE so consumers see the desired code.
259 const live = yield* publish(name, etagToPublish);
260 if (!live?.FunctionSummary) {
261 return yield* Effect.die("publishFunction returned no function summary");
262 }
263
264 yield* session.note(name);
265 return toAttrs(live.FunctionSummary, live.ETag, name);
266 }),
267 delete: Effect.fn(function* ({ output }) {
268 yield* Effect.gen(function* () {
269 const developmentEtag = yield* getDevelopmentEtag(output.functionName);
270 if (!developmentEtag) {
271 yield* Effect.logInfo(
272 `CloudFront Function delete: ${output.functionName} already absent`,
273 );
274 return;
275 }
276
277 yield* Effect.logInfo(
278 `CloudFront Function delete: deleting ${output.functionName} stage=DEVELOPMENT etag=${developmentEtag}`,
279 );
280 yield* cloudfront.deleteFunction({
281 Name: output.functionName,
282 IfMatch: developmentEtag,
283 });
284 }).pipe(
285 Effect.catchTag("NoSuchFunctionExists", () => Effect.void),
286 Effect.tapError((error) =>
287 isFunctionDeletePending(error)
288 ? Effect.logInfo(
289 `CloudFront Function delete: ${output.functionName} not ready yet (${error._tag}), retrying with capped exponential backoff`,
290 )
291 : Effect.logError(
292 `CloudFront Function delete: ${output.functionName} failed with ${String(error)}`,
293 ),
294 ),
295 Effect.retry({
296 while: isFunctionDeletePending,
297 schedule: cappedCloudFrontRetrySchedule,
298 }),
299 );
300 }),
301 };
302 }),
303 );
304
305 const isFunctionDeletePending = (error: {
306 _tag?: string;
307 }): error is cloudfront.FunctionInUse | cloudfront.PreconditionFailed =>
308 error._tag === "FunctionInUse" || error._tag === "PreconditionFailed";
309
310 const isKeyValueStoreAssociationPending = (error: { message?: string }) => {
311 const message = error.message ?? "";
312 return (
313 message.includes("KeyValueStoreAssociationArn") &&
314 message.includes("cannot be associated before the resource is provisioned")
315 );
316 };
317
318 const cappedCloudFrontRetrySchedule = Schedule.max([
319 Schedule.exponential("100 millis"),
320 Schedule.recurs(24),
321 ]).pipe(
322 Schedule.modifyDelay(({ duration }) =>
323 Effect.succeed(
324 Duration.isGreaterThan(duration, Duration.seconds(2)) ? Duration.seconds(2) : duration,
325 ),
326 ),
327 );
328
329 const createName = (id: string, props: FunctionProps) =>
330 props.name
331 ? Effect.succeed(props.name)
332 : createPhysicalName({
333 id,
334 maxLength: 64,
335 lowercase: true,
336 });
337
338 const toKvAssociations = (
339 arns: string[] | undefined,
340 ): cloudfront.KeyValueStoreAssociations | undefined =>
341 arns && arns.length > 0
342 ? {
343 Quantity: arns.length,
344 Items: arns.map((KeyValueStoreARN) => ({ KeyValueStoreARN })),
345 }
346 : undefined;
347
348 const toAttrs = (
349 summary: cloudfront.FunctionSummary,
350 etag: string | undefined,
351 fallbackName: string,
352 ): Function["Attributes"] => ({
353 functionArn: summary.FunctionMetadata.FunctionARN,
354 functionName: summary.Name || fallbackName,
355 runtime: summary.FunctionConfig.Runtime,
356 comment: summary.FunctionConfig.Comment ?? "",
357 stage: summary.FunctionMetadata.Stage ?? "DEVELOPMENT",
358 lastModifiedTime: summary.FunctionMetadata.LastModifiedTime,
359 etag,
360 keyValueStoreArns:
361 summary.FunctionConfig.KeyValueStoreAssociations?.Items?.flatMap((item) =>
362 item.KeyValueStoreARN ? [item.KeyValueStoreARN] : [],
363 ) ?? [],
364 });