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

main
ts 219 lines 7.72 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 Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 listLocations,
13 hasOwnershipMarker,
14 lastSegment,
15 normalizeLocation,
16 ownedByAlchemy,
17 parentOf,
18 parseResourceName,
19 toResourceId,
20 } from "./internal.ts";
21
22 export type ReservationGroupProps = {
23 /**
24 * Reservation group id (the `{reservationGroup}` segment of
25 * `projects/{project}/locations/{location}/reservationGroups/{reservationGroup}`).
26 * If omitted, a unique name is generated from the stack, stage, and
27 * logical id. Must contain only lowercase letters, digits, or dashes;
28 * start with a letter; not end with a dash; max 64 characters.
29 * Groups have no labels field, so Alchemy stamps ownership into this
30 * id (`alch---…`) for `list` / nuke. Immutable — changing it replaces
31 * the group.
32 */
33 reservationGroupId?: string;
34 /**
35 * BigQuery location (`us-central1`, `US`, `EU`, …). Immutable —
36 * changing it replaces the group. Multi-regions `US` and `EU` stay
37 * uppercase; regional ids are lowercased.
38 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
39 */
40 location?: string;
41 };
42
43 export type ReservationGroup = Resource<
44 "GCP.BigQueryReservation.ReservationGroup",
45 ReservationGroupProps,
46 {
47 /** Full resource name `projects/{project}/locations/{location}/reservationGroups/{reservationGroup}`. */
48 name: string;
49 /** Reservation group id (last path segment), including the Alchemy prefix. */
50 reservationGroupId: string;
51 /** Project id. */
52 project: string;
53 /** Location id (`us-central1`, `US`, …). */
54 location: string;
55 },
56 never,
57 Providers
58 >;
59
60 /**
61 * A BigQuery reservation group — a named container for reservations.
62 *
63 * Groups have no labels or description, so Alchemy stamps ownership into
64 * the group id (`alch---…`) so `list` / `pnpm nuke:gcp` can find them.
65 * There is no update API; `reservationGroupId` and `location` are
66 * identity and changing them replaces the group.
67 *
68 * ### Creating a Reservation Group
69 * **Example:** Generated id
70 * ```typescript
71 * const group = yield* GCP.BigQueryReservation.ReservationGroup("Team", {});
72 * ```
73 *
74 * **Example:** Explicit id and multi-region location
75 * ```typescript
76 * const group = yield* GCP.BigQueryReservation.ReservationGroup("Team", {
77 * reservationGroupId: "analytics-prod",
78 * location: "US",
79 * });
80 * ```
81 *
82 * @resource
83 * @category BigQueryReservation
84 */
85 export const ReservationGroup = Resource<ReservationGroup>(
86 "GCP.BigQueryReservation.ReservationGroup",
87 );
88
89 export class ReservationGroupNotResolved extends Data.TaggedError(
90 "GCP.BigQueryReservation.ReservationGroupNotResolved",
91 )<{
92 resourceName: string;
93 }> {}
94
95 const resourceName = (project: string, location: string, reservationGroupId: string) =>
96 `projects/${project}/locations/${location}/reservationGroups/${reservationGroupId}`;
97
98 const toAttrs = (current: bigqueryreservation.ReservationGroup, project: string) => {
99 const name = current.name ?? "";
100 const parsed = parseResourceName(name, "reservationGroups");
101 return {
102 name,
103 reservationGroupId: parsed.resourceId,
104 project: parsed.project || project,
105 location: parsed.location,
106 };
107 };
108
109 const getByName = (name: string) =>
110 bigqueryreservation
111 .getProjectsLocationsReservationGroups({ name })
112 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
113
114 const listOwnedAt = (project: string, location: string) =>
115 bigqueryreservation.listProjectsLocationsReservationGroups
116 .pages({
117 parent: parentOf(project, location),
118 pageSize: 1000,
119 })
120 .pipe(
121 Stream.flatMap((page) => Stream.fromIterable(page.reservationGroups ?? [])),
122 Stream.filter((item) => hasOwnershipMarker(lastSegment(item.name ?? ""))),
123 Stream.map((item) => toAttrs(item, project)),
124 Stream.runCollect,
125 Effect.map((chunk) => Array.from(chunk)),
126 Effect.catchTag("NotFound", () => Effect.succeed([])),
127 );
128
129 export const ReservationGroupProvider = () =>
130 Provider.succeed(ReservationGroup, {
131 stables: ["name", "reservationGroupId", "project", "location"],
132
133 diff: Effect.fn(function* ({ id, news, olds, output }) {
134 if (!isResolved(news)) return undefined;
135 const env = yield* GcpEnvironment.current;
136
137 const previousId = olds?.reservationGroupId ?? output?.reservationGroupId;
138 const nextId = yield* toResourceId(id, news.reservationGroupId, previousId);
139 const previousLocation = normalizeLocation(olds?.location ?? output?.location ?? env.region);
140 const nextLocation = normalizeLocation(news.location ?? output?.location ?? env.region);
141
142 const replace =
143 (previousId !== undefined && nextId !== previousId) || previousLocation !== nextLocation;
144
145 if (!replace) return undefined;
146 return {
147 action: "replace" as const,
148 deleteFirst:
149 previousLocation === nextLocation && previousId !== undefined && nextId === previousId,
150 };
151 }),
152
153 read: Effect.fn(function* ({ id, olds, output }) {
154 const env = yield* GcpEnvironment.current;
155 const reservationGroupId = yield* toResourceId(
156 id,
157 olds?.reservationGroupId,
158 output?.reservationGroupId,
159 );
160 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
161 const name = output?.name ?? resourceName(env.project, location, reservationGroupId);
162 const existing = yield* getByName(name);
163 if (existing === undefined) return undefined;
164 const attrs = toAttrs(existing, env.project);
165 return (yield* ownedByAlchemy(id, lastSegment(existing.name ?? ""))) ? attrs : Unowned(attrs);
166 }),
167
168 list: () =>
169 Effect.gen(function* () {
170 const env = yield* GcpEnvironment.current;
171 const pages = yield* Effect.forEach(
172 listLocations(env.region),
173 (location) => listOwnedAt(env.project, location),
174 { concurrency: 4 },
175 );
176 const byName = new Map<string, ReturnType<typeof toAttrs>>();
177 for (const item of pages.flat()) {
178 byName.set(item.name, item);
179 }
180 return Array.from(byName.values());
181 }),
182
183 reconcile: Effect.fn(function* ({ id, news, output }) {
184 const env = yield* GcpEnvironment.current;
185 const reservationGroupId = yield* toResourceId(
186 id,
187 news.reservationGroupId,
188 output?.reservationGroupId,
189 );
190 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
191 const name = resourceName(env.project, location, reservationGroupId);
192 const parent = parentOf(env.project, location);
193
194 let current = yield* getByName(output?.name ?? name);
195
196 if (current === undefined) {
197 const created = yield* bigqueryreservation
198 .createProjectsLocationsReservationGroups({
199 parent,
200 reservationGroupId,
201 body: {},
202 })
203 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
204 current = created ?? undefined;
205 }
206
207 if (current === undefined) {
208 return yield* new ReservationGroupNotResolved({ resourceName: name });
209 }
210
211 return toAttrs(current, env.project);
212 }),
213
214 delete: Effect.fn(function* ({ output }) {
215 yield* bigqueryreservation
216 .deleteProjectsLocationsReservationGroups({ name: output.name })
217 .pipe(Effect.catchTag("NotFound", () => Effect.void));
218 }),
219 });