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

main
ts 593 lines 19.2 KB
Raw
1 import * as billingbudgets from "@distilled.cloud/gcp/billingbudgets_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import type { Providers } from "../Providers.ts";
9 import {
10 billingAccountIdOf,
11 billingAccountParent,
12 budgetNameOf,
13 compact,
14 filterChanged,
15 findBudgetByDisplayName,
16 generatedDisplayName,
17 getBudget,
18 jsonEqual,
19 parseBudgetName,
20 resolveBillingAccountId,
21 resolveProjectRefs,
22 sortedStrings,
23 } from "./internal.ts";
24
25 export type Money = {
26 /**
27 * Whole units of the amount. For USD, `1` is one dollar.
28 */
29 units?: string;
30 /**
31 * ISO 4217 currency code. If set on create, it must match the billing
32 * account currency.
33 */
34 currencyCode?: string;
35 /**
36 * Nano (10^-9) units of the amount. Must be between -999,999,999 and
37 * 999,999,999.
38 */
39 nanos?: number;
40 };
41
42 export type BudgetAmount = {
43 /**
44 * Use last calendar period's actual spend as this period's budget.
45 * Cannot be combined with `customPeriod`. Empty object selects this
46 * mode.
47 */
48 lastPeriodAmount?: Record<string, never> | {};
49 /**
50 * Explicit budgeted amount. `currencyCode` is optional on create and
51 * must match the billing account (and the existing budget on update).
52 */
53 specifiedAmount?: Money;
54 };
55
56 export type CustomPeriod = {
57 /**
58 * Inclusive start date. Must be after 2017-01-01.
59 */
60 startDate?: { year?: number; month?: number; day?: number };
61 /**
62 * Inclusive end date. Budgets past this date are not processed. Omit
63 * to track all usage since `startDate`.
64 */
65 endDate?: { year?: number; month?: number; day?: number };
66 };
67
68 export type BudgetFilter = {
69 /**
70 * Folders and organizations whose usage is included, as
71 * `folders/{folderId}` or `organizations/{organizationId}`.
72 */
73 resourceAncestors?: string[];
74 /**
75 * Subaccounts of the form `billingAccounts/{account_id}`.
76 */
77 subaccounts?: string[];
78 /**
79 * Recurring calendar period (`MONTH`, `QUARTER`, `YEAR`). Default
80 * `MONTH` when `customPeriod` is unset.
81 */
82 calendarPeriod?: string;
83 /**
84 * Services of the form `services/{service_id}`.
85 */
86 services?: string[];
87 /**
88 * Credit types subtracted from gross cost when
89 * `creditTypesTreatment` is `INCLUDE_SPECIFIED_CREDITS`.
90 */
91 creditTypes?: string[];
92 /**
93 * How credits are treated (`INCLUDE_ALL_CREDITS`,
94 * `EXCLUDE_ALL_CREDITS`, `INCLUDE_SPECIFIED_CREDITS`).
95 */
96 creditTypesTreatment?: string;
97 /**
98 * Projects of the form `projects/{project}`. Omit to include every
99 * project the billing account pays for.
100 */
101 projects?: string[];
102 /**
103 * Static (non-recurring) time period. Mutually exclusive with
104 * `calendarPeriod`.
105 */
106 customPeriod?: CustomPeriod;
107 /**
108 * Single resource-label key mapped to a list of values. Usage from
109 * only those labeled resources is included.
110 */
111 labels?: Record<string, unknown[] | undefined>;
112 };
113
114 export type ThresholdRule = {
115 /**
116 * Alert when spend exceeds this fraction of the budget (`0.5` is 50%).
117 */
118 thresholdPercent?: number;
119 /**
120 * Spend basis (`CURRENT_SPEND` or `FORECASTED_SPEND`). Defaults to
121 * `CURRENT_SPEND`.
122 */
123 spendBasis?: string;
124 };
125
126 export type NotificationsRule = {
127 /**
128 * Schema version of Pub/Sub notifications. Only `"1.0"` is accepted.
129 */
130 schemaVersion?: string;
131 /**
132 * Pub/Sub topic for programmatic notifications, as
133 * `projects/{project}/topics/{topic}`.
134 */
135 pubsubTopic?: string;
136 /**
137 * When true, default IAM billing-account recipients are not emailed.
138 */
139 disableDefaultIamRecipients?: boolean;
140 /**
141 * When true and the budget tracks a single project, also notify that
142 * project's Owners.
143 */
144 enableProjectLevelRecipients?: boolean;
145 /**
146 * Cloud Monitoring email notification channels, as
147 * `projects/{project}/notificationChannels/{channel}`. Max 5.
148 */
149 monitoringNotificationChannels?: string[];
150 };
151
152 export type BillingBudgetProps = {
153 /**
154 * Billing account id (`XXXXXX-XXXXXX-XXXXXX` or
155 * `billingAccounts/{id}`). If omitted, Alchemy uses the billing
156 * account linked to the current project. Immutable — changing it
157 * replaces the budget.
158 */
159 billingAccountId?: string;
160 /**
161 * Server-assigned budget id (the `{budget}` segment of
162 * `billingAccounts/{billingAccount}/budgets/{budget}`). Omit on
163 * create; pass the observed id to update in place. Immutable —
164 * changing it replaces the budget.
165 */
166 budgetId?: string;
167 /**
168 * User-visible display name (60 characters), shown in budget alert
169 * emails. If omitted, a unique name is generated from the stack, stage,
170 * and logical id.
171 */
172 displayName?: string;
173 /**
174 * Budgeted amount. Required. Either `specifiedAmount` or
175 * `lastPeriodAmount`.
176 */
177 amount: BudgetAmount;
178 /**
179 * Filters that scope actual spend (projects, services, period, …).
180 */
181 budgetFilter?: BudgetFilter;
182 /**
183 * Thresholds that trigger alert emails and populate Pub/Sub payloads.
184 */
185 thresholdRules?: ThresholdRule[];
186 /**
187 * Notification targets (email channels and/or Pub/Sub).
188 */
189 notificationsRule?: NotificationsRule;
190 /**
191 * Who owns the budget (`ALL_USERS` or `BILLING_ACCOUNT`).
192 */
193 ownershipScope?: string;
194 };
195
196 export type BillingBudget = Resource<
197 "GCP.BillingBudgets.BillingBudget",
198 BillingBudgetProps,
199 {
200 /** Full resource name `billingAccounts/{billingAccount}/budgets/{budget}`. */
201 name: string;
202 /** Server-assigned budget id (last path segment). */
203 budgetId: string;
204 /** Billing account id. */
205 billingAccountId: string;
206 /** Display name. */
207 displayName: string | undefined;
208 /** Budgeted amount. */
209 amount: BudgetAmount | undefined;
210 /** Spend filter. */
211 budgetFilter: BudgetFilter | undefined;
212 /** Threshold rules. */
213 thresholdRules: ThresholdRule[];
214 /** Notification rules. */
215 notificationsRule: NotificationsRule | undefined;
216 /** Ownership scope. */
217 ownershipScope: string | undefined;
218 /** Server etag for read-modify-write. */
219 etag: string | undefined;
220 },
221 never,
222 Providers
223 >;
224
225 /**
226 * A Cloud Billing budget.
227 *
228 * Budgets have no labels field and the display name appears in alert
229 * emails, so Alchemy finds its budget by display name within the current
230 * project's scope: `read` reports a budget as owned only when it carries
231 * the generated name (an explicit `displayName` is reported as unowned —
232 * adopt it with `--adopt`), and nuke cannot discover budgets. The
233 * physical id is a server-assigned UUID. Changing `billingAccountId` or
234 * `budgetId` replaces the budget. Amount, filter, thresholds,
235 * notifications, and display name update in place.
236 *
237 * ### Creating a Budget
238 * **Example:** Project-scoped monthly budget
239 * ```typescript
240 * const budget = yield* GCP.BillingBudgets.BillingBudget("Spend", {
241 * displayName: "cap",
242 * amount: { specifiedAmount: { currencyCode: "USD", units: "10" } },
243 * budgetFilter: {
244 * projects: ["projects/my-project"],
245 * calendarPeriod: "MONTH",
246 * },
247 * thresholdRules: [{ thresholdPercent: 0.5, spendBasis: "CURRENT_SPEND" }],
248 * });
249 * ```
250 *
251 * **Example:** Last-period amount
252 * ```typescript
253 * const budget = yield* GCP.BillingBudgets.BillingBudget("Spend", {
254 * amount: { lastPeriodAmount: {} },
255 * budgetFilter: { calendarPeriod: "MONTH" },
256 * });
257 * ```
258 *
259 * ### Updating a Budget
260 * **Example:** Raise the cap and add a forecasted threshold
261 * ```typescript
262 * const budget = yield* GCP.BillingBudgets.BillingBudget("Spend", {
263 * displayName: "cap",
264 * amount: { specifiedAmount: { currencyCode: "USD", units: "25" } },
265 * budgetFilter: {
266 * projects: ["projects/my-project"],
267 * calendarPeriod: "MONTH",
268 * },
269 * thresholdRules: [
270 * { thresholdPercent: 0.5, spendBasis: "CURRENT_SPEND" },
271 * { thresholdPercent: 0.9, spendBasis: "FORECASTED_SPEND" },
272 * ],
273 * });
274 * ```
275 *
276 * @resource
277 * @category BillingBudgets
278 */
279 export const BillingBudget = Resource<BillingBudget>("GCP.BillingBudgets.BillingBudget");
280
281 export class BillingBudgetNotResolved extends Data.TaggedError(
282 "GCP.BillingBudgets.BillingBudgetNotResolved",
283 )<{
284 resourceName: string;
285 }> {}
286
287 const toMoney = (money: billingbudgets.GoogleTypeMoney | Money | undefined): Money | undefined => {
288 if (money === undefined) return undefined;
289 if (money.units === undefined && money.currencyCode === undefined && money.nanos === undefined) {
290 return undefined;
291 }
292 return compact({
293 units: money.units,
294 currencyCode: money.currencyCode,
295 nanos: money.nanos === 0 ? undefined : money.nanos,
296 });
297 };
298
299 const toAmount = (
300 amount: billingbudgets.GoogleCloudBillingBudgetsV1BudgetAmount | BudgetAmount | undefined,
301 ): BudgetAmount | undefined => {
302 if (amount === undefined) return undefined;
303 const specifiedAmount = toMoney(amount.specifiedAmount);
304 const lastPeriodAmount = amount.lastPeriodAmount !== undefined ? {} : undefined;
305 if (specifiedAmount === undefined && lastPeriodAmount === undefined) {
306 return undefined;
307 }
308 return compact({ specifiedAmount, lastPeriodAmount });
309 };
310
311 const toDate = (
312 date: billingbudgets.GoogleTypeDate | CustomPeriod["startDate"] | undefined,
313 ): CustomPeriod["startDate"] | undefined => {
314 if (date === undefined) return undefined;
315 if (date.year === undefined && date.month === undefined && date.day === undefined) {
316 return undefined;
317 }
318 return compact({ year: date.year, month: date.month, day: date.day });
319 };
320
321 const toCustomPeriod = (
322 period: billingbudgets.GoogleCloudBillingBudgetsV1CustomPeriod | CustomPeriod | undefined,
323 ): CustomPeriod | undefined => {
324 if (period === undefined) return undefined;
325 const startDate = toDate(period.startDate);
326 const endDate = toDate(period.endDate);
327 if (startDate === undefined && endDate === undefined) return undefined;
328 return compact({ startDate, endDate });
329 };
330
331 const toFilter = (
332 filter: billingbudgets.GoogleCloudBillingBudgetsV1Filter | BudgetFilter | undefined,
333 ): BudgetFilter | undefined => {
334 if (filter === undefined) return undefined;
335 const next = compact({
336 resourceAncestors: filter.resourceAncestors
337 ? sortedStrings(filter.resourceAncestors)
338 : undefined,
339 subaccounts: filter.subaccounts ? sortedStrings(filter.subaccounts) : undefined,
340 calendarPeriod: filter.calendarPeriod,
341 services: filter.services ? sortedStrings(filter.services) : undefined,
342 creditTypes: filter.creditTypes ? sortedStrings(filter.creditTypes) : undefined,
343 creditTypesTreatment: filter.creditTypesTreatment,
344 projects: filter.projects ? sortedStrings(filter.projects) : undefined,
345 customPeriod: toCustomPeriod(filter.customPeriod),
346 labels: filter.labels,
347 });
348 return Object.keys(next).length > 0 ? next : undefined;
349 };
350
351 const toThresholdRules = (
352 rules:
353 | readonly billingbudgets.GoogleCloudBillingBudgetsV1ThresholdRule[]
354 | readonly ThresholdRule[]
355 | undefined,
356 ): ThresholdRule[] =>
357 (rules ?? [])
358 .map((rule) =>
359 compact({
360 thresholdPercent: rule.thresholdPercent,
361 spendBasis: rule.spendBasis ?? "CURRENT_SPEND",
362 }),
363 )
364 .sort((left, right) => {
365 const percent = (left.thresholdPercent ?? 0) - (right.thresholdPercent ?? 0);
366 if (percent !== 0) return percent;
367 return (left.spendBasis ?? "").localeCompare(right.spendBasis ?? "");
368 });
369
370 const toNotifications = (
371 rule: billingbudgets.GoogleCloudBillingBudgetsV1NotificationsRule | NotificationsRule | undefined,
372 ): NotificationsRule | undefined => {
373 if (rule === undefined) return undefined;
374 const next = compact({
375 schemaVersion: rule.schemaVersion,
376 pubsubTopic: rule.pubsubTopic,
377 disableDefaultIamRecipients: rule.disableDefaultIamRecipients,
378 enableProjectLevelRecipients: rule.enableProjectLevelRecipients,
379 monitoringNotificationChannels: rule.monitoringNotificationChannels
380 ? sortedStrings(rule.monitoringNotificationChannels)
381 : undefined,
382 });
383 return Object.keys(next).length > 0 ? next : undefined;
384 };
385
386 const toAttrs = (
387 budget: billingbudgets.GoogleCloudBillingBudgetsV1Budget,
388 billingAccountId: string,
389 ) => {
390 const name = budget.name ?? "";
391 const parsed = parseBudgetName(name, billingAccountId);
392 return {
393 name,
394 budgetId: parsed.budgetId,
395 billingAccountId: parsed.billingAccountId || billingAccountId,
396 displayName: budget.displayName,
397 amount: toAmount(budget.amount),
398 budgetFilter: toFilter(budget.budgetFilter),
399 thresholdRules: toThresholdRules(budget.thresholdRules),
400 notificationsRule: toNotifications(budget.notificationsRule),
401 ownershipScope: budget.ownershipScope,
402 etag: budget.etag,
403 };
404 };
405
406 const desiredAmount = (
407 news: BudgetAmount,
408 observed: BudgetAmount | undefined,
409 ): billingbudgets.GoogleCloudBillingBudgetsV1BudgetAmount => {
410 if (news.lastPeriodAmount !== undefined) {
411 return { lastPeriodAmount: {} };
412 }
413 const specified = news.specifiedAmount ?? {};
414 return {
415 specifiedAmount: compact({
416 units: specified.units,
417 currencyCode: specified.currencyCode ?? observed?.specifiedAmount?.currencyCode ?? "USD",
418 nanos: specified.nanos,
419 }),
420 };
421 };
422
423 const toCreateBody = (
424 news: BillingBudgetProps,
425 displayName: string,
426 observed: BudgetAmount | undefined,
427 ): billingbudgets.GoogleCloudBillingBudgetsV1Budget =>
428 compact({
429 displayName,
430 amount: desiredAmount(news.amount, observed),
431 budgetFilter: news.budgetFilter
432 ? (toFilter(news.budgetFilter) as
433 | billingbudgets.GoogleCloudBillingBudgetsV1Filter
434 | undefined)
435 : undefined,
436 thresholdRules:
437 news.thresholdRules !== undefined ? toThresholdRules(news.thresholdRules) : undefined,
438 notificationsRule: news.notificationsRule
439 ? (toNotifications(news.notificationsRule) as
440 | billingbudgets.GoogleCloudBillingBudgetsV1NotificationsRule
441 | undefined)
442 : undefined,
443 ownershipScope: news.ownershipScope,
444 }) as billingbudgets.GoogleCloudBillingBudgetsV1Budget;
445
446 export const BillingBudgetProvider = () =>
447 Provider.succeed(BillingBudget, {
448 stables: ["name", "budgetId", "billingAccountId"],
449
450 diff: Effect.fn(function* ({ news, olds, output }) {
451 if (!isResolved(news)) return undefined;
452 const previousId = olds?.budgetId ?? output?.budgetId;
453 const idChanged =
454 previousId !== undefined && news.budgetId !== undefined && news.budgetId !== previousId;
455 const previousAccount = olds?.billingAccountId ?? output?.billingAccountId;
456 const accountChanged =
457 previousAccount !== undefined &&
458 news.billingAccountId !== undefined &&
459 billingAccountIdOf(news.billingAccountId) !== billingAccountIdOf(previousAccount);
460 if (!idChanged && !accountChanged) return undefined;
461 return { action: "replace" as const, deleteFirst: true };
462 }),
463
464 read: Effect.fn(function* ({ id, olds, output, previous }) {
465 const billingAccountId = yield* resolveBillingAccountId(
466 olds?.billingAccountId,
467 output?.billingAccountId,
468 );
469 const budgetId = output?.budgetId ?? olds?.budgetId;
470 const name = output?.name ?? (budgetId ? budgetNameOf(billingAccountId, budgetId) : "");
471 const generated = yield* generatedDisplayName(id);
472 const existing =
473 (yield* getBudget(name)) ??
474 (yield* findBudgetByDisplayName(
475 billingAccountParent(billingAccountId),
476 olds?.displayName ?? output?.displayName ?? generated,
477 ));
478 if (existing === undefined) return undefined;
479 const attrs = toAttrs(existing, billingAccountId);
480 return existing.displayName === generated
481 ? attrs
482 : unownedUnlessPrevious(attrs, previous, "name");
483 }),
484
485 reconcile: Effect.fn(function* ({ id, news, output }) {
486 const billingAccountId = yield* resolveBillingAccountId(
487 news.billingAccountId,
488 output?.billingAccountId,
489 );
490 const parent = billingAccountParent(billingAccountId);
491 const desiredDisplayName =
492 news.displayName ?? output?.displayName ?? (yield* generatedDisplayName(id));
493 const resolvedProjects = yield* resolveProjectRefs(news.budgetFilter?.projects);
494 const desiredNews =
495 resolvedProjects === undefined
496 ? news
497 : {
498 ...news,
499 budgetFilter: {
500 ...news.budgetFilter,
501 projects: resolvedProjects,
502 },
503 };
504
505 let current = yield* getBudget(
506 output?.name ?? (news.budgetId ? budgetNameOf(billingAccountId, news.budgetId) : ""),
507 );
508 if (current === undefined && news.budgetId === undefined) {
509 current = yield* findBudgetByDisplayName(parent, desiredDisplayName);
510 }
511
512 if (current === undefined) {
513 const created = yield* billingbudgets
514 .createBillingAccountsBudgets({
515 parent,
516 body: toCreateBody(desiredNews, desiredDisplayName, undefined),
517 })
518 .pipe(
519 Effect.catchTag("Conflict", () => findBudgetByDisplayName(parent, desiredDisplayName)),
520 );
521 current = created ?? undefined;
522 }
523
524 if (current === undefined || !current.name) {
525 return yield* new BillingBudgetNotResolved({
526 resourceName: output?.name ?? `${parent}/budgets`,
527 });
528 }
529
530 const observedAmount = toAmount(current.amount);
531 const desiredBody = toCreateBody(desiredNews, desiredDisplayName, observedAmount);
532 const mask: string[] = [];
533 if ((current.displayName ?? "") !== desiredDisplayName) {
534 mask.push("displayName");
535 }
536 if (!jsonEqual(toAmount(current.amount), toAmount(desiredBody.amount))) {
537 mask.push("amount");
538 }
539 if (
540 desiredNews.budgetFilter !== undefined &&
541 filterChanged(
542 toFilter(current.budgetFilter) as Record<string, unknown> | undefined,
543 toFilter(desiredNews.budgetFilter) as Record<string, unknown> | undefined,
544 )
545 ) {
546 mask.push("budgetFilter");
547 }
548 if (
549 desiredNews.thresholdRules !== undefined &&
550 !jsonEqual(
551 toThresholdRules(current.thresholdRules),
552 toThresholdRules(desiredNews.thresholdRules),
553 )
554 ) {
555 mask.push("thresholdRules");
556 }
557 if (
558 desiredNews.notificationsRule !== undefined &&
559 !jsonEqual(
560 toNotifications(current.notificationsRule),
561 toNotifications(desiredNews.notificationsRule),
562 )
563 ) {
564 mask.push("notificationsRule");
565 }
566 if (
567 desiredNews.ownershipScope !== undefined &&
568 (current.ownershipScope ?? "") !== desiredNews.ownershipScope
569 ) {
570 mask.push("ownershipScope");
571 }
572
573 if (mask.length > 0) {
574 current = yield* billingbudgets.patchBillingAccountsBudgets({
575 name: current.name,
576 updateMask: mask.join(","),
577 body: {
578 ...desiredBody,
579 etag: current.etag,
580 },
581 });
582 }
583
584 return toAttrs(current, billingAccountId);
585 }),
586
587 delete: Effect.fn(function* ({ output }) {
588 if (!output.name) return;
589 yield* billingbudgets
590 .deleteBillingAccountsBudgets({ name: output.name })
591 .pipe(Effect.catchTag(["NotFound", "BudgetNotFound"], () => Effect.void));
592 }),
593 });