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

main
ts 440 lines 16.9 KB
Raw
1 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
2 import * as im from "@distilled.cloud/aws/internetmonitor";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14
15 export class InternetMonitorMonitorNotReady extends Data.TaggedError(
16 "InternetMonitorMonitorNotReady",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export interface MonitorProps {
23 /**
24 * Name of the monitor. Must be 1-255 characters of letters, digits,
25 * hyphens (-), periods (.) and underscores (_). If omitted, a
26 * deterministic physical name is generated. Changing the name replaces
27 * the monitor.
28 */
29 monitorName?: string;
30 /**
31 * ARNs of the resources to monitor — VPCs, Network Load Balancers,
32 * CloudFront distributions, or Amazon WorkSpaces directories. Added and
33 * removed in place via UpdateMonitor.
34 * @default [] — no resources are monitored until some are added
35 */
36 resources?: string[];
37 /**
38 * The maximum number of city-networks (client locations and ASNs,
39 * typically ISPs) to monitor for your resources. Caps the total traffic
40 * that Internet Monitor monitors (and therefore the cost). You must set
41 * either this or `trafficPercentageToMonitor`.
42 */
43 maxCityNetworksToMonitor?: number;
44 /**
45 * The percentage of the internet-facing traffic for your application to
46 * monitor. You must set either this or `maxCityNetworksToMonitor`.
47 */
48 trafficPercentageToMonitor?: number;
49 /**
50 * Publish internet measurements for the monitor to an Amazon S3 bucket
51 * (in addition to CloudWatch Logs).
52 */
53 internetMeasurementsLogDelivery?: im.InternetMeasurementsLogDelivery;
54 /**
55 * Health-event thresholds — the percentage of overall traffic impact at
56 * which the monitor creates availability or performance health events.
57 * @default AWS creates health events at a 95% threshold
58 */
59 healthEventsConfig?: im.HealthEventsConfig;
60 /**
61 * Desired state of the monitor — `"ACTIVE"` (monitoring) or
62 * `"INACTIVE"` (paused). Toggled in place via UpdateMonitor.
63 * @default "ACTIVE"
64 */
65 status?: "ACTIVE" | "INACTIVE";
66 /**
67 * User-defined tags for the monitor.
68 */
69 tags?: Record<string, string>;
70 }
71
72 export interface Monitor extends Resource<
73 "AWS.InternetMonitor.Monitor",
74 MonitorProps,
75 {
76 /** The name of the monitor. */
77 monitorName: string;
78 /** The ARN of the monitor. */
79 monitorArn: string;
80 /** The current status of the monitor (`ACTIVE`, `INACTIVE`, ...). */
81 status: string;
82 /** The health-event data-processing status of the monitor. */
83 processingStatus: string | undefined;
84 /** The ARNs of the resources the monitor watches. */
85 resources: string[];
86 /** The effective cap on monitored city-networks. */
87 maxCityNetworksToMonitor: number | undefined;
88 /** The effective percentage of traffic monitored. */
89 trafficPercentageToMonitor: number | undefined;
90 /** The tags applied to the monitor. */
91 tags: Record<string, string>;
92 },
93 never,
94 Providers
95 > {}
96
97 /**
98 * An Amazon CloudWatch Internet Monitor **monitor** — measures internet
99 * availability and performance between your AWS-hosted application and your
100 * end users' city-networks (client locations and ASNs, typically ISPs).
101 *
102 * A monitor is built from the application resources you add to it: VPCs,
103 * Network Load Balancers, CloudFront distributions, or WorkSpaces
104 * directories. Cost is controlled by capping the number of monitored
105 * city-networks (`maxCityNetworksToMonitor`) or the percentage of traffic
106 * monitored (`trafficPercentageToMonitor`).
107 *
108 * ### Creating a Monitor
109 * **Example:** Monitor for a VPC
110 * ```typescript
111 * import * as InternetMonitor from "@alchemy.run/aws/InternetMonitor";
112 *
113 * const monitor = yield* InternetMonitor.Monitor("AppMonitor", {
114 * resources: [`arn:aws:ec2:us-east-1:123456789012:vpc/${vpc.vpcId}`],
115 * maxCityNetworksToMonitor: 100,
116 * });
117 * ```
118 *
119 * **Example:** Monitor a percentage of traffic
120 * ```typescript
121 * const monitor = yield* InternetMonitor.Monitor("AppMonitor", {
122 * resources: [cloudfrontDistributionArn],
123 * trafficPercentageToMonitor: 50,
124 * });
125 * ```
126 *
127 * ### Health Events
128 * **Example:** Custom health-event thresholds
129 * ```typescript
130 * const monitor = yield* InternetMonitor.Monitor("AppMonitor", {
131 * resources: [vpcArn],
132 * maxCityNetworksToMonitor: 100,
133 * healthEventsConfig: {
134 * AvailabilityScoreThreshold: 90,
135 * PerformanceScoreThreshold: 90,
136 * },
137 * });
138 * ```
139 *
140 * ### Log Delivery
141 * **Example:** Publish measurements to S3
142 * ```typescript
143 * const monitor = yield* InternetMonitor.Monitor("AppMonitor", {
144 * resources: [vpcArn],
145 * maxCityNetworksToMonitor: 100,
146 * internetMeasurementsLogDelivery: {
147 * S3Config: {
148 * BucketName: bucket.bucketName,
149 * LogDeliveryStatus: "ENABLED",
150 * },
151 * },
152 * });
153 * ```
154 *
155 * @resource
156 */
157 export const Monitor = Resource<Monitor>("AWS.InternetMonitor.Monitor");
158
159 /** Normalize the wire tag map (values may be undefined) to a plain record. */
160 const toTagRecord = (
161 tags: { [key: string]: string | undefined } | undefined,
162 ): Record<string, string> =>
163 Object.fromEntries(
164 Object.entries(tags ?? {}).filter((entry): entry is [string, string] => entry[1] !== undefined),
165 );
166
167 const sameJson = (a: unknown, b: unknown): boolean => JSON.stringify(a) === JSON.stringify(b);
168
169 export const MonitorProvider = () =>
170 Provider.effect(
171 Monitor,
172 Effect.gen(function* () {
173 const createName = Effect.fn(function* (id: string, props: MonitorProps) {
174 return props.monitorName ?? (yield* createPhysicalName({ id }));
175 });
176
177 const readMonitor = Effect.fn(function* (name: string) {
178 return yield* im
179 .getMonitor({ MonitorName: name })
180 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
181 });
182
183 // Bounded wait for the monitor to leave PENDING (create and updates
184 // both transition PENDING -> ACTIVE/INACTIVE, typically in seconds).
185 const waitUntilSettled = Effect.fn(function* (name: string) {
186 const policy = Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(8)]);
187 return yield* readMonitor(name).pipe(
188 Effect.flatMap((monitor) => {
189 if (monitor === undefined) {
190 return Effect.fail(
191 new InternetMonitorMonitorNotReady({
192 message: `Internet Monitor monitor '${name}' not found`,
193 }),
194 );
195 }
196 if (monitor.Status === "PENDING") {
197 return Effect.fail(
198 new InternetMonitorMonitorNotReady({
199 message: `Internet Monitor monitor '${name}' is still PENDING`,
200 }),
201 );
202 }
203 return Effect.succeed(monitor);
204 }),
205 Effect.retry({ schedule: policy }),
206 );
207 });
208
209 const toAttrs = (monitor: im.GetMonitorOutput) => ({
210 monitorName: monitor.MonitorName,
211 monitorArn: monitor.MonitorArn,
212 status: monitor.Status,
213 processingStatus: monitor.ProcessingStatus,
214 resources: [...monitor.Resources],
215 maxCityNetworksToMonitor: monitor.MaxCityNetworksToMonitor,
216 trafficPercentageToMonitor: monitor.TrafficPercentageToMonitor,
217 tags: toTagRecord(monitor.Tags),
218 });
219
220 return Monitor.Provider.of({
221 stables: ["monitorName", "monitorArn"],
222
223 list: () =>
224 im.listMonitors.items({}).pipe(
225 Stream.runCollect,
226 Effect.flatMap((monitors) =>
227 Effect.forEach(
228 Array.from(monitors),
229 (monitor) =>
230 im.getMonitor({ MonitorName: monitor.MonitorName }).pipe(
231 Effect.map(toAttrs),
232 // Tolerate delete races between list and get.
233 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
234 ),
235 { concurrency: 4 },
236 ),
237 ),
238 Effect.map((attrs) => attrs.flatMap((a) => (a === undefined ? [] : [a]))),
239 ),
240
241 read: Effect.fn(function* ({ id, olds, output }) {
242 const name = output?.monitorName ?? (yield* createName(id, olds ?? {}));
243 const monitor = yield* readMonitor(name);
244 if (monitor === undefined) return undefined;
245 const attrs = toAttrs(monitor);
246 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
247 }),
248
249 diff: Effect.fn(function* ({ id, news, olds }) {
250 if (!isResolved(news)) return undefined;
251 // The name is the only immutable property; everything else is
252 // updatable in place via UpdateMonitor.
253 if ((yield* createName(id, olds)) !== (yield* createName(id, news))) {
254 return { action: "replace" } as const;
255 }
256 return undefined;
257 }),
258
259 reconcile: Effect.fn(function* ({ id, news, output, session }) {
260 const props = news!;
261 const name = output?.monitorName ?? (yield* createName(id, props));
262 const internalTags = yield* createInternalTags(id);
263 const desiredTags = { ...props.tags, ...internalTags };
264 const desiredStatus = props.status ?? "ACTIVE";
265
266 // 1. Observe — cloud state is authoritative.
267 let observed = yield* readMonitor(name);
268
269 // 2. Ensure — create if missing; a ConflictException means a peer
270 // created the same-named monitor concurrently, so re-observe.
271 if (observed === undefined) {
272 yield* im
273 .createMonitor({
274 MonitorName: name,
275 Resources: props.resources,
276 MaxCityNetworksToMonitor: props.maxCityNetworksToMonitor,
277 TrafficPercentageToMonitor: props.trafficPercentageToMonitor,
278 InternetMeasurementsLogDelivery: props.internetMeasurementsLogDelivery,
279 HealthEventsConfig: props.healthEventsConfig,
280 Tags: desiredTags,
281 })
282 .pipe(Effect.catchTag("ConflictException", () => Effect.void));
283 }
284
285 // Creation (and prior updates) surface as PENDING; wait (bounded)
286 // so UpdateMonitor is not rejected mid-transition.
287 observed = yield* waitUntilSettled(name);
288
289 // 3. Sync — compute the update delta from OBSERVED state and
290 // apply a single UpdateMonitor only when something changed.
291 const update: im.UpdateMonitorInput = { MonitorName: name };
292 let mutated = false;
293
294 if (props.resources !== undefined) {
295 const observedResources = observed.Resources;
296 const toAdd = props.resources.filter((arn) => !observedResources.includes(arn));
297 const toRemove = observedResources.filter((arn) => !props.resources!.includes(arn));
298 if (toAdd.length > 0) {
299 update.ResourcesToAdd = toAdd;
300 mutated = true;
301 }
302 if (toRemove.length > 0) {
303 update.ResourcesToRemove = toRemove;
304 mutated = true;
305 }
306 }
307 if (
308 props.maxCityNetworksToMonitor !== undefined &&
309 props.maxCityNetworksToMonitor !== observed.MaxCityNetworksToMonitor
310 ) {
311 update.MaxCityNetworksToMonitor = props.maxCityNetworksToMonitor;
312 mutated = true;
313 }
314 if (
315 props.trafficPercentageToMonitor !== undefined &&
316 props.trafficPercentageToMonitor !== observed.TrafficPercentageToMonitor
317 ) {
318 update.TrafficPercentageToMonitor = props.trafficPercentageToMonitor;
319 mutated = true;
320 }
321 if (
322 props.internetMeasurementsLogDelivery !== undefined &&
323 !sameJson(
324 props.internetMeasurementsLogDelivery,
325 observed.InternetMeasurementsLogDelivery,
326 )
327 ) {
328 update.InternetMeasurementsLogDelivery = props.internetMeasurementsLogDelivery;
329 mutated = true;
330 }
331 if (
332 props.healthEventsConfig !== undefined &&
333 !sameJson(props.healthEventsConfig, observed.HealthEventsConfig)
334 ) {
335 update.HealthEventsConfig = props.healthEventsConfig;
336 mutated = true;
337 }
338 if (
339 observed.Status !== desiredStatus &&
340 (observed.Status === "ACTIVE" || observed.Status === "INACTIVE")
341 ) {
342 update.Status = desiredStatus;
343 mutated = true;
344 }
345 if (mutated) {
346 yield* im.updateMonitor(update);
347 observed = yield* waitUntilSettled(name);
348 }
349
350 // 3b. Sync tags — diff against OBSERVED cloud tags.
351 const observedTags = toTagRecord(observed.Tags);
352 const { removed, upsert } = diffTags(observedTags, desiredTags);
353 if (upsert.length > 0) {
354 yield* im.tagResource({
355 ResourceArn: observed.MonitorArn,
356 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
357 });
358 }
359 if (removed.length > 0) {
360 yield* im.untagResource({
361 ResourceArn: observed.MonitorArn,
362 TagKeys: removed,
363 });
364 }
365
366 yield* session.note(name);
367 observed = (yield* readMonitor(name)) ?? observed;
368 return toAttrs(observed);
369 }),
370
371 delete: Effect.fn(function* ({ output }) {
372 const name = output.monitorName;
373 // DeleteMonitor rejects monitors that are not INACTIVE
374 // ("must be in inactive state before deletion") — deactivate
375 // first, then wait (bounded) for the transition to land.
376 const observed = yield* readMonitor(name);
377 if (observed === undefined) return;
378 if (observed.Status !== "INACTIVE") {
379 yield* im
380 .updateMonitor({ MonitorName: name, Status: "INACTIVE" })
381 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
382 yield* readMonitor(name).pipe(
383 Effect.flatMap((monitor) =>
384 monitor !== undefined && monitor.Status !== "INACTIVE"
385 ? Effect.fail(
386 new InternetMonitorMonitorNotReady({
387 message: `Internet Monitor monitor '${name}' is not yet INACTIVE (status: ${monitor.Status})`,
388 }),
389 )
390 : Effect.succeed(monitor),
391 ),
392 Effect.retry({
393 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(10)]),
394 }),
395 );
396 }
397 yield* im
398 .deleteMonitor({ MonitorName: name })
399 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
400
401 // Internet Monitor auto-creates per-monitor CloudWatch log groups
402 // (/aws/internet-monitor/{name}/{byCity,byCountry,byMetro,
403 // bySubdivision}) that survive DeleteMonitor — reap them so the
404 // monitor leaves no orphans (same doctrine as the Lambda Function
405 // /aws/lambda/{name} log-group reap).
406 const logGroupPrefix = `/aws/internet-monitor/${name}`;
407 const reapLogGroups = logs.describeLogGroups({ logGroupNamePrefix: logGroupPrefix }).pipe(
408 Effect.map((r) => r.logGroups ?? []),
409 Effect.flatMap((groups) =>
410 Effect.forEach(
411 groups.flatMap((g) =>
412 // Exact-prefix guard: never reap a sibling monitor whose
413 // name merely starts with ours.
414 g.logGroupName !== undefined &&
415 (g.logGroupName === logGroupPrefix ||
416 g.logGroupName.startsWith(`${logGroupPrefix}/`))
417 ? [g.logGroupName]
418 : [],
419 ),
420 (logGroupName) =>
421 logs
422 .deleteLogGroup({ logGroupName })
423 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)),
424 { concurrency: 4 },
425 ),
426 ),
427 );
428 // Log-group creation/delivery is asynchronous — a group can
429 // materialize shortly after the monitor is gone, so sweep again on
430 // a short bounded schedule (t=0s / 10s / 20s, each sweep idempotent).
431 yield* reapLogGroups.pipe(
432 Effect.repeat({
433 schedule: Schedule.spaced("10 seconds"),
434 times: 2,
435 }),
436 );
437 }),
438 });
439 }),
440 );