@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 650 lines 23.6 KB
Raw
1 import * as cloudtrail from "@distilled.cloud/aws/cloudtrail";
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, 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 /**
13 * A data-event resource selection inside a basic event selector. Mirrors the
14 * CloudTrail `DataResource` wire shape.
15 */
16 export interface TrailDataResource {
17 /** The resource type, e.g. `AWS::S3::Object` or `AWS::Lambda::Function`. */
18 type: string;
19 /** ARNs (or ARN prefixes) of the resources to log data events for. */
20 values?: string[];
21 }
22
23 /**
24 * A basic event selector controlling which management/data events the trail
25 * logs. Mirrors the CloudTrail `EventSelector` wire shape.
26 */
27 export interface TrailEventSelector {
28 /**
29 * Whether to log read-only events, write-only events, or all.
30 * @default "All"
31 */
32 readWriteType?: "ReadOnly" | "WriteOnly" | "All";
33 /**
34 * Whether the selector includes management events.
35 * @default true
36 */
37 includeManagementEvents?: boolean;
38 /** Data-event resources to log (S3 objects, Lambda functions, …). */
39 dataResources?: TrailDataResource[];
40 /**
41 * Management event sources to exclude (`kms.amazonaws.com`,
42 * `rdsdata.amazonaws.com`).
43 */
44 excludeManagementEventSources?: string[];
45 }
46
47 /**
48 * A field selector inside an advanced event selector. Mirrors the CloudTrail
49 * `AdvancedFieldSelector` wire shape.
50 */
51 export interface TrailFieldSelector {
52 /**
53 * The event record field to select on (e.g. `eventCategory`,
54 * `resources.type`).
55 */
56 field: string;
57 /** Exact-match values. */
58 equals?: string[];
59 /** Prefix-match values. */
60 startsWith?: string[];
61 /** Suffix-match values. */
62 endsWith?: string[];
63 /** Exact-mismatch values. */
64 notEquals?: string[];
65 /** Prefix-mismatch values. */
66 notStartsWith?: string[];
67 /** Suffix-mismatch values. */
68 notEndsWith?: string[];
69 }
70
71 /**
72 * An advanced event selector controlling which events the trail logs.
73 * Advanced and basic event selectors are mutually exclusive.
74 */
75 export interface TrailAdvancedEventSelector {
76 /** Descriptive name for the selector. */
77 name?: string;
78 /** Field selectors that events must match to be logged. */
79 fieldSelectors: TrailFieldSelector[];
80 }
81
82 /**
83 * An Insights selector enabling anomaly detection on the trail's events.
84 */
85 export interface TrailInsightSelector {
86 /** The type of Insights to enable. */
87 insightType: "ApiCallRateInsight" | "ApiErrorRateInsight";
88 }
89
90 export interface TrailProps {
91 /**
92 * Name of the trail. Must be 3-128 characters, contain only letters,
93 * numbers, periods, underscores, and dashes, and start and end with a
94 * letter or number.
95 * @default ${app}-${stage}-${id}
96 */
97 trailName?: string;
98 /**
99 * Name of the Amazon S3 bucket designated for publishing log files.
100 * The bucket policy must grant `cloudtrail.amazonaws.com` the
101 * `s3:GetBucketAcl` and `s3:PutObject` permissions, scoped with an
102 * `aws:SourceArn` condition on the trail's ARN.
103 */
104 s3BucketName: string;
105 /**
106 * Amazon S3 key prefix that follows the name of the bucket designated
107 * for log file delivery.
108 */
109 s3KeyPrefix?: string;
110 /**
111 * Whether the trail publishes events from global services such as IAM
112 * to the log files.
113 * @default true
114 */
115 includeGlobalServiceEvents?: boolean;
116 /**
117 * Whether the trail applies to all Regions or only the Region in which
118 * it was created.
119 * @default false
120 */
121 isMultiRegionTrail?: boolean;
122 /**
123 * Whether log file validation (SHA-256 digest files) is enabled.
124 * @default false
125 */
126 enableLogFileValidation?: boolean;
127 /**
128 * ARN of the CloudWatch Logs log group to which CloudTrail delivers
129 * events. Requires `cloudWatchLogsRoleArn`.
130 */
131 cloudWatchLogsLogGroupArn?: string;
132 /**
133 * Role ARN that CloudTrail assumes to write to the CloudWatch Logs
134 * log group. Requires `cloudWatchLogsLogGroupArn`.
135 */
136 cloudWatchLogsRoleArn?: string;
137 /**
138 * KMS key ID (ID, alias, or ARN) used to encrypt the log files
139 * delivered by CloudTrail. Compared verbatim against the observed
140 * trail's key, so prefer the full key ARN to avoid a perpetual diff.
141 */
142 kmsKeyId?: string;
143 /**
144 * Name of the Amazon SNS topic notified of new log file delivery.
145 */
146 snsTopicName?: string;
147 /**
148 * Whether the trail is created for all accounts in an organization,
149 * or only for the current account.
150 * @default false
151 */
152 isOrganizationTrail?: boolean;
153 /**
154 * Whether the trail is actively logging. Synced via `StartLogging` /
155 * `StopLogging`.
156 * @default true
157 */
158 isLogging?: boolean;
159 /**
160 * Basic event selectors, synced via `PutEventSelectors`. Mutually
161 * exclusive with `advancedEventSelectors`. When omitted, the trail's
162 * selectors are left untouched; pass `[]`-free defaults explicitly to
163 * converge them.
164 */
165 eventSelectors?: TrailEventSelector[];
166 /**
167 * Advanced event selectors, synced via `PutEventSelectors`. Mutually
168 * exclusive with `eventSelectors`. When omitted, the trail's selectors
169 * are left untouched.
170 */
171 advancedEventSelectors?: TrailAdvancedEventSelector[];
172 /**
173 * Insights selectors, synced via `PutInsightSelectors`. Pass `[]` to
174 * disable Insights; when omitted, the trail's Insights configuration is
175 * left untouched.
176 */
177 insightSelectors?: TrailInsightSelector[];
178 /**
179 * Tags to apply to the trail. Merged with internal Alchemy tags.
180 */
181 tags?: Record<string, string>;
182 }
183
184 export interface Trail extends Resource<
185 "AWS.CloudTrail.Trail",
186 TrailProps,
187 {
188 /** Physical name of the trail. */
189 trailName: string;
190 /** ARN of the trail. */
191 trailArn: string;
192 /** The region in which the trail was created. */
193 homeRegion: string;
194 /** S3 bucket the trail delivers log files to. */
195 s3BucketName: string;
196 /** Whether the trail is currently logging. */
197 isLogging: boolean;
198 },
199 never,
200 Providers
201 > {}
202
203 /**
204 * An AWS CloudTrail trail that records AWS API activity and delivers log
205 * files to an S3 bucket.
206 *
207 * The destination bucket must carry a bucket policy that allows the
208 * `cloudtrail.amazonaws.com` service principal to call `s3:GetBucketAcl`
209 * on the bucket and `s3:PutObject` under `AWSLogs/{accountId}/*`, both
210 * scoped with an `aws:SourceArn` condition on the trail's ARN.
211 * ### Creating Trails
212 * **Example:** Basic Trail
213 * ```typescript
214 * import * as AWS from "@alchemy.run/aws";
215 *
216 * const bucket = yield* AWS.S3.Bucket("TrailLogs", {
217 * bucketName: `audit-logs-${accountId}`,
218 * forceDestroy: true,
219 * policy: [
220 * {
221 * Effect: "Allow",
222 * Principal: { Service: "cloudtrail.amazonaws.com" },
223 * Action: ["s3:GetBucketAcl"],
224 * Resource: `arn:aws:s3:::audit-logs-${accountId}`,
225 * Condition: { StringEquals: { "aws:SourceArn": trailArn } },
226 * },
227 * {
228 * Effect: "Allow",
229 * Principal: { Service: "cloudtrail.amazonaws.com" },
230 * Action: ["s3:PutObject"],
231 * Resource: `arn:aws:s3:::audit-logs-${accountId}/AWSLogs/${accountId}/*`,
232 * Condition: {
233 * StringEquals: {
234 * "s3:x-amz-acl": "bucket-owner-full-control",
235 * "aws:SourceArn": trailArn,
236 * },
237 * },
238 * },
239 * ],
240 * });
241 *
242 * const trail = yield* AWS.CloudTrail.Trail("Audit", {
243 * trailName: "audit-trail",
244 * s3BucketName: bucket.bucketName,
245 * });
246 * ```
247 *
248 * **Example:** Multi-Region Trail with Log File Validation
249 * ```typescript
250 * const trail = yield* AWS.CloudTrail.Trail("Audit", {
251 * trailName: "org-audit-trail",
252 * s3BucketName: bucket.bucketName,
253 * isMultiRegionTrail: true,
254 * enableLogFileValidation: true,
255 * });
256 * ```
257 *
258 * ### Controlling Logging
259 * **Example:** Pause logging without deleting the trail
260 * ```typescript
261 * const trail = yield* AWS.CloudTrail.Trail("Audit", {
262 * trailName: "audit-trail",
263 * s3BucketName: bucket.bucketName,
264 * isLogging: false,
265 * });
266 * ```
267 *
268 * ### Selecting Events
269 * **Example:** Advanced Event Selectors and Insights
270 * ```typescript
271 * const trail = yield* AWS.CloudTrail.Trail("Audit", {
272 * trailName: "audit-trail",
273 * s3BucketName: bucket.bucketName,
274 * advancedEventSelectors: [
275 * {
276 * name: "Management events only",
277 * fieldSelectors: [
278 * { field: "eventCategory", equals: ["Management"] },
279 * ],
280 * },
281 * ],
282 * insightSelectors: [{ insightType: "ApiCallRateInsight" }],
283 * });
284 * ```
285 *
286 * @resource
287 */
288 export const Trail = Resource<Trail>("AWS.CloudTrail.Trail");
289
290 /**
291 * S3 bucket-policy propagation is eventually consistent: `CreateTrail` /
292 * `UpdateTrail` can transiently reject a bucket whose policy was written
293 * moments earlier with `InsufficientS3BucketPolicyException` (or
294 * `S3BucketDoesNotExistException` right after bucket creation).
295 *
296 * Expressed as an explicitly-typed helper: inlining `Effect.retry` here
297 * leaves `Retry.Return`'s conditional type unresolved in the provider's
298 * inferred layer type, which TypeScript's declaration emit widens to an
299 * `unknown` R — poisoning the whole `AWS.providers()` union for every
300 * downstream consumer.
301 */
302 const retryThroughBucketPropagation = <A, E extends { _tag: string }, R>(
303 self: Effect.Effect<A, E, R>,
304 ): Effect.Effect<A, E, R> =>
305 Effect.retry(self, {
306 while: (e) =>
307 e._tag === "InsufficientS3BucketPolicyException" ||
308 e._tag === "S3BucketDoesNotExistException" ||
309 e._tag === "ConflictException",
310 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
311 });
312
313 /**
314 * Trail deletion right after a Start/StopLogging call (or another
315 * concurrent mutation) can raise a transient `ConflictException`.
316 */
317 const retryWhileConflict = <A, E extends { _tag: string }, R>(
318 self: Effect.Effect<A, E, R>,
319 ): Effect.Effect<A, E, R> =>
320 Effect.retry(self, {
321 while: (e) => e._tag === "ConflictException",
322 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
323 });
324
325 const toWireEventSelectors = (selectors: TrailEventSelector[]): cloudtrail.EventSelector[] =>
326 selectors.map((s) => ({
327 ReadWriteType: s.readWriteType,
328 IncludeManagementEvents: s.includeManagementEvents,
329 DataResources: s.dataResources?.map((r) => ({
330 Type: r.type,
331 Values: r.values,
332 })),
333 ExcludeManagementEventSources: s.excludeManagementEventSources,
334 }));
335
336 const toWireAdvancedSelectors = (
337 selectors: TrailAdvancedEventSelector[],
338 ): cloudtrail.AdvancedEventSelector[] =>
339 selectors.map((s) => ({
340 Name: s.name,
341 FieldSelectors: s.fieldSelectors.map((f) => ({
342 Field: f.field,
343 Equals: f.equals,
344 StartsWith: f.startsWith,
345 EndsWith: f.endsWith,
346 NotEquals: f.notEquals,
347 NotStartsWith: f.notStartsWith,
348 NotEndsWith: f.notEndsWith,
349 })),
350 }));
351
352 export const TrailProvider = () =>
353 Provider.effect(
354 Trail,
355 Effect.gen(function* () {
356 const createTrailName = Effect.fn(function* (
357 id: string,
358 props: { trailName?: string | undefined },
359 ) {
360 if (props.trailName) {
361 return props.trailName;
362 }
363 return yield* createPhysicalName({ id, maxLength: 128 });
364 });
365
366 const fetchObservedTags = (trailArn: string) =>
367 cloudtrail.listTags({ ResourceIdList: [trailArn] }).pipe(
368 Effect.map((r) => {
369 const tags: Record<string, string> = {};
370 for (const t of r.ResourceTagList?.[0]?.TagsList ?? []) {
371 tags[t.Key] = t.Value ?? "";
372 }
373 return tags;
374 }),
375 Effect.orElseSucceed(() => ({}) as Record<string, string>),
376 );
377
378 const readTrail = (name: string) =>
379 cloudtrail.getTrail({ Name: name }).pipe(
380 Effect.map((r) => r.Trail),
381 Effect.catchTag("TrailNotFoundException", () => Effect.undefined),
382 );
383
384 const toAttributes = Effect.fn(function* (trail: cloudtrail.Trail) {
385 const name = trail.Name!;
386 const isLogging = yield* cloudtrail.getTrailStatus({ Name: trail.TrailARN ?? name }).pipe(
387 Effect.map((s) => s.IsLogging ?? false),
388 Effect.catchTag("TrailNotFoundException", () => Effect.succeed(false)),
389 );
390 return {
391 trailName: name,
392 trailArn: trail.TrailARN!,
393 homeRegion: trail.HomeRegion!,
394 s3BucketName: trail.S3BucketName!,
395 isLogging,
396 };
397 });
398
399 return Trail.Provider.of({
400 stables: ["trailName", "trailArn", "homeRegion"],
401 list: () =>
402 Effect.gen(function* () {
403 const trails = yield* cloudtrail
404 .describeTrails({ includeShadowTrails: false })
405 .pipe(Effect.map((r) => r.trailList ?? []));
406 return yield* Effect.forEach(
407 trails.filter((t) => t.Name !== undefined && t.TrailARN !== undefined),
408 (t) => toAttributes(t),
409 { concurrency: 5 },
410 );
411 }),
412 read: Effect.fn(function* ({ id, olds, output }) {
413 const name = output?.trailName ?? (yield* createTrailName(id, olds ?? {}));
414 const trail = yield* readTrail(name);
415 if (trail === undefined) return undefined;
416 const attrs = yield* toAttributes(trail);
417 const tags = yield* fetchObservedTags(attrs.trailArn);
418 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
419 }),
420 diff: Effect.fn(function* ({ id, news, olds }) {
421 if (!isResolved(news)) return undefined;
422 const oldName = yield* createTrailName(id, olds ?? {});
423 const newName = yield* createTrailName(id, news);
424 if (oldName !== newName) {
425 return { action: "replace" } as const;
426 }
427 // Everything else is mutable via UpdateTrail / Start/StopLogging.
428 }),
429 reconcile: Effect.fn(function* ({ id, news, output, session }) {
430 const name = output?.trailName ?? (yield* createTrailName(id, news));
431 const internalTags = yield* createInternalTags(id);
432
433 // Desired settings, with AWS defaults made explicit so removing a
434 // prop converges back to the default.
435 const desired = {
436 S3BucketName: news.s3BucketName,
437 S3KeyPrefix: news.s3KeyPrefix,
438 IncludeGlobalServiceEvents: news.includeGlobalServiceEvents ?? true,
439 IsMultiRegionTrail: news.isMultiRegionTrail ?? false,
440 EnableLogFileValidation: news.enableLogFileValidation ?? false,
441 CloudWatchLogsLogGroupArn: news.cloudWatchLogsLogGroupArn,
442 CloudWatchLogsRoleArn: news.cloudWatchLogsRoleArn,
443 KmsKeyId: news.kmsKeyId,
444 SnsTopicName: news.snsTopicName,
445 IsOrganizationTrail: news.isOrganizationTrail ?? false,
446 };
447
448 // 1. OBSERVE — cloud state is authoritative.
449 let trail = yield* readTrail(name);
450
451 // 2. ENSURE — create if missing; tolerate the AlreadyExists race.
452 if (trail === undefined) {
453 yield* session.note(`Creating CloudTrail trail ${name}`);
454 yield* retryThroughBucketPropagation(
455 cloudtrail.createTrail({
456 Name: name,
457 ...desired,
458 TagsList: Object.entries({
459 ...news.tags,
460 ...internalTags,
461 }).map(([Key, Value]) => ({ Key, Value })),
462 }),
463 ).pipe(Effect.catchTag("TrailAlreadyExistsException", () => Effect.void));
464 trail = yield* readTrail(name);
465 }
466 if (trail === undefined) {
467 // The trail vanished between create and re-read — surface the
468 // typed not-found from a direct get instead of inventing one.
469 trail = (yield* cloudtrail.getTrail({ Name: name })).Trail!;
470 }
471
472 // 3. SYNC settings — diff observed against desired, push only the
473 // fields that actually changed (UpdateTrail leaves omitted fields
474 // untouched, except booleans which we always pin to desired).
475 const settingsDelta: Partial<Omit<cloudtrail.UpdateTrailRequest, "Name">> = {};
476 if (trail.S3BucketName !== desired.S3BucketName) {
477 settingsDelta.S3BucketName = desired.S3BucketName;
478 }
479 if ((trail.S3KeyPrefix ?? "") !== (desired.S3KeyPrefix ?? "")) {
480 settingsDelta.S3KeyPrefix = desired.S3KeyPrefix ?? "";
481 }
482 if ((trail.IncludeGlobalServiceEvents ?? true) !== desired.IncludeGlobalServiceEvents) {
483 settingsDelta.IncludeGlobalServiceEvents = desired.IncludeGlobalServiceEvents;
484 }
485 if ((trail.IsMultiRegionTrail ?? false) !== desired.IsMultiRegionTrail) {
486 settingsDelta.IsMultiRegionTrail = desired.IsMultiRegionTrail;
487 }
488 if ((trail.LogFileValidationEnabled ?? false) !== desired.EnableLogFileValidation) {
489 settingsDelta.EnableLogFileValidation = desired.EnableLogFileValidation;
490 }
491 if (
492 desired.CloudWatchLogsLogGroupArn !== undefined &&
493 trail.CloudWatchLogsLogGroupArn !== desired.CloudWatchLogsLogGroupArn
494 ) {
495 settingsDelta.CloudWatchLogsLogGroupArn = desired.CloudWatchLogsLogGroupArn;
496 settingsDelta.CloudWatchLogsRoleArn = desired.CloudWatchLogsRoleArn;
497 }
498 if (desired.KmsKeyId !== undefined && trail.KmsKeyId !== desired.KmsKeyId) {
499 settingsDelta.KmsKeyId = desired.KmsKeyId;
500 }
501 if ((trail.IsOrganizationTrail ?? false) !== desired.IsOrganizationTrail) {
502 settingsDelta.IsOrganizationTrail = desired.IsOrganizationTrail;
503 }
504 if (desired.SnsTopicName !== undefined && trail.SnsTopicName !== desired.SnsTopicName) {
505 settingsDelta.SnsTopicName = desired.SnsTopicName;
506 }
507 if (Object.keys(settingsDelta).length > 0) {
508 yield* session.note(
509 `Updating trail settings: ${Object.keys(settingsDelta).join(", ")}`,
510 );
511 yield* retryThroughBucketPropagation(
512 cloudtrail.updateTrail({ Name: name, ...settingsDelta }),
513 );
514 trail = (yield* cloudtrail.getTrail({ Name: name })).Trail ?? trail;
515 }
516
517 const trailArn = trail.TrailARN!;
518
519 // 3b. SYNC logging state via Start/StopLogging.
520 const desiredLogging = news.isLogging ?? true;
521 const observedLogging = yield* cloudtrail
522 .getTrailStatus({ Name: trailArn })
523 .pipe(Effect.map((s) => s.IsLogging ?? false));
524 if (observedLogging !== desiredLogging) {
525 if (desiredLogging) {
526 yield* session.note(`Starting logging for trail ${name}`);
527 yield* retryWhileConflict(cloudtrail.startLogging({ Name: trailArn }));
528 } else {
529 yield* session.note(`Stopping logging for trail ${name}`);
530 yield* retryWhileConflict(cloudtrail.stopLogging({ Name: trailArn }));
531 }
532 }
533
534 // 3c. SYNC event selectors — only when declared (undefined leaves
535 // the trail's selectors untouched). Basic and advanced selectors
536 // are mutually exclusive in the API; observed cloud selectors are
537 // the diff baseline.
538 if (news.eventSelectors !== undefined || news.advancedEventSelectors !== undefined) {
539 const observedSelectors = yield* cloudtrail.getEventSelectors({
540 TrailName: trailArn,
541 });
542 if (news.advancedEventSelectors !== undefined) {
543 const desiredAdvanced = toWireAdvancedSelectors(news.advancedEventSelectors);
544 if (
545 JSON.stringify(observedSelectors.AdvancedEventSelectors ?? []) !==
546 JSON.stringify(desiredAdvanced)
547 ) {
548 yield* session.note(`Updating advanced event selectors`);
549 yield* retryWhileConflict(
550 cloudtrail.putEventSelectors({
551 TrailName: trailArn,
552 AdvancedEventSelectors: desiredAdvanced,
553 }),
554 );
555 }
556 } else {
557 const desiredBasic = toWireEventSelectors(news.eventSelectors!);
558 if (
559 JSON.stringify(observedSelectors.EventSelectors ?? []) !==
560 JSON.stringify(desiredBasic)
561 ) {
562 yield* session.note(`Updating event selectors`);
563 yield* retryWhileConflict(
564 cloudtrail.putEventSelectors({
565 TrailName: trailArn,
566 EventSelectors: desiredBasic,
567 }),
568 );
569 }
570 }
571 }
572
573 // 3d. SYNC Insights selectors — only when declared. `[]` disables
574 // Insights; a trail with Insights disabled reads as [] (the typed
575 // InsightNotEnabledException).
576 if (news.insightSelectors !== undefined) {
577 const observedInsights = yield* cloudtrail
578 .getInsightSelectors({ TrailName: trailArn })
579 .pipe(
580 Effect.map((r) => r.InsightSelectors ?? []),
581 Effect.catchTag("InsightNotEnabledException", () =>
582 Effect.succeed([] as cloudtrail.InsightSelector[]),
583 ),
584 );
585 const desiredInsights = news.insightSelectors.map((s) => ({
586 InsightType: s.insightType,
587 }));
588 if (
589 JSON.stringify(
590 observedInsights
591 .map((s) => s.InsightType)
592 .sort((a, b) => ((a ?? "") < (b ?? "") ? -1 : (a ?? "") > (b ?? "") ? 1 : 0)),
593 ) !==
594 JSON.stringify(
595 desiredInsights
596 .map((s) => s.InsightType)
597 .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)),
598 )
599 ) {
600 yield* session.note(`Updating Insights selectors`);
601 yield* retryWhileConflict(
602 cloudtrail.putInsightSelectors({
603 TrailName: trailArn,
604 InsightSelectors: desiredInsights,
605 }),
606 );
607 }
608 }
609
610 // 3e. SYNC tags against OBSERVED cloud tags (adoption-safe).
611 const observedTags = yield* fetchObservedTags(trailArn);
612 const { upsert, removed } = diffTags(observedTags, {
613 ...news.tags,
614 ...internalTags,
615 });
616 if (upsert.length > 0) {
617 yield* cloudtrail.addTags({
618 ResourceId: trailArn,
619 TagsList: upsert.map((t) => ({ Key: t.Key, Value: t.Value })),
620 });
621 }
622 if (removed.length > 0) {
623 yield* cloudtrail.removeTags({
624 ResourceId: trailArn,
625 TagsList: removed.map((Key) => ({ Key })),
626 });
627 }
628
629 yield* session.note(trailArn);
630 return {
631 trailName: name,
632 trailArn,
633 homeRegion: trail.HomeRegion!,
634 s3BucketName: trail.S3BucketName!,
635 isLogging: desiredLogging,
636 };
637 }),
638 delete: Effect.fn(function* ({ output }) {
639 yield* retryWhileConflict(cloudtrail.deleteTrail({ Name: output.trailArn })).pipe(
640 Effect.catchTags({
641 TrailNotFoundException: () => Effect.void,
642 // A stale ARN whose trail is already gone can also surface as an
643 // invalid-ARN complaint; both mean "nothing left to delete".
644 CloudTrailARNInvalidException: () => Effect.void,
645 }),
646 );
647 }),
648 });
649 }),
650 );