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

main
ts 313 lines 11.4 KB
Raw
1 import * as incidents from "@distilled.cloud/aws/ssm-incidents";
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 * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11
12 export interface ResponsePlanProps {
13 /**
14 * The name of the response plan. Must be unique in the account and can't
15 * contain spaces. Changing it replaces the response plan.
16 *
17 * @default ${app}-${id}-${stage}-${suffix}
18 */
19 name?: string;
20
21 /**
22 * A human-readable name shown in the Incident Manager console.
23 */
24 displayName?: string;
25
26 /**
27 * Details used to create the incident when this response plan starts an
28 * incident: title, impact (1 = critical … 5 = no impact), optional summary,
29 * dedupe string, SNS notification targets, and tags applied to the incident
30 * record.
31 */
32 incidentTemplate: incidents.IncidentTemplate;
33
34 /**
35 * The AWS Chatbot chat channel used for collaboration during an incident.
36 */
37 chatChannel?: incidents.ChatChannel;
38
39 /**
40 * ARNs of the Incident Manager contacts and escalation plans that the
41 * response plan engages during an incident.
42 */
43 engagements?: string[];
44
45 /**
46 * The Systems Manager Automation runbooks to run at the beginning of the
47 * incident.
48 */
49 actions?: incidents.Action[];
50
51 /**
52 * PagerDuty integrations to associate with the response plan.
53 */
54 integrations?: incidents.Integration[];
55
56 /**
57 * Tags applied to the response plan. Alchemy ownership tags are merged in
58 * automatically.
59 */
60 tags?: Record<string, string>;
61 }
62
63 /** @resource */
64 export interface ResponsePlan extends Resource<
65 "AWS.SSMIncidents.ResponsePlan",
66 ResponsePlanProps,
67 {
68 /** ARN of the response plan. */
69 arn: string;
70 /** Name of the response plan. */
71 name: string;
72 },
73 never,
74 Providers
75 > {}
76
77 /**
78 * An Incident Manager response plan — the template that automates the initial
79 * response to incidents by engaging contacts, starting chat-channel
80 * collaboration, and running Automation runbooks.
81 *
82 * Requires the account's Incident Manager replication set
83 * (`SSMIncidents.ReplicationSet`) to exist.
84 *
85 * ### Creating Response Plans
86 * **Example:** Minimal response plan
87 * ```typescript
88 * const replicationSet = yield* SSMIncidents.ReplicationSet("Incidents", {});
89 * const plan = yield* SSMIncidents.ResponsePlan("Critical", {
90 * incidentTemplate: { title: "Critical failure", impact: 1 },
91 * });
92 * ```
93 *
94 * **Example:** Response plan with engagements and chat channel
95 * ```typescript
96 * const plan = yield* SSMIncidents.ResponsePlan("Sev1", {
97 * displayName: "Severity 1 response",
98 * incidentTemplate: {
99 * title: "Sev1 incident",
100 * impact: 1,
101 * summary: "Automated Sev1 response",
102 * notificationTargets: [{ snsTopicArn: topic.topicArn }],
103 * },
104 * engagements: [oncall.contactArn],
105 * chatChannel: { chatbotSns: [topic.topicArn] },
106 * });
107 * ```
108 */
109 const ResponsePlanResource = Resource<ResponsePlan>("AWS.SSMIncidents.ResponsePlan");
110
111 export { ResponsePlanResource as ResponsePlan };
112
113 // Normalized deep-equality for desired-vs-observed sync comparisons —
114 // tolerates key ordering and treats absent optional lists as empty.
115 const normalize = (value: unknown): unknown => {
116 if (Array.isArray(value)) return value.map(normalize);
117 if (value !== null && typeof value === "object") {
118 return Object.fromEntries(
119 Object.entries(value as Record<string, unknown>)
120 .filter(([, v]) => v !== undefined)
121 .sort(([l], [r]) => l.localeCompare(r))
122 .map(([k, v]) => [k, normalize(v)]),
123 );
124 }
125 return value;
126 };
127 const same = (l: unknown, r: unknown) =>
128 JSON.stringify(normalize(l)) === JSON.stringify(normalize(r));
129
130 export const ResponsePlanProvider = () =>
131 Provider.effect(
132 ResponsePlanResource,
133 Effect.gen(function* () {
134 const createName = Effect.fn(function* (id: string, props: { name?: string }) {
135 // Response plan names can't contain spaces; physical names are
136 // DNS-safe already.
137 return props.name ?? (yield* createPhysicalName({ id, maxLength: 200 }));
138 });
139
140 const findArnByName = (name: string) =>
141 incidents.listResponsePlans.items({}).pipe(
142 Stream.filter((summary) => summary.name === name),
143 Stream.take(1),
144 Stream.runCollect,
145 Effect.map((chunk) => Array.from(chunk)[0]?.arn),
146 );
147
148 const getPlan = (arn: string) =>
149 incidents
150 .getResponsePlan({ arn })
151 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
152
153 const observe = Effect.fn(function* (name: string, arn: string | undefined) {
154 if (arn !== undefined) {
155 const byArn = yield* getPlan(arn);
156 if (byArn !== undefined) return byArn;
157 }
158 const found = yield* findArnByName(name);
159 return found === undefined ? undefined : yield* getPlan(found);
160 });
161
162 const readTags = (arn: string) =>
163 incidents.listTagsForResource({ resourceArn: arn }).pipe(
164 Effect.map(
165 (r) =>
166 Object.fromEntries(
167 Object.entries(r.tags).filter((e): e is [string, string] => e[1] !== undefined),
168 ) as Record<string, string>,
169 ),
170 Effect.orElseSucceed(() => ({})),
171 );
172
173 return ResponsePlanResource.Provider.of({
174 stables: ["arn", "name"],
175
176 list: () =>
177 incidents.listResponsePlans.items({}).pipe(
178 Stream.runCollect,
179 Effect.map((chunk) =>
180 Array.from(chunk).map((summary) => ({
181 arn: summary.arn,
182 name: summary.name,
183 })),
184 ),
185 ),
186
187 read: Effect.fn(function* ({ id, olds, output }) {
188 const name = output?.name ?? (yield* createName(id, olds ?? {}));
189 const plan = yield* observe(name, output?.arn);
190 if (plan === undefined) return undefined;
191 const attrs = { arn: plan.arn, name: plan.name };
192 const tags = yield* readTags(plan.arn);
193 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
194 }),
195
196 // The name is create-only; everything else updates in place.
197 diff: Effect.fn(function* ({ id, news, olds }) {
198 if (!isResolved(news)) return undefined;
199 const oldName = yield* createName(id, olds);
200 const newName = yield* createName(id, news);
201 if (oldName !== newName) return { action: "replace" } as const;
202 }),
203
204 reconcile: Effect.fn(function* ({ id, news, output, session }) {
205 const name = output?.name ?? (yield* createName(id, news));
206 const internalTags = yield* createInternalTags(id);
207 const desiredTags = { ...news.tags, ...internalTags };
208
209 // 1. OBSERVE
210 let plan = yield* observe(name, output?.arn);
211
212 // 2. ENSURE — create if missing; tolerate the already-exists race.
213 if (plan === undefined) {
214 yield* session.note(`creating response plan ${name}`);
215 const arn = yield* incidents
216 .createResponsePlan({
217 name,
218 displayName: news.displayName,
219 incidentTemplate: news.incidentTemplate,
220 chatChannel: news.chatChannel,
221 engagements: news.engagements,
222 actions: news.actions,
223 integrations: news.integrations,
224 tags: desiredTags,
225 })
226 .pipe(
227 Effect.map((r) => r.arn),
228 Effect.catchTag("ConflictException", () =>
229 findArnByName(name).pipe(Effect.map((found) => found!)),
230 ),
231 );
232 plan = (yield* getPlan(arn))!;
233 }
234 const arn = plan.arn;
235
236 // 3. SYNC — diff each mutable aspect of the OBSERVED plan against
237 // the desired state; call updateResponsePlan only on a delta.
238 // Empty strings / empty arrays clear a previously-set value.
239 const desired = {
240 displayName: news.displayName ?? "",
241 incidentTemplate: {
242 title: news.incidentTemplate.title,
243 impact: news.incidentTemplate.impact,
244 summary: news.incidentTemplate.summary ?? "",
245 dedupeString: news.incidentTemplate.dedupeString ?? "",
246 notificationTargets: news.incidentTemplate.notificationTargets ?? [],
247 incidentTags: news.incidentTemplate.incidentTags ?? {},
248 },
249 engagements: [...(news.engagements ?? [])].sort(),
250 actions: news.actions ?? [],
251 integrations: news.integrations ?? [],
252 };
253 const observed = {
254 displayName: plan.displayName ?? "",
255 incidentTemplate: {
256 title: plan.incidentTemplate.title,
257 impact: plan.incidentTemplate.impact,
258 summary: plan.incidentTemplate.summary ?? "",
259 dedupeString: plan.incidentTemplate.dedupeString ?? "",
260 notificationTargets: plan.incidentTemplate.notificationTargets ?? [],
261 incidentTags: plan.incidentTemplate.incidentTags ?? {},
262 },
263 engagements: [...(plan.engagements ?? [])].sort(),
264 actions: plan.actions ?? [],
265 integrations: plan.integrations ?? [],
266 };
267 const chatChannelDelta =
268 news.chatChannel !== undefined && !same(plan.chatChannel, news.chatChannel);
269 if (!same(desired, observed) || chatChannelDelta) {
270 yield* incidents.updateResponsePlan({
271 arn,
272 displayName: desired.displayName,
273 incidentTemplateTitle: desired.incidentTemplate.title,
274 incidentTemplateImpact: desired.incidentTemplate.impact,
275 incidentTemplateSummary: desired.incidentTemplate.summary,
276 incidentTemplateDedupeString: desired.incidentTemplate.dedupeString,
277 incidentTemplateNotificationTargets: desired.incidentTemplate.notificationTargets,
278 incidentTemplateTags: desired.incidentTemplate.incidentTags,
279 chatChannel: news.chatChannel,
280 engagements: desired.engagements,
281 actions: desired.actions,
282 integrations: desired.integrations,
283 });
284 }
285
286 // 3b. SYNC tags — diff against OBSERVED cloud tags.
287 const currentTags = yield* readTags(arn);
288 const { upsert, removed } = diffTags(currentTags, desiredTags);
289 if (upsert.length > 0) {
290 yield* incidents.tagResource({
291 resourceArn: arn,
292 tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
293 });
294 }
295 if (removed.length > 0) {
296 yield* incidents.untagResource({
297 resourceArn: arn,
298 tagKeys: removed,
299 });
300 }
301
302 yield* session.note(arn);
303 return { arn, name };
304 }),
305
306 delete: Effect.fn(function* ({ output }) {
307 // deleteResponsePlan is idempotent for missing plans; tolerate the
308 // typed not-found in case AWS starts returning it.
309 yield* incidents.deleteResponsePlan({ arn: output.arn }).pipe(Effect.asVoid);
310 }),
311 });
312 }),
313 );