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

main
ts 248 lines 7.89 KB
Raw
1 import * as cloudwatch from "@distilled.cloud/aws/cloudwatch";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { detectorIdentity, matchesDetectorIdentity, retryConcurrent } from "./common.ts";
11
12 class AnomalyDetectorNotVisible extends Data.TaggedError("AnomalyDetectorNotVisible")<{
13 message: string;
14 }> {}
15
16 export interface AnomalyDetectorProps extends cloudwatch.PutAnomalyDetectorInput {}
17
18 export interface AnomalyDetector extends Resource<
19 "AWS.CloudWatch.AnomalyDetector",
20 AnomalyDetectorProps,
21 {
22 /** Synthetic identifier derived from the detector's metric identity. */
23 detectorId: string;
24 /** The full AnomalyDetector description as last read from CloudWatch. */
25 anomalyDetector: cloudwatch.AnomalyDetector;
26 },
27 never,
28 Providers
29 > {}
30
31 /**
32 * A CloudWatch anomaly detector — trains a model on a metric's historical
33 * data and computes an expected-value band, which alarms can use via the
34 * `ANOMALY_DETECTION_BAND` metric-math function.
35 * ### Creating Detectors
36 * **Example:** Single Metric Detector
37 * ```typescript
38 * const detector = yield* AnomalyDetector("ErrorsDetector", {
39 * Namespace: "AWS/Lambda",
40 * MetricName: "Errors",
41 * Stat: "Sum",
42 * });
43 * ```
44 *
45 * **Example:** Detector on a Custom Metric
46 * ```typescript
47 * // pair with PutMetricData publishing to the same namespace/metric
48 * const detector = yield* AnomalyDetector("PaymentsDetector", {
49 * Namespace: "MyApp/Payments",
50 * MetricName: "PaymentProcessed",
51 * Stat: "Sum",
52 * });
53 * ```
54 *
55 * ### Reading Detectors at Runtime
56 * **Example:** List Detectors from a Function
57 * ```typescript
58 * // init — see DescribeAnomalyDetectors
59 * const describeAnomalyDetectors = yield* AWS.CloudWatch.DescribeAnomalyDetectors();
60 *
61 * // runtime
62 * const result = yield* describeAnomalyDetectors({ Namespace: "MyApp/Payments" });
63 * ```
64 *
65 * @resource
66 */
67 export const AnomalyDetector = Resource<AnomalyDetector>("AWS.CloudWatch.AnomalyDetector");
68
69 const toDescribeRequest = (
70 input: cloudwatch.PutAnomalyDetectorInput,
71 ): cloudwatch.DescribeAnomalyDetectorsInput => {
72 if (input.MetricMathAnomalyDetector) {
73 return {
74 AnomalyDetectorTypes: ["METRIC_MATH"],
75 };
76 }
77
78 return {
79 Namespace: input.Namespace,
80 MetricName: input.MetricName,
81 Dimensions: input.Dimensions,
82 AnomalyDetectorTypes: ["SINGLE_METRIC"],
83 };
84 };
85
86 const toDeleteRequest = (
87 input: Pick<
88 cloudwatch.AnomalyDetector,
89 | "Namespace"
90 | "MetricName"
91 | "Dimensions"
92 | "Stat"
93 | "SingleMetricAnomalyDetector"
94 | "MetricMathAnomalyDetector"
95 >,
96 ): cloudwatch.DeleteAnomalyDetectorInput => {
97 if (input.MetricMathAnomalyDetector) {
98 return {
99 MetricMathAnomalyDetector: input.MetricMathAnomalyDetector,
100 };
101 }
102
103 if (input.SingleMetricAnomalyDetector) {
104 return {
105 SingleMetricAnomalyDetector: input.SingleMetricAnomalyDetector,
106 };
107 }
108
109 return {
110 Namespace: input.Namespace,
111 MetricName: input.MetricName,
112 Dimensions: input.Dimensions,
113 Stat: input.Stat,
114 };
115 };
116
117 const detectorReadinessSchedule = Schedule.max([Schedule.exponential(200), Schedule.recurs(8)]);
118
119 const describeDetector = Effect.fn(function* (
120 props: cloudwatch.PutAnomalyDetectorInput,
121 options?: {
122 resourceId?: string;
123 attempt?: number;
124 logMisses?: boolean;
125 },
126 ) {
127 const request = toDescribeRequest(props);
128 // Stop paginating at the first identity match; a miss drains every page
129 // anyway, which is exactly what the miss diagnostics below need.
130 const detectors = yield* cloudwatch.describeAnomalyDetectors.items(request).pipe(
131 Stream.takeUntil((candidate) => matchesDetectorIdentity(candidate, props)),
132 Stream.runCollect,
133 Effect.map((chunk) => Array.from(chunk)),
134 );
135 const detector = detectors.find((candidate) => matchesDetectorIdentity(candidate, props));
136
137 if (!detector && options?.logMisses) {
138 const prefix = options.resourceId
139 ? `${options.resourceId}: anomaly detector not yet visible`
140 : "anomaly detector not yet visible";
141 const attempt = options.attempt === undefined ? "" : ` (attempt ${options.attempt})`;
142
143 yield* Effect.logInfo(
144 `${prefix}${attempt}; request=${JSON.stringify(request)} candidates=${JSON.stringify(
145 detectors.map((candidate) => ({
146 identity: detectorIdentity(candidate),
147 Namespace: candidate.Namespace,
148 MetricName: candidate.MetricName,
149 Stat: candidate.Stat,
150 SingleMetricAnomalyDetector: candidate.SingleMetricAnomalyDetector,
151 MetricMathAnomalyDetector: candidate.MetricMathAnomalyDetector,
152 })),
153 )}`,
154 );
155 }
156
157 return detector;
158 });
159
160 export const AnomalyDetectorProvider = () =>
161 Provider.succeed(AnomalyDetector, {
162 stables: ["detectorId"],
163 list: () =>
164 // `describeAnomalyDetectors` is paginated and account/region-scoped;
165 // collect every page and flatten the `AnomalyDetectors` array into the
166 // full `Attributes` shape `read` produces (keyed by detector identity).
167 cloudwatch.describeAnomalyDetectors.pages({}).pipe(
168 Stream.runCollect,
169 Effect.map((chunk) =>
170 Array.from(chunk).flatMap((page) =>
171 (page.AnomalyDetectors ?? []).map((detector) => ({
172 detectorId: detectorIdentity(detector),
173 anomalyDetector: detector,
174 })),
175 ),
176 ),
177 ),
178 diff: Effect.fn(function* ({ olds = {}, news = {} }) {
179 if (!isResolved(news)) return undefined;
180 if (detectorIdentity(olds) !== detectorIdentity(news)) {
181 return { action: "replace" } as const;
182 }
183 }),
184 read: Effect.fn(function* ({ olds, output }) {
185 const props = output?.anomalyDetector ?? olds;
186 if (!props) {
187 return undefined;
188 }
189
190 const detector = yield* describeDetector(props);
191
192 if (!detector) {
193 return undefined;
194 }
195
196 return {
197 detectorId: detectorIdentity(props),
198 anomalyDetector: detector,
199 };
200 }),
201 reconcile: Effect.fn(function* ({ news, session }) {
202 // Ensure — `putAnomalyDetector` is an upsert keyed by the detector's
203 // identity (Namespace+MetricName+Dimensions+Stat or MetricMath
204 // expression). Sending desired props every reconcile converges the
205 // cloud regardless of whether this is first-create or an update.
206 yield* retryConcurrent(cloudwatch.putAnomalyDetector(news));
207 const detectorId = detectorIdentity(news);
208 yield* session.note(detectorId);
209
210 // Sync — describe the detector after the put. CloudWatch is
211 // eventually consistent for `DescribeAnomalyDetectors`, so we retry
212 // until the detector matching our identity is visible.
213 let attempt = 0;
214 const state = yield* Effect.suspend(() => {
215 attempt += 1;
216 return describeDetector(news, {
217 resourceId: "AnomalyDetector",
218 attempt,
219 logMisses: true,
220 }).pipe(
221 Effect.flatMap((state) =>
222 state
223 ? Effect.succeed(state)
224 : Effect.fail(
225 new AnomalyDetectorNotVisible({
226 message: "Anomaly detector not yet visible",
227 }),
228 ),
229 ),
230 );
231 }).pipe(
232 Effect.retry({
233 while: (error) => error._tag === "AnomalyDetectorNotVisible",
234 schedule: detectorReadinessSchedule,
235 }),
236 );
237
238 return {
239 detectorId,
240 anomalyDetector: state,
241 };
242 }),
243 delete: Effect.fn(function* ({ output }) {
244 yield* retryConcurrent(
245 cloudwatch.deleteAnomalyDetector(toDeleteRequest(output.anomalyDetector)),
246 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
247 }),
248 });