@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 391 lines 13.6 KB
Raw
1 import * as config from "@distilled.cloud/aws/config-service";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import type { Providers } from "../Providers.ts";
11
12 export interface RecordingGroupProps {
13 /**
14 * Record every supported (regional) resource type. Mutually exclusive
15 * with `resourceTypes`.
16 * @default false
17 */
18 allSupported?: boolean;
19 /**
20 * Also record global resource types (e.g. IAM). Only meaningful with
21 * `allSupported: true`.
22 * @default false
23 */
24 includeGlobalResourceTypes?: boolean;
25 /**
26 * The specific resource types to record, e.g. `AWS::S3::Bucket`. Only
27 * meaningful when `allSupported` is `false`.
28 */
29 resourceTypes?: string[];
30 /**
31 * Resource types to exclude from recording. Requires
32 * `recordingStrategy.useOnly: "EXCLUSION_BY_RESOURCE_TYPES"`.
33 */
34 exclusionByResourceTypes?: {
35 /**
36 * The resource types excluded from recording.
37 */
38 resourceTypes: string[];
39 };
40 /**
41 * Which recording strategy the recorder uses.
42 */
43 recordingStrategy?: {
44 /**
45 * `ALL_SUPPORTED_RESOURCE_TYPES`, `INCLUSION_BY_RESOURCE_TYPES`, or
46 * `EXCLUSION_BY_RESOURCE_TYPES`.
47 */
48 useOnly?:
49 | "ALL_SUPPORTED_RESOURCE_TYPES"
50 | "INCLUSION_BY_RESOURCE_TYPES"
51 | "EXCLUSION_BY_RESOURCE_TYPES";
52 };
53 }
54
55 export interface RecordingModeProps {
56 /**
57 * The default recording frequency for all recorded resource types.
58 */
59 recordingFrequency: "CONTINUOUS" | "DAILY";
60 /**
61 * Per-resource-type overrides of the recording frequency.
62 */
63 recordingModeOverrides?: {
64 /**
65 * Description of the override.
66 */
67 description?: string;
68 /**
69 * The resource types the override applies to.
70 */
71 resourceTypes: string[];
72 /**
73 * The recording frequency for the overridden resource types.
74 */
75 recordingFrequency: "CONTINUOUS" | "DAILY";
76 }[];
77 }
78
79 export interface ConfigurationRecorderProps {
80 /**
81 * Name of the configuration recorder. AWS allows only ONE customer
82 * managed configuration recorder per account per region. Changing the
83 * name replaces the recorder.
84 * @default ${app}-${stage}-${id}
85 */
86 name?: string;
87 /**
88 * ARN of the IAM role the recorder assumes to read your resources'
89 * configurations, e.g. the `AWSServiceRoleForConfig` service-linked role
90 * (`arn:aws:iam::{account}:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig`).
91 */
92 roleArn: string;
93 /**
94 * Which resource types the recorder records.
95 * @default all supported resource types
96 */
97 recordingGroup?: RecordingGroupProps;
98 /**
99 * How frequently the recorder records configuration changes.
100 * @default CONTINUOUS
101 */
102 recordingMode?: RecordingModeProps;
103 /**
104 * Desired recording state. `true` starts the recorder (requires a
105 * delivery channel), `false` stops it. When omitted the recording state
106 * is left untouched.
107 */
108 recording?: boolean;
109 /**
110 * Tags to apply to the recorder. Merged with internal Alchemy tags.
111 */
112 tags?: Record<string, string>;
113 }
114
115 export interface ConfigurationRecorder extends Resource<
116 "AWS.Config.ConfigurationRecorder",
117 ConfigurationRecorderProps,
118 {
119 /** Physical name of the configuration recorder. */
120 recorderName: string;
121 /** ARN of the configuration recorder. */
122 recorderArn: string;
123 },
124 never,
125 Providers
126 > {}
127
128 /**
129 * The AWS Config configuration recorder that detects and records changes to
130 * your AWS resource configurations.
131 *
132 * AWS allows only **one** customer managed configuration recorder per
133 * account per region — treat this resource as an account-region singleton.
134 * Starting the recorder (`recording: true`) requires a delivery channel
135 * (see `AWS.Config.DeliveryChannel`) and incurs per-configuration-item
136 * charges.
137 * ### Creating the Recorder
138 * **Example:** Recorder with the Config service-linked role
139 * ```typescript
140 * import * as Config from "@alchemy.run/aws/Config";
141 *
142 * const recorder = yield* Config.ConfigurationRecorder("Recorder", {
143 * roleArn: `arn:aws:iam::${accountId}:role/aws-service-role/config.amazonaws.com/AWSServiceRoleForConfig`,
144 * recordingGroup: { allSupported: true },
145 * });
146 * ```
147 *
148 * **Example:** Record only specific resource types
149 * ```typescript
150 * const recorder = yield* Config.ConfigurationRecorder("Recorder", {
151 * roleArn: serviceLinkedRoleArn,
152 * recordingGroup: {
153 * resourceTypes: ["AWS::S3::Bucket", "AWS::EC2::SecurityGroup"],
154 * },
155 * });
156 * ```
157 *
158 * ### Recording State
159 * **Example:** Start recording (requires a delivery channel)
160 * ```typescript
161 * const channel = yield* Config.DeliveryChannel("Channel", {
162 * s3BucketName: bucket.bucketName,
163 * });
164 * const recorder = yield* Config.ConfigurationRecorder("Recorder", {
165 * roleArn: serviceLinkedRoleArn,
166 * recording: true,
167 * });
168 * ```
169 *
170 * @resource
171 */
172 export const ConfigurationRecorder = Resource<ConfigurationRecorder>(
173 "AWS.Config.ConfigurationRecorder",
174 );
175
176 /**
177 * A recorder role that was just created can be transiently rejected with
178 * `InvalidRoleException` until IAM propagates. Bounded retry (~40s).
179 *
180 * Explicitly typed: inlining `Effect.retry` with options in provider
181 * lifecycle code can widen the provider layer to `unknown` in declaration
182 * emit.
183 *
184 * @internal
185 */
186 const retryWhileInvalidRole = <A, E extends { readonly _tag: string }, R>(
187 self: Effect.Effect<A, E, R>,
188 ): Effect.Effect<A, E, R> =>
189 Effect.retry(self, {
190 while: (e) => e._tag === "InvalidRoleException",
191 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
192 });
193
194 export const ConfigurationRecorderProvider = () =>
195 Provider.effect(
196 ConfigurationRecorder,
197 Effect.gen(function* () {
198 const createRecorderName = Effect.fn(function* (
199 id: string,
200 props: Pick<ConfigurationRecorderProps, "name">,
201 ) {
202 return props.name ?? (yield* createPhysicalName({ id, maxLength: 256 }));
203 });
204
205 const toWireRecordingGroup = (
206 group: RecordingGroupProps | undefined,
207 ): config.RecordingGroup | undefined =>
208 group === undefined
209 ? undefined
210 : {
211 allSupported: group.allSupported,
212 includeGlobalResourceTypes: group.includeGlobalResourceTypes,
213 resourceTypes: group.resourceTypes,
214 exclusionByResourceTypes: group.exclusionByResourceTypes,
215 recordingStrategy: group.recordingStrategy,
216 };
217
218 const toWireRecordingMode = (
219 mode: RecordingModeProps | undefined,
220 ): config.RecordingMode | undefined =>
221 mode === undefined
222 ? undefined
223 : {
224 recordingFrequency: mode.recordingFrequency,
225 recordingModeOverrides: mode.recordingModeOverrides,
226 };
227
228 const observeRecorder = Effect.fn(function* (name: string) {
229 const response = yield* config
230 .describeConfigurationRecorders({
231 ConfigurationRecorderNames: [name],
232 })
233 .pipe(
234 Effect.catchTag("NoSuchConfigurationRecorderException", () =>
235 Effect.succeed({ ConfigurationRecorders: [] }),
236 ),
237 );
238 return (response.ConfigurationRecorders ?? []).at(0);
239 });
240
241 const observedTags = (arn: string) =>
242 config.listTagsForResource({ ResourceArn: arn }).pipe(
243 Effect.map((r) =>
244 Object.fromEntries(
245 (r.Tags ?? []).flatMap((t) => (t.Key !== undefined ? [[t.Key, t.Value ?? ""]] : [])),
246 ),
247 ),
248 Effect.catchTag("ResourceNotFoundException", () =>
249 Effect.succeed({} as Record<string, string>),
250 ),
251 );
252
253 return ConfigurationRecorder.Provider.of({
254 stables: ["recorderName", "recorderArn"],
255 list: () =>
256 config.describeConfigurationRecorders({}).pipe(
257 Effect.map((response) =>
258 (response.ConfigurationRecorders ?? []).flatMap((recorder) =>
259 recorder.name && recorder.arn
260 ? [
261 {
262 recorderName: recorder.name,
263 recorderArn: recorder.arn,
264 },
265 ]
266 : [],
267 ),
268 ),
269 ),
270 read: Effect.fn(function* ({ id, olds, output }) {
271 const name = output?.recorderName ?? (yield* createRecorderName(id, olds ?? {}));
272 const recorder = yield* observeRecorder(name);
273 if (recorder?.arn === undefined) return undefined;
274 const attrs = { recorderName: name, recorderArn: recorder.arn };
275 const tags = yield* observedTags(recorder.arn);
276 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
277 }),
278 diff: Effect.fn(function* ({ id, news, olds }) {
279 if (!isResolved(news)) return undefined;
280 const oldName = yield* createRecorderName(id, olds ?? {});
281 const newName = yield* createRecorderName(id, news);
282 if (oldName !== newName) {
283 return { action: "replace" } as const;
284 }
285 // fall through: engine default update logic for mutable fields
286 }),
287 reconcile: Effect.fn(function* ({ id, news, output, session }) {
288 const name = output?.recorderName ?? (yield* createRecorderName(id, news));
289 const internalTags = yield* createInternalTags(id);
290 const desiredTags = { ...news.tags, ...internalTags };
291 const desiredGroup = toWireRecordingGroup(news.recordingGroup);
292 const desiredMode = toWireRecordingMode(news.recordingMode);
293
294 // 1. OBSERVE — cloud state is authoritative.
295 const observed = yield* observeRecorder(name);
296
297 // 2+3. ENSURE + SYNC — PutConfigurationRecorder is a full upsert;
298 // apply when missing or when a user-declared aspect drifted
299 // (fields AWS defaults are only compared when declared).
300 const inSync =
301 observed !== undefined &&
302 observed.roleARN === news.roleArn &&
303 (desiredGroup === undefined ||
304 JSON.stringify(observed.recordingGroup) ===
305 JSON.stringify({
306 ...observed.recordingGroup,
307 ...desiredGroup,
308 })) &&
309 (desiredMode === undefined ||
310 JSON.stringify(observed.recordingMode) ===
311 JSON.stringify({ ...observed.recordingMode, ...desiredMode }));
312 if (!inSync) {
313 yield* retryWhileInvalidRole(
314 config.putConfigurationRecorder({
315 ConfigurationRecorder: {
316 name,
317 roleARN: news.roleArn,
318 recordingGroup: desiredGroup,
319 recordingMode: desiredMode,
320 },
321 Tags: createTagsList(desiredTags),
322 }),
323 );
324 }
325
326 // Re-observe for the ARN (Put returns an empty body).
327 const live = yield* observeRecorder(name);
328 const recorderArn = live?.arn ?? output?.recorderArn;
329
330 // 3b. SYNC TAGS — diff against OBSERVED cloud tags.
331 if (recorderArn !== undefined) {
332 const currentTags = yield* observedTags(recorderArn);
333 const { upsert, removed } = diffTags(currentTags, desiredTags);
334 if (upsert.length > 0) {
335 yield* config.tagResource({
336 ResourceArn: recorderArn,
337 Tags: upsert,
338 });
339 }
340 if (removed.length > 0) {
341 yield* config.untagResource({
342 ResourceArn: recorderArn,
343 TagKeys: removed,
344 });
345 }
346 }
347
348 // 3c. SYNC RECORDING STATE — only when the user declared a desired
349 // state; diff against the OBSERVED status.
350 if (news.recording !== undefined) {
351 const status = yield* config
352 .describeConfigurationRecorderStatus({
353 ConfigurationRecorderNames: [name],
354 })
355 .pipe(
356 Effect.map((r) => (r.ConfigurationRecordersStatus ?? []).at(0)?.recording ?? false),
357 Effect.catchTag("NoSuchConfigurationRecorderException", () =>
358 Effect.succeed(false),
359 ),
360 );
361 if (news.recording && !status) {
362 yield* config.startConfigurationRecorder({
363 ConfigurationRecorderName: name,
364 });
365 } else if (!news.recording && status) {
366 yield* config.stopConfigurationRecorder({
367 ConfigurationRecorderName: name,
368 });
369 }
370 }
371
372 yield* session.note(name);
373 return { recorderName: name, recorderArn: recorderArn! };
374 }),
375 delete: Effect.fn(function* ({ output }) {
376 // A recorder must be stopped before it can be deleted; both calls
377 // treat an already-gone recorder as success.
378 yield* config
379 .stopConfigurationRecorder({
380 ConfigurationRecorderName: output.recorderName,
381 })
382 .pipe(Effect.catchTag("NoSuchConfigurationRecorderException", () => Effect.void));
383 yield* config
384 .deleteConfigurationRecorder({
385 ConfigurationRecorderName: output.recorderName,
386 })
387 .pipe(Effect.catchTag("NoSuchConfigurationRecorderException", () => Effect.void));
388 }),
389 });
390 }),
391 );