@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, 06:00 UTC

main
ts 255 lines 8.84 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, type AccountID } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import type { RegionID } from "../Region.ts";
13 import { createName, readResourceTags, retryConcurrent, updateResourceTags } from "./common.ts";
14
15 export class AlarmUnexpectedResponse extends Data.TaggedError("AlarmUnexpectedResponse")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export type AlarmName = string;
21 export type AlarmArn = `arn:aws:cloudwatch:${RegionID}:${AccountID}:alarm:${string}`;
22 export type AlarmStateValue = cloudwatch.StateValue;
23
24 export interface AlarmProps extends Omit<cloudwatch.PutMetricAlarmInput, "AlarmName" | "Tags"> {
25 /**
26 * Name of the alarm. If omitted, a unique name is generated.
27 */
28 name?: AlarmName;
29 /**
30 * Optional tags to apply to the alarm.
31 */
32 tags?: Record<string, string>;
33 }
34
35 export interface Alarm extends Resource<
36 "AWS.CloudWatch.Alarm",
37 AlarmProps,
38 {
39 /** Physical name of the alarm. */
40 alarmName: AlarmName;
41 /** ARN of the alarm. */
42 alarmArn: AlarmArn;
43 /** Current state of the alarm (`OK`, `ALARM`, or `INSUFFICIENT_DATA`). */
44 stateValue: AlarmStateValue | undefined;
45 /** Human-readable reason for the current state. */
46 stateReason: string | undefined;
47 /** The full MetricAlarm description as last read from CloudWatch. */
48 metricAlarm: cloudwatch.MetricAlarm;
49 /** Tags on the alarm, including the internal Alchemy ownership tags. */
50 tags: Record<string, string>;
51 },
52 never,
53 Providers
54 > {}
55
56 /**
57 * A CloudWatch metric alarm — watches a single metric (or metric-math
58 * expression) and transitions between `OK`, `ALARM`, and
59 * `INSUFFICIENT_DATA`, optionally firing actions on state change.
60 * ### Creating Alarms
61 * **Example:** Threshold Alarm
62 * ```typescript
63 * const alarm = yield* Alarm("HighErrors", {
64 * MetricName: "Errors",
65 * Namespace: "AWS/Lambda",
66 * Statistic: "Sum",
67 * Period: 60,
68 * EvaluationPeriods: 1,
69 * Threshold: 1,
70 * ComparisonOperator: "GreaterThanOrEqualToThreshold",
71 * });
72 * ```
73 *
74 * **Example:** Alarm on a Lambda Function's Errors
75 * ```typescript
76 * const fn = yield* MyFunction;
77 *
78 * const alarm = yield* Alarm("FnErrors", {
79 * MetricName: "Errors",
80 * Namespace: "AWS/Lambda",
81 * Dimensions: [{ Name: "FunctionName", Value: fn.functionName }],
82 * Statistic: "Sum",
83 * Period: 60,
84 * EvaluationPeriods: 1,
85 * Threshold: 1,
86 * ComparisonOperator: "GreaterThanOrEqualToThreshold",
87 * TreatMissingData: "notBreaching",
88 * });
89 * ```
90 *
91 * ### Reading Alarm State at Runtime
92 * **Example:** Read the Alarm's State from a Function
93 * ```typescript
94 * // init — bind the alarm to the function (see DescribeAlarms)
95 * const describeAlarms = yield* AWS.CloudWatch.DescribeAlarms(alarm);
96 *
97 * // runtime
98 * const result = yield* describeAlarms();
99 * const state = result.MetricAlarms?.[0]?.StateValue;
100 * ```
101 *
102 * @resource
103 */
104 export const Alarm = Resource<Alarm>("AWS.CloudWatch.Alarm");
105
106 export const AlarmProvider = () =>
107 Provider.effect(
108 Alarm,
109 Effect.gen(function* () {
110 const createAlarmName = (id: string, props: { name?: string } = {}) =>
111 createName(id, props.name, 255);
112
113 const alarmArn = (alarmName: string) =>
114 AWSEnvironment.current.pipe(
115 Effect.map(
116 (env) =>
117 `arn:aws:cloudwatch:${env.region}:${env.accountId}:alarm:${alarmName}` as AlarmArn,
118 ),
119 );
120
121 const readAlarm = Effect.fn(function* (alarmName: string) {
122 const described = yield* cloudwatch.describeAlarms({
123 AlarmNames: [alarmName],
124 AlarmTypes: ["MetricAlarm"],
125 });
126 const metricAlarm = described.MetricAlarms?.find(
127 (candidate) => candidate.AlarmName === alarmName,
128 );
129
130 if (!metricAlarm?.AlarmName || !metricAlarm.AlarmArn) {
131 return undefined;
132 }
133
134 const tags = yield* readResourceTags(metricAlarm.AlarmArn).pipe(
135 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({})),
136 );
137
138 return {
139 alarmName: metricAlarm.AlarmName,
140 alarmArn: metricAlarm.AlarmArn as AlarmArn,
141 stateValue: metricAlarm.StateValue,
142 stateReason: metricAlarm.StateReason,
143 metricAlarm,
144 tags,
145 };
146 });
147
148 return {
149 stables: ["alarmName", "alarmArn"],
150 diff: Effect.fn(function* ({ id, olds = {}, news = {} }) {
151 if (!isResolved(news)) return undefined;
152 const oldName = yield* createAlarmName(id, olds);
153 const newName = yield* createAlarmName(id, news);
154
155 if (oldName !== newName) {
156 return { action: "replace" } as const;
157 }
158 }),
159 // Enumerate every MetricAlarm in the account/region by exhaustively
160 // paginating `describeAlarms` filtered to `MetricAlarm` (CompositeAlarm
161 // is owned by a separate resource). Each item is mapped to the same
162 // Attributes shape `read` produces, fetching tags per alarm.
163 list: () =>
164 Effect.gen(function* () {
165 const alarms = yield* cloudwatch.describeAlarms
166 .pages({ AlarmTypes: ["MetricAlarm"] })
167 .pipe(
168 Stream.runCollect,
169 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.MetricAlarms ?? [])),
170 );
171
172 const attrs: Alarm["Attributes"][] = yield* Effect.forEach(
173 alarms.filter(
174 (
175 metricAlarm,
176 ): metricAlarm is typeof metricAlarm & {
177 AlarmName: string;
178 AlarmArn: string;
179 } => metricAlarm.AlarmName != null && metricAlarm.AlarmArn != null,
180 ),
181 (metricAlarm) =>
182 Effect.gen(function* () {
183 const tags = yield* readResourceTags(metricAlarm.AlarmArn).pipe(
184 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({})),
185 );
186 return {
187 alarmName: metricAlarm.AlarmName,
188 alarmArn: metricAlarm.AlarmArn as AlarmArn,
189 stateValue: metricAlarm.StateValue,
190 stateReason: metricAlarm.StateReason,
191 metricAlarm,
192 tags,
193 };
194 }),
195 { concurrency: 10 },
196 );
197 return attrs;
198 }),
199 read: Effect.fn(function* ({ id, olds, output }) {
200 const name = output?.alarmName ?? (yield* createAlarmName(id, olds ?? {}));
201 const state = yield* readAlarm(name);
202 if (!state) return undefined;
203 return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state);
204 }),
205 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
206 // Observe — derive the alarm name and read whatever is currently
207 // in CloudWatch under that name. `output.alarmName` wins when
208 // present so an existing physical resource is never renamed.
209 const name = output?.alarmName ?? (yield* createAlarmName(id, news));
210 const existing = yield* readAlarm(name);
211
212 // Ensure — `putMetricAlarm` is an upsert; we always send the full
213 // desired config so the cloud converges to `news` regardless of
214 // whether the alarm pre-existed.
215 yield* retryConcurrent(
216 cloudwatch.putMetricAlarm({
217 ...news,
218 AlarmName: name,
219 }),
220 );
221
222 // Sync tags — diff observed (or prior) tags against desired and
223 // apply only the delta. On adoption `olds` is undefined, so we
224 // fall back to whatever we just observed.
225 const tags = yield* updateResourceTags({
226 id,
227 resourceArn: yield* alarmArn(name),
228 olds: olds?.tags ?? existing?.tags,
229 news: news.tags,
230 });
231
232 yield* session.note(yield* alarmArn(name));
233
234 const state = yield* readAlarm(name);
235 if (!state) {
236 return yield* new AlarmUnexpectedResponse({
237 message: `failed to read reconciled alarm '${name}'`,
238 });
239 }
240
241 return {
242 ...state,
243 tags,
244 };
245 }),
246 delete: Effect.fn(function* ({ output }) {
247 yield* retryConcurrent(
248 cloudwatch.deleteAlarms({
249 AlarmNames: [output.alarmName],
250 }),
251 );
252 }),
253 };
254 }),
255 );