@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 317 lines 11 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 * as Option from "effect/Option";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11
12 export class OriginAccessControlConflict extends Data.TaggedError("OriginAccessControlConflict")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export class OriginAccessControlUnexpectedResponse extends Data.TaggedError(
18 "OriginAccessControlUnexpectedResponse",
19 )<{
20 readonly message: string;
21 readonly cause?: unknown;
22 }> {}
23
24 export interface OriginAccessControlProps {
25 /**
26 * Name of the origin access control. If omitted, a deterministic name is generated.
27 */
28 name?: string;
29 /**
30 * Optional description of the origin access control.
31 */
32 description?: string;
33 /**
34 * The origin type this OAC signs for.
35 * @default "s3"
36 */
37 originType?: cloudfront.OriginAccessControlOriginTypes;
38 /**
39 * How CloudFront should apply signing.
40 * @default "always"
41 */
42 signingBehavior?: cloudfront.OriginAccessControlSigningBehaviors;
43 /**
44 * Signing protocol used by CloudFront.
45 * @default "sigv4"
46 */
47 signingProtocol?: cloudfront.OriginAccessControlSigningProtocols;
48 }
49
50 export interface OriginAccessControl extends Resource<
51 "AWS.CloudFront.OriginAccessControl",
52 OriginAccessControlProps,
53 {
54 /**
55 * CloudFront-assigned OAC identifier.
56 */
57 originAccessControlId: string;
58 /**
59 * Name of the OAC.
60 */
61 name: string;
62 /**
63 * Current description of the OAC.
64 */
65 description: string | undefined;
66 /**
67 * Origin type configured for the OAC.
68 */
69 originType: cloudfront.OriginAccessControlOriginTypes;
70 /**
71 * Signing behavior configured for the OAC.
72 */
73 signingBehavior: cloudfront.OriginAccessControlSigningBehaviors;
74 /**
75 * Signing protocol configured for the OAC.
76 */
77 signingProtocol: cloudfront.OriginAccessControlSigningProtocols;
78 /**
79 * Most recent entity tag for update/delete operations.
80 */
81 etag: string | undefined;
82 },
83 never,
84 Providers
85 > {}
86
87 /**
88 * A CloudFront Origin Access Control for private origins.
89 *
90 * `OriginAccessControl` is the recommended CloudFront access model for private
91 * S3 origins and newer signed-origin integrations.
92 * ### Creating Origin Access Controls
93 * **Example:** S3 Origin Access Control
94 * ```typescript
95 * const oac = yield* OriginAccessControl("SiteOriginAccess", {
96 * originType: "s3",
97 * });
98 * ```
99 *
100 * @resource
101 */
102 export const OriginAccessControl = Resource<OriginAccessControl>(
103 "AWS.CloudFront.OriginAccessControl",
104 );
105
106 export const OriginAccessControlProvider = () =>
107 Provider.effect(
108 OriginAccessControl,
109 Effect.gen(function* () {
110 const getByName = Effect.fn(function* (name: string) {
111 const summary = yield* cloudfront.listOriginAccessControls.pages({}).pipe(
112 Stream.map((page) => page.OriginAccessControlList?.Items ?? []),
113 Stream.flattenIterable,
114 Stream.filter((item) => item.Name === name),
115 Stream.runHead,
116 Effect.map(Option.getOrUndefined),
117 );
118 if (!summary?.Id) {
119 return undefined;
120 }
121 const config = yield* cloudfront.getOriginAccessControlConfig({
122 Id: summary.Id,
123 });
124 return {
125 OriginAccessControl: {
126 Id: summary.Id,
127 OriginAccessControlConfig: config.OriginAccessControlConfig,
128 },
129 ETag: config.ETag,
130 };
131 });
132
133 const getCurrent = Effect.fn(function* (
134 output: OriginAccessControl["Attributes"] | undefined,
135 ) {
136 if (!output?.originAccessControlId) {
137 return undefined;
138 }
139 const config = yield* cloudfront
140 .getOriginAccessControlConfig({
141 Id: output.originAccessControlId,
142 })
143 .pipe(Effect.catchTag("NoSuchOriginAccessControl", () => Effect.undefined));
144
145 if (!config?.OriginAccessControlConfig) {
146 return undefined;
147 }
148
149 return {
150 OriginAccessControl: {
151 Id: output.originAccessControlId,
152 OriginAccessControlConfig: config.OriginAccessControlConfig,
153 },
154 ETag: config.ETag,
155 };
156 });
157
158 return {
159 stables: ["originAccessControlId"],
160 list: () =>
161 cloudfront.listOriginAccessControls.pages({}).pipe(
162 Stream.map((page) => page.OriginAccessControlList?.Items ?? []),
163 Stream.flattenIterable,
164 Stream.filter((summary) => summary.Id !== undefined),
165 Stream.mapEffect((summary) =>
166 Effect.gen(function* () {
167 // Fetch per-item config for the fresh ETag (the list summary
168 // omits it). Tolerate a concurrent delete between list and get.
169 const config = yield* cloudfront
170 .getOriginAccessControlConfig({ Id: summary.Id! })
171 .pipe(Effect.catchTag("NoSuchOriginAccessControl", () => Effect.undefined));
172 return toAttrs(
173 {
174 Id: summary.Id!,
175 OriginAccessControlConfig: config?.OriginAccessControlConfig ?? {
176 Name: summary.Name,
177 Description: summary.Description,
178 OriginAccessControlOriginType: summary.OriginAccessControlOriginType,
179 SigningBehavior: summary.SigningBehavior,
180 SigningProtocol: summary.SigningProtocol,
181 },
182 },
183 config?.ETag,
184 summary.Name,
185 );
186 }),
187 ),
188 Stream.runCollect,
189 Effect.map((chunk) => Array.from(chunk)),
190 ),
191 diff: Effect.fn(function* ({ id, olds, news: _news }) {
192 if (!isResolved(_news)) return undefined;
193 const news = _news as typeof olds;
194 if ((yield* createName(id, olds ?? {})) !== (yield* createName(id, news))) {
195 return { action: "replace" } as const;
196 }
197 }),
198 read: Effect.fn(function* ({ id, olds, output }) {
199 const existing =
200 (yield* getCurrent(output)) ?? (yield* getByName(yield* createName(id, olds ?? {})));
201
202 if (!existing?.OriginAccessControl?.Id) {
203 return undefined;
204 }
205
206 return toAttrs(
207 existing.OriginAccessControl,
208 existing.ETag,
209 yield* createName(id, olds ?? {}),
210 );
211 }),
212 reconcile: Effect.fn(function* ({ id, news, output, session }) {
213 const name = yield* createName(id, news);
214
215 // Observe — locate the OAC by id (cached on `output`) or by
216 // name. Trust observed cloud state, not stale `olds`.
217 const observed = (yield* getCurrent(output)) ?? (yield* getByName(name));
218
219 // Ensure — create the OAC if it's missing. Tolerate
220 // `OriginAccessControlAlreadyExists` (race with a peer
221 // reconciler).
222 if (!observed?.OriginAccessControl?.Id) {
223 const created = yield* cloudfront
224 .createOriginAccessControl({
225 OriginAccessControlConfig: {
226 Name: name,
227 Description: news.description,
228 OriginAccessControlOriginType: news.originType ?? "s3",
229 SigningBehavior: news.signingBehavior ?? "always",
230 SigningProtocol: news.signingProtocol ?? "sigv4",
231 },
232 })
233 .pipe(
234 Effect.catchTag("OriginAccessControlAlreadyExists", () =>
235 getByName(name).pipe(
236 Effect.flatMap((existing) =>
237 existing
238 ? Effect.succeed(existing)
239 : Effect.fail(
240 new OriginAccessControlConflict({
241 message: `Origin access control '${name}' already exists but could not be recovered`,
242 }),
243 ),
244 ),
245 ),
246 ),
247 );
248
249 if (!created.OriginAccessControl?.Id) {
250 return yield* new OriginAccessControlUnexpectedResponse({
251 message: "createOriginAccessControl returned no identifier",
252 });
253 }
254
255 yield* session.note(created.OriginAccessControl.Id);
256 return toAttrs(created.OriginAccessControl, created.ETag, name);
257 }
258
259 // Sync — patch the observed config to the desired state. The
260 // freshly observed ETag handles optimistic concurrency.
261 const observedConfig = observed.OriginAccessControl.OriginAccessControlConfig;
262 const updated = yield* cloudfront.updateOriginAccessControl({
263 Id: observed.OriginAccessControl.Id,
264 IfMatch: observed.ETag,
265 OriginAccessControlConfig: {
266 Name: observedConfig?.Name ?? name,
267 Description: news.description,
268 OriginAccessControlOriginType:
269 news.originType ?? observedConfig?.OriginAccessControlOriginType ?? "s3",
270 SigningBehavior: news.signingBehavior ?? observedConfig?.SigningBehavior ?? "always",
271 SigningProtocol: news.signingProtocol ?? observedConfig?.SigningProtocol ?? "sigv4",
272 },
273 });
274
275 if (!updated.OriginAccessControl?.Id) {
276 return yield* new OriginAccessControlUnexpectedResponse({
277 message: "updateOriginAccessControl returned no identifier",
278 });
279 }
280
281 yield* session.note(observed.OriginAccessControl.Id);
282 return toAttrs(updated.OriginAccessControl, updated.ETag, observedConfig?.Name ?? name);
283 }),
284 delete: Effect.fn(function* ({ output }) {
285 yield* cloudfront
286 .deleteOriginAccessControl({
287 Id: output.originAccessControlId,
288 IfMatch: output.etag,
289 })
290 .pipe(Effect.catchTag("NoSuchOriginAccessControl", () => Effect.void));
291 }),
292 };
293 }),
294 );
295
296 const createName = (id: string, props: OriginAccessControlProps) =>
297 props.name
298 ? Effect.succeed(props.name)
299 : createPhysicalName({
300 id,
301 maxLength: 64,
302 lowercase: true,
303 });
304
305 const toAttrs = (
306 oac: cloudfront.OriginAccessControl,
307 etag: string | undefined,
308 fallbackName: string,
309 ) => ({
310 originAccessControlId: oac.Id,
311 name: oac.OriginAccessControlConfig?.Name ?? fallbackName,
312 description: oac.OriginAccessControlConfig?.Description,
313 originType: oac.OriginAccessControlConfig?.OriginAccessControlOriginType ?? "s3",
314 signingBehavior: oac.OriginAccessControlConfig?.SigningBehavior ?? "always",
315 signingProtocol: oac.OriginAccessControlConfig?.SigningProtocol ?? "sigv4",
316 etag,
317 });