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

main
ts 373 lines 13 KB
Raw
1 import * as rum from "@distilled.cloud/aws/rum";
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
11 /**
12 * One extended or custom metric a RUM app monitor derives from its telemetry
13 * events and sends to the destination.
14 */
15 export interface MetricDefinition {
16 /**
17 * Name of the metric. For extended metrics this must be one of the valid
18 * extended metric names (e.g. `SessionCount`, `JsErrorCount`); for custom
19 * metrics (CloudWatch destinations with a `namespace`) any name is
20 * allowed.
21 */
22 name: string;
23 /**
24 * Field within the event to use as the metric value. Omit to count
25 * matching events (value 1 per event).
26 */
27 valueKey?: string;
28 /**
29 * CloudWatch metric unit label (e.g. `Count`, `Milliseconds`).
30 */
31 unitLabel?: string;
32 /**
33 * Extra dimensions derived from event fields — maps the event field path
34 * (e.g. `metadata.browserName`) to the dimension name (e.g.
35 * `BrowserName`).
36 */
37 dimensionKeys?: Record<string, string>;
38 /**
39 * JSON event-pattern filter — only events matching the pattern contribute
40 * to the metric. Required for extended metrics, where it must match the
41 * metric's event type (e.g.
42 * `{"event_type":["com.amazon.rum.session_start_event"]}` for
43 * `SessionCount`).
44 */
45 eventPattern?: string;
46 /**
47 * Custom-metric namespace (CloudWatch destinations only). RUM prepends
48 * `RUM/CustomMetrics/`; it must not start with `AWS/`. Omit for extended
49 * metrics.
50 */
51 namespace?: string;
52 }
53
54 export interface MetricsDestinationProps {
55 /**
56 * Name of the CloudWatch RUM app monitor that sends metrics to this
57 * destination. Changing it replaces the destination.
58 */
59 appMonitorName: string;
60 /**
61 * Where the extended/custom metrics are sent. Changing it replaces the
62 * destination.
63 */
64 destination: "CloudWatch" | "Evidently";
65 /**
66 * ARN of the CloudWatch Evidently experiment receiving the metrics.
67 * Required when `destination` is `"Evidently"`; changing it replaces the
68 * destination.
69 */
70 destinationArn?: string;
71 /**
72 * ARN of the IAM role RUM assumes to write to the Evidently experiment.
73 * Required when `destination` is `"Evidently"`.
74 */
75 iamRoleArn?: string;
76 /**
77 * The extended/custom metric definitions the app monitor sends to this
78 * destination. Synced in place: added, updated, and removed definitions
79 * converge to this list.
80 */
81 metricDefinitions?: MetricDefinition[];
82 }
83
84 export interface MetricsDestination extends Resource<
85 "AWS.RUM.MetricsDestination",
86 MetricsDestinationProps,
87 {
88 /**
89 * Name of the app monitor sending metrics.
90 */
91 appMonitorName: string;
92 /**
93 * The destination kind (`CloudWatch` or `Evidently`).
94 */
95 destination: "CloudWatch" | "Evidently";
96 /**
97 * ARN of the Evidently experiment, when `destination` is `Evidently`.
98 */
99 destinationArn: string | undefined;
100 /**
101 * IAM role RUM assumes to write to the destination, when set.
102 */
103 iamRoleArn: string | undefined;
104 },
105 never,
106 Providers
107 > {}
108
109 /**
110 * A destination for CloudWatch RUM extended and custom metrics — sends
111 * metrics that a RUM app monitor derives from its telemetry events to
112 * CloudWatch or to a CloudWatch Evidently experiment, including the metric
113 * definitions themselves.
114 *
115 * ### Creating a Metrics Destination
116 * **Example:** Send Extended Metrics to CloudWatch
117 * ```typescript
118 * const monitor = yield* RUM.AppMonitor("SiteMonitor", {
119 * domain: "example.com",
120 * });
121 * const metrics = yield* RUM.MetricsDestination("SiteMetrics", {
122 * appMonitorName: monitor.appMonitorName,
123 * destination: "CloudWatch",
124 * // extended metrics require the event pattern matching the metric
125 * metricDefinitions: [
126 * {
127 * name: "SessionCount",
128 * eventPattern: JSON.stringify({
129 * event_type: ["com.amazon.rum.session_start_event"],
130 * }),
131 * },
132 * ],
133 * });
134 * ```
135 *
136 * ### Custom Metrics
137 * **Example:** Derive a Custom Metric from Events
138 * ```typescript
139 * const metrics = yield* RUM.MetricsDestination("CustomMetrics", {
140 * appMonitorName: monitor.appMonitorName,
141 * destination: "CloudWatch",
142 * metricDefinitions: [
143 * {
144 * name: "Checkouts",
145 * namespace: "MyApp",
146 * unitLabel: "Count",
147 * eventPattern: JSON.stringify({
148 * event_type: ["com.example.checkout"],
149 * }),
150 * },
151 * ],
152 * });
153 * ```
154 *
155 * @resource
156 */
157 export const MetricsDestination = Resource<MetricsDestination>("AWS.RUM.MetricsDestination");
158
159 /**
160 * Raised when a `BatchCreateRumMetricDefinitions` /
161 * `BatchDeleteRumMetricDefinitions` call reports per-definition errors.
162 */
163 export class RumMetricDefinitionsError extends Data.TaggedError("RumMetricDefinitionsError")<{
164 message: string;
165 }> {}
166
167 const toWireDefinition = (def: MetricDefinition): rum.MetricDefinitionRequest => ({
168 Name: def.name,
169 ValueKey: def.valueKey,
170 UnitLabel: def.unitLabel,
171 DimensionKeys: def.dimensionKeys,
172 EventPattern: def.eventPattern,
173 Namespace: def.namespace,
174 });
175
176 const sameRecord = (
177 a: Record<string, string | undefined> | undefined,
178 b: Record<string, string | undefined> | undefined,
179 ) => {
180 const left = Object.entries(a ?? {}).filter(([, v]) => v !== undefined);
181 const right = Object.entries(b ?? {}).filter(([, v]) => v !== undefined);
182 return left.length === right.length && left.every(([k, v]) => (b ?? {})[k] === v);
183 };
184
185 const definitionInSync = (observed: rum.MetricDefinition, desired: MetricDefinition) =>
186 observed.ValueKey === desired.valueKey &&
187 observed.UnitLabel === desired.unitLabel &&
188 observed.EventPattern === desired.eventPattern &&
189 observed.Namespace === desired.namespace &&
190 sameRecord(observed.DimensionKeys, desired.dimensionKeys);
191
192 export const MetricsDestinationProvider = () =>
193 Provider.effect(
194 MetricsDestination,
195 Effect.gen(function* () {
196 /**
197 * Observe the live destination on the monitor; typed not-found (the
198 * monitor itself is gone) → undefined.
199 */
200 const observeDestination = Effect.fn(function* (
201 props: Pick<MetricsDestinationProps, "appMonitorName" | "destination" | "destinationArn">,
202 ) {
203 const destinations = yield* rum.listRumMetricsDestinations
204 .items({ AppMonitorName: props.appMonitorName })
205 .pipe(
206 Stream.runCollect,
207 Effect.catchTag("ResourceNotFoundException", () =>
208 Effect.succeed([] as rum.MetricDestinationSummary[]),
209 ),
210 );
211 return Array.from(destinations).find(
212 (d) =>
213 d.Destination === props.destination &&
214 (props.destination !== "Evidently" || d.DestinationArn === props.destinationArn),
215 );
216 });
217
218 const toAttrs = (
219 props: MetricsDestinationProps,
220 observed: rum.MetricDestinationSummary | undefined,
221 ) => ({
222 appMonitorName: props.appMonitorName,
223 destination: props.destination,
224 destinationArn: props.destinationArn,
225 iamRoleArn: observed?.IamRoleArn ?? props.iamRoleArn,
226 });
227
228 return {
229 stables: ["appMonitorName", "destination", "destinationArn"],
230
231 diff: Effect.fn(function* ({ olds, news }) {
232 if (!isResolved(news)) return undefined;
233 if (
234 olds?.appMonitorName !== news.appMonitorName ||
235 olds?.destination !== news.destination ||
236 olds?.destinationArn !== news.destinationArn
237 ) {
238 return { action: "replace" } as const;
239 }
240 }),
241
242 read: Effect.fn(function* ({ olds, output }) {
243 const identity = output ?? olds;
244 if (!identity) return undefined;
245 const observed = yield* observeDestination(identity);
246 if (observed === undefined) return undefined;
247 // Metrics destinations are not taggable — ownership is implied by
248 // the owned parent app monitor.
249 return {
250 appMonitorName: identity.appMonitorName,
251 destination: identity.destination,
252 destinationArn: identity.destinationArn,
253 iamRoleArn: observed.IamRoleArn,
254 };
255 }),
256
257 reconcile: Effect.fn(function* ({ news, session }) {
258 const props = news!;
259 const key = {
260 AppMonitorName: props.appMonitorName,
261 Destination: props.destination,
262 ...(props.destination === "Evidently" ? { DestinationArn: props.destinationArn } : {}),
263 };
264
265 // 1. OBSERVE — the live destination list is authoritative.
266 const observed = yield* observeDestination(props);
267
268 // 2. ENSURE + SYNC destination — `putRumMetricsDestination` is a
269 // true upsert; call it when missing or when the role drifts. A
270 // concurrent put surfaces as the typed ConflictException — a
271 // race, not a failure.
272 if (
273 observed === undefined ||
274 (props.iamRoleArn !== undefined && observed.IamRoleArn !== props.iamRoleArn)
275 ) {
276 yield* rum
277 .putRumMetricsDestination({
278 ...key,
279 IamRoleArn: props.iamRoleArn,
280 })
281 .pipe(
282 Effect.asVoid,
283 Effect.catchTag("ConflictException", () => Effect.void),
284 );
285 }
286
287 // 3. SYNC metric definitions — diff the OBSERVED definitions
288 // (keyed by name) against the desired list and apply only the
289 // delta: batch-create missing, update drifted, batch-delete
290 // extraneous.
291 const live = yield* rum.batchGetRumMetricDefinitions.items(key).pipe(
292 Stream.runCollect,
293 Effect.map((c) => Array.from(c)),
294 );
295 const desired = props.metricDefinitions ?? [];
296 const liveByName = new Map(live.map((d) => [d.Name, d]));
297 const desiredNames = new Set(desired.map((d) => d.name));
298
299 const toCreate = desired.filter((d) => !liveByName.has(d.name));
300 if (toCreate.length > 0) {
301 const { Errors } = yield* rum.batchCreateRumMetricDefinitions({
302 ...key,
303 MetricDefinitions: toCreate.map(toWireDefinition),
304 });
305 if (Errors.length > 0) {
306 return yield* new RumMetricDefinitionsError({
307 message: `failed to create ${Errors.length} metric definition(s): ${Errors.map(
308 (e) => `${e.MetricDefinition.Name}: ${e.ErrorMessage}`,
309 ).join("; ")}`,
310 });
311 }
312 }
313
314 yield* Effect.forEach(
315 desired.flatMap((d) => {
316 const current = liveByName.get(d.name);
317 return current !== undefined && !definitionInSync(current, d)
318 ? [{ id: current.MetricDefinitionId, definition: d }]
319 : [];
320 }),
321 ({ id, definition }) =>
322 rum.updateRumMetricDefinition({
323 ...key,
324 MetricDefinitionId: id,
325 MetricDefinition: toWireDefinition(definition),
326 }),
327 );
328
329 const toDelete = live.filter((d) => !desiredNames.has(d.Name));
330 if (toDelete.length > 0) {
331 const { Errors } = yield* rum.batchDeleteRumMetricDefinitions({
332 ...key,
333 MetricDefinitionIds: toDelete.map((d) => d.MetricDefinitionId),
334 });
335 if (Errors.length > 0) {
336 return yield* new RumMetricDefinitionsError({
337 message: `failed to delete ${Errors.length} metric definition(s): ${Errors.map(
338 (e) => `${e.MetricDefinitionId}: ${e.ErrorMessage}`,
339 ).join("; ")}`,
340 });
341 }
342 }
343
344 yield* session.note(`${props.appMonitorName}/${props.destination}`);
345 const final = yield* observeDestination(props);
346 return toAttrs(props, final);
347 }),
348
349 delete: Effect.fn(function* ({ output }) {
350 yield* rum
351 .deleteRumMetricsDestination({
352 AppMonitorName: output.appMonitorName,
353 Destination: output.destination,
354 ...(output.destination === "Evidently"
355 ? { DestinationArn: output.destinationArn }
356 : {}),
357 })
358 .pipe(
359 // idempotent — the destination (or its whole monitor) may be gone
360 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
361 Effect.retry({
362 while: (e) => e._tag === "ConflictException",
363 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(8)]),
364 }),
365 );
366 }),
367
368 // Sub-resource keyed by its parent app monitor — enumerating it
369 // would require listing every monitor's destinations.
370 list: () => Effect.succeed([]),
371 };
372 }),
373 );