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

main
ts 241 lines 8.35 KB
Raw
1 import * as cloudwatch from "@distilled.cloud/aws/cloudwatch";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { hasAlchemyTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import type { AlarmArn } from "./Alarm.ts";
13 import { createName, readResourceTags, retryConcurrent, updateResourceTags } from "./common.ts";
14
15 export class CompositeAlarmUnexpectedResponse extends Data.TaggedError(
16 "CompositeAlarmUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export type CompositeAlarmName = string;
23
24 export interface CompositeAlarmProps extends Omit<
25 cloudwatch.PutCompositeAlarmInput,
26 "AlarmName" | "Tags"
27 > {
28 /**
29 * Name of the composite alarm. If omitted, a unique name is generated.
30 */
31 name?: CompositeAlarmName;
32 /**
33 * Optional tags to apply to the composite alarm.
34 */
35 tags?: Record<string, string>;
36 }
37
38 export interface CompositeAlarm extends Resource<
39 "AWS.CloudWatch.CompositeAlarm",
40 CompositeAlarmProps,
41 {
42 /** Physical name of the composite alarm. */
43 alarmName: CompositeAlarmName;
44 /** ARN of the composite alarm. */
45 alarmArn: AlarmArn;
46 /** Current state of the composite alarm (`OK`, `ALARM`, or `INSUFFICIENT_DATA`). */
47 stateValue: cloudwatch.StateValue | undefined;
48 /** Human-readable reason for the current state. */
49 stateReason: string | undefined;
50 /** The full CompositeAlarm description as last read from CloudWatch. */
51 compositeAlarm: cloudwatch.CompositeAlarm;
52 /** Tags on the composite alarm, including the internal Alchemy ownership tags. */
53 tags: Record<string, string>;
54 },
55 never,
56 Providers
57 > {}
58
59 /**
60 * A CloudWatch composite alarm — combines the states of other alarms with
61 * a boolean `AlarmRule` expression so a single alarm (and its actions)
62 * reflects overall health.
63 * ### Creating Composite Alarms
64 * **Example:** Composite Rule
65 * ```typescript
66 * const composite = yield* CompositeAlarm("HighSeverity", {
67 * AlarmRule: 'ALARM("HighErrors") OR ALARM("HighLatency")',
68 * });
69 * ```
70 *
71 * **Example:** Compose Alarm Resources with Output.interpolate
72 * ```typescript
73 * const errors = yield* Alarm("HighErrors", {
74 * MetricName: "Errors",
75 * Namespace: "AWS/Lambda",
76 * Statistic: "Sum",
77 * Period: 60,
78 * EvaluationPeriods: 1,
79 * Threshold: 1,
80 * ComparisonOperator: "GreaterThanOrEqualToThreshold",
81 * });
82 *
83 * const composite = yield* CompositeAlarm("HighSeverity", {
84 * AlarmRule: Output.interpolate`ALARM("${errors.alarmName}")`,
85 * });
86 * ```
87 *
88 * @resource
89 */
90 export const CompositeAlarm = Resource<CompositeAlarm>("AWS.CloudWatch.CompositeAlarm");
91
92 export const CompositeAlarmProvider = () =>
93 Provider.effect(
94 CompositeAlarm,
95 Effect.gen(function* () {
96 const createAlarmName = (id: string, props: { name?: string } = {}) =>
97 createName(id, props.name, 255);
98
99 const alarmArn = (alarmName: string) =>
100 AWSEnvironment.current.pipe(
101 Effect.map(
102 (env) =>
103 `arn:aws:cloudwatch:${env.region}:${env.accountId}:alarm:${alarmName}` as AlarmArn,
104 ),
105 );
106
107 const readCompositeAlarm = Effect.fn(function* (alarmName: string) {
108 const described = yield* cloudwatch.describeAlarms({
109 AlarmNames: [alarmName],
110 AlarmTypes: ["CompositeAlarm"],
111 });
112 const compositeAlarm = described.CompositeAlarms?.find(
113 (candidate) => candidate.AlarmName === alarmName,
114 );
115
116 if (!compositeAlarm?.AlarmName || !compositeAlarm.AlarmArn) {
117 return undefined;
118 }
119
120 const tags = yield* readResourceTags(compositeAlarm.AlarmArn).pipe(
121 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({})),
122 );
123
124 return {
125 alarmName: compositeAlarm.AlarmName,
126 alarmArn: compositeAlarm.AlarmArn as AlarmArn,
127 stateValue: compositeAlarm.StateValue,
128 stateReason: compositeAlarm.StateReason,
129 compositeAlarm,
130 tags,
131 };
132 });
133
134 return {
135 stables: ["alarmName", "alarmArn"],
136 diff: Effect.fn(function* ({ id, olds = {}, news = {} }) {
137 if (!isResolved(news)) return undefined;
138 const oldName = yield* createAlarmName(id, olds);
139 const newName = yield* createAlarmName(id, news);
140
141 if (oldName !== newName) {
142 return { action: "replace" } as const;
143 }
144 }),
145 read: Effect.fn(function* ({ id, olds, output }) {
146 const name = output?.alarmName ?? (yield* createAlarmName(id, olds ?? {}));
147 const state = yield* readCompositeAlarm(name);
148 if (!state) return undefined;
149 return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state);
150 }),
151 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
152 // Observe — pin the physical name from `output` if present so we
153 // never rename an existing alarm; otherwise derive from desired
154 // props.
155 const name = output?.alarmName ?? (yield* createAlarmName(id, news));
156 const existing = yield* readCompositeAlarm(name);
157
158 // Ensure — `putCompositeAlarm` is an upsert. We always send the
159 // full desired config so the cloud converges to `news` whether
160 // the alarm pre-existed or not.
161 yield* retryConcurrent(
162 cloudwatch.putCompositeAlarm({
163 ...news,
164 AlarmName: name,
165 }),
166 );
167
168 // Sync tags — diff observed (or prior) tags against desired.
169 // `olds` is undefined on adoption, so fall back to what we just
170 // observed.
171 const tags = yield* updateResourceTags({
172 id,
173 resourceArn: yield* alarmArn(name),
174 olds: olds?.tags ?? existing?.tags,
175 news: news.tags,
176 });
177
178 yield* session.note(yield* alarmArn(name));
179
180 const state = yield* readCompositeAlarm(name);
181 if (!state) {
182 return yield* new CompositeAlarmUnexpectedResponse({
183 message: `failed to read reconciled composite alarm '${name}'`,
184 });
185 }
186
187 return {
188 ...state,
189 tags,
190 };
191 }),
192 delete: Effect.fn(function* ({ output }) {
193 yield* retryConcurrent(
194 cloudwatch.deleteAlarms({
195 AlarmNames: [output.alarmName],
196 }),
197 );
198 }),
199 list: () =>
200 Effect.gen(function* () {
201 // Enumerate every composite alarm in the account/region by
202 // exhaustively paginating `describeAlarms` filtered to composite
203 // alarms (items live under the `CompositeAlarms` field).
204 const alarms = yield* cloudwatch.describeAlarms
205 .pages({ AlarmTypes: ["CompositeAlarm"] })
206 .pipe(
207 Stream.runCollect,
208 Effect.map((chunk) =>
209 Array.from(chunk).flatMap((page) =>
210 (page.CompositeAlarms ?? []).filter(
211 (
212 candidate,
213 ): candidate is cloudwatch.CompositeAlarm & {
214 AlarmName: string;
215 AlarmArn: string;
216 } => candidate.AlarmName != null && candidate.AlarmArn != null,
217 ),
218 ),
219 ),
220 );
221
222 return yield* Effect.forEach(
223 alarms,
224 (compositeAlarm) =>
225 readResourceTags(compositeAlarm.AlarmArn).pipe(
226 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({})),
227 Effect.map((tags) => ({
228 alarmName: compositeAlarm.AlarmName,
229 alarmArn: compositeAlarm.AlarmArn as AlarmArn,
230 stateValue: compositeAlarm.StateValue,
231 stateReason: compositeAlarm.StateReason,
232 compositeAlarm,
233 tags,
234 })),
235 ),
236 { concurrency: 10 },
237 );
238 }),
239 };
240 }),
241 );