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

main
ts 210 lines 7.66 KB
Raw
1 import * as devopsguru from "@distilled.cloud/aws/devops-guru";
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 Stream from "effect/Stream";
7 import type { Providers } from "../Providers.ts";
8
9 export interface NotificationChannelProps {
10 /**
11 * ARN of the Amazon SNS topic DevOps Guru sends notifications to. DevOps
12 * Guru only supports standard (non-FIFO) topics and adds the required
13 * topic policy on your behalf for same-account topics. Changing the topic
14 * replaces the channel.
15 */
16 topicArn: string;
17 /**
18 * Insight severities to be notified about. When omitted, notifications are
19 * sent for all severities.
20 * @default all severities
21 */
22 severities?: devopsguru.InsightSeverity[];
23 /**
24 * Notification message types to receive (e.g. `NEW_INSIGHT`,
25 * `CLOSED_INSIGHT`, `SEVERITY_UPGRADED`). When omitted, all message types
26 * are sent.
27 * @default all message types
28 */
29 messageTypes?: devopsguru.NotificationMessageType[];
30 }
31
32 export interface NotificationChannel extends Resource<
33 "AWS.DevOpsGuru.NotificationChannel",
34 NotificationChannelProps,
35 {
36 /** ID of the notification channel. */
37 id: string;
38 /** ARN of the SNS topic the channel notifies. */
39 topicArn: string;
40 },
41 never,
42 Providers
43 > {}
44
45 /**
46 * A DevOps Guru notification channel — an Amazon SNS topic that DevOps Guru
47 * uses to notify you when insights are generated, closed, or change severity.
48 *
49 * The channel configuration is immutable in the AWS API: changing the topic
50 * replaces the channel, while filter changes are converged in place by
51 * removing and re-adding the channel (the channel `id` attribute changes).
52 *
53 * ### Creating a Notification Channel
54 * **Example:** Notify an SNS topic about all insights
55 * ```typescript
56 * const topic = yield* SNS.Topic("Alerts", {});
57 *
58 * const channel = yield* DevOpsGuru.NotificationChannel("Channel", {
59 * topicArn: topic.topicArn,
60 * });
61 * ```
62 *
63 * **Example:** Filter to high-severity new insights
64 * ```typescript
65 * const channel = yield* DevOpsGuru.NotificationChannel("Channel", {
66 * topicArn: topic.topicArn,
67 * severities: ["HIGH"],
68 * messageTypes: ["NEW_INSIGHT", "SEVERITY_UPGRADED"],
69 * });
70 * ```
71 *
72 * @resource
73 */
74 export const NotificationChannel = Resource<NotificationChannel>(
75 "AWS.DevOpsGuru.NotificationChannel",
76 );
77
78 const sameSet = (left: readonly string[] | undefined, right: readonly string[] | undefined) => {
79 const l = [...(left ?? [])].sort();
80 const r = [...(right ?? [])].sort();
81 return l.length === r.length && l.every((value, i) => value === r[i]);
82 };
83
84 const matchesDesired = (
85 config: devopsguru.NotificationChannelConfig | undefined,
86 news: NotificationChannelProps,
87 ) =>
88 config?.Sns?.TopicArn === news.topicArn &&
89 sameSet(config?.Filters?.Severities, news.severities) &&
90 sameSet(config?.Filters?.MessageTypes, news.messageTypes);
91
92 const desiredConfig = (news: NotificationChannelProps): devopsguru.NotificationChannelConfig => ({
93 Sns: { TopicArn: news.topicArn },
94 ...(news.severities !== undefined || news.messageTypes !== undefined
95 ? {
96 Filters: {
97 ...(news.severities !== undefined ? { Severities: news.severities } : {}),
98 ...(news.messageTypes !== undefined ? { MessageTypes: news.messageTypes } : {}),
99 },
100 }
101 : {}),
102 });
103
104 export const NotificationChannelProvider = () =>
105 Provider.effect(
106 NotificationChannel,
107 Effect.gen(function* () {
108 // An account has at most a handful of channels (quota is 2), so a full
109 // paginated listing is the exact observation for every operation.
110 const listChannels = devopsguru.listNotificationChannels.items({}).pipe(
111 Stream.runCollect,
112 Effect.map((chunk) => Array.from(chunk)),
113 );
114
115 const findByTopic = (channels: readonly devopsguru.NotificationChannel[], topicArn: string) =>
116 channels.find((c) => c.Config?.Sns?.TopicArn === topicArn);
117
118 return {
119 stables: ["topicArn"],
120
121 list: () =>
122 listChannels.pipe(
123 Effect.map((channels) =>
124 channels.flatMap((c) =>
125 c.Id !== undefined && c.Config?.Sns?.TopicArn !== undefined
126 ? [{ id: c.Id, topicArn: c.Config.Sns.TopicArn }]
127 : [],
128 ),
129 ),
130 ),
131
132 read: Effect.fn(function* ({ olds, output }) {
133 const channels = yield* listChannels;
134 // Prefer the stored channel id; fall back to the topic lookup
135 // (state-loss recovery). A half-created state row can't round-trip
136 // an Output-valued `topicArn` — report "not found".
137 const found =
138 output?.id !== undefined
139 ? channels.find((c) => c.Id === output.id)
140 : typeof olds?.topicArn === "string"
141 ? findByTopic(channels, olds.topicArn)
142 : undefined;
143 const topicArn = found?.Config?.Sns?.TopicArn;
144 if (found?.Id === undefined || topicArn === undefined) {
145 return undefined;
146 }
147 return { id: found.Id, topicArn };
148 }),
149
150 // The channel's identity is its SNS topic — changing the topic
151 // replaces the channel. Filter changes are converged in `reconcile`.
152 diff: Effect.fn(function* ({ olds, news }) {
153 if (!isResolved(news)) return undefined;
154 if (olds.topicArn !== news.topicArn) {
155 return { action: "replace" } as const;
156 }
157 }),
158
159 reconcile: Effect.fn(function* ({ news, output, session }) {
160 // 1. OBSERVE — cloud state is authoritative; output.id is a cache.
161 const channels = yield* listChannels;
162 let observed =
163 (output?.id !== undefined ? channels.find((c) => c.Id === output.id) : undefined) ??
164 findByTopic(channels, news.topicArn);
165
166 // 2. SYNC — the config is immutable; converge drifted filters by
167 // removing and re-adding the channel.
168 if (observed?.Id !== undefined && !matchesDesired(observed.Config, news)) {
169 yield* devopsguru
170 .removeNotificationChannel({ Id: observed.Id })
171 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
172 observed = undefined;
173 }
174
175 // 3. ENSURE — add the channel when missing. A ConflictException is
176 // a race with a peer reconciler; re-observe by topic.
177 let id = observed?.Id;
178 if (id === undefined) {
179 const added = yield* devopsguru
180 .addNotificationChannel({ Config: desiredConfig(news) })
181 .pipe(
182 Effect.catchTag("ConflictException", (error) =>
183 listChannels.pipe(
184 Effect.flatMap((latest) => {
185 const existing = findByTopic(latest, news.topicArn);
186 return existing?.Id !== undefined
187 ? Effect.succeed({ Id: existing.Id })
188 : Effect.fail(error);
189 }),
190 ),
191 ),
192 );
193 id = added.Id;
194 }
195
196 // 4. RETURN fresh attributes.
197 yield* session.note(id);
198 return { id, topicArn: news.topicArn };
199 }),
200
201 // removeNotificationChannel succeeds on unknown ids, but the
202 // not-found tag is still caught for belt-and-braces idempotency.
203 delete: Effect.fn(function* ({ output }) {
204 yield* devopsguru
205 .removeNotificationChannel({ Id: output.id })
206 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
207 }),
208 };
209 }),
210 );