The best way to control Claude Code, Codex and more from any computer or phone

main
ts 520 lines 19.1 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 { 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 { Providers } from "../Providers.ts";
14
15 /**
16 * A field selector inside an advanced event selector. Mirrors the
17 * CloudTrail `AdvancedFieldSelector` wire shape.
18 */
19 export interface EventDataStoreFieldSelector {
20 /**
21 * The event record field to select on (e.g. `eventCategory`,
22 * `resources.type`).
23 */
24 field: string;
25 /** Exact-match values. */
26 equals?: string[];
27 /** Prefix-match values. */
28 startsWith?: string[];
29 /** Suffix-match values. */
30 endsWith?: string[];
31 /** Exact-mismatch values. */
32 notEquals?: string[];
33 /** Prefix-mismatch values. */
34 notStartsWith?: string[];
35 /** Suffix-mismatch values. */
36 notEndsWith?: string[];
37 }
38
39 /**
40 * An advanced event selector controlling which events the event data
41 * store collects.
42 */
43 export interface EventDataStoreEventSelector {
44 /** Descriptive name for the selector. */
45 name?: string;
46 /** Field selectors that events must match to be collected. */
47 fieldSelectors: EventDataStoreFieldSelector[];
48 }
49
50 export interface EventDataStoreProps {
51 /**
52 * Name of the event data store. Must be 3-128 characters, contain only
53 * letters, numbers, periods, underscores, and dashes, and start and end
54 * with a letter or number. Renaming updates the store in place (the ARN
55 * is the stable identity).
56 * @default ${app}-${stage}-${id}
57 */
58 name?: string;
59 /**
60 * Advanced event selectors controlling which events are collected.
61 * @default management events
62 */
63 advancedEventSelectors?: EventDataStoreEventSelector[];
64 /**
65 * Whether the event data store collects events from all Regions or
66 * only the current Region.
67 * @default true
68 */
69 multiRegionEnabled?: boolean;
70 /**
71 * Whether the event data store collects events for all accounts in an
72 * organization.
73 * @default false
74 */
75 organizationEnabled?: boolean;
76 /**
77 * Retention period, e.g. `"30 days"` or `Duration.days(30)` (minimum
78 * 7 days; maximum 2557 days under `EXTENDABLE_RETENTION_PRICING`,
79 * 3653 days under `FIXED_RETENTION_PRICING`). Rounded to whole days
80 * on the wire.
81 * @default 366 days
82 */
83 retentionPeriod?: Duration.Input;
84 /**
85 * Whether termination protection is enabled. A protected store cannot
86 * be deleted until protection is disabled.
87 * @default true (AWS default)
88 */
89 terminationProtectionEnabled?: boolean;
90 /**
91 * The billing mode for the event data store.
92 * @default "EXTENDABLE_RETENTION_PRICING"
93 */
94 billingMode?: "EXTENDABLE_RETENTION_PRICING" | "FIXED_RETENTION_PRICING";
95 /**
96 * KMS key ID (ID, alias, or ARN) used to encrypt the events delivered
97 * to the event data store.
98 */
99 kmsKeyId?: string;
100 /**
101 * Whether the event data store ingests live events. Synced via
102 * `StartEventDataStoreIngestion` / `StopEventDataStoreIngestion`; a
103 * stopped store keeps its collected events queryable.
104 * @default true (AWS default)
105 */
106 ingestionEnabled?: boolean;
107 /**
108 * Tags to apply to the event data store. Merged with internal Alchemy
109 * tags.
110 */
111 tags?: Record<string, string>;
112 }
113
114 export interface EventDataStore extends Resource<
115 "AWS.CloudTrail.EventDataStore",
116 EventDataStoreProps,
117 {
118 /** ARN of the event data store (its stable identity). */
119 eventDataStoreArn: string;
120 /** Name of the event data store. */
121 name: string;
122 /** Current status (e.g. `ENABLED`, `STARTING_INGESTION`). */
123 status: string;
124 },
125 never,
126 Providers
127 > {}
128
129 /**
130 * A CloudTrail Lake event data store — an immutable collection of events
131 * that can be queried with SQL via CloudTrail Lake.
132 *
133 * Deleting an event data store schedules it for deletion
134 * (`PENDING_DELETION`); AWS purges it after a seven-day wait period during
135 * which it incurs no cost. If a store with the same name is still pending
136 * deletion, the reconciler restores it instead of creating a duplicate.
137 * ### Creating Event Data Stores
138 * **Example:** Basic Event Data Store
139 * ```typescript
140 * import * as AWS from "@alchemy.run/aws";
141 *
142 * const store = yield* AWS.CloudTrail.EventDataStore("Lake", {
143 * retentionPeriod: "7 days",
144 * terminationProtectionEnabled: false,
145 * });
146 * ```
147 *
148 * **Example:** Single-Region Store with Custom Selectors
149 * ```typescript
150 * const store = yield* AWS.CloudTrail.EventDataStore("S3DataEvents", {
151 * multiRegionEnabled: false,
152 * retentionPeriod: "30 days",
153 * terminationProtectionEnabled: false,
154 * advancedEventSelectors: [
155 * {
156 * name: "S3 data events",
157 * fieldSelectors: [
158 * { field: "eventCategory", equals: ["Data"] },
159 * { field: "resources.type", equals: ["AWS::S3::Object"] },
160 * ],
161 * },
162 * ],
163 * });
164 * ```
165 *
166 * @resource
167 */
168 export const EventDataStore = Resource<EventDataStore>("AWS.CloudTrail.EventDataStore");
169
170 /**
171 * A just-created or just-restored event data store transitions through
172 * `CREATED`/`STARTING_INGESTION` before mutations are accepted; concurrent
173 * mutations surface as transient `ConflictException` /
174 * `InvalidEventDataStoreStatusException`.
175 *
176 * Expressed as an explicitly-typed helper: inlining `Effect.retry` in a
177 * lifecycle op leaks `Retry.Return`'s conditional into declaration emit
178 * and widens the provider layer to an `unknown` R for every consumer of
179 * `AWS.providers()`.
180 */
181 const retryWhileSettling = <A, E extends { _tag: string }, R>(
182 self: Effect.Effect<A, E, R>,
183 ): Effect.Effect<A, E, R> =>
184 Effect.retry(self, {
185 while: (e) =>
186 e._tag === "ConflictException" ||
187 e._tag === "InvalidEventDataStoreStatusException" ||
188 e._tag === "InactiveEventDataStoreException",
189 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
190 });
191
192 /**
193 * Deletion right after another mutation can raise a transient
194 * `ConflictException`; already-inactive stores are handled by the caller
195 * as success and must NOT be retried.
196 */
197 const retryWhileDeleteConflict = <A, E extends { _tag: string }, R>(
198 self: Effect.Effect<A, E, R>,
199 ): Effect.Effect<A, E, R> =>
200 Effect.retry(self, {
201 while: (e) => e._tag === "ConflictException",
202 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
203 });
204
205 const toWireSelectors = (
206 selectors: EventDataStoreEventSelector[] | undefined,
207 ): cloudtrail.AdvancedEventSelector[] | undefined =>
208 selectors?.map((s) => ({
209 Name: s.name,
210 FieldSelectors: s.fieldSelectors.map((f) => ({
211 Field: f.field,
212 Equals: f.equals,
213 StartsWith: f.startsWith,
214 EndsWith: f.endsWith,
215 NotEquals: f.notEquals,
216 NotStartsWith: f.notStartsWith,
217 NotEndsWith: f.notEndsWith,
218 })),
219 }));
220
221 export const EventDataStoreProvider = () =>
222 Provider.effect(
223 EventDataStore,
224 Effect.gen(function* () {
225 const createName = Effect.fn(function* (id: string, props: { name?: string | undefined }) {
226 if (props.name) {
227 return props.name;
228 }
229 return yield* createPhysicalName({ id, maxLength: 128 });
230 });
231
232 const fetchObservedTags = (arn: string) =>
233 cloudtrail.listTags({ ResourceIdList: [arn] }).pipe(
234 Effect.map((r) => {
235 const tags: Record<string, string> = {};
236 for (const t of r.ResourceTagList?.[0]?.TagsList ?? []) {
237 tags[t.Key] = t.Value ?? "";
238 }
239 return tags;
240 }),
241 Effect.orElseSucceed(() => ({}) as Record<string, string>),
242 );
243
244 // Look up a store by ARN, tolerating the typed not-found.
245 const getByArn = (arn: string) =>
246 cloudtrail
247 .getEventDataStore({ EventDataStore: arn })
248 .pipe(
249 Effect.catchTag(
250 ["EventDataStoreNotFoundException", "EventDataStoreARNInvalidException"],
251 () => Effect.undefined,
252 ),
253 );
254
255 // Find a store by name, INCLUDING pending-deletion ones — the caller
256 // decides whether a `PENDING_DELETION` match should be restored.
257 const findByName = (name: string) =>
258 cloudtrail.listEventDataStores.pages({}).pipe(
259 Stream.runCollect,
260 Effect.map((chunk) =>
261 Array.from(chunk)
262 .flatMap((page) => page.EventDataStores ?? [])
263 .find((s) => s.Name === name),
264 ),
265 );
266
267 return EventDataStore.Provider.of({
268 stables: ["eventDataStoreArn", "name"],
269 list: () =>
270 Effect.gen(function* () {
271 const stores = yield* cloudtrail.listEventDataStores.pages({}).pipe(
272 Stream.runCollect,
273 Effect.map((chunk) =>
274 Array.from(chunk).flatMap((page) => page.EventDataStores ?? []),
275 ),
276 );
277 return stores
278 .filter(
279 (s) =>
280 s.EventDataStoreArn !== undefined &&
281 s.Name !== undefined &&
282 s.Status !== "PENDING_DELETION",
283 )
284 .map((s) => ({
285 eventDataStoreArn: s.EventDataStoreArn!,
286 name: s.Name!,
287 status: s.Status ?? "ENABLED",
288 }));
289 }),
290 read: Effect.fn(function* ({ id, olds, output }) {
291 const store = output?.eventDataStoreArn
292 ? yield* getByArn(output.eventDataStoreArn)
293 : yield* findByName(yield* createName(id, olds ?? {}));
294 if (store === undefined || store.Status === "PENDING_DELETION") {
295 return undefined;
296 }
297 const attrs = {
298 eventDataStoreArn: store.EventDataStoreArn!,
299 name: store.Name!,
300 status: store.Status ?? "ENABLED",
301 };
302 const tags = yield* fetchObservedTags(attrs.eventDataStoreArn);
303 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
304 }),
305 diff: Effect.fn(function* ({ news }) {
306 if (!isResolved(news)) return undefined;
307 // Every prop (including the name) is mutable via
308 // UpdateEventDataStore — the ARN is the stable identity, so no
309 // prop change forces a replacement.
310 }),
311 reconcile: Effect.fn(function* ({ id, news, output, session }) {
312 const name = yield* createName(id, news);
313 const internalTags = yield* createInternalTags(id);
314 const desiredSelectors = toWireSelectors(news.advancedEventSelectors);
315 // The CloudTrail wire unit for RetentionPeriod is whole days.
316 const retentionDays = toWireDays(news.retentionPeriod);
317
318 // 1. OBSERVE — prefer the cached ARN, fall back to name lookup.
319 let store = output?.eventDataStoreArn
320 ? yield* getByArn(output.eventDataStoreArn)
321 : yield* findByName(name).pipe(
322 Effect.flatMap((s) =>
323 s?.EventDataStoreArn ? getByArn(s.EventDataStoreArn) : Effect.undefined,
324 ),
325 );
326
327 // A pending-deletion store still holds the name — restore it and
328 // let the sync step converge it to the desired state.
329 if (store !== undefined && store.Status === "PENDING_DELETION") {
330 yield* session.note(`Restoring pending-deletion event data store ${store.Name}`);
331 yield* retryWhileSettling(
332 cloudtrail.restoreEventDataStore({
333 EventDataStore: store.EventDataStoreArn!,
334 }),
335 );
336 store = yield* getByArn(store.EventDataStoreArn!);
337 }
338
339 // 2. ENSURE — create if missing; on the AlreadyExists race (or a
340 // same-name store pending deletion), converge via name lookup +
341 // restore.
342 if (store === undefined) {
343 yield* session.note(`Creating event data store ${name}`);
344 const created = yield* cloudtrail
345 .createEventDataStore({
346 Name: name,
347 AdvancedEventSelectors: desiredSelectors,
348 MultiRegionEnabled: news.multiRegionEnabled,
349 OrganizationEnabled: news.organizationEnabled,
350 RetentionPeriod: retentionDays,
351 TerminationProtectionEnabled: news.terminationProtectionEnabled,
352 BillingMode: news.billingMode,
353 KmsKeyId: news.kmsKeyId,
354 StartIngestion: news.ingestionEnabled,
355 TagsList: Object.entries({
356 ...news.tags,
357 ...internalTags,
358 }).map(([Key, Value]) => ({ Key, Value })),
359 })
360 .pipe(
361 Effect.catchTag("EventDataStoreAlreadyExistsException", () => Effect.undefined),
362 );
363 if (created?.EventDataStoreArn) {
364 store = yield* getByArn(created.EventDataStoreArn);
365 } else {
366 // AlreadyExists race — the holder may be active (peer created
367 // it) or pending deletion (a prior stack run deleted it).
368 const existing = yield* findByName(name);
369 if (existing?.Status === "PENDING_DELETION") {
370 yield* session.note(
371 `Name ${name} is held by a pending-deletion store — restoring it`,
372 );
373 yield* retryWhileSettling(
374 cloudtrail.restoreEventDataStore({
375 EventDataStore: existing.EventDataStoreArn!,
376 }),
377 );
378 }
379 store = existing?.EventDataStoreArn
380 ? yield* getByArn(existing.EventDataStoreArn)
381 : undefined;
382 }
383 }
384 if (store === undefined) {
385 // Surface the typed not-found from a direct name-keyed get.
386 store = yield* cloudtrail.getEventDataStore({
387 EventDataStore: name,
388 });
389 }
390
391 const arn = store.EventDataStoreArn!;
392
393 // 3. SYNC — diff observed against desired, push only the delta.
394 const updateDelta: Partial<
395 Omit<cloudtrail.UpdateEventDataStoreRequest, "EventDataStore">
396 > = {};
397 if (store.Name !== name) {
398 updateDelta.Name = name;
399 }
400 if (retentionDays !== undefined && store.RetentionPeriod !== retentionDays) {
401 updateDelta.RetentionPeriod = retentionDays;
402 }
403 if (
404 news.multiRegionEnabled !== undefined &&
405 store.MultiRegionEnabled !== news.multiRegionEnabled
406 ) {
407 updateDelta.MultiRegionEnabled = news.multiRegionEnabled;
408 }
409 if (
410 news.organizationEnabled !== undefined &&
411 store.OrganizationEnabled !== news.organizationEnabled
412 ) {
413 updateDelta.OrganizationEnabled = news.organizationEnabled;
414 }
415 if (
416 news.terminationProtectionEnabled !== undefined &&
417 store.TerminationProtectionEnabled !== news.terminationProtectionEnabled
418 ) {
419 updateDelta.TerminationProtectionEnabled = news.terminationProtectionEnabled;
420 }
421 if (news.billingMode !== undefined && store.BillingMode !== news.billingMode) {
422 updateDelta.BillingMode = news.billingMode;
423 }
424 if (news.kmsKeyId !== undefined && store.KmsKeyId !== news.kmsKeyId) {
425 updateDelta.KmsKeyId = news.kmsKeyId;
426 }
427 if (
428 desiredSelectors !== undefined &&
429 JSON.stringify(store.AdvancedEventSelectors ?? []) !== JSON.stringify(desiredSelectors)
430 ) {
431 updateDelta.AdvancedEventSelectors = desiredSelectors;
432 }
433 if (Object.keys(updateDelta).length > 0) {
434 yield* session.note(
435 `Updating event data store: ${Object.keys(updateDelta).join(", ")}`,
436 );
437 store = yield* retryWhileSettling(
438 cloudtrail.updateEventDataStore({
439 EventDataStore: arn,
440 ...updateDelta,
441 }),
442 );
443 }
444
445 // 3b. SYNC ingestion state — only when declared. The store's
446 // Status is the observed ingestion state: ENABLED ingests,
447 // STOPPED_INGESTION does not. retryWhileSettling rides out the
448 // CREATED/STARTING_INGESTION window after create/restore.
449 if (news.ingestionEnabled !== undefined) {
450 const status = store.Status ?? "ENABLED";
451 if (news.ingestionEnabled && status === "STOPPED_INGESTION") {
452 yield* session.note(`Starting ingestion for ${name}`);
453 yield* retryWhileSettling(
454 cloudtrail.startEventDataStoreIngestion({
455 EventDataStore: arn,
456 }),
457 );
458 store = (yield* getByArn(arn)) ?? store;
459 } else if (!news.ingestionEnabled && status !== "STOPPED_INGESTION") {
460 yield* session.note(`Stopping ingestion for ${name}`);
461 yield* retryWhileSettling(
462 cloudtrail.stopEventDataStoreIngestion({
463 EventDataStore: arn,
464 }),
465 );
466 store = (yield* getByArn(arn)) ?? store;
467 }
468 }
469
470 // 3c. SYNC tags against OBSERVED cloud tags (adoption-safe).
471 const observedTags = yield* fetchObservedTags(arn);
472 const { upsert, removed } = diffTags(observedTags, {
473 ...news.tags,
474 ...internalTags,
475 });
476 if (upsert.length > 0) {
477 yield* cloudtrail.addTags({
478 ResourceId: arn,
479 TagsList: upsert.map((t) => ({ Key: t.Key, Value: t.Value })),
480 });
481 }
482 if (removed.length > 0) {
483 yield* cloudtrail.removeTags({
484 ResourceId: arn,
485 TagsList: removed.map((Key) => ({ Key })),
486 });
487 }
488
489 yield* session.note(arn);
490 return {
491 eventDataStoreArn: arn,
492 name: store.Name ?? name,
493 status: store.Status ?? "ENABLED",
494 };
495 }),
496 // DeleteEventDataStore schedules PENDING_DELETION (7-day window, no
497 // cost). Idempotent: already-deleted (NotFound/ARNInvalid) and
498 // already-pending (Inactive) stores are both success. A protected
499 // store fails with the typed
500 // `EventDataStoreTerminationProtectedException` — disable
501 // `terminationProtectionEnabled` first.
502 delete: Effect.fn(function* ({ output }) {
503 yield* retryWhileDeleteConflict(
504 cloudtrail.deleteEventDataStore({
505 EventDataStore: output.eventDataStoreArn,
506 }),
507 ).pipe(
508 Effect.catchTag(
509 [
510 "EventDataStoreNotFoundException",
511 "EventDataStoreARNInvalidException",
512 "InactiveEventDataStoreException",
513 ],
514 () => Effect.void,
515 ),
516 );
517 }),
518 });
519 }),
520 );