@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 307 lines 11.3 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 Effect from "effect/Effect";
8 import type { Providers } from "../Providers.ts";
9
10 export class OriginRequestPolicyConflict extends Data.TaggedError("OriginRequestPolicyConflict")<{
11 readonly message: string;
12 readonly cause?: unknown;
13 }> {}
14
15 export class OriginRequestPolicyUnexpectedResponse extends Data.TaggedError(
16 "OriginRequestPolicyUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export interface OriginRequestPolicyProps {
23 /**
24 * Name of the origin request policy. If omitted, a deterministic name is
25 * generated. Names must be unique per AWS account. Changing the name
26 * triggers a replacement.
27 */
28 name?: string;
29 /**
30 * Optional comment describing the policy.
31 */
32 comment?: string;
33 /**
34 * Headers to forward to the origin (in addition to the cache key).
35 */
36 headersConfig: cloudfront.OriginRequestPolicyHeadersConfig;
37 /**
38 * Cookies to forward to the origin (in addition to the cache key).
39 */
40 cookiesConfig: cloudfront.OriginRequestPolicyCookiesConfig;
41 /**
42 * Query strings to forward to the origin (in addition to the cache key).
43 */
44 queryStringsConfig: cloudfront.OriginRequestPolicyQueryStringsConfig;
45 }
46
47 export interface OriginRequestPolicy extends Resource<
48 "AWS.CloudFront.OriginRequestPolicy",
49 OriginRequestPolicyProps,
50 {
51 /**
52 * CloudFront-assigned origin request policy identifier.
53 */
54 originRequestPolicyId: string;
55 /**
56 * Name of the origin request policy.
57 */
58 name: string;
59 /**
60 * Most recent entity tag for update/delete operations.
61 */
62 etag: string | undefined;
63 /**
64 * Current comment on the policy.
65 */
66 comment: string | undefined;
67 /**
68 * Current headers configuration.
69 */
70 headersConfig: cloudfront.OriginRequestPolicyHeadersConfig;
71 /**
72 * Current cookies configuration.
73 */
74 cookiesConfig: cloudfront.OriginRequestPolicyCookiesConfig;
75 /**
76 * Current query strings configuration.
77 */
78 queryStringsConfig: cloudfront.OriginRequestPolicyQueryStringsConfig;
79 },
80 never,
81 Providers
82 > {}
83
84 /**
85 * A CloudFront origin request policy.
86 *
87 * Origin request policies control which values from the viewer request (in
88 * addition to those used in the cache key) CloudFront includes when sending
89 * a request to the origin. They are referenced by ID on a Distribution's
90 * default behavior or per-path cache behaviors.
91 * ### Creating Origin Request Policies
92 * **Example:** Forward all viewer headers and cookies
93 * ```typescript
94 * const originRequestPolicy = yield* OriginRequestPolicy("AppOriginRequest", {
95 * comment: "Forward auth + locale",
96 * headersConfig: {
97 * HeaderBehavior: "whitelist",
98 * Headers: { Quantity: 2, Items: ["Authorization", "Accept-Language"] },
99 * },
100 * cookiesConfig: { CookieBehavior: "all" },
101 * queryStringsConfig: { QueryStringBehavior: "all" },
102 * });
103 * ```
104 *
105 * @resource
106 */
107 export const OriginRequestPolicy = Resource<OriginRequestPolicy>(
108 "AWS.CloudFront.OriginRequestPolicy",
109 );
110
111 export const OriginRequestPolicyProvider = () =>
112 Provider.effect(
113 OriginRequestPolicy,
114 Effect.gen(function* () {
115 const getById = Effect.fn(function* (id: string) {
116 const config = yield* cloudfront
117 .getOriginRequestPolicyConfig({ Id: id })
118 .pipe(Effect.catchTag("NoSuchOriginRequestPolicy", () => Effect.undefined));
119 if (!config?.OriginRequestPolicyConfig) return undefined;
120 return { config: config.OriginRequestPolicyConfig, etag: config.ETag };
121 });
122
123 const getByName = Effect.fn(function* (name: string) {
124 const listed = yield* cloudfront.listOriginRequestPolicies({
125 Type: "custom",
126 });
127 const summary = listed.OriginRequestPolicyList?.Items?.find(
128 (item) => item.OriginRequestPolicy?.OriginRequestPolicyConfig?.Name === name,
129 );
130 if (!summary?.OriginRequestPolicy?.Id) return undefined;
131 return yield* getById(summary.OriginRequestPolicy.Id).pipe(
132 Effect.map((found) =>
133 found ? { id: summary.OriginRequestPolicy.Id, ...found } : undefined,
134 ),
135 );
136 });
137
138 const buildConfig = (
139 name: string,
140 props: OriginRequestPolicyProps,
141 ): cloudfront.OriginRequestPolicyConfig => ({
142 Name: name,
143 Comment: props.comment,
144 HeadersConfig: props.headersConfig,
145 CookiesConfig: props.cookiesConfig,
146 QueryStringsConfig: props.queryStringsConfig,
147 });
148
149 const toAttrs = (
150 id: string,
151 config: cloudfront.OriginRequestPolicyConfig,
152 etag: string | undefined,
153 ) => ({
154 originRequestPolicyId: id,
155 name: config.Name,
156 etag,
157 comment: config.Comment,
158 headersConfig: config.HeadersConfig,
159 cookiesConfig: config.CookiesConfig,
160 queryStringsConfig: config.QueryStringsConfig,
161 });
162
163 return {
164 stables: ["originRequestPolicyId"],
165 diff: Effect.fn(function* ({ id, news, olds }) {
166 if (!isResolved(news)) return undefined;
167 if ((yield* createName(id, olds ?? {})) !== (yield* createName(id, news))) {
168 return { action: "replace" } as const;
169 }
170 }),
171 read: Effect.fn(function* ({ id, olds, output }) {
172 if (output?.originRequestPolicyId) {
173 const found = yield* getById(output.originRequestPolicyId);
174 if (found) {
175 return toAttrs(output.originRequestPolicyId, found.config, found.etag);
176 }
177 }
178 const name = yield* createName(id, olds ?? {});
179 const found = yield* getByName(name);
180 if (!found) return undefined;
181 return toAttrs(found.id, found.config, found.etag);
182 }),
183 // CloudFront is global (no region). `listOriginRequestPolicies`
184 // returns both AWS-managed and custom policies; we filter to
185 // `Type: "custom"` since those are the only ones we create/delete.
186 // The op is marker-paginated (no `.pages`), so we loop until
187 // `NextMarker` is exhausted and hydrate each summary's ETag via
188 // `getById` so every row matches read().
189 list: () =>
190 Effect.gen(function* () {
191 const items: ReturnType<typeof toAttrs>[] = [];
192 let marker: string | undefined = undefined;
193 do {
194 const listed: cloudfront.ListOriginRequestPoliciesResult =
195 yield* cloudfront.listOriginRequestPolicies({
196 Type: "custom",
197 Marker: marker,
198 });
199 for (const summary of listed.OriginRequestPolicyList?.Items ?? []) {
200 if (summary.Type !== "custom") continue;
201 const id = summary.OriginRequestPolicy?.Id;
202 const config = summary.OriginRequestPolicy?.OriginRequestPolicyConfig;
203 if (!id || !config) continue;
204 const found = yield* getById(id);
205 items.push(toAttrs(id, found?.config ?? config, found?.etag));
206 }
207 marker = listed.OriginRequestPolicyList?.NextMarker;
208 } while (marker);
209 return items;
210 }),
211 reconcile: Effect.fn(function* ({ id, news, output, session }) {
212 const name = yield* createName(id, news);
213
214 // Observe — locate the policy by id (cached on `output`) or
215 // by name. Trust observed cloud state, not stale `olds`.
216 let observed = output?.originRequestPolicyId
217 ? yield* getById(output.originRequestPolicyId).pipe(
218 Effect.map((found) =>
219 found ? { id: output.originRequestPolicyId, ...found } : undefined,
220 ),
221 )
222 : undefined;
223 if (!observed) {
224 observed = yield* getByName(name);
225 }
226
227 // Ensure — create the policy if it's missing. Tolerate
228 // `OriginRequestPolicyAlreadyExists` (race with a peer
229 // reconciler).
230 if (!observed) {
231 const created = yield* cloudfront
232 .createOriginRequestPolicy({
233 OriginRequestPolicyConfig: buildConfig(name, news),
234 })
235 .pipe(
236 Effect.catchTag("OriginRequestPolicyAlreadyExists", () =>
237 getByName(name).pipe(
238 Effect.flatMap((existing) =>
239 existing
240 ? Effect.succeed({
241 OriginRequestPolicy: {
242 Id: existing.id,
243 LastModifiedTime: new Date(),
244 OriginRequestPolicyConfig: existing.config,
245 },
246 ETag: existing.etag,
247 Location: undefined,
248 })
249 : Effect.fail(
250 new OriginRequestPolicyConflict({
251 message: `Origin request policy '${name}' already exists but could not be recovered`,
252 }),
253 ),
254 ),
255 ),
256 ),
257 );
258 if (!created.OriginRequestPolicy?.Id) {
259 return yield* new OriginRequestPolicyUnexpectedResponse({
260 message: "createOriginRequestPolicy returned no identifier",
261 });
262 }
263 yield* session.note(created.OriginRequestPolicy.Id);
264 return toAttrs(
265 created.OriginRequestPolicy.Id,
266 created.OriginRequestPolicy.OriginRequestPolicyConfig,
267 created.ETag,
268 );
269 }
270
271 // Sync — patch the observed config to the desired state. The
272 // freshly observed ETag handles optimistic concurrency.
273 const updated = yield* cloudfront.updateOriginRequestPolicy({
274 Id: observed.id,
275 IfMatch: observed.etag,
276 OriginRequestPolicyConfig: buildConfig(observed.config.Name, news),
277 });
278 if (!updated.OriginRequestPolicy?.Id) {
279 return yield* new OriginRequestPolicyUnexpectedResponse({
280 message: "updateOriginRequestPolicy returned no identifier",
281 });
282 }
283 yield* session.note(observed.id);
284 return toAttrs(
285 updated.OriginRequestPolicy.Id,
286 updated.OriginRequestPolicy.OriginRequestPolicyConfig,
287 updated.ETag,
288 );
289 }),
290 delete: Effect.fn(function* ({ output }) {
291 const current = yield* getById(output.originRequestPolicyId);
292 if (!current) return;
293 yield* cloudfront
294 .deleteOriginRequestPolicy({
295 Id: output.originRequestPolicyId,
296 IfMatch: current.etag,
297 })
298 .pipe(Effect.catchTag("NoSuchOriginRequestPolicy", () => Effect.void));
299 }),
300 };
301 }),
302 );
303
304 const createName = (id: string, props: OriginRequestPolicyProps) =>
305 props.name
306 ? Effect.succeed(props.name)
307 : createPhysicalName({ id, maxLength: 128, lowercase: true });