@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 321 lines 10.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 instanceNameOf,
14 listAlchemyInstances,
15 logicalViewName,
16 MAX_LOGICAL_VIEW_ID_LENGTH,
17 parentOwned,
18 parseResourceName,
19 toPhysicalId,
20 waitForOperation,
21 collectPages,
22 } from "./operations.ts";
23
24 export type InstancesLogicalViewProps = {
25 /**
26 * Parent instance. Full name `projects/{project}/instances/{instance}`
27 * or the instance id. Immutable — changing it replaces the view.
28 */
29 instance: string;
30 /**
31 * Logical view id (the `{logical_view}` segment of
32 * `.../instances/{instance}/logicalViews/{logical_view}`). If omitted,
33 * a unique name is generated from the stack, stage, and logical id.
34 * Must be unique among table ids and view ids in the instance.
35 * Immutable — changing it replaces the view.
36 */
37 logicalViewId?: string;
38 /**
39 * GoogleSQL SELECT query that defines the view. `SELECT *` is not
40 * allowed. Must reference a table in the same instance.
41 */
42 query: string;
43 /**
44 * Protect the view from Admin API deletes. Disabled automatically on
45 * destroy.
46 * @default false
47 */
48 deletionProtection?: boolean;
49 };
50
51 export type InstancesLogicalView = Resource<
52 "GCP.Bigtable.InstancesLogicalView",
53 InstancesLogicalViewProps,
54 {
55 /** Full resource name `.../instances/{instance}/logicalViews/{logical_view}`. */
56 name: string;
57 /** Logical view id (last path segment). */
58 logicalViewId: string;
59 /** Parent instance resource name. */
60 instance: string;
61 /** Parent instance id. */
62 instanceId: string;
63 /** Project id. */
64 project: string;
65 /** Defining SELECT query. */
66 query: string | undefined;
67 /** Whether Admin API deletes are blocked. */
68 deletionProtection: boolean;
69 /** Server etag. */
70 etag: string | undefined;
71 },
72 never,
73 Providers
74 >;
75
76 /**
77 * A Cloud Bigtable logical view — a SQL SELECT over a table that can
78 * be queried as a virtual table.
79 *
80 * The parent instance must already exist and the query cannot use
81 * `SELECT *`. Changing `logicalViewId` or `instance` replaces the view.
82 * `query` and `deletionProtection` update in place.
83 *
84 * Logical views have no labels field. Alchemy treats a view as owned
85 * when its parent instance carries Alchemy labels, so `list` /
86 * `pnpm nuke:gcp` can find it.
87 *
88 * ### Creating a Logical View
89 * **Example:** View over one table
90 * ```typescript
91 * const users = yield* GCP.Bigtable.Table("Users", {
92 * instance: instance.name,
93 * columnFamilies: { cf: {} },
94 * });
95 * const view = yield* GCP.Bigtable.InstancesLogicalView("Active", {
96 * instance: instance.name,
97 * query: "SELECT _key FROM users",
98 * });
99 * ```
100 *
101 * @resource
102 * @category Bigtable
103 */
104 export const InstancesLogicalView = Resource<InstancesLogicalView>(
105 "GCP.Bigtable.InstancesLogicalView",
106 );
107
108 export class LogicalViewNotResolved extends Data.TaggedError(
109 "GCP.Bigtable.LogicalViewNotResolved",
110 )<{
111 resourceName: string;
112 }> {}
113
114 export class LogicalViewStillExists extends Data.TaggedError(
115 "GCP.Bigtable.LogicalViewStillExists",
116 )<{
117 resourceName: string;
118 }> {}
119
120 const toId = (id: string, logicalViewId: string | undefined, existing?: string) =>
121 toPhysicalId(id, logicalViewId, existing, MAX_LOGICAL_VIEW_ID_LENGTH);
122
123 const queryOf = (value: string | undefined) => (value ?? "").trim();
124
125 const toAttrs = (view: bigtable.LogicalView, project: string) => {
126 const name = view.name ?? "";
127 const parsed = parseResourceName(name);
128 return {
129 name,
130 logicalViewId: parsed.logicalViewId,
131 instance: parsed.instance,
132 instanceId: parsed.instanceId,
133 project: parsed.project || project,
134 query: view.query,
135 deletionProtection: view.deletionProtection === true,
136 etag: view.etag,
137 };
138 };
139
140 const getByName = (name: string) =>
141 bigtable
142 .getProjectsInstancesLogicalViews({ name })
143 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
144
145 const waitUntilExists = (name: string) =>
146 getByName(name).pipe(
147 Effect.flatMap((view) =>
148 view ? Effect.succeed(view) : Effect.fail(new LogicalViewNotResolved({ resourceName: name })),
149 ),
150 Effect.retry({
151 while: (error) => error._tag === "GCP.Bigtable.LogicalViewNotResolved",
152 times: 8,
153 schedule: Schedule.spaced("1 second"),
154 }),
155 );
156
157 const waitUntilGone = (name: string) =>
158 getByName(name).pipe(
159 Effect.flatMap((view) =>
160 view === undefined
161 ? Effect.void
162 : Effect.fail(new LogicalViewStillExists({ resourceName: name })),
163 ),
164 Effect.retry({
165 while: (error) => error._tag === "GCP.Bigtable.LogicalViewStillExists",
166 times: 8,
167 schedule: Schedule.spaced("2 seconds"),
168 }),
169 );
170
171 const unprotect = (name: string, etag: string | undefined) =>
172 Effect.gen(function* () {
173 const patched = yield* bigtable.patchProjectsInstancesLogicalViews({
174 name,
175 updateMask: "deletion_protection",
176 body: { deletionProtection: false, etag },
177 });
178 yield* waitForOperation(patched);
179 });
180
181 export const InstancesLogicalViewProvider = () =>
182 Provider.succeed(InstancesLogicalView, {
183 stables: ["name", "logicalViewId", "instance", "instanceId", "project"],
184
185 diff: Effect.fn(function* ({ news, olds, output }) {
186 if (!isResolved(news)) return undefined;
187 const previousId = olds?.logicalViewId ?? output?.logicalViewId;
188 const nextId = news.logicalViewId ?? previousId;
189 const previousInstance = instanceIdOf(
190 olds?.instance ?? output?.instance ?? output?.instanceId ?? "",
191 );
192 const nextInstance = instanceIdOf(news.instance);
193 if (
194 (previousId !== undefined && nextId !== undefined && previousId !== nextId) ||
195 (previousInstance.length > 0 && previousInstance !== nextInstance)
196 ) {
197 return { action: "replace" as const };
198 }
199 return undefined;
200 }),
201
202 read: Effect.fn(function* ({ id, olds, output }) {
203 const env = yield* GcpEnvironment.current;
204 const logicalViewId = yield* toId(id, olds?.logicalViewId, output?.logicalViewId);
205 const instanceRef = olds?.instance ?? output?.instance;
206 const name =
207 output?.name ??
208 (instanceRef
209 ? logicalViewName(env.project, instanceIdOf(instanceRef), logicalViewId)
210 : undefined);
211 if (name === undefined) return undefined;
212 const existing = yield* getByName(name);
213 if (existing === undefined) return undefined;
214 const attrs = toAttrs(existing, env.project);
215 return (yield* parentOwned(attrs.instance)) ? attrs : Unowned(attrs);
216 }),
217
218 list: () =>
219 Effect.gen(function* () {
220 const env = yield* GcpEnvironment.current;
221 const instances = (yield* listAlchemyInstances(env.project)).filter(
222 (instance): instance is bigtable.Instance & { name: string } =>
223 typeof instance.name === "string" && instance.name.length > 0,
224 );
225 const pages = yield* Effect.forEach(
226 instances,
227 (instance) =>
228 collectPages(
229 bigtable.listProjectsInstancesLogicalViews.pages({
230 parent: instance.name,
231 pageSize: 1000,
232 }),
233 (page) => page.logicalViews,
234 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as bigtable.LogicalView[]))),
235 { concurrency: 4 },
236 );
237 return pages.flat().map((view) => toAttrs(view, env.project));
238 }),
239
240 reconcile: Effect.fn(function* ({ id, news, output }) {
241 const env = yield* GcpEnvironment.current;
242 const logicalViewId = yield* toId(id, news.logicalViewId, output?.logicalViewId);
243 const parent = instanceNameOf(env.project, news.instance);
244 const name = `${parent}/logicalViews/${logicalViewId}`;
245 const desiredProtection = news.deletionProtection === true;
246 const query = news.query;
247
248 let current = yield* getByName(output?.name ?? name);
249
250 if (current === undefined) {
251 const created = yield* bigtable
252 .createProjectsInstancesLogicalViews({
253 parent,
254 logicalViewId,
255 body: {
256 query,
257 deletionProtection: desiredProtection,
258 },
259 })
260 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
261 if (created !== undefined) {
262 yield* waitForOperation(created, { alreadyExistsOk: true });
263 }
264 current = yield* waitUntilExists(name);
265 }
266
267 const queryChanged = queryOf(current.query) !== queryOf(query);
268 const protectionChanged = (current.deletionProtection === true) !== desiredProtection;
269 if (queryChanged || protectionChanged) {
270 const mask = [
271 queryChanged ? "query" : undefined,
272 protectionChanged ? "deletion_protection" : undefined,
273 ].filter((field): field is string => field !== undefined);
274 const patched = yield* bigtable
275 .patchProjectsInstancesLogicalViews({
276 name,
277 updateMask: mask.join(","),
278 body: {
279 query,
280 deletionProtection: desiredProtection,
281 etag: current.etag,
282 },
283 })
284 .pipe(
285 Effect.retry({
286 while: (error) => error._tag === "Conflict",
287 times: 8,
288 schedule: Schedule.spaced("1 second"),
289 }),
290 );
291 yield* waitForOperation(patched);
292 current = yield* getByName(name);
293 if (current === undefined) {
294 return yield* new LogicalViewNotResolved({ resourceName: name });
295 }
296 }
297
298 return toAttrs(current, env.project);
299 }),
300
301 delete: Effect.fn(function* ({ output }) {
302 const current = yield* getByName(output.name);
303 if (current === undefined) return;
304 if (current.deletionProtection === true) {
305 yield* unprotect(output.name, current.etag);
306 }
307 yield* bigtable
308 .deleteProjectsInstancesLogicalViews({
309 name: output.name,
310 })
311 .pipe(
312 Effect.catchTag("NotFound", () => Effect.void),
313 Effect.retry({
314 while: (error) => error._tag === "Conflict",
315 times: 8,
316 schedule: Schedule.spaced("2 seconds"),
317 }),
318 );
319 yield* waitUntilGone(output.name);
320 }),
321 });