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

main
ts 434 lines 16 KB
Raw
1 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
2 import * as rum from "@distilled.cloud/aws/rum";
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 { AWSEnvironment } from "../Environment.ts";
14 import type { Providers } from "../Providers.ts";
15
16 /**
17 * Configuration for how the CloudWatch RUM web client collects data from
18 * your application's user sessions.
19 */
20 export interface AppMonitorConfiguration {
21 /**
22 * The ID of the Amazon Cognito identity pool used to authorize the sending
23 * of data to RUM.
24 */
25 identityPoolId?: string;
26 /**
27 * Pages in your application excluded from RUM data collection. You can't
28 * specify both `excludedPages` and `includedPages`.
29 */
30 excludedPages?: string[];
31 /**
32 * If your application has pages that RUM should collect data from and
33 * others it should not, list the pages to collect here. You can't specify
34 * both `excludedPages` and `includedPages`.
35 */
36 includedPages?: string[];
37 /**
38 * Pages to be displayed with a "favorite" icon in the CloudWatch RUM
39 * console.
40 */
41 favoritePages?: string[];
42 /**
43 * The portion of user sessions to sample for RUM data collection, between
44 * 0 and 1 (e.g. `0.1` samples 10% of sessions).
45 * @default 0.1
46 */
47 sessionSampleRate?: number;
48 /**
49 * The ARN of the guest IAM role attached to the Cognito identity pool that
50 * authorizes sending data to RUM.
51 */
52 guestRoleArn?: string;
53 /**
54 * Whether the RUM web client sets a cookie so that RUM can collect data
55 * about user sessions across page views.
56 * @default false
57 */
58 allowCookies?: boolean;
59 /**
60 * The kinds of telemetry to collect: `"errors"`, `"performance"`, and/or
61 * `"http"`.
62 */
63 telemetries?: ("errors" | "performance" | "http")[];
64 /**
65 * Whether RUM sends client-side traces to AWS X-Ray for sampled sessions.
66 * @default false
67 */
68 enableXRay?: boolean;
69 }
70
71 export interface AppMonitorProps {
72 /**
73 * Name of the app monitor. Changing the name replaces the app monitor.
74 * @default ${app}-${stage}-${id}
75 */
76 appMonitorName?: string;
77 /**
78 * The top-level internet domain name your application has administrative
79 * authority over, e.g. `example.com` or `*.example.com`. Specify exactly
80 * one of `domain` or `domainList`.
81 */
82 domain?: string;
83 /**
84 * List of internet domain names your application has administrative
85 * authority over (up to 5). Specify exactly one of `domain` or
86 * `domainList`.
87 */
88 domainList?: string[];
89 /**
90 * Configuration for how the RUM web client collects session data.
91 */
92 appMonitorConfiguration?: AppMonitorConfiguration;
93 /**
94 * Whether the app monitor copies the telemetry data it collects to a
95 * CloudWatch Logs log group in your account (retained for 30 days).
96 * @default false
97 */
98 cwLogEnabled?: boolean;
99 /**
100 * Whether the app monitor accepts custom events sent by the RUM web
101 * client.
102 * @default "DISABLED"
103 */
104 customEvents?: "ENABLED" | "DISABLED";
105 /**
106 * Tags to apply to the app monitor. Merged with internal Alchemy tags.
107 */
108 tags?: Record<string, string>;
109 }
110
111 export interface AppMonitor extends Resource<
112 "AWS.RUM.AppMonitor",
113 AppMonitorProps,
114 {
115 /**
116 * Name of the app monitor.
117 */
118 appMonitorName: string;
119 /**
120 * Unique ID of the app monitor (used by the RUM web client configuration).
121 */
122 appMonitorId: string;
123 /**
124 * ARN of the app monitor.
125 */
126 appMonitorArn: string;
127 },
128 never,
129 Providers
130 > {}
131
132 /**
133 * An Amazon CloudWatch RUM app monitor that collects client-side telemetry
134 * (page load times, JavaScript errors, user behavior) from your web
135 * application.
136 * ### Creating App Monitors
137 * **Example:** Monitor a single domain
138 * ```typescript
139 * import * as RUM from "@alchemy.run/aws/RUM";
140 *
141 * const monitor = yield* RUM.AppMonitor("SiteMonitor", {
142 * domain: "example.com",
143 * });
144 * ```
145 *
146 * **Example:** Sample all sessions and collect every telemetry type
147 * ```typescript
148 * const monitor = yield* RUM.AppMonitor("SiteMonitor", {
149 * domain: "*.example.com",
150 * appMonitorConfiguration: {
151 * sessionSampleRate: 1,
152 * telemetries: ["errors", "performance", "http"],
153 * allowCookies: true,
154 * },
155 * });
156 * ```
157 *
158 * ### Log Retention and Custom Events
159 * **Example:** Copy telemetry to CloudWatch Logs and accept custom events
160 * ```typescript
161 * const monitor = yield* RUM.AppMonitor("SiteMonitor", {
162 * domainList: ["example.com", "app.example.com"],
163 * cwLogEnabled: true,
164 * customEvents: "ENABLED",
165 * });
166 * ```
167 *
168 * @resource
169 */
170 export const AppMonitor = Resource<AppMonitor>("AWS.RUM.AppMonitor");
171
172 /**
173 * Raised when an `AppMonitor` is configured with both or neither of
174 * `domain` / `domainList` — the API requires exactly one.
175 */
176 export class RumAppMonitorInvalidDomains extends Data.TaggedError("RumAppMonitorInvalidDomains")<{
177 message: string;
178 }> {}
179
180 const validateDomains = (props: Pick<AppMonitorProps, "domain" | "domainList">) => {
181 const hasDomain = props.domain !== undefined;
182 const hasDomainList = (props.domainList?.length ?? 0) > 0;
183 if (hasDomain === hasDomainList) {
184 return Effect.fail(
185 new RumAppMonitorInvalidDomains({
186 message: hasDomain
187 ? "specify exactly one of domain or domainList, not both."
188 : "an AppMonitor requires either domain or domainList.",
189 }),
190 );
191 }
192 return Effect.void;
193 };
194
195 const sameStringList = (a: readonly string[] | undefined, b: readonly string[] | undefined) => {
196 const left = [...(a ?? [])].sort();
197 const right = [...(b ?? [])].sort();
198 return left.length === right.length && left.every((v, i) => v === right[i]);
199 };
200
201 const desiredConfiguration = (props: AppMonitorProps): rum.AppMonitorConfiguration | undefined => {
202 const c = props.appMonitorConfiguration;
203 if (c === undefined) return undefined;
204 return {
205 IdentityPoolId: c.identityPoolId,
206 ExcludedPages: c.excludedPages,
207 IncludedPages: c.includedPages,
208 FavoritePages: c.favoritePages,
209 SessionSampleRate: c.sessionSampleRate,
210 GuestRoleArn: c.guestRoleArn,
211 AllowCookies: c.allowCookies,
212 Telemetries: c.telemetries,
213 EnableXRay: c.enableXRay,
214 };
215 };
216
217 /** Compares only the fields the user explicitly configured against the observed cloud state. */
218 const configurationInSync = (
219 observed: rum.AppMonitorConfiguration | undefined,
220 desired: rum.AppMonitorConfiguration | undefined,
221 ) => {
222 if (desired === undefined) return true;
223 const o = observed ?? {};
224 return (
225 (desired.IdentityPoolId === undefined || o.IdentityPoolId === desired.IdentityPoolId) &&
226 (desired.ExcludedPages === undefined ||
227 sameStringList(o.ExcludedPages, desired.ExcludedPages)) &&
228 (desired.IncludedPages === undefined ||
229 sameStringList(o.IncludedPages, desired.IncludedPages)) &&
230 (desired.FavoritePages === undefined ||
231 sameStringList(o.FavoritePages, desired.FavoritePages)) &&
232 (desired.SessionSampleRate === undefined ||
233 o.SessionSampleRate === desired.SessionSampleRate) &&
234 (desired.GuestRoleArn === undefined || o.GuestRoleArn === desired.GuestRoleArn) &&
235 (desired.AllowCookies === undefined || (o.AllowCookies ?? false) === desired.AllowCookies) &&
236 (desired.Telemetries === undefined || sameStringList(o.Telemetries, desired.Telemetries)) &&
237 (desired.EnableXRay === undefined || (o.EnableXRay ?? false) === desired.EnableXRay)
238 );
239 };
240
241 const appMonitorArn = (region: string, accountId: string, name: string) =>
242 `arn:aws:rum:${region}:${accountId}:appmonitor/${name}`;
243
244 export const AppMonitorProvider = () =>
245 Provider.effect(
246 AppMonitor,
247 Effect.gen(function* () {
248 const createName = Effect.fn(function* (
249 id: string,
250 props: Pick<AppMonitorProps, "appMonitorName">,
251 ) {
252 return props.appMonitorName ?? (yield* createPhysicalName({ id, maxLength: 64 }));
253 });
254
255 const observeMonitor = (name: string) =>
256 rum.getAppMonitor({ Name: name }).pipe(
257 Effect.map((r) => r.AppMonitor),
258 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
259 );
260
261 return AppMonitor.Provider.of({
262 stables: ["appMonitorName", "appMonitorId", "appMonitorArn"],
263 list: () =>
264 Effect.gen(function* () {
265 const { accountId, region } = yield* AWSEnvironment.current;
266 const summaries = yield* rum.listAppMonitors.items({}).pipe(Stream.runCollect);
267 return Array.from(summaries).flatMap((monitor) =>
268 monitor.Name !== undefined && monitor.Id !== undefined
269 ? [
270 {
271 appMonitorName: monitor.Name,
272 appMonitorId: monitor.Id,
273 appMonitorArn: appMonitorArn(region, accountId, monitor.Name),
274 },
275 ]
276 : [],
277 );
278 }),
279 read: Effect.fn(function* ({ id, olds, output }) {
280 const { accountId, region } = yield* AWSEnvironment.current;
281 const name = output?.appMonitorName ?? (yield* createName(id, olds ?? {}));
282 const found = yield* observeMonitor(name);
283 if (found?.Id === undefined) return undefined;
284 const attrs = {
285 appMonitorName: name,
286 appMonitorId: found.Id,
287 appMonitorArn: appMonitorArn(region, accountId, name),
288 };
289 const tags = Object.fromEntries(
290 Object.entries(found.Tags ?? {}).filter(
291 (t): t is [string, string] => t[1] !== undefined,
292 ),
293 );
294 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
295 }),
296 diff: Effect.fn(function* ({ id, news, olds }) {
297 if (!isResolved(news)) return undefined;
298 yield* validateDomains(news ?? {});
299 const oldName = yield* createName(id, olds ?? {});
300 const newName = yield* createName(id, news ?? {});
301 if (oldName !== newName) {
302 return { action: "replace" } as const;
303 }
304 // fall through: engine default update logic for mutable fields
305 }),
306 reconcile: Effect.fn(function* ({ id, news, output, session }) {
307 yield* validateDomains(news);
308 const { accountId, region } = yield* AWSEnvironment.current;
309 const name = output?.appMonitorName ?? (yield* createName(id, news));
310 const arn = appMonitorArn(region, accountId, name);
311 const internalTags = yield* createInternalTags(id);
312 const desiredTags: Record<string, string> = {
313 ...news.tags,
314 ...internalTags,
315 };
316 const desiredConfig = desiredConfiguration(news);
317 const desiredCwLogEnabled = news.cwLogEnabled ?? false;
318 const desiredCustomEvents = news.customEvents ?? "DISABLED";
319
320 // 1. OBSERVE — cloud state is authoritative; output is only a
321 // cache of the derived physical name.
322 let live = yield* observeMonitor(name);
323
324 // 2. ENSURE — create when missing; a concurrent create surfaces as
325 // the typed ConflictException, which we treat as a race and
326 // re-observe. CreateAppMonitor is eventually consistent — an
327 // immediate GetAppMonitor can still miss it, and persisting an
328 // undefined appMonitorId poisons every downstream binding env —
329 // so poll (bounded) until the monitor is observable.
330 if (live === undefined) {
331 yield* rum
332 .createAppMonitor({
333 Name: name,
334 Domain: news.domain,
335 DomainList: news.domainList,
336 Tags: desiredTags,
337 AppMonitorConfiguration: desiredConfig,
338 CwLogEnabled: desiredCwLogEnabled,
339 CustomEvents: { Status: desiredCustomEvents },
340 })
341 .pipe(
342 Effect.asVoid,
343 Effect.catchTag("ConflictException", () => Effect.void),
344 );
345 live = yield* observeMonitor(name).pipe(
346 Effect.repeat({
347 schedule: Schedule.spaced("2 seconds"),
348 until: (monitor) => monitor !== undefined,
349 times: 15,
350 }),
351 );
352 }
353
354 // 3. SYNC — diff the OBSERVED domain(s), configuration, log
355 // setting, and custom-events status against the desired state;
356 // update only on drift.
357 const inSync =
358 live !== undefined &&
359 (news.domain === undefined || live.Domain === news.domain) &&
360 (news.domainList === undefined || sameStringList(live.DomainList, news.domainList)) &&
361 configurationInSync(live.AppMonitorConfiguration, desiredConfig) &&
362 (live.DataStorage?.CwLog?.CwLogEnabled ?? false) === desiredCwLogEnabled &&
363 (live.CustomEvents?.Status ?? "DISABLED") === desiredCustomEvents;
364 if (!inSync) {
365 yield* rum.updateAppMonitor({
366 Name: name,
367 Domain: news.domain,
368 DomainList: news.domainList,
369 AppMonitorConfiguration: desiredConfig,
370 CwLogEnabled: desiredCwLogEnabled,
371 CustomEvents: { Status: desiredCustomEvents },
372 });
373 live = yield* observeMonitor(name);
374 }
375
376 // 3b. SYNC TAGS — diff against OBSERVED cloud tags so adoption
377 // converges (create-time Tags only apply on first create).
378 const currentTags = Object.fromEntries(
379 Object.entries(live?.Tags ?? {}).filter(
380 (t): t is [string, string] => t[1] !== undefined,
381 ),
382 );
383 const { upsert, removed } = diffTags(currentTags, desiredTags);
384 if (upsert.length > 0) {
385 yield* rum.tagResource({
386 ResourceArn: arn,
387 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
388 });
389 }
390 if (removed.length > 0) {
391 yield* rum.untagResource({ ResourceArn: arn, TagKeys: removed });
392 }
393
394 yield* session.note(name);
395 return {
396 appMonitorName: name,
397 appMonitorId: live?.Id ?? output?.appMonitorId!,
398 appMonitorArn: arn,
399 };
400 }),
401 delete: Effect.fn(function* ({ output }) {
402 yield* rum.deleteAppMonitor({ Name: output.appMonitorName }).pipe(
403 // idempotent — the monitor may already be gone
404 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
405 );
406
407 // When cwLogEnabled is (or was ever) on, RUM vends telemetry into
408 // a log group named
409 // /aws/vendedlogs/RUMService_{appMonitorName}{first 8 hex chars of Id}
410 // and deleteAppMonitor does NOT remove it — without this reap every
411 // deleted log-enabled monitor leaks an orphaned log group. Match
412 // the observed groups against the monitor's Id so a sibling
413 // monitor whose name extends ours is never reaped by accident.
414 const logGroupPrefix = `/aws/vendedlogs/RUMService_${output.appMonitorName}`;
415 const idHex = output.appMonitorId.replaceAll("-", "");
416 const groups = yield* logs
417 .describeLogGroups({ logGroupNamePrefix: logGroupPrefix })
418 .pipe(Effect.map((r) => r.logGroups ?? []));
419 yield* Effect.forEach(
420 groups.flatMap((g) =>
421 g.logGroupName !== undefined &&
422 idHex.startsWith(g.logGroupName.slice(logGroupPrefix.length))
423 ? [g.logGroupName]
424 : [],
425 ),
426 (logGroupName) =>
427 logs
428 .deleteLogGroup({ logGroupName })
429 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)),
430 );
431 }),
432 });
433 }),
434 );