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

main
ts 329 lines 12 KB
Raw
1 import * as notifications from "@distilled.cloud/aws/notifications";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Option from "effect/Option";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { pinNotificationsRegion } from "./internal.ts";
11
12 export interface EventRuleProps {
13 /**
14 * The ARN of the {@link NotificationConfiguration} this rule feeds.
15 * Changing the configuration replaces the rule.
16 */
17 notificationConfigurationArn: string;
18
19 /**
20 * The EventBridge event source, e.g. `aws.s3`, `aws.cloudwatch`,
21 * `aws.ec2`. Changing the source replaces the rule.
22 */
23 source: string;
24
25 /**
26 * The event type emitted by the source, e.g. `Object Created`,
27 * `CloudWatch Alarm State Change`, `EC2 Instance State-change
28 * Notification`. Changing the event type replaces the rule.
29 */
30 eventType: string;
31
32 /**
33 * Optional EventBridge event pattern that further restricts which events
34 * match. Provided as a JSON string or a plain pattern object. When
35 * omitted, all events of `source`/`eventType` match.
36 */
37 eventPattern?: string | Record<string, any>;
38
39 /**
40 * The AWS regions whose events this rule captures. User Notifications
41 * creates a managed EventBridge rule in each listed region.
42 */
43 regions: string[];
44 }
45
46 export interface EventRule extends Resource<
47 "AWS.Notifications.EventRule",
48 EventRuleProps,
49 {
50 /** The ARN of the event rule. */
51 eventRuleArn: string;
52 /** The ARN of the parent notification configuration. */
53 notificationConfigurationArn: string;
54 /** The EventBridge event source. */
55 source: string;
56 /** The event type. */
57 eventType: string;
58 /** The regions whose events the rule captures. */
59 regions: string[];
60 },
61 never,
62 Providers
63 > {}
64
65 /**
66 * An AWS User Notifications **event rule** — attaches an EventBridge
67 * source/event-type (optionally narrowed by an event pattern) to a
68 * {@link NotificationConfiguration}, across one or more regions.
69 *
70 * `source`, `eventType` and the parent configuration are immutable
71 * (changing them replaces the rule); `eventPattern` and `regions` update
72 * in place. User Notifications materializes a managed EventBridge rule in
73 * every listed region.
74 *
75 * ### Creating an Event Rule
76 * **Example:** Notify on S3 object creation
77 * ```typescript
78 * import * as Notifications from "@alchemy.run/aws/Notifications";
79 *
80 * const config = yield* Notifications.NotificationConfiguration("Alerts");
81 * const rule = yield* Notifications.EventRule("S3Created", {
82 * notificationConfigurationArn: config.notificationConfigurationArn,
83 * source: "aws.s3",
84 * eventType: "Object Created",
85 * regions: ["us-west-2"],
86 * });
87 * ```
88 *
89 * **Example:** Restrict matches with an event pattern
90 * ```typescript
91 * const rule = yield* Notifications.EventRule("BucketRule", {
92 * notificationConfigurationArn: config.notificationConfigurationArn,
93 * source: "aws.s3",
94 * eventType: "Object Created",
95 * eventPattern: { detail: { bucket: { name: ["my-bucket"] } } },
96 * regions: ["us-west-2", "us-east-2"],
97 * });
98 * ```
99 *
100 * @resource
101 */
102 export const EventRule = Resource<EventRule>("AWS.Notifications.EventRule");
103
104 /** Normalize an `eventPattern` prop to the wire JSON string ("" = none). */
105 const toPatternString = (pattern: string | Record<string, any> | undefined): string =>
106 pattern === undefined ? "" : typeof pattern === "string" ? pattern : JSON.stringify(pattern);
107
108 /** Order-insensitive region list equality. */
109 const sameRegions = (a: readonly string[], b: readonly string[]): boolean =>
110 a.length === b.length && [...a].sort().join(",") === [...b].sort().join(",");
111
112 /**
113 * Poll a rule until no region is in a transitional state (`CREATING` /
114 * `UPDATING` / `DELETING`). Bounded and fail-open — regional propagation
115 * completes in seconds and a still-pending region is not an error.
116 *
117 * Expressed as an explicitly-typed helper: inlining `Effect.repeat` in the
118 * provider leaves its conditional return type unresolved in declaration
119 * emit, widening the provider layer to an `unknown` R.
120 */
121 const untilSettled = <A, E, R>(
122 self: Effect.Effect<A, E, R>,
123 pending: (a: A) => boolean,
124 ): Effect.Effect<A, E, R> =>
125 Effect.repeat(self, {
126 schedule: Schedule.fixed("2 seconds"),
127 until: (a) => !pending(a),
128 times: 20,
129 });
130
131 /**
132 * Retry an operation while the service reports a transitional-lock
133 * `ConflictException` (e.g. "event rule ... has not reached terminal status
134 * in region(s): us-west-2 - DELETING"). User Notifications serializes rule
135 * mutations per configuration, so a create that races a sibling delete is
136 * rejected until the delete settles. Bounded (~40s).
137 */
138 const retryWhileConflict = <A, E extends { _tag: string }, R>(
139 self: Effect.Effect<A, E, R>,
140 ): Effect.Effect<A, E, R> =>
141 Effect.retry(self, {
142 while: (e) => e._tag === "ConflictException",
143 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
144 });
145
146 /**
147 * Poll an observation until the resource is gone (bounded, fail-open).
148 * Rule deletion is asynchronous (regions transition through `DELETING`);
149 * returning before it settles trips ConflictExceptions in follow-up
150 * operations on the same configuration.
151 */
152 const pollUntilGone = <A, E, R>(
153 self: Effect.Effect<A | undefined, E, R>,
154 ): Effect.Effect<A | undefined, E, R> =>
155 Effect.repeat(self, {
156 schedule: Schedule.fixed("2 seconds"),
157 until: (a) => a === undefined,
158 times: 20,
159 });
160
161 const hasPendingRegion = (rule: {
162 statusSummaryByRegion: {
163 [key: string]: { status: string } | undefined;
164 };
165 }): boolean =>
166 Object.values(rule.statusSummaryByRegion).some(
167 (s) =>
168 s !== undefined &&
169 (s.status === "CREATING" || s.status === "UPDATING" || s.status === "DELETING"),
170 );
171
172 export const EventRuleProvider = () =>
173 Provider.effect(
174 EventRule,
175 Effect.gen(function* () {
176 const getByArn = Effect.fn(function* (arn: string) {
177 return yield* pinNotificationsRegion(
178 notifications
179 .getEventRule({ arn })
180 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)),
181 );
182 });
183
184 // Identity fallback when the ARN cache is missing: scan the parent
185 // configuration's rules for the (source, eventType) pair.
186 const findBySignature = Effect.fn(function* (
187 notificationConfigurationArn: string,
188 source: string,
189 eventType: string,
190 ) {
191 return yield* pinNotificationsRegion(
192 notifications.listEventRules.items({ notificationConfigurationArn }).pipe(
193 Stream.filter((rule) => rule.source === source && rule.eventType === eventType),
194 Stream.runHead,
195 Effect.map(Option.getOrUndefined),
196 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
197 ),
198 );
199 });
200
201 const toAttrs = (live: {
202 arn: string;
203 notificationConfigurationArn: string;
204 source: string;
205 eventType: string;
206 regions: readonly string[];
207 }) => ({
208 eventRuleArn: live.arn,
209 notificationConfigurationArn: live.notificationConfigurationArn,
210 source: live.source,
211 eventType: live.eventType,
212 regions: [...live.regions],
213 });
214
215 return EventRule.Provider.of({
216 stables: ["eventRuleArn", "notificationConfigurationArn", "source", "eventType"],
217
218 // Sub-resource keyed by its parent notification configuration —
219 // there is no account-wide enumeration without a parent ARN.
220 list: () => Effect.succeed([]),
221
222 read: Effect.fn(function* ({ olds, output }) {
223 const found = output?.eventRuleArn
224 ? yield* getByArn(output.eventRuleArn)
225 : olds
226 ? yield* findBySignature(
227 olds.notificationConfigurationArn,
228 olds.source,
229 olds.eventType,
230 )
231 : undefined;
232 // Event rules are not taggable, so ownership can't be verified —
233 // identity via the parent-scoped (source, eventType) signature.
234 return found ? toAttrs(found) : undefined;
235 }),
236
237 diff: Effect.fn(function* ({ news, olds }) {
238 if (!isResolved(news)) return undefined;
239 if (
240 news.notificationConfigurationArn !== olds.notificationConfigurationArn ||
241 news.source !== olds.source ||
242 news.eventType !== olds.eventType
243 ) {
244 return { action: "replace" } as const;
245 }
246 return undefined;
247 }),
248
249 reconcile: Effect.fn(function* ({ news, output, session }) {
250 const desiredPattern = toPatternString(news.eventPattern);
251
252 // OBSERVE — cloud state is authoritative; the cached ARN falls
253 // through to a parent-scoped signature scan.
254 let live = output?.eventRuleArn
255 ? yield* getByArn(output.eventRuleArn)
256 : yield* findBySignature(
257 news.notificationConfigurationArn,
258 news.source,
259 news.eventType,
260 );
261
262 // ENSURE — create when missing; ConflictException means a peer
263 // created the same rule concurrently → re-observe.
264 if (live === undefined) {
265 // Retry the transitional lock (a sibling rule still DELETING);
266 // a conflict that persists past the budget means the same rule
267 // already exists → re-observe by signature.
268 const created = yield* notifications
269 .createEventRule({
270 notificationConfigurationArn: news.notificationConfigurationArn,
271 source: news.source,
272 eventType: news.eventType,
273 ...(desiredPattern !== "" ? { eventPattern: desiredPattern } : {}),
274 regions: news.regions,
275 })
276 .pipe(
277 pinNotificationsRegion,
278 retryWhileConflict,
279 Effect.catchTag("ConflictException", () => Effect.undefined),
280 );
281 live = created
282 ? yield* getByArn(created.arn)
283 : yield* findBySignature(
284 news.notificationConfigurationArn,
285 news.source,
286 news.eventType,
287 );
288 }
289 const arn = live!.arn;
290
291 // SYNC — diff observed eventPattern/regions against desired and
292 // apply only the delta.
293 if (live!.eventPattern !== desiredPattern || !sameRegions(live!.regions, news.regions)) {
294 yield* notifications
295 .updateEventRule({
296 arn,
297 eventPattern: desiredPattern,
298 regions: news.regions,
299 })
300 .pipe(pinNotificationsRegion, retryWhileConflict);
301 }
302
303 // Wait for regional managed rules to settle (bounded, fail-open).
304 const settled = yield* untilSettled(
305 pinNotificationsRegion(notifications.getEventRule({ arn })),
306 hasPendingRegion,
307 );
308
309 yield* session.note(arn);
310 return toAttrs(settled);
311 }),
312
313 delete: Effect.fn(function* ({ output }) {
314 // Idempotent — the parent configuration's deletion cascades rules,
315 // so the rule may already be gone. A ConflictException means a
316 // sibling mutation is still settling — retry through it.
317 yield* notifications.deleteEventRule({ arn: output.eventRuleArn }).pipe(
318 pinNotificationsRegion,
319 retryWhileConflict,
320 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
321 );
322 // Deletion is asynchronous — wait until the rule is actually gone
323 // so follow-up mutations on the configuration don't hit the
324 // transitional lock (bounded, fail-open).
325 yield* pollUntilGone(getByArn(output.eventRuleArn));
326 }),
327 });
328 }),
329 );