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

main
ts 402 lines 15.1 KB
Raw
1 import * as cur from "@distilled.cloud/aws/cost-and-usage-report-service";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import { Region } from "../Region.ts";
14
15 // The Cost and Usage Report API (`cur`) is a global service hosted only in
16 // us-east-1 (the report's delivery bucket may live in any region — that is
17 // what `s3Region` describes). Every control-plane call is pinned there
18 // regardless of the ambient stack region. The distilled Region service value
19 // is `Effect<RegionName>`, not a raw string, hence Effect.succeed.
20 const CUR_REGION = "us-east-1";
21 const pin = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
22 effect.pipe(Effect.provideService(Region, Effect.succeed(CUR_REGION)));
23
24 // PutReportDefinition validates that the delivery bucket's policy grants
25 // billingreports.amazonaws.com access. A policy applied moments earlier (the
26 // usual case — the bucket is deployed in the same stack) can still be
27 // propagating, surfacing as a bucket-mentioning ValidationException (patched
28 // in distilled into the typed ReportBucketNotVerified tag). Bounded retry:
29 // 8 recurrences x 3s ≈ 24s. Explicit return annotation so the Retry.Return
30 // conditional type never leaks into declaration emit.
31 const retryBucketVerification = <A, E extends { readonly _tag: string }, R>(
32 self: Effect.Effect<A, E, R>,
33 ): Effect.Effect<A, E, R> =>
34 Effect.retry(self, {
35 while: (e) => e._tag === "ReportBucketNotVerified",
36 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(8)]),
37 });
38
39 export interface ReportDefinitionProps {
40 /**
41 * Name of the report (also the prefix of the report files in S3). Must be
42 * unique in the account; up to 256 characters of `A-Za-z0-9!\-_.*'()`.
43 * If omitted, a unique name is generated from the app, stage, and logical
44 * ID.
45 *
46 * Changing the name replaces the report definition.
47 */
48 reportName?: string;
49 /**
50 * The granularity of line items in the report.
51 */
52 timeUnit: "HOURLY" | "DAILY" | "MONTHLY" | (string & {});
53 /**
54 * The format the report files are generated in.
55 */
56 format: "textORcsv" | "Parquet" | (string & {});
57 /**
58 * The compression applied to the report files. Must be `Parquet` when
59 * `format` is `Parquet`.
60 */
61 compression: "ZIP" | "GZIP" | "Parquet" | (string & {});
62 /**
63 * Additional detail included in the report, e.g. `["RESOURCES"]` to include
64 * individual resource IDs.
65 * @default []
66 */
67 additionalSchemaElements?: (
68 | "RESOURCES"
69 | "SPLIT_COST_ALLOCATION_DATA"
70 | "MANUAL_DISCOUNT_COMPATIBILITY"
71 | (string & {})
72 )[];
73 /**
74 * Name of the S3 bucket the report is delivered to. The bucket policy must
75 * allow `billingreports.amazonaws.com` to call `s3:GetBucketAcl`,
76 * `s3:GetBucketPolicy`, and `s3:PutObject`.
77 */
78 s3Bucket: string;
79 /**
80 * S3 key prefix the report files are delivered under.
81 */
82 s3Prefix: string;
83 /**
84 * The region the delivery bucket lives in, e.g. `us-east-1`.
85 */
86 s3Region: string;
87 /**
88 * Artifacts AWS additionally prepares the report for (`REDSHIFT`,
89 * `QUICKSIGHT`, or `ATHENA`). `ATHENA` requires Parquet format/compression
90 * and `OVERWRITE_REPORT` versioning, and cannot be combined with the other
91 * artifacts.
92 */
93 additionalArtifacts?: ("REDSHIFT" | "QUICKSIGHT" | "ATHENA" | (string & {}))[];
94 /**
95 * Whether AWS updates previously delivered reports when charges are applied
96 * retroactively (refunds, credits, RI fees).
97 * @default true
98 */
99 refreshClosedReports?: boolean;
100 /**
101 * Whether each report update overwrites the previous version
102 * (`OVERWRITE_REPORT`) or is delivered alongside it (`CREATE_NEW_REPORT`).
103 * @default "CREATE_NEW_REPORT"
104 */
105 reportVersioning?: "CREATE_NEW_REPORT" | "OVERWRITE_REPORT" | (string & {});
106 /**
107 * ARN of the billing view the report is scoped to. Omit for the account's
108 * primary billing view.
109 *
110 * Changing the billing view replaces the report definition.
111 */
112 billingViewArn?: string;
113 /**
114 * Tags to apply to the report definition.
115 */
116 tags?: Record<string, string>;
117 }
118
119 export interface ReportDefinition extends Resource<
120 "AWS.CostAndUsageReport.ReportDefinition",
121 ReportDefinitionProps,
122 {
123 /** Name of the report definition. */
124 reportName: string;
125 /** ARN of the report definition. */
126 reportArn: string;
127 /** Granularity of the report (`HOURLY`, `DAILY`, `MONTHLY`). */
128 timeUnit: string;
129 /** File format of the report (`textORcsv` or `Parquet`). */
130 format: string;
131 /** Compression applied to report files (`ZIP`, `GZIP`, `Parquet`). */
132 compression: string;
133 /** Name of the S3 bucket the report is delivered to. */
134 s3Bucket: string;
135 /** S3 key prefix the report is delivered under. */
136 s3Prefix: string;
137 /** Region of the delivery S3 bucket. */
138 s3Region: string;
139 },
140 never,
141 Providers
142 > {}
143
144 /**
145 * An AWS Cost and Usage Report (CUR) definition — the most granular billing
146 * data AWS offers, delivered as CSV or Parquet files to an S3 bucket you own.
147 *
148 * The CUR API is a global service hosted only in `us-east-1`; this resource
149 * pins every control-plane call there regardless of the stack region. The
150 * delivery bucket may live in any region (declared via `s3Region`) but its
151 * bucket policy must grant `billingreports.amazonaws.com` the
152 * `s3:GetBucketAcl`, `s3:GetBucketPolicy`, and `s3:PutObject` permissions —
153 * report creation fails validation otherwise.
154 *
155 * Report definitions are free; you pay only for the S3 storage of delivered
156 * reports.
157 *
158 * ### Creating a Report
159 * **Example:** Daily CSV report with resource IDs
160 * ```typescript
161 * import * as AWS from "@alchemy.run/aws";
162 *
163 * const bucket = yield* AWS.S3.Bucket("ReportBucket", {
164 * bucketName: "my-cur-reports",
165 * policy: [
166 * {
167 * Effect: "Allow",
168 * Principal: { Service: "billingreports.amazonaws.com" },
169 * Action: ["s3:GetBucketAcl", "s3:GetBucketPolicy"],
170 * Resource: "arn:aws:s3:::my-cur-reports",
171 * },
172 * {
173 * Effect: "Allow",
174 * Principal: { Service: "billingreports.amazonaws.com" },
175 * Action: ["s3:PutObject"],
176 * Resource: "arn:aws:s3:::my-cur-reports/*",
177 * },
178 * ],
179 * });
180 *
181 * const report = yield* AWS.CostAndUsageReport.ReportDefinition("Costs", {
182 * timeUnit: "DAILY",
183 * format: "textORcsv",
184 * compression: "GZIP",
185 * additionalSchemaElements: ["RESOURCES"],
186 * s3Bucket: bucket.bucketName,
187 * s3Prefix: "cur",
188 * s3Region: bucket.region,
189 * });
190 * ```
191 *
192 * **Example:** Athena-ready Parquet report
193 * ```typescript
194 * const report = yield* AWS.CostAndUsageReport.ReportDefinition("Athena", {
195 * timeUnit: "HOURLY",
196 * format: "Parquet",
197 * compression: "Parquet",
198 * additionalArtifacts: ["ATHENA"],
199 * reportVersioning: "OVERWRITE_REPORT",
200 * s3Bucket: bucket.bucketName,
201 * s3Prefix: "athena-cur",
202 * s3Region: bucket.region,
203 * });
204 * ```
205 *
206 * @resource
207 */
208 export const ReportDefinition = Resource<ReportDefinition>(
209 "AWS.CostAndUsageReport.ReportDefinition",
210 );
211
212 const toTagRecord = (tags: cur.Tag[] | undefined): Record<string, string> =>
213 Object.fromEntries((tags ?? []).map((t) => [t.Key, t.Value]));
214
215 const setEquals = (
216 left: readonly string[] | undefined,
217 right: readonly string[] | undefined,
218 ): boolean => {
219 const l = [...(left ?? [])].sort();
220 const r = [...(right ?? [])].sort();
221 return l.length === r.length && l.every((v, i) => v === r[i]);
222 };
223
224 export const ReportDefinitionProvider = () =>
225 Provider.effect(
226 ReportDefinition,
227 Effect.gen(function* () {
228 const createName = Effect.fn(function* (
229 id: string,
230 props: { reportName?: string | undefined },
231 ) {
232 return props.reportName ?? (yield* createPhysicalName({ id, maxLength: 256 }));
233 });
234
235 const reportArn = (accountId: string, name: string) =>
236 `arn:aws:cur:${CUR_REGION}:${accountId}:definition/${name}`;
237
238 // There is no Get operation — observe by scanning the (small,
239 // account-max ~10 entries) paginated list.
240 const findReport = Effect.fn(function* (name: string) {
241 const pages = yield* pin(cur.describeReportDefinitions.pages({}).pipe(Stream.runCollect));
242 return Array.from(pages)
243 .flatMap((page) => page.ReportDefinitions ?? [])
244 .find((r) => r.ReportName === name);
245 });
246
247 const readTags = (name: string) =>
248 pin(cur.listTagsForResource({ ReportName: name })).pipe(
249 Effect.map((r) => toTagRecord(r.Tags)),
250 Effect.catchTag("ResourceNotFoundException", () =>
251 Effect.succeed({} as Record<string, string>),
252 ),
253 );
254
255 const buildDefinition = (
256 name: string,
257 props: ReportDefinitionProps,
258 ): cur.ReportDefinition => ({
259 ReportName: name,
260 TimeUnit: props.timeUnit,
261 Format: props.format,
262 Compression: props.compression,
263 AdditionalSchemaElements: props.additionalSchemaElements ?? [],
264 S3Bucket: props.s3Bucket,
265 S3Prefix: props.s3Prefix,
266 S3Region: props.s3Region,
267 AdditionalArtifacts: props.additionalArtifacts,
268 RefreshClosedReports: props.refreshClosedReports,
269 ReportVersioning: props.reportVersioning,
270 BillingViewArn: props.billingViewArn,
271 });
272
273 const needsModify = (
274 observed: cur.ReportDefinition,
275 desired: cur.ReportDefinition,
276 ): boolean =>
277 observed.TimeUnit !== desired.TimeUnit ||
278 observed.Format !== desired.Format ||
279 observed.Compression !== desired.Compression ||
280 observed.S3Bucket !== desired.S3Bucket ||
281 observed.S3Prefix !== desired.S3Prefix ||
282 observed.S3Region !== desired.S3Region ||
283 !setEquals(observed.AdditionalSchemaElements, desired.AdditionalSchemaElements) ||
284 !setEquals(observed.AdditionalArtifacts, desired.AdditionalArtifacts) ||
285 (desired.RefreshClosedReports !== undefined &&
286 observed.RefreshClosedReports !== desired.RefreshClosedReports) ||
287 (desired.ReportVersioning !== undefined &&
288 observed.ReportVersioning !== desired.ReportVersioning);
289
290 const toAttributes = (accountId: string, observed: cur.ReportDefinition) => ({
291 reportName: observed.ReportName,
292 reportArn: reportArn(accountId, observed.ReportName),
293 timeUnit: observed.TimeUnit,
294 format: observed.Format,
295 compression: observed.Compression,
296 s3Bucket: observed.S3Bucket,
297 s3Prefix: observed.S3Prefix,
298 s3Region: observed.S3Region,
299 });
300
301 const syncTags = Effect.fn(function* (name: string, desiredTags: Record<string, string>) {
302 // Diff against OBSERVED cloud tags — adoption may bring foreign tags.
303 const observedTags = yield* readTags(name);
304 const { upsert, removed } = diffTags(observedTags, desiredTags);
305 if (upsert.length > 0) {
306 yield* pin(cur.tagResource({ ReportName: name, Tags: upsert }));
307 }
308 if (removed.length > 0) {
309 yield* pin(cur.untagResource({ ReportName: name, TagKeys: removed }));
310 }
311 });
312
313 return ReportDefinition.Provider.of({
314 stables: ["reportName", "reportArn"],
315 list: () =>
316 Effect.gen(function* () {
317 const { accountId } = yield* AWSEnvironment.current;
318 const pages = yield* pin(
319 cur.describeReportDefinitions.pages({}).pipe(Stream.runCollect),
320 );
321 return Array.from(pages)
322 .flatMap((page) => page.ReportDefinitions ?? [])
323 .map((r) => toAttributes(accountId, r));
324 }),
325 read: Effect.fn(function* ({ id, olds, output }) {
326 const { accountId } = yield* AWSEnvironment.current;
327 const name = output?.reportName ?? (yield* createName(id, olds ?? {}));
328 const observed = yield* findReport(name);
329 if (!observed) return undefined;
330 const attrs = toAttributes(accountId, observed);
331 const tags = yield* readTags(name);
332 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
333 }),
334 diff: Effect.fn(function* ({ id, olds, news }) {
335 if (!isResolved(news)) return;
336 const oldName = yield* createName(id, olds ?? {});
337 const newName = yield* createName(id, news);
338 if (oldName !== newName) return { action: "replace" } as const;
339 if (olds && olds.billingViewArn !== news.billingViewArn) {
340 return { action: "replace" } as const;
341 }
342 }),
343 reconcile: Effect.fn(function* ({ id, news, output, session }) {
344 const { accountId } = yield* AWSEnvironment.current;
345 const name = output?.reportName ?? (yield* createName(id, news));
346 const internalTags = yield* createInternalTags(id);
347 const desiredTags = { ...news.tags, ...internalTags };
348 const desired = buildDefinition(name, news);
349
350 // OBSERVE — cloud state is authoritative; output is only a name cache.
351 const observed = yield* findReport(name);
352
353 if (!observed) {
354 // ENSURE — create; tolerate the duplicate-name race by converging
355 // through modify instead.
356 yield* cur
357 .putReportDefinition({
358 ReportDefinition: desired,
359 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
360 Key,
361 Value,
362 })),
363 })
364 .pipe(
365 pin,
366 retryBucketVerification,
367 Effect.catchTag("DuplicateReportNameException", () =>
368 pin(
369 cur.modifyReportDefinition({
370 ReportName: name,
371 ReportDefinition: desired,
372 }),
373 ),
374 ),
375 );
376 } else if (needsModify(observed, desired)) {
377 // SYNC — apply the delta only; skip the API entirely on no-op.
378 yield* cur
379 .modifyReportDefinition({
380 ReportName: name,
381 ReportDefinition: desired,
382 })
383 .pipe(pin, retryBucketVerification);
384 }
385
386 // SYNC TAGS — against observed cloud tags.
387 yield* syncTags(name, desiredTags);
388
389 yield* session.note(name);
390 const final = yield* findReport(name);
391 return toAttributes(accountId, final ?? desired);
392 }),
393 delete: Effect.fn(function* ({ output }) {
394 // Idempotent: DeleteReportDefinition's error semantics for a missing
395 // report are undocumented, so observe first and treat absent as done.
396 const observed = yield* findReport(output.reportName);
397 if (!observed) return;
398 yield* pin(cur.deleteReportDefinition({ ReportName: output.reportName }));
399 }),
400 });
401 }),
402 );