@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, 04:45 UTC

main
ts 276 lines 9.84 KB
Raw
1 import * as notifications from "@distilled.cloud/aws/notifications";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Option from "effect/Option";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import {
13 pinNotificationsRegion,
14 readNotificationsTags,
15 syncNotificationsTags,
16 } from "./internal.ts";
17
18 /**
19 * How long User Notifications aggregates events of the same kind into a
20 * single notification before delivering it.
21 */
22 export type AggregationDuration = "LONG" | "SHORT" | "NONE";
23
24 export interface NotificationConfigurationProps {
25 /**
26 * Name of the notification configuration. Must be unique in the account
27 * (letters, numbers, underscores and hyphens). If omitted, a unique name
28 * is generated from the app, stage and logical ID. The name can be
29 * changed in place (no replacement).
30 */
31 name?: string;
32
33 /**
34 * Human-readable description of the configuration.
35 * @default "Managed by Alchemy"
36 */
37 description?: string;
38
39 /**
40 * How long to aggregate matching events into a single notification:
41 * `LONG` (12 hours), `SHORT` (5 minutes) or `NONE` (no aggregation).
42 * @default "NONE"
43 */
44 aggregationDuration?: AggregationDuration;
45
46 /**
47 * User tags to attach to the configuration. Merged with internal
48 * Alchemy tags.
49 */
50 tags?: Record<string, string>;
51 }
52
53 export interface NotificationConfiguration extends Resource<
54 "AWS.Notifications.NotificationConfiguration",
55 NotificationConfigurationProps,
56 {
57 /** The ARN of the notification configuration (regionless). */
58 notificationConfigurationArn: string;
59 /** The unique name of the configuration. */
60 name: string;
61 /** The description of the configuration. */
62 description: string;
63 /**
64 * Current status: `ACTIVE`, `PARTIALLY_ACTIVE`, `INACTIVE` (no event
65 * rules / channels associated yet) or `DELETING`.
66 */
67 status: string;
68 },
69 never,
70 Providers
71 > {}
72
73 /**
74 * An AWS User Notifications **notification configuration** — the container
75 * that groups {@link EventRule}s (which events to notify on) and delivery
76 * channels (where notifications go: Console bell, email contacts, chat).
77 *
78 * User Notifications is a global service managed from `us-east-1`; the
79 * provider pins the control-plane region automatically, so the resource
80 * works from a stack deployed in any region.
81 *
82 * ### Creating a Notification Configuration
83 * **Example:** Basic configuration
84 * ```typescript
85 * import * as Notifications from "@alchemy.run/aws/Notifications";
86 *
87 * const config = yield* Notifications.NotificationConfiguration("Alerts", {
88 * description: "Deployment alerts",
89 * });
90 * ```
91 *
92 * **Example:** Aggregate duplicate events for 5 minutes
93 * ```typescript
94 * const config = yield* Notifications.NotificationConfiguration("Alerts", {
95 * description: "Deployment alerts",
96 * aggregationDuration: "SHORT",
97 * tags: { team: "platform" },
98 * });
99 * ```
100 *
101 * ### Adding Event Rules
102 * **Example:** Notify on CloudWatch alarm state changes
103 * ```typescript
104 * const rule = yield* Notifications.EventRule("AlarmRule", {
105 * notificationConfigurationArn: config.notificationConfigurationArn,
106 * source: "aws.cloudwatch",
107 * eventType: "CloudWatch Alarm State Change",
108 * regions: ["us-west-2"],
109 * });
110 * ```
111 *
112 * @resource
113 */
114 export const NotificationConfiguration = Resource<NotificationConfiguration>(
115 "AWS.Notifications.NotificationConfiguration",
116 );
117
118 const DEFAULT_DESCRIPTION = "Managed by Alchemy";
119
120 /**
121 * Retry a mutation while the service reports a transitional-lock
122 * `ConflictException` (e.g. an event rule of this configuration is still
123 * `DELETING`). Bounded (~40s). Explicitly typed so `Effect.retry`'s
124 * conditional return type doesn't widen the provider layer in declaration
125 * emit.
126 */
127 const retryWhileConflict = <A, E extends { _tag: string }, R>(
128 self: Effect.Effect<A, E, R>,
129 ): Effect.Effect<A, E, R> =>
130 Effect.retry(self, {
131 while: (e) => e._tag === "ConflictException",
132 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
133 });
134
135 export const NotificationConfigurationProvider = () =>
136 Provider.effect(
137 NotificationConfiguration,
138 Effect.gen(function* () {
139 const createName = Effect.fn(function* (id: string, props: NotificationConfigurationProps) {
140 return props.name ?? (yield* createPhysicalName({ id }));
141 });
142
143 // Names are unique account-wide (CreateNotificationConfiguration
144 // rejects duplicates with ConflictException), so a name scan is a
145 // reliable identity fallback when the ARN cache is missing.
146 const findByName = Effect.fn(function* (name: string) {
147 return yield* pinNotificationsRegion(
148 notifications.listNotificationConfigurations.items({}).pipe(
149 Stream.filter((item) => item.name === name),
150 Stream.runHead,
151 Effect.map(Option.getOrUndefined),
152 ),
153 );
154 });
155
156 const getByArn = Effect.fn(function* (arn: string) {
157 return yield* pinNotificationsRegion(
158 notifications
159 .getNotificationConfiguration({ arn })
160 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined)),
161 );
162 });
163
164 const toAttrs = (live: {
165 arn: string;
166 name: string;
167 description: string;
168 status: string;
169 }) => ({
170 notificationConfigurationArn: live.arn,
171 name: live.name,
172 description: live.description,
173 status: live.status,
174 });
175
176 return NotificationConfiguration.Provider.of({
177 stables: ["notificationConfigurationArn"],
178
179 list: () =>
180 pinNotificationsRegion(
181 notifications.listNotificationConfigurations.items({}).pipe(
182 Stream.runCollect,
183 Effect.map((chunk) => Array.from(chunk).map(toAttrs)),
184 ),
185 ),
186
187 read: Effect.fn(function* ({ id, olds, output }) {
188 const name = output?.name ?? (yield* createName(id, olds ?? {}));
189 const found = output?.notificationConfigurationArn
190 ? yield* getByArn(output.notificationConfigurationArn)
191 : yield* findByName(name);
192 if (!found) return undefined;
193 const attrs = toAttrs(found);
194 const tags = yield* readNotificationsTags(found.arn);
195 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
196 }),
197
198 // Everything (including the name) is mutable in place — no diff
199 // needed; the engine's default update path always reconciles.
200
201 reconcile: Effect.fn(function* ({ id, news, output, session }) {
202 const desiredName = yield* createName(id, news);
203 const desiredDescription = news.description ?? DEFAULT_DESCRIPTION;
204
205 // OBSERVE — cloud state is authoritative; the cached ARN falls
206 // through to a name scan when it no longer resolves.
207 let live = output?.notificationConfigurationArn
208 ? yield* getByArn(output.notificationConfigurationArn)
209 : yield* findByName(desiredName);
210
211 // ENSURE — create when missing; ConflictException means a peer
212 // created the same-named configuration concurrently → re-observe.
213 if (live === undefined) {
214 const created = yield* pinNotificationsRegion(
215 notifications
216 .createNotificationConfiguration({
217 name: desiredName,
218 description: desiredDescription,
219 aggregationDuration: news.aggregationDuration,
220 tags: news.tags,
221 })
222 .pipe(Effect.catchTag("ConflictException", () => Effect.undefined)),
223 );
224 live = created ? yield* getByArn(created.arn) : yield* findByName(desiredName);
225 }
226 const arn = live!.arn;
227
228 // SYNC settings — diff observed name/description/aggregation
229 // against desired and update only on change. An absent
230 // aggregationDuration prop leaves the observed value untouched.
231 const wantsAggregation = news.aggregationDuration;
232 const aggregationDrifted =
233 wantsAggregation !== undefined &&
234 (live!.aggregationDuration ?? "NONE") !== wantsAggregation;
235 if (
236 live!.name !== desiredName ||
237 live!.description !== desiredDescription ||
238 aggregationDrifted
239 ) {
240 yield* pinNotificationsRegion(
241 notifications.updateNotificationConfiguration({
242 arn,
243 name: desiredName,
244 description: desiredDescription,
245 ...(wantsAggregation !== undefined
246 ? { aggregationDuration: wantsAggregation }
247 : {}),
248 }),
249 );
250 }
251
252 // SYNC tags — against observed cloud tags (adoption-safe).
253 yield* syncNotificationsTags(arn, id, news.tags);
254
255 const fresh = yield* getByArn(arn);
256 yield* session.note(arn);
257 return toAttrs(fresh ?? live!);
258 }),
259
260 delete: Effect.fn(function* ({ output }) {
261 // Idempotent — deleting also cascades any remaining event rules.
262 // Retry the transitional lock (a rule still DELETING blocks the
263 // configuration delete with a ConflictException).
264 yield* notifications
265 .deleteNotificationConfiguration({
266 arn: output.notificationConfigurationArn,
267 })
268 .pipe(
269 pinNotificationsRegion,
270 retryWhileConflict,
271 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
272 );
273 }),
274 });
275 }),
276 );