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

main
ts 409 lines 13.5 KB
Raw
1 import * as bigtable from "@distilled.cloud/gcp/bigtableadmin_v2";
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 { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 instanceIdOf,
13 listAlchemyTables,
14 MAX_AUTHORIZED_VIEW_ID_LENGTH,
15 parentOwned,
16 parseResourceName,
17 tableIdOf,
18 tableNameOf,
19 toPhysicalId,
20 waitForOperation,
21 collectPages,
22 } from "./operations.ts";
23
24 export type FamilySubsets = {
25 /** Exact column qualifiers included in the view (base64 bytes). */
26 qualifiers?: string[];
27 /**
28 * Qualifier prefixes included in the view. The empty string includes
29 * every qualifier in the family.
30 */
31 qualifierPrefixes?: string[];
32 };
33
34 export type SubsetView = {
35 /**
36 * Row-key prefixes included in the view (base64 bytes). The empty
37 * string includes every row.
38 */
39 rowPrefixes?: string[];
40 /** Column families included in the view, keyed by family id. */
41 familySubsets?: Record<string, FamilySubsets>;
42 };
43
44 export type InstancesTablesAuthorizedViewProps = {
45 /**
46 * Parent instance. Full name `projects/{project}/instances/{instance}`
47 * or the instance id. Immutable — changing it replaces the view.
48 */
49 instance: string;
50 /**
51 * Parent table. Full name
52 * `projects/{project}/instances/{instance}/tables/{table}` or the table
53 * id. Immutable — changing it replaces the view.
54 */
55 table: string;
56 /**
57 * Authorized view id (the `{authorized_view}` segment of
58 * `.../tables/{table}/authorizedViews/{authorized_view}`). If omitted,
59 * a unique name is generated from the stack, stage, and logical id.
60 * Immutable — changing it replaces the view.
61 */
62 authorizedViewId?: string;
63 /**
64 * Subset of the table this view exposes.
65 */
66 subsetView?: SubsetView;
67 /**
68 * Protect the view (and its table/instance) from Admin API deletes.
69 * Disabled automatically on destroy.
70 * @default false
71 */
72 deletionProtection?: boolean;
73 /**
74 * Ignore safety checks on update.
75 * @default true
76 */
77 ignoreWarnings?: boolean;
78 };
79
80 export type InstancesTablesAuthorizedView = Resource<
81 "GCP.Bigtable.InstancesTablesAuthorizedView",
82 InstancesTablesAuthorizedViewProps,
83 {
84 /** Full resource name `.../tables/{table}/authorizedViews/{authorized_view}`. */
85 name: string;
86 /** Authorized view id (last path segment). */
87 authorizedViewId: string;
88 /** Parent table resource name. */
89 table: string;
90 /** Parent table id. */
91 tableId: string;
92 /** Parent instance resource name. */
93 instance: string;
94 /** Parent instance id. */
95 instanceId: string;
96 /** Project id. */
97 project: string;
98 /** Subset of the table currently exposed. */
99 subsetView: SubsetView | undefined;
100 /** Whether Admin API deletes are blocked. */
101 deletionProtection: boolean;
102 /** Server etag. */
103 etag: string | undefined;
104 },
105 never,
106 Providers
107 >;
108
109 /**
110 * A Cloud Bigtable authorized view — a named subset of a table used for
111 * fine-grained IAM.
112 *
113 * The parent instance and table must already exist. Changing
114 * `authorizedViewId`, `instance`, or `table` replaces the view.
115 * `subsetView` and `deletionProtection` update in place.
116 *
117 * Authorized views have no labels field. Alchemy treats a view as owned
118 * when its parent instance carries Alchemy labels, so `list` /
119 * `pnpm nuke:gcp` can find it.
120 *
121 * ### Creating an Authorized View
122 * **Example:** All rows of one column family
123 * ```typescript
124 * const view = yield* GCP.Bigtable.InstancesTablesAuthorizedView("Public", {
125 * instance: instance.name,
126 * table: table.name,
127 * subsetView: {
128 * rowPrefixes: [""],
129 * familySubsets: {
130 * cf: { qualifierPrefixes: [""] },
131 * },
132 * },
133 * });
134 * ```
135 *
136 * @resource
137 * @category Bigtable
138 */
139 export const InstancesTablesAuthorizedView = Resource<InstancesTablesAuthorizedView>(
140 "GCP.Bigtable.InstancesTablesAuthorizedView",
141 );
142
143 export class AuthorizedViewNotResolved extends Data.TaggedError(
144 "GCP.Bigtable.AuthorizedViewNotResolved",
145 )<{
146 resourceName: string;
147 }> {}
148
149 export class AuthorizedViewStillExists extends Data.TaggedError(
150 "GCP.Bigtable.AuthorizedViewStillExists",
151 )<{
152 resourceName: string;
153 }> {}
154
155 const toId = (id: string, authorizedViewId: string | undefined, existing?: string) =>
156 toPhysicalId(id, authorizedViewId, existing, MAX_AUTHORIZED_VIEW_ID_LENGTH);
157
158 const familyOf = (
159 family: FamilySubsets | bigtable.GoogleBigtableAdminV2AuthorizedViewFamilySubsets,
160 ): FamilySubsets => ({
161 qualifiers: family.qualifiers,
162 qualifierPrefixes: family.qualifierPrefixes,
163 });
164
165 const subsetOf = (
166 view: SubsetView | bigtable.GoogleBigtableAdminV2AuthorizedViewSubsetView | undefined,
167 ): SubsetView | undefined => {
168 if (view === undefined) return undefined;
169 const familySubsets: Record<string, FamilySubsets> = {};
170 for (const [id, family] of Object.entries(view.familySubsets ?? {})) {
171 if (family === undefined) continue;
172 familySubsets[id] = familyOf(family);
173 }
174 return {
175 rowPrefixes: view.rowPrefixes,
176 familySubsets: Object.keys(familySubsets).length > 0 ? familySubsets : undefined,
177 };
178 };
179
180 const subsetKey = (view: SubsetView | undefined) => {
181 const families = Object.entries(view?.familySubsets ?? {})
182 .sort(([left], [right]) => left.localeCompare(right))
183 .map(([id, family]) => [
184 id,
185 {
186 qualifierPrefixes: [...(family?.qualifierPrefixes ?? [])].sort(),
187 qualifiers: [...(family?.qualifiers ?? [])].sort(),
188 },
189 ]);
190 return JSON.stringify({
191 rowPrefixes: [...(view?.rowPrefixes ?? [])].sort(),
192 familySubsets: families,
193 });
194 };
195
196 const toAttrs = (view: bigtable.AuthorizedView, project: string) => {
197 const name = view.name ?? "";
198 const parsed = parseResourceName(name);
199 return {
200 name,
201 authorizedViewId: parsed.authorizedViewId,
202 table: parsed.table,
203 tableId: parsed.tableId,
204 instance: parsed.instance,
205 instanceId: parsed.instanceId,
206 project: parsed.project || project,
207 subsetView: subsetOf(view.subsetView),
208 deletionProtection: view.deletionProtection === true,
209 etag: view.etag,
210 };
211 };
212
213 const getByName = (name: string) =>
214 bigtable
215 .getProjectsInstancesTablesAuthorizedViews({ name, view: "FULL" })
216 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
217
218 const waitUntilExists = (name: string) =>
219 getByName(name).pipe(
220 Effect.flatMap((view) =>
221 view
222 ? Effect.succeed(view)
223 : Effect.fail(new AuthorizedViewNotResolved({ resourceName: name })),
224 ),
225 Effect.retry({
226 while: (error) => error._tag === "GCP.Bigtable.AuthorizedViewNotResolved",
227 times: 8,
228 schedule: Schedule.spaced("1 second"),
229 }),
230 );
231
232 const waitUntilGone = (name: string) =>
233 getByName(name).pipe(
234 Effect.flatMap((view) =>
235 view === undefined
236 ? Effect.void
237 : Effect.fail(new AuthorizedViewStillExists({ resourceName: name })),
238 ),
239 Effect.retry({
240 while: (error) => error._tag === "GCP.Bigtable.AuthorizedViewStillExists",
241 times: 8,
242 schedule: Schedule.spaced("2 seconds"),
243 }),
244 );
245
246 const unprotect = (name: string, etag: string | undefined, ignoreWarnings: boolean) =>
247 Effect.gen(function* () {
248 const patched = yield* bigtable.patchProjectsInstancesTablesAuthorizedViews({
249 name,
250 updateMask: "deletion_protection",
251 ignoreWarnings,
252 body: { deletionProtection: false, etag },
253 });
254 yield* waitForOperation(patched);
255 });
256
257 export const InstancesTablesAuthorizedViewProvider = () =>
258 Provider.succeed(InstancesTablesAuthorizedView, {
259 stables: ["name", "authorizedViewId", "table", "tableId", "instance", "instanceId", "project"],
260
261 diff: Effect.fn(function* ({ news, olds, output }) {
262 if (!isResolved(news)) return undefined;
263 const previousId = olds?.authorizedViewId ?? output?.authorizedViewId;
264 const nextId = news.authorizedViewId ?? previousId;
265 const previousInstance = instanceIdOf(
266 olds?.instance ?? output?.instance ?? output?.instanceId ?? "",
267 );
268 const nextInstance = instanceIdOf(news.instance);
269 const previousTable = tableIdOf(olds?.table ?? output?.table ?? output?.tableId ?? "");
270 const nextTable = tableIdOf(news.table);
271 if (
272 (previousId !== undefined && nextId !== undefined && previousId !== nextId) ||
273 (previousInstance.length > 0 && previousInstance !== nextInstance) ||
274 (previousTable.length > 0 && previousTable !== nextTable)
275 ) {
276 return { action: "replace" as const };
277 }
278 return undefined;
279 }),
280
281 read: Effect.fn(function* ({ id, olds, output }) {
282 const env = yield* GcpEnvironment.current;
283 const authorizedViewId = yield* toId(id, olds?.authorizedViewId, output?.authorizedViewId);
284 const instanceRef = olds?.instance ?? output?.instance;
285 const tableRef = olds?.table ?? output?.table;
286 const name =
287 output?.name ??
288 (instanceRef && tableRef
289 ? `${tableNameOf(env.project, instanceRef, tableRef)}/authorizedViews/${authorizedViewId}`
290 : undefined);
291 if (name === undefined) return undefined;
292 const existing = yield* getByName(name);
293 if (existing === undefined) return undefined;
294 const attrs = toAttrs(existing, env.project);
295 return (yield* parentOwned(attrs.instance)) ? attrs : Unowned(attrs);
296 }),
297
298 list: () =>
299 Effect.gen(function* () {
300 const env = yield* GcpEnvironment.current;
301 const tables = (yield* listAlchemyTables(env.project)).filter(
302 (table): table is bigtable.Table & { name: string } =>
303 typeof table.name === "string" && table.name.length > 0,
304 );
305 const pages = yield* Effect.forEach(
306 tables,
307 (table) =>
308 collectPages(
309 bigtable.listProjectsInstancesTablesAuthorizedViews.pages({
310 parent: table.name,
311 pageSize: 1000,
312 }),
313 (page) => page.authorizedViews,
314 ).pipe(
315 Effect.catchTag("NotFound", () => Effect.succeed([] as bigtable.AuthorizedView[])),
316 ),
317 { concurrency: 4 },
318 );
319 return pages.flat().map((view) => toAttrs(view, env.project));
320 }),
321
322 reconcile: Effect.fn(function* ({ id, news, output }) {
323 const env = yield* GcpEnvironment.current;
324 const authorizedViewId = yield* toId(id, news.authorizedViewId, output?.authorizedViewId);
325 const parent = tableNameOf(env.project, news.instance, news.table);
326 const name = `${parent}/authorizedViews/${authorizedViewId}`;
327 const desiredProtection = news.deletionProtection === true;
328 const ignoreWarnings = news.ignoreWarnings ?? true;
329 const desiredSubset = subsetOf(news.subsetView);
330
331 let current = yield* getByName(output?.name ?? name);
332
333 if (current === undefined) {
334 const created = yield* bigtable
335 .createProjectsInstancesTablesAuthorizedViews({
336 parent,
337 authorizedViewId,
338 body: {
339 subsetView: desiredSubset,
340 deletionProtection: desiredProtection,
341 },
342 })
343 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
344 if (created !== undefined) {
345 yield* waitForOperation(created, { alreadyExistsOk: true });
346 }
347 current = yield* waitUntilExists(name);
348 }
349
350 const observedSubset = subsetOf(current.subsetView);
351 const subsetChanged =
352 news.subsetView !== undefined && subsetKey(observedSubset) !== subsetKey(desiredSubset);
353 const protectionChanged = (current.deletionProtection === true) !== desiredProtection;
354
355 if (subsetChanged || protectionChanged) {
356 const mask = [
357 subsetChanged ? "subset_view" : undefined,
358 protectionChanged ? "deletion_protection" : undefined,
359 ].filter((field): field is string => field !== undefined);
360 const patched = yield* bigtable
361 .patchProjectsInstancesTablesAuthorizedViews({
362 name,
363 updateMask: mask.join(","),
364 ignoreWarnings,
365 body: {
366 subsetView: desiredSubset,
367 deletionProtection: desiredProtection,
368 etag: current.etag,
369 },
370 })
371 .pipe(
372 Effect.retry({
373 while: (error) => error._tag === "Conflict",
374 times: 8,
375 schedule: Schedule.spaced("1 second"),
376 }),
377 );
378 yield* waitForOperation(patched);
379 current = yield* getByName(name);
380 if (current === undefined) {
381 return yield* new AuthorizedViewNotResolved({ resourceName: name });
382 }
383 }
384
385 return toAttrs(current, env.project);
386 }),
387
388 delete: Effect.fn(function* ({ output, olds }) {
389 const ignoreWarnings = olds?.ignoreWarnings ?? true;
390 const current = yield* getByName(output.name);
391 if (current === undefined) return;
392 if (current.deletionProtection === true) {
393 yield* unprotect(output.name, current.etag, ignoreWarnings);
394 }
395 yield* bigtable
396 .deleteProjectsInstancesTablesAuthorizedViews({
397 name: output.name,
398 })
399 .pipe(
400 Effect.catchTag("NotFound", () => Effect.void),
401 Effect.retry({
402 while: (error) => error._tag === "Conflict",
403 times: 8,
404 schedule: Schedule.spaced("2 seconds"),
405 }),
406 );
407 yield* waitUntilGone(output.name);
408 }),
409 });