@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 542 lines 18.1 KB
Raw
1 import * as budgets from "@distilled.cloud/aws/budgets";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Redacted from "effect/Redacted";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 /**
14 * A subscriber notified when a budget notification is triggered.
15 */
16 export interface BudgetSubscriber {
17 /**
18 * How the subscriber is notified.
19 */
20 subscriptionType: "EMAIL" | "SNS" | (string & {});
21 /**
22 * The destination — an email address (for `EMAIL`) or an SNS topic ARN
23 * (for `SNS`).
24 */
25 address: string;
26 }
27
28 /**
29 * A threshold that, when crossed, notifies the configured subscribers.
30 */
31 export interface BudgetNotification {
32 /**
33 * Whether the notification is based on actual or forecasted spend/usage.
34 */
35 notificationType: "ACTUAL" | "FORECASTED" | (string & {});
36 /**
37 * How the actual/forecasted amount is compared to the threshold.
38 */
39 comparisonOperator: "GREATER_THAN" | "LESS_THAN" | "EQUAL_TO" | (string & {});
40 /**
41 * The threshold value. Interpreted as a percentage of the budget limit by
42 * default, or an absolute amount when `thresholdType` is `ABSOLUTE_VALUE`.
43 */
44 threshold: number;
45 /**
46 * Whether `threshold` is a percentage of the budget or an absolute value.
47 * @default "PERCENTAGE"
48 */
49 thresholdType?: "PERCENTAGE" | "ABSOLUTE_VALUE" | (string & {});
50 /**
51 * Subscribers notified when this threshold is crossed.
52 */
53 subscribers: BudgetSubscriber[];
54 }
55
56 /**
57 * The types of cost included in a `COST` budget, such as tax and
58 * subscriptions. Other budget types do not have cost types. A flag left out
59 * is sent with its AWS default.
60 *
61 * AWS deprecated cost types in favor of budget metrics and filter
62 * expressions, but the Budgets API still accepts them.
63 */
64 export interface BudgetCostTypes {
65 /**
66 * Whether the budget includes taxes.
67 * @default true
68 */
69 includeTax?: boolean;
70 /**
71 * Whether the budget includes subscriptions.
72 * @default true
73 */
74 includeSubscription?: boolean;
75 /**
76 * Whether the budget uses the blended rate.
77 * @default false
78 */
79 useBlended?: boolean;
80 /**
81 * Whether the budget includes refunds.
82 * @default true
83 */
84 includeRefund?: boolean;
85 /**
86 * Whether the budget includes credits.
87 * @default true
88 */
89 includeCredit?: boolean;
90 /**
91 * Whether the budget includes upfront reserved instance costs.
92 * @default true
93 */
94 includeUpfront?: boolean;
95 /**
96 * Whether the budget includes recurring fees, such as monthly reserved
97 * instance fees.
98 * @default true
99 */
100 includeRecurring?: boolean;
101 /**
102 * Whether the budget includes subscription costs other than reserved
103 * instances.
104 * @default true
105 */
106 includeOtherSubscription?: boolean;
107 /**
108 * Whether the budget includes support subscription fees.
109 * @default true
110 */
111 includeSupport?: boolean;
112 /**
113 * Whether the budget includes discounts.
114 * @default true
115 */
116 includeDiscount?: boolean;
117 /**
118 * Whether the budget uses the amortized rate.
119 * @default false
120 */
121 useAmortized?: boolean;
122 }
123
124 export interface BudgetProps {
125 /**
126 * Name of the budget. Must be unique within the account. If omitted, a
127 * unique name is generated from the app, stage, and logical ID.
128 *
129 * Changing the name replaces the budget.
130 */
131 budgetName?: string;
132 /**
133 * What the budget tracks.
134 * @default "COST"
135 */
136 budgetType?:
137 | "COST"
138 | "USAGE"
139 | "RI_UTILIZATION"
140 | "RI_COVERAGE"
141 | "SAVINGS_PLANS_UTILIZATION"
142 | "SAVINGS_PLANS_COVERAGE"
143 | (string & {});
144 /**
145 * The period the budget resets over.
146 * @default "MONTHLY"
147 */
148 timeUnit?: "DAILY" | "MONTHLY" | "QUARTERLY" | "ANNUALLY" | (string & {});
149 /**
150 * The budgeted amount and its unit, e.g. `{ amount: "100", unit: "USD" }`.
151 * Required for `COST` and `USAGE` budgets.
152 */
153 budgetLimit?: {
154 /** The amount, as a string, e.g. `"100"`. */
155 amount: string;
156 /** The unit — `"USD"` for cost budgets, or the usage unit. */
157 unit: string;
158 };
159 /**
160 * Cost filters restricting which costs count against the budget, e.g.
161 * `{ Service: ["Amazon Elastic Compute Cloud - Compute"] }`.
162 */
163 costFilters?: Record<string, string[]>;
164 /**
165 * The types of cost included in a `COST` budget, e.g.
166 * `{ includeCredit: false, includeRefund: false }` to track spend before
167 * credits and refunds.
168 */
169 costTypes?: BudgetCostTypes;
170 /**
171 * Notifications and their subscribers.
172 */
173 notifications?: BudgetNotification[];
174 /**
175 * Tags applied to the budget at creation.
176 */
177 tags?: Record<string, string>;
178 }
179
180 export interface Budget extends Resource<
181 "AWS.Budgets.Budget",
182 BudgetProps,
183 {
184 /**
185 * Name of the budget.
186 */
187 budgetName: string;
188 /**
189 * The AWS account ID that owns the budget.
190 */
191 accountId: string;
192 /**
193 * ARN of the budget, e.g. `arn:aws:budgets::123456789012:budget/my-budget`.
194 */
195 budgetArn: string;
196 },
197 never,
198 Providers
199 > {}
200
201 /**
202 * An AWS Budget — tracks cost or usage against a defined limit over a time
203 * period and notifies subscribers when configured thresholds are crossed.
204 *
205 * Budgets are a global (account-level) resource; they are free and take
206 * effect immediately.
207 *
208 * ### Creating a Budget
209 * **Example:** Monthly cost budget with an email alert at 80%
210 * ```typescript
211 * import * as Budgets from "@alchemy.run/aws/Budgets";
212 *
213 * const budget = yield* Budgets.Budget("MonthlyCost", {
214 * budgetType: "COST",
215 * timeUnit: "MONTHLY",
216 * budgetLimit: { amount: "100", unit: "USD" },
217 * notifications: [
218 * {
219 * notificationType: "ACTUAL",
220 * comparisonOperator: "GREATER_THAN",
221 * threshold: 80,
222 * thresholdType: "PERCENTAGE",
223 * subscribers: [{ subscriptionType: "EMAIL", address: "team@example.com" }],
224 * },
225 * ],
226 * });
227 * ```
228 *
229 * **Example:** Budget scoped to a single service
230 * ```typescript
231 * const budget = yield* Budgets.Budget("EC2Spend", {
232 * budgetLimit: { amount: "500", unit: "USD" },
233 * costFilters: {
234 * Service: ["Amazon Elastic Compute Cloud - Compute"],
235 * },
236 * });
237 * ```
238 *
239 * **Example:** Budget that credits and refunds do not offset
240 * ```typescript
241 * const budget = yield* Budgets.Budget("GrossSpend", {
242 * budgetLimit: { amount: "600", unit: "USD" },
243 * costTypes: { includeCredit: false, includeRefund: false },
244 * });
245 * ```
246 *
247 * @resource
248 */
249 export const Budget = Resource<Budget>("AWS.Budgets.Budget");
250
251 /**
252 * Compute the ARN of a budget. Budgets is a global service, so the ARN has no
253 * region component.
254 */
255 export const budgetArn = (accountId: string, budgetName: string): string =>
256 `arn:aws:budgets::${accountId}:budget/${budgetName}`;
257
258 const notificationKey = (n: budgets.Notification): string =>
259 JSON.stringify({
260 NotificationType: n.NotificationType,
261 ComparisonOperator: n.ComparisonOperator,
262 Threshold: n.Threshold,
263 ThresholdType: n.ThresholdType ?? "PERCENTAGE",
264 });
265
266 const toNotification = (n: BudgetNotification): budgets.Notification => ({
267 NotificationType: n.notificationType,
268 ComparisonOperator: n.comparisonOperator,
269 Threshold: n.threshold,
270 ThresholdType: n.thresholdType ?? "PERCENTAGE",
271 });
272
273 const toCostTypes = (c: BudgetCostTypes): budgets.CostTypes => ({
274 IncludeTax: c.includeTax ?? true,
275 IncludeSubscription: c.includeSubscription ?? true,
276 UseBlended: c.useBlended ?? false,
277 IncludeRefund: c.includeRefund ?? true,
278 IncludeCredit: c.includeCredit ?? true,
279 IncludeUpfront: c.includeUpfront ?? true,
280 IncludeRecurring: c.includeRecurring ?? true,
281 IncludeOtherSubscription: c.includeOtherSubscription ?? true,
282 IncludeSupport: c.includeSupport ?? true,
283 IncludeDiscount: c.includeDiscount ?? true,
284 UseAmortized: c.useAmortized ?? false,
285 });
286
287 /**
288 * Distilled marks `Subscriber.Address` sensitive, so observed subscribers
289 * come back as `Redacted` — unwrap before diffing, or every observed
290 * subscriber compares as `<redacted>` and gets torn down (and deleting the
291 * last subscriber deletes the whole notification).
292 */
293 const subscriberAddress = (s: budgets.Subscriber): string =>
294 Redacted.isRedacted(s.Address) ? Redacted.value(s.Address) : s.Address;
295
296 const subscriberKey = (s: budgets.Subscriber): string =>
297 `${s.SubscriptionType}:${subscriberAddress(s)}`;
298
299 export const BudgetProvider = () =>
300 Provider.effect(
301 Budget,
302 Effect.gen(function* () {
303 const createName = Effect.fn(function* (
304 id: string,
305 props: { budgetName?: string | undefined },
306 ) {
307 return props.budgetName ?? (yield* createPhysicalName({ id, maxLength: 100 }));
308 });
309
310 const buildBudget = (name: string, props: BudgetProps): budgets.Budget => ({
311 BudgetName: name,
312 BudgetType: props.budgetType ?? "COST",
313 TimeUnit: props.timeUnit ?? "MONTHLY",
314 BudgetLimit: props.budgetLimit
315 ? { Amount: props.budgetLimit.amount, Unit: props.budgetLimit.unit }
316 : undefined,
317 CostFilters: props.costFilters,
318 CostTypes: props.costTypes ? toCostTypes(props.costTypes) : undefined,
319 });
320
321 const syncNotifications = Effect.fn(function* (
322 accountId: string,
323 name: string,
324 desired: BudgetNotification[],
325 ) {
326 const current = yield* budgets.describeNotificationsForBudget
327 .pages({
328 AccountId: accountId,
329 BudgetName: name,
330 })
331 .pipe(
332 Stream.runCollect,
333 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Notifications ?? [])),
334 Effect.catchTag("NotFoundException", () => Effect.succeed([])),
335 );
336 const currentKeys = new Set(current.map(notificationKey));
337 const desiredNotifs = desired.map(toNotification);
338 const desiredKeys = new Set(desiredNotifs.map(notificationKey));
339
340 for (const n of desired) {
341 const notif = toNotification(n);
342 const desiredSubscribers = n.subscribers.map((s): budgets.Subscriber => ({
343 SubscriptionType: s.subscriptionType,
344 Address: s.address,
345 }));
346 if (!currentKeys.has(notificationKey(notif))) {
347 // The notification listing is eventually consistent — right after
348 // `createBudget(NotificationsWithSubscribers)` it can come back
349 // empty, so an already-created notification surfaces here as a
350 // DuplicateRecordException race.
351 yield* budgets
352 .createNotification({
353 AccountId: accountId,
354 BudgetName: name,
355 Notification: notif,
356 Subscribers: desiredSubscribers,
357 })
358 .pipe(Effect.catchTag("DuplicateRecordException", () => Effect.void));
359 continue;
360 }
361 // The notification already exists — converge its subscribers by
362 // diffing the OBSERVED subscriber list against the desired one.
363 const observedSubscribers = yield* budgets
364 .describeSubscribersForNotification({
365 AccountId: accountId,
366 BudgetName: name,
367 Notification: notif,
368 })
369 .pipe(
370 Effect.map((r) => r.Subscribers ?? []),
371 Effect.catchTag("NotFoundException", () => Effect.succeed([])),
372 );
373 const observedKeys = new Set(observedSubscribers.map(subscriberKey));
374 const desiredSubKeys = new Set(desiredSubscribers.map(subscriberKey));
375 // Create before delete so the notification never drops to zero
376 // subscribers (the API requires at least one).
377 for (const s of desiredSubscribers) {
378 if (observedKeys.has(subscriberKey(s))) continue;
379 yield* budgets
380 .createSubscriber({
381 AccountId: accountId,
382 BudgetName: name,
383 Notification: notif,
384 Subscriber: s,
385 })
386 .pipe(Effect.catchTag("DuplicateRecordException", () => Effect.void));
387 }
388 for (const s of observedSubscribers) {
389 if (desiredSubKeys.has(subscriberKey(s))) continue;
390 yield* budgets
391 .deleteSubscriber({
392 AccountId: accountId,
393 BudgetName: name,
394 Notification: notif,
395 Subscriber: s,
396 })
397 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
398 }
399 }
400 for (const n of current) {
401 if (desiredKeys.has(notificationKey(n))) continue;
402 yield* budgets
403 .deleteNotification({
404 AccountId: accountId,
405 BudgetName: name,
406 Notification: n,
407 })
408 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
409 }
410 });
411
412 const syncTags = Effect.fn(function* (arn: string, desired: Record<string, string>) {
413 // Diff against OBSERVED cloud tags (not olds/output) so adoption and
414 // out-of-band drift converge correctly.
415 const observed = yield* budgets.listTagsForResource({ ResourceARN: arn }).pipe(
416 Effect.map((r) =>
417 Object.fromEntries((r.ResourceTags ?? []).map((t) => [t.Key, t.Value])),
418 ),
419 Effect.catchTag("NotFoundException", () => Effect.succeed({} as Record<string, string>)),
420 );
421 const { removed, upsert } = diffTags(observed, desired);
422 if (upsert.length > 0) {
423 yield* budgets.tagResource({
424 ResourceARN: arn,
425 ResourceTags: upsert,
426 });
427 }
428 if (removed.length > 0) {
429 yield* budgets.untagResource({
430 ResourceARN: arn,
431 ResourceTagKeys: removed,
432 });
433 }
434 });
435
436 return Budget.Provider.of({
437 stables: ["budgetName", "accountId", "budgetArn"],
438 list: () =>
439 Effect.gen(function* () {
440 const { accountId } = yield* AWSEnvironment.current;
441 return yield* budgets.describeBudgets.pages({ AccountId: accountId }).pipe(
442 Stream.runCollect,
443 Effect.map((chunk) =>
444 Array.from(chunk)
445 .flatMap((page) => page.Budgets ?? [])
446 .map((b) => ({
447 budgetName: b.BudgetName,
448 accountId,
449 budgetArn: budgetArn(accountId, b.BudgetName),
450 })),
451 ),
452 Effect.catchTag("NotFoundException", () => Effect.succeed([])),
453 );
454 }),
455 read: Effect.fn(function* ({ id, olds, output }) {
456 const { accountId } = yield* AWSEnvironment.current;
457 const name = output?.budgetName ?? (yield* createName(id, olds ?? {}));
458 const found = yield* budgets
459 .describeBudget({ AccountId: accountId, BudgetName: name })
460 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
461 if (!found?.Budget) return undefined;
462 return {
463 budgetName: name,
464 accountId,
465 budgetArn: budgetArn(accountId, name),
466 };
467 }),
468 diff: Effect.fn(function* ({ id, news = {}, olds = {} }) {
469 if (!isResolved(news)) return undefined;
470 const oldName = yield* createName(id, olds);
471 const newName = yield* createName(id, news);
472 if (oldName !== newName) return { action: "replace" } as const;
473 }),
474 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
475 const { accountId } = yield* AWSEnvironment.current;
476 const name = output?.budgetName ?? (yield* createName(id, news));
477 const internalTags = yield* createInternalTags(id);
478 const budgetBody = buildBudget(name, news);
479
480 // OBSERVE — cloud state is authoritative.
481 const live = yield* budgets
482 .describeBudget({ AccountId: accountId, BudgetName: name })
483 .pipe(
484 Effect.map((r) => r.Budget),
485 Effect.catchTag("NotFoundException", () => Effect.undefined),
486 );
487
488 if (!live) {
489 // ENSURE — create; tolerate a DuplicateRecord race.
490 yield* budgets
491 .createBudget({
492 AccountId: accountId,
493 Budget: budgetBody,
494 NotificationsWithSubscribers: news.notifications?.map((n) => ({
495 Notification: toNotification(n),
496 Subscribers: n.subscribers.map((s) => ({
497 SubscriptionType: s.subscriptionType,
498 Address: s.address,
499 })),
500 })),
501 ResourceTags: Object.entries({
502 ...news.tags,
503 ...internalTags,
504 }).map(([Key, Value]) => ({ Key, Value })),
505 })
506 .pipe(
507 Effect.catchTag("DuplicateRecordException", () =>
508 budgets.updateBudget({
509 AccountId: accountId,
510 NewBudget: budgetBody,
511 }),
512 ),
513 );
514 } else {
515 // SYNC — updateBudget is a full replace of the budget definition.
516 yield* budgets.updateBudget({
517 AccountId: accountId,
518 NewBudget: budgetBody,
519 });
520 }
521
522 // SYNC notifications — the budget update does not touch these.
523 yield* syncNotifications(accountId, name, news.notifications ?? []);
524
525 // SYNC tags against observed cloud tags.
526 const arn = budgetArn(accountId, name);
527 yield* syncTags(arn, { ...news.tags, ...internalTags });
528
529 yield* session.note(name);
530 return { budgetName: name, accountId, budgetArn: arn };
531 }),
532 delete: Effect.fn(function* ({ output }) {
533 yield* budgets
534 .deleteBudget({
535 AccountId: output.accountId,
536 BudgetName: output.budgetName,
537 })
538 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
539 }),
540 });
541 }),
542 );