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

main
ts 404 lines 14.4 KB
Raw
1 import * as bigqueryreservation from "@distilled.cloud/gcp/bigqueryreservation_v1";
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 * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 compact,
14 listLocations,
15 hasOwnershipMarker,
16 lastSegment,
17 normalizeLocation,
18 ownedByAlchemy,
19 parentOf,
20 parseResourceName,
21 toResourceId,
22 } from "./internal.ts";
23
24 const DEFAULT_EDITION = "ENTERPRISE";
25
26 export type CapacityCommitmentPlan = bigqueryreservation.CapacityCommitmentPlanEnum | (string & {});
27
28 export type CapacityCommitmentEdition =
29 | bigqueryreservation.CapacityCommitmentEditionEnum
30 | (string & {});
31
32 export type CapacityCommitmentRenewalPlan =
33 | bigqueryreservation.CapacityCommitmentRenewalPlanEnum
34 | (string & {});
35
36 export type CapacityCommitmentProps = {
37 /**
38 * Capacity commitment id (the `{capacityCommitment}` segment of
39 * `projects/{project}/locations/{location}/capacityCommitments/{capacityCommitment}`).
40 * If omitted, a unique name is generated from the stack, stage, and
41 * logical id. Must contain only lowercase letters, digits, or dashes;
42 * start with a letter; not end with a dash; max 64 characters.
43 * Commitments have no labels field, so Alchemy stamps ownership into
44 * this id (`alch---…`) for `list` / nuke. Immutable — changing it
45 * replaces the commitment. Split/merge drops a caller-assigned id.
46 */
47 capacityCommitmentId?: string;
48 /**
49 * BigQuery location (`us-central1`, `US`, `EU`, …). Immutable —
50 * changing it replaces the commitment. Multi-regions `US` and `EU`
51 * stay uppercase; regional ids are lowercased.
52 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
53 */
54 location?: string;
55 /**
56 * Number of slots in this commitment. Immutable — changing it
57 * replaces the commitment. Edition commitments are typically sold in
58 * 50-slot increments (legacy flat-rate in 100-slot increments).
59 */
60 slotCount: string;
61 /**
62 * Commitment plan (`FLEX`, `MONTHLY`, `ANNUAL`, `THREE_YEAR`, and
63 * the `*_FLAT_RATE` variants). `FLEX` (or `FLEX_FLAT_RATE`) can be
64 * deleted about 60 seconds after it becomes `ACTIVE`. Longer plans
65 * cannot be deleted until they expire or are converted to a shorter
66 * plan after expiry. Plan may be updated in place only to a longer
67 * committed period.
68 */
69 plan: CapacityCommitmentPlan;
70 /**
71 * Plan this commitment converts to after `commitmentEndTime`. Only
72 * applicable for `ANNUAL` and `TRIAL` commitments.
73 */
74 renewalPlan?: CapacityCommitmentRenewalPlan;
75 /**
76 * Reservation edition. Immutable — changing it replaces the
77 * commitment. `STANDARD` cannot purchase commitments; use
78 * `ENTERPRISE` or `ENTERPRISE_PLUS`.
79 * @default "ENTERPRISE"
80 */
81 edition?: CapacityCommitmentEdition;
82 /**
83 * Place the commitment in the organization's DR secondary region
84 * (multi-region `US` or `EU` only). Preview; the project must be
85 * allow-listed. Immutable — changing it replaces the commitment.
86 */
87 multiRegionAuxiliary?: boolean;
88 /**
89 * When true, fail the create if another project in the organization
90 * already has a capacity commitment.
91 * @default false
92 */
93 enforceSingleAdminProjectPerOrg?: boolean;
94 };
95
96 export type CapacityCommitment = Resource<
97 "GCP.BigQueryReservation.CapacityCommitment",
98 CapacityCommitmentProps,
99 {
100 /** Full resource name `projects/{project}/locations/{location}/capacityCommitments/{capacityCommitment}`. */
101 name: string;
102 /** Capacity commitment id (last path segment), including the Alchemy prefix. */
103 capacityCommitmentId: string;
104 /** Project id. */
105 project: string;
106 /** Location id (`us-central1`, `US`, …). */
107 location: string;
108 /** Number of slots. */
109 slotCount: string | undefined;
110 /** Commitment plan. */
111 plan: string | undefined;
112 /** Renewal plan, if set. */
113 renewalPlan: string | undefined;
114 /** Reservation edition. */
115 edition: string | undefined;
116 /** Commitment state (`PENDING`, `ACTIVE`, `FAILED`). */
117 state: string | undefined;
118 /** Whether this is a legacy flat-rate commitment. */
119 isFlatRate: boolean;
120 /** Whether this is a multi-region auxiliary commitment. */
121 multiRegionAuxiliary: boolean;
122 /** RFC3339 start of the current commitment period. */
123 commitmentStartTime: string | undefined;
124 /** RFC3339 end of the current commitment period. */
125 commitmentEndTime: string | undefined;
126 /** Failure reason when `state` is `FAILED`. */
127 failureStatus: bigqueryreservation.Status | undefined;
128 },
129 never,
130 Providers
131 >;
132
133 /**
134 * A BigQuery capacity commitment — purchased slot capacity with a
135 * committed period of usage.
136 *
137 * Commitments have no labels, so Alchemy stamps ownership into the
138 * commitment id (`alch---…`) so `list` / `pnpm nuke:gcp` can find them.
139 * Changing `capacityCommitmentId`, `location`, `slotCount`, `edition`,
140 * or `multiRegionAuxiliary` replaces the commitment. `plan` and
141 * `renewalPlan` update in place (plan can only lengthen).
142 *
143 * `FLEX` commitments can be deleted about 60 seconds after they become
144 * `ACTIVE`. Annual and three-year commitments cannot be deleted until
145 * they expire.
146 *
147 * ### Creating a Capacity Commitment
148 * **Example:** Flex Enterprise slots
149 * ```typescript
150 * const commit = yield* GCP.BigQueryReservation.CapacityCommitment("Flex", {
151 * location: "US",
152 * slotCount: "50",
153 * plan: "FLEX_FLAT_RATE",
154 * edition: "ENTERPRISE",
155 * });
156 * ```
157 *
158 * **Example:** Annual commitment with flex renewal
159 * ```typescript
160 * const commit = yield* GCP.BigQueryReservation.CapacityCommitment("Year", {
161 * location: "US",
162 * slotCount: "100",
163 * plan: "ANNUAL",
164 * renewalPlan: "FLEX",
165 * edition: "ENTERPRISE",
166 * });
167 * ```
168 *
169 * @resource
170 * @category BigQueryReservation
171 */
172 export const CapacityCommitment = Resource<CapacityCommitment>(
173 "GCP.BigQueryReservation.CapacityCommitment",
174 );
175
176 export class CapacityCommitmentNotResolved extends Data.TaggedError(
177 "GCP.BigQueryReservation.CapacityCommitmentNotResolved",
178 )<{
179 resourceName: string;
180 }> {}
181
182 const resourceName = (project: string, location: string, capacityCommitmentId: string) =>
183 `projects/${project}/locations/${location}/capacityCommitments/${capacityCommitmentId}`;
184
185 const normalizeEdition = (edition: string | undefined) => {
186 const value = (edition ?? DEFAULT_EDITION).toUpperCase();
187 return value === "EDITION_UNSPECIFIED" ? DEFAULT_EDITION : value;
188 };
189
190 const normalizePlan = (plan: string) => plan.toUpperCase();
191
192 const toAttrs = (current: bigqueryreservation.CapacityCommitment, project: string) => {
193 const name = current.name ?? "";
194 const parsed = parseResourceName(name, "capacityCommitments");
195 return {
196 name,
197 capacityCommitmentId: parsed.resourceId,
198 project: parsed.project || project,
199 location: parsed.location,
200 slotCount: current.slotCount,
201 plan: current.plan,
202 renewalPlan: current.renewalPlan,
203 edition: current.edition,
204 state: current.state,
205 isFlatRate: current.isFlatRate === true,
206 multiRegionAuxiliary: current.multiRegionAuxiliary === true,
207 commitmentStartTime: current.commitmentStartTime,
208 commitmentEndTime: current.commitmentEndTime,
209 failureStatus: current.failureStatus,
210 };
211 };
212
213 const getByName = (name: string) =>
214 bigqueryreservation
215 .getProjectsLocationsCapacityCommitments({ name })
216 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
217
218 const waitUntilSettled = (name: string) =>
219 getByName(name).pipe(
220 Effect.repeat({
221 schedule: Schedule.spaced("2 seconds"),
222 until: (row) => row === undefined || row.state !== "PENDING",
223 times: 10,
224 }),
225 );
226
227 const listOwnedAt = (project: string, location: string) =>
228 bigqueryreservation.listProjectsLocationsCapacityCommitments
229 .pages({
230 parent: parentOf(project, location),
231 pageSize: 1000,
232 })
233 .pipe(
234 Stream.flatMap((page) => Stream.fromIterable(page.capacityCommitments ?? [])),
235 Stream.filter((item) => hasOwnershipMarker(lastSegment(item.name ?? ""))),
236 Stream.map((item) => toAttrs(item, project)),
237 Stream.runCollect,
238 Effect.map((chunk) => Array.from(chunk)),
239 Effect.catchTag("NotFound", () => Effect.succeed([])),
240 );
241
242 const toBody = (
243 news: CapacityCommitmentProps,
244 edition: string,
245 ): bigqueryreservation.CapacityCommitment =>
246 compact({
247 slotCount: news.slotCount,
248 plan: news.plan,
249 edition,
250 renewalPlan: news.renewalPlan,
251 multiRegionAuxiliary: news.multiRegionAuxiliary,
252 });
253
254 const stillCommitted = (
255 error: bigqueryreservation.DeleteProjectsLocationsCapacityCommitmentsError,
256 ) => error._tag === "Conflict" || error._tag === "CapacityCommitmentNotExpired";
257
258 export const CapacityCommitmentProvider = () =>
259 Provider.succeed(CapacityCommitment, {
260 stables: [
261 "name",
262 "capacityCommitmentId",
263 "project",
264 "location",
265 "edition",
266 "slotCount",
267 "commitmentStartTime",
268 ],
269
270 diff: Effect.fn(function* ({ id, news, olds, output }) {
271 if (!isResolved(news)) return undefined;
272 const env = yield* GcpEnvironment.current;
273
274 const previousId = olds?.capacityCommitmentId ?? output?.capacityCommitmentId;
275 const nextId = yield* toResourceId(id, news.capacityCommitmentId, previousId);
276 const previousLocation = normalizeLocation(olds?.location ?? output?.location ?? env.region);
277 const nextLocation = normalizeLocation(news.location ?? output?.location ?? env.region);
278 const previousEdition = normalizeEdition(olds?.edition ?? output?.edition);
279 const nextEdition = normalizeEdition(news.edition ?? previousEdition);
280 const previousAuxiliary = olds?.multiRegionAuxiliary ?? output?.multiRegionAuxiliary ?? false;
281 const nextAuxiliary = news.multiRegionAuxiliary ?? previousAuxiliary;
282 const previousSlots = olds?.slotCount ?? output?.slotCount;
283 const nextSlots = news.slotCount ?? previousSlots;
284
285 const replace =
286 (previousId !== undefined && nextId !== previousId) ||
287 previousLocation !== nextLocation ||
288 previousEdition !== nextEdition ||
289 previousAuxiliary !== nextAuxiliary ||
290 (previousSlots !== undefined && nextSlots !== undefined && previousSlots !== nextSlots);
291
292 if (!replace) return undefined;
293 return {
294 action: "replace" as const,
295 deleteFirst:
296 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
297 };
298 }),
299
300 read: Effect.fn(function* ({ id, olds, output }) {
301 const env = yield* GcpEnvironment.current;
302 const capacityCommitmentId = yield* toResourceId(
303 id,
304 olds?.capacityCommitmentId,
305 output?.capacityCommitmentId,
306 );
307 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
308 const name = output?.name ?? resourceName(env.project, location, capacityCommitmentId);
309 const existing = yield* getByName(name);
310 if (existing === undefined) return undefined;
311 const attrs = toAttrs(existing, env.project);
312 return (yield* ownedByAlchemy(id, lastSegment(existing.name ?? ""))) ? attrs : Unowned(attrs);
313 }),
314
315 list: () =>
316 Effect.gen(function* () {
317 const env = yield* GcpEnvironment.current;
318 const pages = yield* Effect.forEach(
319 listLocations(env.region),
320 (location) => listOwnedAt(env.project, location),
321 { concurrency: 4 },
322 );
323 const byName = new Map<string, ReturnType<typeof toAttrs>>();
324 for (const item of pages.flat()) {
325 byName.set(item.name, item);
326 }
327 return Array.from(byName.values());
328 }),
329
330 reconcile: Effect.fn(function* ({ id, news, output }) {
331 const env = yield* GcpEnvironment.current;
332 const capacityCommitmentId = yield* toResourceId(
333 id,
334 news.capacityCommitmentId,
335 output?.capacityCommitmentId,
336 );
337 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
338 const name = resourceName(env.project, location, capacityCommitmentId);
339 const parent = parentOf(env.project, location);
340 const edition = normalizeEdition(news.edition ?? output?.edition);
341 const createBody = toBody(news, edition);
342
343 let current = yield* getByName(output?.name ?? name);
344
345 if (current === undefined) {
346 const created = yield* bigqueryreservation
347 .createProjectsLocationsCapacityCommitments({
348 parent,
349 capacityCommitmentId,
350 enforceSingleAdminProjectPerOrg: news.enforceSingleAdminProjectPerOrg,
351 body: createBody,
352 })
353 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
354 current = created ?? undefined;
355 if (current?.state === "PENDING") {
356 current = (yield* waitUntilSettled(current.name ?? name)) ?? current;
357 }
358 }
359
360 if (current === undefined) {
361 return yield* new CapacityCommitmentNotResolved({ resourceName: name });
362 }
363
364 const desiredPlan = normalizePlan(news.plan);
365 const observedPlan = normalizePlan(current.plan ?? desiredPlan);
366 const planChanged = observedPlan !== desiredPlan;
367 const renewalChanged =
368 news.renewalPlan !== undefined && (current.renewalPlan ?? "") !== news.renewalPlan;
369
370 const updateMask = [
371 planChanged ? "plan" : undefined,
372 renewalChanged ? "renewalPlan" : undefined,
373 ].filter((field): field is string => field !== undefined);
374
375 if (updateMask.length > 0) {
376 current = yield* bigqueryreservation.patchProjectsLocationsCapacityCommitments({
377 name: current.name ?? name,
378 updateMask: updateMask.join(","),
379 body: compact({
380 plan: news.plan,
381 renewalPlan: news.renewalPlan,
382 }),
383 });
384 }
385
386 return toAttrs(current, env.project);
387 }),
388
389 delete: Effect.fn(function* ({ output }) {
390 yield* bigqueryreservation
391 .deleteProjectsLocationsCapacityCommitments({
392 name: output.name,
393 force: true,
394 })
395 .pipe(
396 Effect.retry({
397 while: stillCommitted,
398 times: 8,
399 schedule: Schedule.spaced("8 seconds"),
400 }),
401 Effect.catchTag("NotFound", () => Effect.void),
402 );
403 }),
404 });