@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 325 lines 10.8 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 Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import type { Providers } from "../Providers.ts";
9
10 export interface RealtimeLogEndpoint {
11 /**
12 * ARN of the Kinesis data stream that receives the real-time log records.
13 */
14 streamArn: string;
15 /**
16 * ARN of an IAM role that CloudFront can assume to write to the stream.
17 * The role's trust policy must allow the `cloudfront.amazonaws.com`
18 * service principal, and it needs `kinesis:DescribeStreamSummary`,
19 * `kinesis:DescribeStream`, `kinesis:PutRecord` and `kinesis:PutRecords`
20 * on the stream.
21 */
22 roleArn: string;
23 }
24
25 export interface RealtimeLogConfigProps {
26 /**
27 * Name of the real-time log configuration. If omitted, a deterministic
28 * name is generated. Changing this forces replacement.
29 */
30 name?: string;
31 /**
32 * Percentage of viewer requests sampled into the log stream, between 1 and
33 * 100. Updated in place.
34 */
35 samplingRate: number;
36 /**
37 * Real-time log record fields to include (e.g. `timestamp`, `c-ip`,
38 * `cs-uri-stem`, `sc-status`). Updated in place.
39 */
40 fields: string[];
41 /**
42 * Kinesis endpoints that receive the log records. Updated in place.
43 */
44 endpoints: RealtimeLogEndpoint[];
45 }
46
47 export interface RealtimeLogConfig extends Resource<
48 "AWS.CloudFront.RealtimeLogConfig",
49 RealtimeLogConfigProps,
50 {
51 /**
52 * ARN of the real-time log configuration.
53 */
54 arn: string;
55 /**
56 * Name of the configuration.
57 */
58 name: string;
59 /**
60 * Current sampling rate.
61 */
62 samplingRate: number;
63 /**
64 * Current log record fields.
65 */
66 fields: string[];
67 /**
68 * Current Kinesis endpoints.
69 */
70 endpoints: RealtimeLogEndpoint[];
71 },
72 never,
73 Providers
74 > {}
75
76 /**
77 * A CloudFront real-time log configuration.
78 *
79 * Real-time logs deliver per-request records to a Kinesis data stream within
80 * seconds. Attach the configuration to a distribution's cache behavior via
81 * `Distribution` (`realtimeLogConfigArn`).
82 * ### Creating Real-Time Log Configs
83 * **Example:** Stream Viewer Requests to Kinesis
84 * ```typescript
85 * const stream = yield* Kinesis.Stream("EdgeLogs", {});
86 *
87 * const role = yield* IAM.Role("EdgeLogsRole", {
88 * assumeRolePolicyDocument: {
89 * Version: "2012-10-17",
90 * Statement: [
91 * {
92 * Effect: "Allow",
93 * Principal: { Service: "cloudfront.amazonaws.com" },
94 * Action: "sts:AssumeRole",
95 * },
96 * ],
97 * },
98 * inlinePolicies: {
99 * kinesis: {
100 * Version: "2012-10-17",
101 * Statement: [
102 * {
103 * Effect: "Allow",
104 * Action: [
105 * "kinesis:DescribeStreamSummary",
106 * "kinesis:DescribeStream",
107 * "kinesis:PutRecord",
108 * "kinesis:PutRecords",
109 * ],
110 * Resource: stream.streamArn,
111 * },
112 * ],
113 * },
114 * },
115 * });
116 *
117 * const logConfig = yield* RealtimeLogConfig("EdgeLogConfig", {
118 * samplingRate: 100,
119 * fields: ["timestamp", "c-ip", "cs-uri-stem", "sc-status"],
120 * endpoints: [{ streamArn: stream.streamArn, roleArn: role.roleArn }],
121 * });
122 * ```
123 *
124 * @resource
125 */
126 export const RealtimeLogConfig = Resource<RealtimeLogConfig>("AWS.CloudFront.RealtimeLogConfig");
127
128 const createName = (id: string, props: RealtimeLogConfigProps) =>
129 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 64 });
130
131 const toEndPoints = (endpoints: RealtimeLogEndpoint[]): cloudfront.EndPoint[] =>
132 endpoints.map((endpoint) => ({
133 StreamType: "Kinesis",
134 KinesisStreamConfig: {
135 RoleARN: endpoint.roleArn,
136 StreamARN: endpoint.streamArn,
137 },
138 }));
139
140 const fromEndPoints = (endpoints: cloudfront.EndPoint[] | undefined): RealtimeLogEndpoint[] =>
141 (endpoints ?? []).flatMap((endpoint) =>
142 endpoint.KinesisStreamConfig
143 ? [
144 {
145 streamArn: endpoint.KinesisStreamConfig.StreamARN,
146 roleArn: endpoint.KinesisStreamConfig.RoleARN,
147 },
148 ]
149 : [],
150 );
151
152 const toAttrs = (config: cloudfront.RealtimeLogConfig): RealtimeLogConfig["Attributes"] => ({
153 arn: config.ARN,
154 name: config.Name,
155 samplingRate: config.SamplingRate,
156 fields: [...config.Fields],
157 endpoints: fromEndPoints([...config.EndPoints]),
158 });
159
160 const sameEndpoints = (a: RealtimeLogEndpoint[], b: RealtimeLogEndpoint[]) =>
161 a.length === b.length &&
162 a.every(
163 (endpoint, index) =>
164 endpoint.streamArn === b[index]?.streamArn && endpoint.roleArn === b[index]?.roleArn,
165 );
166
167 // CloudFront canonicalizes (reorders) the field list, so compare as sets.
168 const sameFields = (a: readonly string[], b: readonly string[]) => {
169 if (a.length !== b.length) return false;
170 const sortedA = [...a].sort();
171 const sortedB = [...b].sort();
172 return sortedA.every((field, index) => field === sortedB[index]);
173 };
174
175 /**
176 * CloudFront validates at create/update time that it can assume the
177 * endpoint's IAM role. A role created in the same deploy can take a few
178 * seconds to propagate through IAM, surfacing as `InvalidArgument` — retry
179 * it on a bounded schedule (~40s). Genuine validation errors fail after the
180 * cap.
181 *
182 * Explicitly typed: inlining `Effect.retry` with options in provider
183 * lifecycle code can widen the provider layer to `unknown` in declaration
184 * emit.
185 *
186 * @internal
187 */
188 const retryIamPropagation = <A, E extends { _tag: string }, R>(
189 self: Effect.Effect<A, E, R>,
190 ): Effect.Effect<A, E, R> =>
191 Effect.retry(self, {
192 while: (e) => e._tag === "InvalidArgument",
193 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
194 });
195
196 /**
197 * Deleting a config shortly after a distribution stopped referencing it can
198 * surface `RealtimeLogConfigInUse` until the distribution update propagates
199 * — retry on a bounded schedule (~40s).
200 *
201 * @internal
202 */
203 const retryConfigInUse = <A, E extends { _tag: string }, R>(
204 self: Effect.Effect<A, E, R>,
205 ): Effect.Effect<A, E, R> =>
206 Effect.retry(self, {
207 while: (e) => e._tag === "RealtimeLogConfigInUse",
208 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
209 });
210
211 export const RealtimeLogConfigProvider = () =>
212 Provider.effect(
213 RealtimeLogConfig,
214 Effect.gen(function* () {
215 const observe = Effect.fn(function* (name: string) {
216 const response = yield* cloudfront
217 .getRealtimeLogConfig({ Name: name })
218 .pipe(Effect.catchTag("NoSuchRealtimeLogConfig", () => Effect.undefined));
219 return response?.RealtimeLogConfig;
220 });
221
222 return {
223 stables: ["arn", "name"],
224 // Enumerate every config in the account. `listRealtimeLogConfigs`
225 // pages via Marker/NextMarker inside a wrapper struct (no distilled
226 // paginator) — hand-roll a bounded loop; an empty NextMarker is
227 // terminal.
228 list: () =>
229 Effect.gen(function* () {
230 const items: RealtimeLogConfig["Attributes"][] = [];
231 let marker: string | undefined;
232 for (let page = 0; page < 20; page++) {
233 const response = yield* cloudfront.listRealtimeLogConfigs({
234 Marker: marker,
235 MaxItems: 100,
236 });
237 for (const config of response.RealtimeLogConfigs?.Items ?? []) {
238 items.push(toAttrs(config));
239 }
240 if (!response.RealtimeLogConfigs?.NextMarker) {
241 break;
242 }
243 marker = response.RealtimeLogConfigs.NextMarker;
244 }
245 return items;
246 }),
247 diff: Effect.fn(function* ({ id, olds, news }) {
248 if (!isResolved(news)) return undefined;
249 if ((yield* createName(id, olds)) !== (yield* createName(id, news))) {
250 return { action: "replace" } as const;
251 }
252 }),
253 read: Effect.fn(function* ({ id, olds, output }) {
254 const name =
255 output?.name ?? (yield* createName(id, olds ?? ({} as RealtimeLogConfigProps)));
256 const observed = yield* observe(name);
257 if (!observed) {
258 return undefined;
259 }
260 return toAttrs(observed);
261 }),
262 reconcile: Effect.fn(function* ({ id, news, output, session }) {
263 const name = output?.name ?? (yield* createName(id, news));
264 const desiredEndpoints = news.endpoints;
265 const desiredFields = news.fields;
266
267 // Observe — live config is authoritative; `output` only caches the
268 // name.
269 let observed = yield* observe(name);
270
271 // Ensure — create when missing; `RealtimeLogConfigAlreadyExists`
272 // is a race with a peer reconciler, re-observe.
273 if (!observed) {
274 observed = yield* retryIamPropagation(
275 cloudfront.createRealtimeLogConfig({
276 Name: name,
277 SamplingRate: news.samplingRate,
278 Fields: desiredFields,
279 EndPoints: toEndPoints(desiredEndpoints),
280 }),
281 ).pipe(
282 Effect.map((response) => response.RealtimeLogConfig),
283 Effect.catchTag("RealtimeLogConfigAlreadyExists", () => observe(name)),
284 );
285 if (!observed) {
286 return yield* Effect.die(
287 `CloudFront RealtimeLogConfig '${name}' could not be observed after create`,
288 );
289 }
290 yield* session.note(observed.ARN);
291 return toAttrs(observed);
292 }
293
294 // Sync — `updateRealtimeLogConfig` replaces every mutable aspect
295 // at once; skip the call entirely when observed matches desired.
296 const current = toAttrs(observed);
297 if (
298 current.samplingRate !== news.samplingRate ||
299 !sameFields(current.fields, desiredFields) ||
300 !sameEndpoints(current.endpoints, desiredEndpoints)
301 ) {
302 const updated = yield* retryIamPropagation(
303 cloudfront.updateRealtimeLogConfig({
304 Name: name,
305 SamplingRate: news.samplingRate,
306 Fields: desiredFields,
307 EndPoints: toEndPoints(desiredEndpoints),
308 }),
309 );
310 if (updated.RealtimeLogConfig) {
311 observed = updated.RealtimeLogConfig;
312 }
313 }
314
315 yield* session.note(observed.ARN);
316 return toAttrs(observed);
317 }),
318 delete: Effect.fn(function* ({ output }) {
319 yield* retryConfigInUse(
320 cloudfront.deleteRealtimeLogConfig({ Name: output.name }).pipe(Effect.asVoid),
321 ).pipe(Effect.catchTag("NoSuchRealtimeLogConfig", () => Effect.void));
322 }),
323 };
324 }),
325 );