The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as cloudwatch from "@distilled.cloud/aws/cloudwatch"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import type { Input } from "alchemy/Input"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Stream from "effect/Stream"; |
| 11 | import { AWSEnvironment, type AccountID } from "../Environment.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import type { RegionID } from "../Region.ts"; |
| 14 | import { createName, readResourceTags, retryConcurrent, updateResourceTags } from "./common.ts"; |
| 15 | |
| 16 | export class MetricStreamUnexpectedResponse extends Data.TaggedError( |
| 17 | "MetricStreamUnexpectedResponse", |
| 18 | )<{ |
| 19 | readonly message: string; |
| 20 | readonly cause?: unknown; |
| 21 | }> {} |
| 22 | |
| 23 | export type MetricStreamName = string; |
| 24 | export type MetricStreamArn = `arn:aws:cloudwatch:${RegionID}:${AccountID}:metric-stream/${string}`; |
| 25 | |
| 26 | export interface MetricStreamProps extends Omit<cloudwatch.PutMetricStreamInput, "Name" | "Tags"> { |
| 27 | /** |
| 28 | * Name of the metric stream. If omitted, a unique name is generated. |
| 29 | */ |
| 30 | name?: MetricStreamName; |
| 31 | /** |
| 32 | * Whether the stream should be running after deployment. |
| 33 | * @default true |
| 34 | */ |
| 35 | enabled?: boolean; |
| 36 | /** |
| 37 | * Optional tags to apply to the metric stream. |
| 38 | */ |
| 39 | tags?: Record<string, string>; |
| 40 | } |
| 41 | |
| 42 | export interface MetricStream extends Resource< |
| 43 | "AWS.CloudWatch.MetricStream", |
| 44 | MetricStreamProps, |
| 45 | { |
| 46 | /** Physical name of the metric stream. */ |
| 47 | metricStreamName: MetricStreamName; |
| 48 | /** ARN of the metric stream. */ |
| 49 | metricStreamArn: MetricStreamArn; |
| 50 | /** Current state of the stream (`running` or `stopped`). */ |
| 51 | state: string | undefined; |
| 52 | /** The full metric stream description as last read from CloudWatch. */ |
| 53 | metricStream: cloudwatch.GetMetricStreamOutput; |
| 54 | /** Tags on the metric stream, including the internal Alchemy ownership tags. */ |
| 55 | tags: Record<string, string>; |
| 56 | }, |
| 57 | never, |
| 58 | Providers |
| 59 | > {} |
| 60 | |
| 61 | /** |
| 62 | * A CloudWatch metric stream — continuously exports CloudWatch metrics to |
| 63 | * a Kinesis Data Firehose delivery stream (and on to S3, Datadog, etc.). |
| 64 | * ### Creating Metric Streams |
| 65 | * **Example:** Firehose Delivery Stream |
| 66 | * ```typescript |
| 67 | * const stream = yield* MetricStream("MetricsExport", { |
| 68 | * FirehoseArn: "arn:aws:firehose:us-east-1:123456789012:deliverystream/example", |
| 69 | * RoleArn: "arn:aws:iam::123456789012:role/example", |
| 70 | * OutputFormat: "json", |
| 71 | * }); |
| 72 | * ``` |
| 73 | * |
| 74 | * **Example:** Stream Only Selected Namespaces |
| 75 | * ```typescript |
| 76 | * const stream = yield* MetricStream("LambdaMetricsExport", { |
| 77 | * FirehoseArn: firehose.deliveryStreamArn, |
| 78 | * RoleArn: role.roleArn, |
| 79 | * OutputFormat: "json", |
| 80 | * IncludeFilters: [{ Namespace: "AWS/Lambda" }], |
| 81 | * }); |
| 82 | * ``` |
| 83 | * |
| 84 | * ### Reading Metric Streams at Runtime |
| 85 | * **Example:** Read the Stream's State from a Function |
| 86 | * ```typescript |
| 87 | * // init — bind the stream to the function (see GetMetricStream) |
| 88 | * const getMetricStream = yield* AWS.CloudWatch.GetMetricStream(stream); |
| 89 | * |
| 90 | * // runtime |
| 91 | * const result = yield* getMetricStream(); |
| 92 | * const state = result.State; // "running" | "stopped" |
| 93 | * ``` |
| 94 | * |
| 95 | * @resource |
| 96 | */ |
| 97 | export const MetricStream = Resource<MetricStream>("AWS.CloudWatch.MetricStream"); |
| 98 | |
| 99 | export const MetricStreamProvider = () => |
| 100 | Provider.effect( |
| 101 | MetricStream, |
| 102 | Effect.gen(function* () { |
| 103 | const createMetricStreamName = (id: string, props: { name?: string } = {}) => |
| 104 | createName(id, props.name, 255); |
| 105 | |
| 106 | const metricStreamArn = (name: string) => |
| 107 | AWSEnvironment.current.pipe( |
| 108 | Effect.map( |
| 109 | (env) => |
| 110 | `arn:aws:cloudwatch:${env.region}:${env.accountId}:metric-stream/${name}` as MetricStreamArn, |
| 111 | ), |
| 112 | ); |
| 113 | |
| 114 | const readMetricStream = Effect.fn(function* (name: string) { |
| 115 | const output = yield* cloudwatch |
| 116 | .getMetricStream({ |
| 117 | Name: name, |
| 118 | }) |
| 119 | .pipe( |
| 120 | Effect.catchTags({ |
| 121 | InvalidParameterValueException: () => Effect.undefined, |
| 122 | ResourceNotFoundException: () => Effect.undefined, |
| 123 | }), |
| 124 | ); |
| 125 | |
| 126 | if (!output?.Name || !output.Arn) { |
| 127 | return undefined; |
| 128 | } |
| 129 | |
| 130 | const tags = yield* readResourceTags(output.Arn).pipe( |
| 131 | Effect.catchTags({ |
| 132 | ResourceNotFoundException: () => Effect.succeed({}), |
| 133 | InvalidParameterValueException: () => Effect.succeed({}), |
| 134 | }), |
| 135 | ); |
| 136 | |
| 137 | return { |
| 138 | metricStreamName: output.Name, |
| 139 | metricStreamArn: output.Arn as MetricStreamArn, |
| 140 | state: output.State, |
| 141 | metricStream: output, |
| 142 | tags, |
| 143 | }; |
| 144 | }); |
| 145 | |
| 146 | const syncMetricStreamState = Effect.fn(function* ({ |
| 147 | name, |
| 148 | enabled, |
| 149 | }: { |
| 150 | name: string; |
| 151 | enabled: boolean | undefined; |
| 152 | }) { |
| 153 | if (enabled === false) { |
| 154 | yield* retryConcurrent( |
| 155 | cloudwatch.stopMetricStreams({ |
| 156 | Names: [name], |
| 157 | }), |
| 158 | ); |
| 159 | return; |
| 160 | } |
| 161 | |
| 162 | yield* retryConcurrent( |
| 163 | cloudwatch.startMetricStreams({ |
| 164 | Names: [name], |
| 165 | }), |
| 166 | ); |
| 167 | }); |
| 168 | |
| 169 | return { |
| 170 | stables: ["metricStreamName", "metricStreamArn"], |
| 171 | diff: Effect.fn(function* ({ id, olds = {}, news = {} as Input<MetricStreamProps> }) { |
| 172 | if (!isResolved(news)) return undefined; |
| 173 | const oldName = yield* createMetricStreamName(id, olds); |
| 174 | const newName = yield* createMetricStreamName(id, news); |
| 175 | |
| 176 | if (oldName !== newName) { |
| 177 | return { action: "replace" } as const; |
| 178 | } |
| 179 | }), |
| 180 | list: () => |
| 181 | Effect.gen(function* () { |
| 182 | // Enumerate every metric stream in the account/region. The list |
| 183 | // op only returns summary entries, so re-read each by name to |
| 184 | // produce the full Attributes shape `read` returns. |
| 185 | const entries = yield* cloudwatch.listMetricStreams.pages({}).pipe( |
| 186 | Stream.runCollect, |
| 187 | Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Entries ?? [])), |
| 188 | ); |
| 189 | |
| 190 | const results = yield* Effect.forEach( |
| 191 | entries, |
| 192 | (entry) => (entry.Name ? readMetricStream(entry.Name) : Effect.undefined), |
| 193 | { concurrency: 10 }, |
| 194 | ); |
| 195 | |
| 196 | return results.filter( |
| 197 | (state): state is NonNullable<typeof state> => state !== undefined, |
| 198 | ); |
| 199 | }), |
| 200 | read: Effect.fn(function* ({ id, olds, output }) { |
| 201 | const name = output?.metricStreamName ?? (yield* createMetricStreamName(id, olds ?? {})); |
| 202 | const state = yield* readMetricStream(name); |
| 203 | if (!state) return undefined; |
| 204 | return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state); |
| 205 | }), |
| 206 | reconcile: Effect.fn(function* ({ id, news, olds, output, session }) { |
| 207 | // Observe — pin the physical name from `output` if present; |
| 208 | // otherwise derive from desired props. Read existing so we have |
| 209 | // a baseline for tag-diffing on adoption. |
| 210 | const name = output?.metricStreamName ?? (yield* createMetricStreamName(id, news)); |
| 211 | const existing = yield* readMetricStream(name); |
| 212 | |
| 213 | // Ensure — `putMetricStream` is an upsert; we send the full |
| 214 | // desired config every reconcile. |
| 215 | yield* retryConcurrent( |
| 216 | cloudwatch.putMetricStream({ |
| 217 | ...news, |
| 218 | Name: name, |
| 219 | }), |
| 220 | ); |
| 221 | |
| 222 | // Sync running state — `enabled` drives start/stop independently |
| 223 | // of the put call. |
| 224 | yield* syncMetricStreamState({ |
| 225 | name, |
| 226 | enabled: news.enabled, |
| 227 | }); |
| 228 | |
| 229 | // Sync tags — diff against `olds.tags` when we have prior state, |
| 230 | // otherwise fall back to what we observed (adoption path). |
| 231 | const tags = yield* updateResourceTags({ |
| 232 | id, |
| 233 | resourceArn: yield* metricStreamArn(name), |
| 234 | olds: olds?.tags ?? existing?.tags, |
| 235 | news: news.tags, |
| 236 | }); |
| 237 | |
| 238 | yield* session.note(yield* metricStreamArn(name)); |
| 239 | |
| 240 | const state = yield* readMetricStream(name); |
| 241 | if (!state) { |
| 242 | return yield* new MetricStreamUnexpectedResponse({ |
| 243 | message: `failed to read reconciled metric stream '${name}'`, |
| 244 | }); |
| 245 | } |
| 246 | |
| 247 | return { |
| 248 | ...state, |
| 249 | tags, |
| 250 | }; |
| 251 | }), |
| 252 | delete: Effect.fn(function* ({ output }) { |
| 253 | const existing = yield* readMetricStream(output.metricStreamName); |
| 254 | if (!existing) { |
| 255 | return; |
| 256 | } |
| 257 | |
| 258 | yield* retryConcurrent( |
| 259 | cloudwatch.deleteMetricStream({ |
| 260 | Name: output.metricStreamName, |
| 261 | }), |
| 262 | ).pipe(Effect.catchTag("InvalidParameterValueException", () => Effect.void)); |
| 263 | }), |
| 264 | }; |
| 265 | }), |
| 266 | ); |