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

main
ts 329 lines 9.88 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 Stream from "effect/Stream";
8 import { AWSEnvironment, type AccountID } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import { createName, retryConcurrent } from "./common.ts";
11
12 export class DashboardUnexpectedResponse extends Data.TaggedError("DashboardUnexpectedResponse")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export type DashboardName = string;
18 export type DashboardArn = `arn:aws:cloudwatch::${AccountID}:dashboard/${string}`;
19
20 export type DashboardPeriodOverride = "inherit" | "auto";
21 export type DashboardMetricRow = (string | number | boolean | null)[];
22
23 export interface DashboardMetricWidgetProperties {
24 title?: string;
25 region?: string;
26 stat?: string;
27 period?: number;
28 view?: "timeSeries" | "singleValue" | "gauge" | "bar" | "pie";
29 stacked?: boolean;
30 metrics: DashboardMetricRow[];
31 annotations?: Record<string, unknown>;
32 yAxis?: Record<string, unknown>;
33 legend?: Record<string, unknown>;
34 [key: string]: unknown;
35 }
36
37 export interface DashboardTextWidgetProperties {
38 markdown: string;
39 [key: string]: unknown;
40 }
41
42 export interface DashboardAlarmStatusWidgetProperties {
43 alarms: string[];
44 title?: string;
45 sortBy?: string;
46 states?: string[];
47 [key: string]: unknown;
48 }
49
50 export interface DashboardLogWidgetProperties {
51 query: string;
52 region?: string;
53 title?: string;
54 view?: "table" | "timeSeries" | "bar" | "pie";
55 [key: string]: unknown;
56 }
57
58 export interface DashboardMetricWidget {
59 type: "metric";
60 x?: number;
61 y?: number;
62 width?: number;
63 height?: number;
64 properties: DashboardMetricWidgetProperties;
65 }
66
67 export interface DashboardTextWidget {
68 type: "text";
69 x?: number;
70 y?: number;
71 width?: number;
72 height?: number;
73 properties: DashboardTextWidgetProperties;
74 }
75
76 export interface DashboardAlarmStatusWidget {
77 type: "alarm";
78 x?: number;
79 y?: number;
80 width?: number;
81 height?: number;
82 properties: DashboardAlarmStatusWidgetProperties;
83 }
84
85 export interface DashboardLogWidget {
86 type: "log";
87 x?: number;
88 y?: number;
89 width?: number;
90 height?: number;
91 properties: DashboardLogWidgetProperties;
92 }
93
94 export type DashboardWidget =
95 | DashboardMetricWidget
96 | DashboardTextWidget
97 | DashboardAlarmStatusWidget
98 | DashboardLogWidget;
99
100 export interface DashboardBody {
101 start?: string;
102 end?: string;
103 periodOverride?: DashboardPeriodOverride;
104 widgets: DashboardWidget[];
105 variables?: Record<string, unknown>[];
106 }
107
108 export interface DashboardProps extends Omit<
109 cloudwatch.PutDashboardInput,
110 "DashboardName" | "DashboardBody"
111 > {
112 /**
113 * Name of the dashboard. If omitted, a unique name is generated.
114 */
115 name?: DashboardName;
116 /**
117 * Structured dashboard document. The provider serializes it to the JSON
118 * string expected by the CloudWatch API.
119 */
120 DashboardBody: DashboardBody;
121 /**
122 * Optional tags to apply to the dashboard.
123 *
124 * CloudWatch dashboards do not currently support the generic CloudWatch
125 * tagging APIs, so these values are accepted for API consistency but are not
126 * persisted remotely.
127 */
128 tags?: Record<string, string>;
129 }
130
131 export interface Dashboard extends Resource<
132 "AWS.CloudWatch.Dashboard",
133 DashboardProps,
134 {
135 /** Physical name of the dashboard. */
136 dashboardName: DashboardName;
137 /** ARN of the dashboard. */
138 dashboardArn: DashboardArn;
139 /** The parsed dashboard document as last read from CloudWatch. */
140 dashboardBody: DashboardBody | undefined;
141 /** Tags accepted for API consistency (not persisted remotely). */
142 tags: Record<string, string>;
143 },
144 never,
145 Providers
146 > {}
147
148 /**
149 * An Amazon CloudWatch dashboard. The `DashboardBody` is a structured,
150 * typed document (metric, text, alarm-status, and log widgets) that the
151 * provider serializes to the JSON string CloudWatch expects.
152 * ### Creating Dashboards
153 * **Example:** Basic Dashboard
154 * ```typescript
155 * const dashboard = yield* Dashboard("OpsDashboard", {
156 * DashboardBody: {
157 * widgets: [],
158 * },
159 * });
160 * ```
161 *
162 * **Example:** Dashboard with Metric and Text Widgets
163 * ```typescript
164 * const dashboard = yield* Dashboard("PaymentsDashboard", {
165 * DashboardBody: {
166 * widgets: [
167 * {
168 * type: "text",
169 * x: 0, y: 0, width: 6, height: 3,
170 * properties: { markdown: "# Payments service" },
171 * },
172 * {
173 * type: "metric",
174 * x: 0, y: 3, width: 12, height: 6,
175 * properties: {
176 * title: "Payments processed",
177 * metrics: [["MyApp/Payments", "PaymentProcessed"]],
178 * stat: "Sum",
179 * period: 60,
180 * view: "timeSeries",
181 * },
182 * },
183 * ],
184 * },
185 * });
186 * ```
187 *
188 * ### Reading Dashboards at Runtime
189 * **Example:** Read the Dashboard Body from a Function
190 * ```typescript
191 * // init — bind the dashboard to the function (see GetDashboard)
192 * const getDashboard = yield* AWS.CloudWatch.GetDashboard(dashboard);
193 *
194 * // runtime
195 * const result = yield* getDashboard();
196 * const body = JSON.parse(result.DashboardBody ?? "{}");
197 * ```
198 *
199 * @resource
200 */
201 export const Dashboard = Resource<Dashboard>("AWS.CloudWatch.Dashboard");
202
203 const serializeDashboardBody = (body: DashboardBody) => JSON.stringify(body);
204
205 const parseDashboardBody = (body: string | undefined) => {
206 if (!body) {
207 return undefined;
208 }
209 return JSON.parse(body) as DashboardBody;
210 };
211
212 export const DashboardProvider = () =>
213 Provider.effect(
214 Dashboard,
215 Effect.gen(function* () {
216 const createDashboardName = (id: string, props: { name?: string } = {}) =>
217 createName(id, props.name, 255);
218
219 const dashboardArn = (dashboardName: string) =>
220 AWSEnvironment.current.pipe(
221 Effect.map(
222 (env) =>
223 `arn:aws:cloudwatch::${env.accountId}:dashboard/${dashboardName}` as DashboardArn,
224 ),
225 );
226
227 const readDashboard = Effect.fn(function* (dashboardName: string) {
228 const output = yield* cloudwatch
229 .getDashboard({
230 DashboardName: dashboardName,
231 })
232 .pipe(Effect.catchTag("DashboardNotFoundError", () => Effect.undefined));
233
234 if (!output?.DashboardName) {
235 return undefined;
236 }
237
238 return {
239 dashboardName: output.DashboardName,
240 dashboardArn: yield* dashboardArn(output.DashboardName),
241 dashboardBody: parseDashboardBody(output.DashboardBody),
242 tags: {},
243 };
244 });
245
246 return {
247 stables: ["dashboardName", "dashboardArn"],
248 diff: Effect.fn(function* ({ id, olds = {}, news = {} as DashboardProps }) {
249 if (!isResolved(news)) return undefined;
250 const oldName = yield* createDashboardName(id, olds);
251 const newName = yield* createDashboardName(id, news);
252
253 if (oldName !== newName) {
254 return { action: "replace" } as const;
255 }
256 }),
257 read: Effect.fn(function* ({ id, olds, output }) {
258 const name = output?.dashboardName ?? (yield* createDashboardName(id, olds ?? {}));
259 return yield* readDashboard(name);
260 }),
261 reconcile: Effect.fn(function* ({ id, news, output, session }) {
262 // Observe — pin the physical name from `output` if present so we
263 // never rename an existing dashboard; otherwise derive from
264 // desired props.
265 const name = output?.dashboardName ?? (yield* createDashboardName(id, news));
266
267 // Ensure — `putDashboard` is a pure upsert. The CloudWatch
268 // dashboard API has no separate update path, so we always send
269 // the full body and let the API converge.
270 yield* retryConcurrent(
271 cloudwatch.putDashboard({
272 DashboardName: name,
273 DashboardBody: serializeDashboardBody(news.DashboardBody),
274 }),
275 );
276
277 yield* session.note(yield* dashboardArn(name));
278
279 const state = yield* readDashboard(name);
280 if (!state) {
281 return yield* new DashboardUnexpectedResponse({
282 message: `failed to read reconciled dashboard '${name}'`,
283 });
284 }
285
286 // Dashboards do not support the generic CloudWatch tagging APIs,
287 // so `tags` is always returned as an empty record.
288 return {
289 ...state,
290 tags: {},
291 };
292 }),
293 delete: Effect.fn(function* ({ output }) {
294 // `DeleteDashboards` is idempotent: AWS returns success (not
295 // `DashboardNotFoundError`) for names that don't exist, so a
296 // re-delete after a state-persistence failure is a safe no-op.
297 yield* retryConcurrent(
298 cloudwatch.deleteDashboards({
299 DashboardNames: [output.dashboardName],
300 }),
301 );
302 }),
303 list: () =>
304 Effect.gen(function* () {
305 // `listDashboards` only returns entry metadata (name/arn/size),
306 // not the body, so we re-read each dashboard to produce the full
307 // Attributes shape `read` returns.
308 const names = yield* cloudwatch.listDashboards.pages({}).pipe(
309 Stream.runCollect,
310 Effect.map((chunk) =>
311 Array.from(chunk).flatMap((page) =>
312 (page.DashboardEntries ?? [])
313 .map((entry) => entry.DashboardName)
314 .filter((name): name is string => name != null),
315 ),
316 ),
317 );
318
319 const states = yield* Effect.forEach(names, (name) => readDashboard(name), {
320 concurrency: 10,
321 });
322
323 return states.filter(
324 (state): state is NonNullable<typeof state> => state !== undefined,
325 );
326 }),
327 };
328 }),
329 );