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

main
ts 395 lines 14.6 KB
Raw
1 import * as amp from "@distilled.cloud/aws/amp";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import { toWireDays } from "alchemy/Util/Duration";
8 import * as Data from "effect/Data";
9 import type * as Duration from "effect/Duration";
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 import { syncAmpTags, toTagRecord } from "./internal.ts";
15
16 export class AMPWorkspaceNotReady extends Data.TaggedError("AMPWorkspaceNotReady")<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export interface WorkspaceLabelSetLimit {
22 /**
23 * The label set the limit applies to, as exact label name/value pairs. An
24 * empty record (`{}`) is the default bucket — it applies to all time
25 * series that match no other label set entry.
26 */
27 labelSet: Record<string, string>;
28 /**
29 * Maximum number of active time series that can carry this label set.
30 * Omit to track the label set without enforcing a limit.
31 */
32 maxSeries?: number;
33 }
34
35 export interface WorkspaceProps {
36 /**
37 * A human-readable alias for the workspace. Aliases are not unique — many
38 * workspaces can share one. Updating the alias is an in-place update.
39 */
40 alias?: string;
41 /**
42 * ARN of a customer-managed KMS key used to encrypt data at rest. If
43 * omitted, an AWS-owned key is used. Changing the key replaces the
44 * workspace (encryption configuration is immutable).
45 */
46 kmsKeyArn?: string;
47 /**
48 * How long the workspace retains ingested metric data. Accepts any
49 * `Duration.Input` (e.g. `"30 days"`, `Duration.days(30)`; a bare number
50 * is milliseconds); the wire unit is whole days
51 * (`retentionPeriodInDays`). If omitted, the workspace keeps the service
52 * default retention (150 days) and any retention configured out-of-band
53 * is left untouched.
54 */
55 retentionPeriod?: Duration.Input;
56 /**
57 * Per-label-set ingestion limits (maximum active series per label set).
58 * If omitted, existing label-set limits are left untouched.
59 */
60 limitsPerLabelSet?: WorkspaceLabelSetLimit[];
61 /**
62 * User-defined tags for the workspace.
63 */
64 tags?: Record<string, string>;
65 }
66
67 export interface Workspace extends Resource<
68 "AWS.AMP.Workspace",
69 WorkspaceProps,
70 {
71 workspaceId: string;
72 workspaceArn: string;
73 prometheusEndpoint: string | undefined;
74 alias: string | undefined;
75 status: string;
76 },
77 never,
78 Providers
79 > {}
80
81 /**
82 * An Amazon Managed Service for Prometheus (AMP) workspace — a logical,
83 * fully-managed Prometheus-compatible metrics store. Metrics are ingested
84 * via remote-write and queried through the workspace's Prometheus-compatible
85 * endpoint.
86 *
87 * ### Creating a Workspace
88 * **Example:** Basic Workspace
89 * ```typescript
90 * const workspace = yield* AMP.Workspace("Metrics", {
91 * alias: "production-metrics",
92 * });
93 * ```
94 *
95 * **Example:** Workspace with Customer-Managed Encryption
96 * ```typescript
97 * const workspace = yield* AMP.Workspace("Metrics", {
98 * alias: "production-metrics",
99 * kmsKeyArn: key.keyArn,
100 * tags: { team: "observability" },
101 * });
102 * ```
103 *
104 * **Example:** Workspace with Custom Retention and Series Limits
105 * ```typescript
106 * const workspace = yield* AMP.Workspace("Metrics", {
107 * alias: "production-metrics",
108 * retentionPeriod: "30 days",
109 * limitsPerLabelSet: [
110 * { labelSet: { team: "billing" }, maxSeries: 100_000 },
111 * { labelSet: {}, maxSeries: 1_000_000 }, // default bucket
112 * ],
113 * });
114 * ```
115 *
116 * ### Using the Endpoint
117 * **Example:** Read the Remote-Write URL
118 * ```typescript
119 * // prometheusEndpoint ends in a trailing slash; append `api/v1/remote_write`
120 * const remoteWrite = `${workspace.prometheusEndpoint}api/v1/remote_write`;
121 * ```
122 *
123 * ### Runtime Bindings
124 * **Example:** Write and Query Metrics from a Function
125 * ```typescript
126 * // inside a Lambda Function's effect (provide the *Http layers):
127 * const remoteWrite = yield* AMP.RemoteWrite(workspace);
128 * const metrics = yield* AMP.QueryMetrics(workspace);
129 *
130 * yield* remoteWrite({
131 * timeseries: [{ name: "jobs_done_total", samples: [{ value: 1 }] }],
132 * });
133 * const result = yield* metrics.query({ query: "jobs_done_total" });
134 * ```
135 *
136 * @resource
137 */
138 export const Workspace = Resource<Workspace>("AWS.AMP.Workspace");
139
140 export const WorkspaceProvider = () =>
141 Provider.effect(
142 Workspace,
143 Effect.gen(function* () {
144 const toAttrs = (workspace: amp.WorkspaceDescription) => ({
145 workspaceId: workspace.workspaceId,
146 workspaceArn: workspace.arn,
147 prometheusEndpoint: workspace.prometheusEndpoint,
148 alias: workspace.alias,
149 status: workspace.status.statusCode,
150 });
151
152 /** Describe a workspace by id; typed not-found → undefined. */
153 const describe = Effect.fn(function* (workspaceId: string) {
154 const response = yield* amp
155 .describeWorkspace({ workspaceId })
156 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
157 return response?.workspace;
158 });
159
160 /**
161 * Find the workspace carrying this resource's alchemy ownership tags.
162 * Workspace ids are server-assigned, so when the persisted output is
163 * lost (e.g. a run crashed after create but before state persistence)
164 * this tag search is the only way to reclaim the existing workspace
165 * instead of creating an orphan-producing duplicate.
166 */
167 const findByInternalTags = Effect.fn(function* (internalTags: Record<string, string>) {
168 const pages = yield* amp.listWorkspaces.pages({}).pipe(Stream.runCollect);
169 const summary = Array.from(pages)
170 .flatMap((page) => page.workspaces)
171 .find(
172 (w) =>
173 w.status.statusCode !== "DELETING" &&
174 Object.entries(internalTags).every(
175 ([key, value]) => toTagRecord(w.tags)[key] === value,
176 ),
177 );
178 return summary === undefined ? undefined : yield* describe(summary.workspaceId);
179 });
180
181 /**
182 * Canonical form of a label-set-limits list for observed-vs-desired
183 * comparison: entries keyed and sorted by their sorted label set.
184 */
185 const canonicalLimits = (
186 limits: {
187 labelSet: Record<string, string | undefined>;
188 maxSeries: number | undefined;
189 }[],
190 ) =>
191 JSON.stringify(
192 limits
193 .map((entry) => ({
194 labelSet: Object.fromEntries(
195 Object.entries(entry.labelSet)
196 .filter((kv): kv is [string, string] => typeof kv[1] === "string")
197 .sort(([a], [b]) => a.localeCompare(b)),
198 ),
199 maxSeries: entry.maxSeries ?? null,
200 }))
201 .sort((a, b) => JSON.stringify(a.labelSet).localeCompare(JSON.stringify(b.labelSet))),
202 );
203
204 /**
205 * Sync the workspace configuration (retention period + label-set
206 * limits) — diff OBSERVED configuration against desired and apply
207 * only the delta. Skipped entirely when neither prop is set, so
208 * out-of-band configuration is never clobbered.
209 */
210 const syncWorkspaceConfiguration = Effect.fn(function* (
211 workspaceId: string,
212 news: WorkspaceProps,
213 ) {
214 if (news.retentionPeriod === undefined && news.limitsPerLabelSet === undefined) {
215 return;
216 }
217 const observed = (yield* amp.describeWorkspaceConfiguration({
218 workspaceId,
219 })).workspaceConfiguration;
220
221 const desiredDays = toWireDays(news.retentionPeriod);
222 const retentionDrifts =
223 desiredDays !== undefined && desiredDays !== observed.retentionPeriodInDays;
224
225 const desiredLimits = news.limitsPerLabelSet?.map((entry) => ({
226 labelSet: entry.labelSet,
227 limits: { maxSeries: entry.maxSeries },
228 }));
229 const limitsDrift =
230 desiredLimits !== undefined &&
231 canonicalLimits(
232 desiredLimits.map((l) => ({
233 labelSet: l.labelSet,
234 maxSeries: l.limits.maxSeries,
235 })),
236 ) !==
237 canonicalLimits(
238 (observed.limitsPerLabelSet ?? []).map((l) => ({
239 labelSet: l.labelSet,
240 maxSeries: l.limits.maxSeries,
241 })),
242 );
243
244 if (!retentionDrifts && !limitsDrift) return;
245
246 // A previous configuration update may still be applying
247 // (`UPDATING` rejects new updates with a conflict) — retry briefly.
248 yield* amp
249 .updateWorkspaceConfiguration({
250 workspaceId,
251 retentionPeriodInDays: desiredDays,
252 limitsPerLabelSet: desiredLimits,
253 })
254 .pipe(
255 Effect.retry({
256 while: (e) => e._tag === "ConflictException",
257 schedule: Schedule.max([Schedule.fixed("6 seconds"), Schedule.recurs(15)]),
258 }),
259 );
260
261 // Bounded best-effort wait for the update to apply (the status
262 // returns to ACTIVE once the new configuration is in effect). A
263 // slower apply converges on a later reconcile.
264 yield* amp.describeWorkspaceConfiguration({ workspaceId }).pipe(
265 Effect.map((r) => r.workspaceConfiguration),
266 Effect.repeat({
267 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(30)]),
268 until: (c): boolean =>
269 c.status.statusCode === "ACTIVE" &&
270 (desiredDays === undefined || c.retentionPeriodInDays === desiredDays),
271 }),
272 );
273 });
274
275 /**
276 * Poll until the workspace leaves CREATING/UPDATING and reaches
277 * ACTIVE. Fails fast on a *_FAILED terminal status.
278 */
279 const waitActive = Effect.fn(function* (workspaceId: string) {
280 const workspace = yield* amp.describeWorkspace({ workspaceId }).pipe(
281 Effect.map((r) => r.workspace),
282 Effect.repeat({
283 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]),
284 until: (w) => w.status.statusCode === "ACTIVE",
285 }),
286 );
287 if (workspace.status.statusCode !== "ACTIVE") {
288 return yield* new AMPWorkspaceNotReady({
289 message: `AMP workspace ${workspaceId} did not become ACTIVE (status: ${workspace.status.statusCode})`,
290 });
291 }
292 return workspace;
293 });
294
295 return {
296 stables: ["workspaceId", "workspaceArn", "prometheusEndpoint"],
297
298 diff: Effect.fn(function* ({ olds, news }) {
299 if (!isResolved(news)) return undefined;
300 // Encryption configuration is immutable — a change replaces.
301 if ((olds?.kmsKeyArn ?? undefined) !== (news?.kmsKeyArn ?? undefined)) {
302 return { action: "replace" } as const;
303 }
304 }),
305
306 read: Effect.fn(function* ({ id, output }) {
307 // Workspace ids are server-assigned; without an output cache the
308 // only recoverable identity is the alchemy ownership tags.
309 if (!output?.workspaceId) {
310 const internalTags = yield* createInternalTags(id);
311 const found = yield* findByInternalTags(internalTags);
312 // A tag match is by definition owned by this resource.
313 return found === undefined ? undefined : toAttrs(found);
314 }
315 const workspace = yield* describe(output.workspaceId);
316 if (workspace === undefined) return undefined;
317 const attrs = toAttrs(workspace);
318 const tags = toTagRecord(workspace.tags);
319 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
320 }),
321
322 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
323 const internalTags = yield* createInternalTags(id);
324 const desiredTags = { ...internalTags, ...news.tags };
325
326 // 1. Observe — cloud state is authoritative; output is an id cache.
327 // With no cached id (greenfield OR lost state after a crash), fall
328 // back to searching by ownership tags: the id is server-assigned,
329 // so tags are the only recoverable identity.
330 let workspace =
331 output?.workspaceId !== undefined
332 ? yield* describe(output.workspaceId)
333 : yield* findByInternalTags(internalTags);
334
335 // 2. Ensure — create if missing, then wait for ACTIVE.
336 if (workspace === undefined) {
337 const created = yield* amp.createWorkspace({
338 alias: news.alias,
339 kmsKeyArn: news.kmsKeyArn,
340 tags: desiredTags,
341 });
342 workspace = yield* waitActive(created.workspaceId);
343 }
344
345 const workspaceId = workspace.workspaceId;
346
347 // 3. Sync alias — in-place update when it drifts.
348 if ((news.alias ?? undefined) !== (workspace.alias ?? undefined)) {
349 yield* amp.updateWorkspaceAlias({
350 workspaceId,
351 alias: news.alias,
352 });
353 }
354
355 // 3b. Sync tags — diff against OBSERVED cloud tags.
356 yield* syncAmpTags(workspace.arn, desiredTags);
357
358 // 3c. Sync workspace configuration (retention + label-set limits).
359 yield* syncWorkspaceConfiguration(workspaceId, news);
360
361 // 4. Re-read for fresh attributes (alias/status may have changed).
362 const fresh = (yield* describe(workspaceId)) ?? workspace;
363 yield* session.note(workspaceId);
364 return toAttrs(fresh);
365 }),
366
367 delete: Effect.fn(function* ({ output }) {
368 yield* amp.deleteWorkspace({ workspaceId: output.workspaceId }).pipe(
369 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
370 // A workspace mid-transition rejects deletion; retry briefly.
371 Effect.retry({
372 while: (e) => e._tag === "ConflictException",
373 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
374 }),
375 );
376 }),
377
378 list: () =>
379 amp.listWorkspaces.pages({}).pipe(
380 Stream.runCollect,
381 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.workspaces)),
382 Effect.flatMap(
383 Effect.forEach(
384 (summary) =>
385 describe(summary.workspaceId).pipe(
386 Effect.map((w) => (w ? toAttrs(w) : undefined)),
387 ),
388 { concurrency: 4 },
389 ),
390 ),
391 Effect.map((items) => items.filter((item) => item !== undefined)),
392 ),
393 };
394 }),
395 );