@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, 06:00 UTC

main
ts 482 lines 18.7 KB
Raw
1 import * as aiops from "@distilled.cloud/aws/aiops";
2 import { unownedUnlessPrevious } 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, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import { toWireDays } from "alchemy/Util/Duration";
9 import type * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import type { PolicyStatement } from "../IAM/Policy.ts";
14 import type { Providers } from "../Providers.ts";
15
16 export interface InvestigationGroupEncryptionConfiguration {
17 /**
18 * How investigation data is encrypted — `"AWS_OWNED_KEY"` (the default,
19 * an AWS owned key) or `"CUSTOMER_MANAGED_KMS_KEY"`.
20 * @default "AWS_OWNED_KEY"
21 */
22 type?: aiops.EncryptionConfigurationType;
23 /**
24 * ID or ARN of the customer managed KMS key to encrypt investigation data
25 * with. Required when `type` is `"CUSTOMER_MANAGED_KMS_KEY"`.
26 */
27 kmsKeyId?: string;
28 }
29
30 export interface InvestigationGroupCrossAccountConfiguration {
31 /**
32 * ARN of an IAM role in a source account that CloudWatch investigations
33 * assumes to retrieve telemetry during cross-account investigations.
34 */
35 sourceRoleArn: string;
36 }
37
38 export interface InvestigationGroupProps {
39 /**
40 * Name of the investigation group. If omitted, a deterministic physical
41 * name is generated from the app, stage, and logical ID.
42 *
43 * Changing the name replaces the investigation group.
44 * @default ${app}-${stage}-${id}
45 */
46 name?: string;
47 /**
48 * ARN of the IAM role that CloudWatch investigations assumes to access
49 * telemetry (CloudWatch, X-Ray, CloudTrail, ...) during investigations.
50 * The role's trust policy must allow the `aiops.amazonaws.com` service
51 * principal to assume it.
52 */
53 roleArn: string;
54 /**
55 * How long investigations and their data are retained (e.g. `"7 days"`
56 * or `Duration.days(7)`). Rounded to whole days on the wire
57 * (`retentionInDays`).
58 * The retention period cannot be updated in place — changing it replaces
59 * the investigation group.
60 * @default 90 days
61 */
62 retention?: Duration.Input;
63 /**
64 * Encryption configuration for investigation data. Omit to use an AWS
65 * owned key.
66 * @default AWS owned key
67 */
68 encryptionConfiguration?: InvestigationGroupEncryptionConfiguration;
69 /**
70 * Tag keys whose values CloudWatch investigations uses as boundaries to
71 * narrow the search for related telemetry (useful when resource names
72 * repeat across applications).
73 */
74 tagKeyBoundaries?: string[];
75 /**
76 * Map of Amazon Q Developer in chat applications configuration ARNs to
77 * SNS topic ARNs, used to send investigation updates to chat channels.
78 */
79 chatbotNotificationChannel?: Record<string, string[]>;
80 /**
81 * Whether investigations can query CloudTrail event history for the past
82 * seven days of events.
83 * @default true
84 */
85 isCloudTrailEventHistoryEnabled?: boolean;
86 /**
87 * Source-account role configurations for cross-account investigations.
88 */
89 crossAccountConfigurations?: InvestigationGroupCrossAccountConfiguration[];
90 /**
91 * IAM resource-policy statements attached to the investigation group,
92 * granting other principals or AWS services (for example
93 * `aiops.alarms.cloudwatch.amazonaws.com`, so CloudWatch alarms can start
94 * investigations) access to it. Serialized as a `2012-10-17` policy
95 * document via `PutInvestigationGroupPolicy`.
96 *
97 * Omit to leave any existing policy unmanaged; pass `[]` to delete a
98 * previously attached policy.
99 */
100 policy?: PolicyStatement[];
101 /**
102 * Tags to apply to the investigation group. Merged with internal Alchemy
103 * tags.
104 */
105 tags?: Record<string, string>;
106 }
107
108 export interface InvestigationGroup extends Resource<
109 "AWS.AIOps.InvestigationGroup",
110 InvestigationGroupProps,
111 {
112 /** Name of the investigation group. */
113 name: string;
114 /** ARN of the investigation group. */
115 arn: string;
116 /** ARN of the IAM role investigations assume to access telemetry. */
117 roleArn: string | undefined;
118 /**
119 * How long investigations and their data are retained, in whole days
120 * (the AWS wire unit for the `retention` prop).
121 */
122 retentionInDays: number | undefined;
123 },
124 never,
125 Providers
126 > {}
127
128 /**
129 * A CloudWatch investigations *investigation group* — the one-time,
130 * per-Region container that configures who can run AI-assisted operational
131 * investigations, which IAM role is used to access telemetry, how long
132 * investigation data is retained, and how it is encrypted.
133 *
134 * You can have at most one investigation group per Region in an account, so
135 * replacements are performed delete-first.
136 * ### Creating an Investigation Group
137 * **Example:** Basic Investigation Group
138 * ```typescript
139 * import * as AIOps from "@alchemy.run/aws/AIOps";
140 * import * as IAM from "@alchemy.run/aws/IAM";
141 *
142 * const role = yield* IAM.Role("InvestigationsRole", {
143 * assumeRolePolicyDocument: {
144 * Version: "2012-10-17",
145 * Statement: [{
146 * Effect: "Allow",
147 * Principal: { Service: "aiops.amazonaws.com" },
148 * Action: ["sts:AssumeRole"],
149 * }],
150 * },
151 * managedPolicyArns: ["arn:aws:iam::aws:policy/AIOpsAssistantPolicy"],
152 * });
153 *
154 * const group = yield* AIOps.InvestigationGroup("Investigations", {
155 * roleArn: role.roleArn,
156 * });
157 * ```
158 *
159 * **Example:** Short Retention and Tag Boundaries
160 * ```typescript
161 * const group = yield* AIOps.InvestigationGroup("Investigations", {
162 * roleArn: role.roleArn,
163 * retention: "7 days",
164 * tagKeyBoundaries: ["Application"],
165 * tags: { Environment: "test" },
166 * });
167 * ```
168 *
169 * ### Resource Policy
170 * **Example:** Let CloudWatch Alarms Start Investigations
171 * ```typescript
172 * const group = yield* AIOps.InvestigationGroup("Investigations", {
173 * roleArn: role.roleArn,
174 * policy: [{
175 * Effect: "Allow",
176 * Principal: { Service: "aiops.alarms.cloudwatch.amazonaws.com" },
177 * Action: ["aiops:CreateInvestigation", "aiops:CreateInvestigationEvent"],
178 * Resource: "*",
179 * Condition: {
180 * StringEquals: { "aws:SourceAccount": "111122223333" },
181 * ArnLike: { "aws:SourceArn": "arn:aws:cloudwatch:us-east-1:111122223333:alarm:*" },
182 * },
183 * }],
184 * });
185 * ```
186 *
187 * @resource
188 */
189 export const InvestigationGroup = Resource<InvestigationGroup>("AWS.AIOps.InvestigationGroup");
190
191 /**
192 * Bounded retry for `createInvestigationGroup` while the freshly created IAM
193 * role propagates — AIOps validates that it can assume the role at create
194 * time, which surfaces as a ValidationException/AccessDeniedException that
195 * mentions the role for the first seconds of the role's life.
196 *
197 * Explicitly annotated so the conditional `Retry.Return` type never leaks
198 * into declaration emit (it would widen `AWS.providers()` for consumers).
199 */
200 const retryWhileRolePropagates = <A, R>(
201 self: Effect.Effect<A, aiops.CreateInvestigationGroupError, R>,
202 ): Effect.Effect<A, aiops.CreateInvestigationGroupError, R> =>
203 Effect.retry(self, {
204 while: (e) =>
205 (e._tag === "ValidationException" || e._tag === "AccessDeniedException") &&
206 /role/i.test(e.message ?? ""),
207 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(8)]),
208 });
209
210 const sameStringArray = (l: readonly string[], r: readonly string[]) =>
211 l.length === r.length && l.every((v, i) => v === r[i]);
212
213 export const InvestigationGroupProvider = () =>
214 Provider.effect(
215 InvestigationGroup,
216 Effect.gen(function* () {
217 const createName = Effect.fn(function* (
218 id: string,
219 props: Pick<InvestigationGroupProps, "name">,
220 ) {
221 return props.name ?? (yield* createPhysicalName({ id, maxLength: 64 }));
222 });
223
224 const observeByArn = (arn: string) =>
225 aiops
226 .getInvestigationGroup({ identifier: arn })
227 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
228
229 // At most one investigation group exists per Region, so scanning the
230 // list for our name is a single cheap call.
231 const findArnByName = (name: string) =>
232 aiops.listInvestigationGroups.items({}).pipe(
233 Stream.runCollect,
234 Effect.map((items) => Array.from(items).find((g) => g.name === name)?.arn),
235 );
236
237 const observe = Effect.fn(function* (name: string, arnHint: string | undefined) {
238 if (arnHint !== undefined) {
239 const found = yield* observeByArn(arnHint);
240 if (found !== undefined) return found;
241 }
242 const arn = yield* findArnByName(name);
243 return arn === undefined ? undefined : yield* observeByArn(arn);
244 });
245
246 const observedTags = (arn: string) =>
247 aiops.listTagsForResource({ resourceArn: arn }).pipe(
248 Effect.map((r) => {
249 const tags: Record<string, string> = {};
250 for (const [key, value] of Object.entries(r.tags ?? {})) {
251 if (value !== undefined) tags[key] = value;
252 }
253 return tags;
254 }),
255 Effect.catchTag("ResourceNotFoundException", () =>
256 Effect.succeed({} as Record<string, string>),
257 ),
258 );
259
260 const toAttributes = (live: aiops.GetInvestigationGroupResponse) => ({
261 name: live.name!,
262 arn: live.arn!,
263 roleArn: live.roleArn,
264 retentionInDays: live.retentionInDays,
265 });
266
267 return InvestigationGroup.Provider.of({
268 stables: ["name", "arn"],
269 list: () =>
270 Effect.gen(function* () {
271 const items = yield* aiops.listInvestigationGroups.items({}).pipe(Stream.runCollect);
272 const groups: {
273 name: string;
274 arn: string;
275 roleArn: string | undefined;
276 retentionInDays: number | undefined;
277 }[] = [];
278 for (const item of Array.from(items)) {
279 if (item.arn === undefined) continue;
280 const live = yield* observeByArn(item.arn);
281 if (live?.arn !== undefined && live.name !== undefined) {
282 groups.push(toAttributes(live));
283 }
284 }
285 return groups;
286 }),
287 read: Effect.fn(function* ({ id, olds, output, previous }) {
288 const name = output?.name ?? (yield* createName(id, olds ?? {}));
289 const live = yield* observe(name, output?.arn);
290 if (live?.arn === undefined || live.name === undefined) {
291 return undefined;
292 }
293 const attrs = toAttributes(live);
294 const tags = yield* observedTags(live.arn);
295 return (yield* hasAlchemyTags(id, tags))
296 ? attrs
297 : unownedUnlessPrevious(attrs, previous, "name");
298 }),
299 diff: Effect.fn(function* ({ id, news, olds }) {
300 if (!isResolved(news)) return undefined;
301 const oldName = yield* createName(id, olds ?? {});
302 const newName = yield* createName(id, news ?? {});
303 // Only one investigation group may exist per Region, so a
304 // replacement must delete the old group before creating the new.
305 if (oldName !== newName) {
306 return { action: "replace", deleteFirst: true } as const;
307 }
308 // The retention period has no update API — replace to change it.
309 if (toWireDays(olds?.retention) !== toWireDays(news?.retention)) {
310 return { action: "replace", deleteFirst: true } as const;
311 }
312 // fall through: engine default update logic for mutable fields
313 }),
314 reconcile: Effect.fn(function* ({ id, news, output, session }) {
315 const name = output?.name ?? (yield* createName(id, news));
316 const internalTags = yield* createInternalTags(id);
317 const desiredTags = { ...news.tags, ...internalTags };
318
319 // 1. OBSERVE — cloud state is authoritative; output.arn is only a
320 // cache of the identifier.
321 let live = yield* observe(name, output?.arn);
322
323 // 2. ENSURE — create when missing. A ConflictException here means
324 // a concurrent create raced us (one group per Region): if a
325 // group with OUR name now exists we converge on it, otherwise
326 // the conflict is a real error (a foreign group occupies the
327 // Region's single slot) and is propagated.
328 if (live === undefined) {
329 live = yield* aiops
330 .createInvestigationGroup({
331 name,
332 roleArn: news.roleArn,
333 retentionInDays: toWireDays(news.retention),
334 encryptionConfiguration: news.encryptionConfiguration,
335 tagKeyBoundaries: news.tagKeyBoundaries,
336 chatbotNotificationChannel: news.chatbotNotificationChannel,
337 isCloudTrailEventHistoryEnabled: news.isCloudTrailEventHistoryEnabled,
338 crossAccountConfigurations: news.crossAccountConfigurations,
339 tags: desiredTags,
340 })
341 .pipe(
342 retryWhileRolePropagates,
343 Effect.flatMap((created) =>
344 created.arn === undefined ? observe(name, undefined) : observeByArn(created.arn),
345 ),
346 Effect.catchTag("ConflictException", (error) =>
347 observe(name, undefined).pipe(
348 Effect.flatMap((existing) =>
349 existing === undefined ? Effect.fail(error) : Effect.succeed(existing),
350 ),
351 ),
352 ),
353 );
354 }
355
356 const arn = live?.arn ?? output?.arn;
357
358 // 3. SYNC — diff each OBSERVED mutable aspect against the desired
359 // state and PATCH only on drift. Aspects the user leaves
360 // undefined are unmanaged (left as observed).
361 if (live !== undefined && arn !== undefined) {
362 const update: Omit<aiops.UpdateInvestigationGroupRequest, "identifier"> = {};
363 if (live.roleArn !== news.roleArn) {
364 update.roleArn = news.roleArn;
365 }
366 if (
367 news.encryptionConfiguration !== undefined &&
368 ((live.encryptionConfiguration?.type ?? "AWS_OWNED_KEY") !==
369 (news.encryptionConfiguration.type ?? "AWS_OWNED_KEY") ||
370 live.encryptionConfiguration?.kmsKeyId !== news.encryptionConfiguration.kmsKeyId)
371 ) {
372 update.encryptionConfiguration = news.encryptionConfiguration;
373 }
374 if (
375 news.tagKeyBoundaries !== undefined &&
376 !sameStringArray(live.tagKeyBoundaries ?? [], news.tagKeyBoundaries)
377 ) {
378 update.tagKeyBoundaries = news.tagKeyBoundaries;
379 }
380 if (
381 news.isCloudTrailEventHistoryEnabled !== undefined &&
382 live.isCloudTrailEventHistoryEnabled !== news.isCloudTrailEventHistoryEnabled
383 ) {
384 update.isCloudTrailEventHistoryEnabled = news.isCloudTrailEventHistoryEnabled;
385 }
386 if (
387 news.chatbotNotificationChannel !== undefined &&
388 JSON.stringify(live.chatbotNotificationChannel ?? {}) !==
389 JSON.stringify(news.chatbotNotificationChannel)
390 ) {
391 update.chatbotNotificationChannel = news.chatbotNotificationChannel;
392 }
393 if (
394 news.crossAccountConfigurations !== undefined &&
395 JSON.stringify(live.crossAccountConfigurations ?? []) !==
396 JSON.stringify(news.crossAccountConfigurations)
397 ) {
398 update.crossAccountConfigurations = news.crossAccountConfigurations;
399 }
400 if (Object.keys(update).length > 0) {
401 yield* aiops.updateInvestigationGroup({
402 identifier: arn,
403 ...update,
404 });
405 live = (yield* observeByArn(arn)) ?? live;
406 }
407 }
408
409 // 3b. SYNC POLICY — diff the OBSERVED resource policy against the
410 // desired policy document and put/delete only on drift.
411 // `policy: undefined` leaves any existing policy unmanaged;
412 // `policy: []` deletes it.
413 if (arn !== undefined && news.policy !== undefined) {
414 const observedPolicy = yield* aiops
415 .getInvestigationGroupPolicy({ identifier: arn })
416 .pipe(
417 Effect.map((r) => r.policy),
418 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
419 );
420 if (news.policy.length === 0) {
421 if (observedPolicy !== undefined) {
422 yield* aiops
423 .deleteInvestigationGroupPolicy({ identifier: arn })
424 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
425 }
426 } else {
427 const desiredPolicy = JSON.stringify({
428 Version: "2012-10-17",
429 Statement: news.policy,
430 });
431 const inSync = yield* Effect.sync(() => {
432 if (observedPolicy === undefined) return false;
433 try {
434 return JSON.stringify(JSON.parse(observedPolicy)) === desiredPolicy;
435 } catch {
436 return false;
437 }
438 });
439 if (!inSync) {
440 yield* aiops.putInvestigationGroupPolicy({
441 identifier: arn,
442 policy: desiredPolicy,
443 });
444 }
445 }
446 }
447
448 // 3c. SYNC TAGS — diff against OBSERVED cloud tags so adoption
449 // converges (create-time tags only apply on first create).
450 if (arn !== undefined) {
451 const currentTags = yield* observedTags(arn);
452 const { upsert, removed } = diffTags(currentTags, desiredTags);
453 if (upsert.length > 0) {
454 yield* aiops.tagResource({
455 resourceArn: arn,
456 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
457 });
458 }
459 if (removed.length > 0) {
460 yield* aiops.untagResource({
461 resourceArn: arn,
462 tagKeys: removed,
463 });
464 }
465 }
466
467 yield* session.note(name);
468 return {
469 name: live?.name ?? name,
470 arn: arn!,
471 roleArn: live?.roleArn ?? news.roleArn,
472 retentionInDays: live?.retentionInDays ?? toWireDays(news.retention),
473 };
474 }),
475 delete: Effect.fn(function* ({ output }) {
476 yield* aiops
477 .deleteInvestigationGroup({ identifier: output.arn })
478 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
479 }),
480 });
481 }),
482 );