@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 250 lines 9.14 KB
Raw
1 import * as eventbridge from "@distilled.cloud/aws/eventbridge";
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 { toWireDays } from "alchemy/Util/Duration";
7 import type * as Duration from "effect/Duration";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import { AWSEnvironment, type AccountID } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import type { RegionID } from "../Region.ts";
13
14 export type { ArchiveState } from "@distilled.cloud/aws/eventbridge";
15
16 export type ArchiveName = string;
17 export type ArchiveArn = `arn:aws:events:${RegionID}:${AccountID}:archive/${ArchiveName}`;
18
19 export interface ArchiveProps {
20 /**
21 * Name of the archive. Must match [\.\-_A-Za-z0-9]+, 1-48 characters.
22 * If omitted, a unique name will be generated.
23 */
24 name?: ArchiveName;
25
26 /**
27 * ARN of the event bus whose events are archived. Immutable — changing it
28 * replaces the archive.
29 */
30 eventSourceArn: string;
31
32 /**
33 * Description of the archive. Max 512 characters.
34 */
35 description?: string;
36
37 /**
38 * Event pattern filtering which events are archived, as a JSON-compatible
39 * object. If omitted, all events on the source bus are archived (except
40 * replayed events).
41 */
42 eventPattern?: Record<string, any>;
43
44 /**
45 * How long events are retained in the archive, as any `Duration.Input`
46 * (e.g. `"30 days"`, `Duration.days(90)`); converted to whole days on the
47 * wire (`RetentionDays`).
48 * @default indefinite retention
49 */
50 retention?: Duration.Input;
51
52 /**
53 * The identifier of the KMS customer managed key to encrypt events in this
54 * archive. Strongly recommended when the source event bus uses a customer
55 * managed key.
56 */
57 kmsKeyIdentifier?: string;
58 }
59
60 /**
61 * An Amazon EventBridge archive that retains events from an event bus so
62 * they can later be replayed (see the replay bindings: `StartReplay`,
63 * `DescribeReplay`, `CancelReplay`, `ListReplays`).
64 *
65 * Archives do not support tags, so ownership is tracked by the
66 * deterministic physical name.
67 * ### Archiving Events
68 * **Example:** Archive All Events on a Bus
69 * ```typescript
70 * const bus = yield* AWS.EventBridge.EventBus("AppEvents", {});
71 *
72 * const archive = yield* AWS.EventBridge.Archive("AppArchive", {
73 * eventSourceArn: bus.eventBusArn,
74 * retention: "30 days",
75 * });
76 * ```
77 *
78 * **Example:** Archive a Filtered Subset of Events
79 * ```typescript
80 * const archive = yield* AWS.EventBridge.Archive("OrderArchive", {
81 * eventSourceArn: bus.eventBusArn,
82 * description: "Order events only",
83 * eventPattern: { source: ["my.app"], "detail-type": ["OrderCreated"] },
84 * retention: "90 days",
85 * });
86 * ```
87 *
88 * @resource
89 */
90 export interface Archive extends Resource<
91 "AWS.EventBridge.Archive",
92 ArchiveProps,
93 {
94 /** The name of the archive. */
95 archiveName: ArchiveName;
96 /** The ARN of the archive. */
97 archiveArn: ArchiveArn;
98 /** The ARN of the event bus the archive sources events from. */
99 eventSourceArn: string;
100 },
101 never,
102 Providers
103 > {}
104 export const Archive = Resource<Archive>("AWS.EventBridge.Archive");
105
106 export const ArchiveProvider = () =>
107 Provider.effect(
108 Archive,
109 Effect.gen(function* () {
110 const createArchiveName = (id: string, props: { name?: string } = {}) =>
111 props.name
112 ? Effect.succeed(props.name)
113 : createPhysicalName({
114 id,
115 maxLength: 48,
116 });
117
118 /**
119 * Poll until the archive leaves its transitional state. Archive
120 * creation/updates settle in seconds; the wait is bounded so a stuck
121 * archive surfaces the last observed state instead of hanging.
122 */
123 const awaitSettled = (archiveName: string) =>
124 eventbridge.describeArchive({ ArchiveName: archiveName }).pipe(
125 // A describe fired immediately after create can be eventually
126 // consistent — absorb NotFound briefly before polling the state.
127 Effect.retry({
128 while: (e): boolean => e._tag === "ResourceNotFoundException",
129 schedule: Schedule.spaced("1 second"),
130 times: 5,
131 }),
132 Effect.repeat({
133 schedule: Schedule.spaced("2 seconds"),
134 until: (r): boolean => r.State !== "CREATING" && r.State !== "UPDATING",
135 times: 10,
136 }),
137 );
138
139 return {
140 stables: ["archiveName", "archiveArn", "eventSourceArn"],
141 diff: Effect.fn(function* ({ id, news, olds }) {
142 if (!isResolved(news)) return;
143 const oldName = yield* createArchiveName(id, olds);
144 const newName = yield* createArchiveName(id, news);
145 if (oldName !== newName) {
146 return { action: "replace" } as const;
147 }
148 if (olds.eventSourceArn !== news.eventSourceArn) {
149 return { action: "replace" } as const;
150 }
151 }),
152 read: Effect.fn(function* ({ id, olds, output }) {
153 // Archives don't support tags; the deterministic physical name is
154 // the ownership signal (it embeds app/stage/logical id).
155 const archiveName = output?.archiveName ?? (yield* createArchiveName(id, olds ?? {}));
156 const described = yield* eventbridge
157 .describeArchive({ ArchiveName: archiveName })
158 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
159 if (!described?.ArchiveName || !described.ArchiveArn) {
160 return undefined;
161 }
162 return {
163 archiveName: described.ArchiveName,
164 archiveArn: described.ArchiveArn as ArchiveArn,
165 eventSourceArn: described.EventSourceArn ?? "",
166 };
167 }),
168 list: () =>
169 Effect.gen(function* () {
170 const { accountId, region } = yield* AWSEnvironment.current;
171 const attrs: {
172 archiveName: ArchiveName;
173 archiveArn: ArchiveArn;
174 eventSourceArn: string;
175 }[] = [];
176 let nextToken: string | undefined;
177 do {
178 const page = yield* eventbridge.listArchives({
179 NextToken: nextToken,
180 });
181 for (const archive of page.Archives ?? []) {
182 if (!archive.ArchiveName) {
183 continue;
184 }
185 attrs.push({
186 archiveName: archive.ArchiveName,
187 archiveArn:
188 `arn:aws:events:${region}:${accountId}:archive/${archive.ArchiveName}` as ArchiveArn,
189 eventSourceArn: archive.EventSourceArn ?? "",
190 });
191 }
192 nextToken = page.NextToken;
193 } while (nextToken);
194 return attrs;
195 }),
196 reconcile: Effect.fn(function* ({ id, news, output, session }) {
197 const archiveName = output?.archiveName ?? (yield* createArchiveName(id, news));
198 const eventPattern = news.eventPattern ? JSON.stringify(news.eventPattern) : undefined;
199 const retentionDays = toWireDays(news.retention);
200
201 // Observe — live cloud state is authoritative; a vanished archive
202 // falls through to create.
203 const observed = yield* eventbridge
204 .describeArchive({ ArchiveName: archiveName })
205 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
206
207 if (!observed?.ArchiveArn) {
208 // Ensure — create the archive; tolerate an AlreadyExists race
209 // with a peer reconciler and converge via the update below.
210 yield* eventbridge
211 .createArchive({
212 ArchiveName: archiveName,
213 EventSourceArn: news.eventSourceArn,
214 Description: news.description,
215 EventPattern: eventPattern,
216 RetentionDays: retentionDays,
217 KmsKeyIdentifier: news.kmsKeyIdentifier,
218 })
219 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void));
220 } else {
221 // Sync — updateArchive overwrites description, pattern,
222 // retention, and KMS key in one shot (idempotent on matching
223 // values).
224 yield* eventbridge.updateArchive({
225 ArchiveName: archiveName,
226 Description: news.description,
227 EventPattern: eventPattern,
228 RetentionDays: retentionDays,
229 KmsKeyIdentifier: news.kmsKeyIdentifier,
230 });
231 }
232
233 const settled = yield* awaitSettled(archiveName);
234 const archiveArn = (settled.ArchiveArn ?? observed?.ArchiveArn) as ArchiveArn;
235
236 yield* session.note(archiveArn);
237 return {
238 archiveName,
239 archiveArn,
240 eventSourceArn: settled.EventSourceArn ?? news.eventSourceArn,
241 };
242 }),
243 delete: Effect.fn(function* ({ output }) {
244 yield* eventbridge
245 .deleteArchive({ ArchiveName: output.archiveName })
246 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
247 }),
248 };
249 }),
250 );