@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 380 lines 12.6 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 instanceNameOf,
13 listAlchemyInstances,
14 MAX_APP_PROFILE_ID_LENGTH,
15 parentOwned,
16 parseResourceName,
17 toPhysicalId,
18 waitForOperation,
19 collectPages,
20 } from "./operations.ts";
21
22 export type SingleClusterRouting = {
23 /** Cluster id to route all requests to. */
24 clusterId: string;
25 /**
26 * Allow `CheckAndMutateRow` and `ReadModifyWriteRow` on this profile.
27 * @default false
28 */
29 allowTransactionalWrites?: boolean;
30 };
31
32 export type MultiClusterRouting = {
33 /**
34 * Cluster ids to route to. Empty means every cluster in the instance.
35 */
36 clusterIds?: string[];
37 };
38
39 export type StandardIsolation = {
40 /** Request priority (`PRIORITY_LOW`, `PRIORITY_MEDIUM`, `PRIORITY_HIGH`). */
41 priority?: bigtable.StandardIsolationPriorityEnum | (string & {});
42 };
43
44 export type AppProfileProps = {
45 /**
46 * Parent instance. Full name `projects/{project}/instances/{instance}`
47 * or the instance id. Immutable — changing it replaces the app profile.
48 */
49 instance: string;
50 /**
51 * App profile id (the `{appProfile}` segment of
52 * `.../instances/{instance}/appProfiles/{appProfile}`). If omitted, a
53 * unique name is generated from the stack, stage, and logical id. Must
54 * be 1-50 characters. Immutable — changing it replaces the app profile.
55 */
56 appProfileId?: string;
57 /**
58 * Long-form description of the use case.
59 */
60 description?: string;
61 /**
62 * Route all traffic to one cluster. Mutually exclusive with
63 * `multiClusterRouting`.
64 */
65 singleClusterRouting?: SingleClusterRouting;
66 /**
67 * Route to the nearest eligible cluster. Default when neither routing
68 * policy is set.
69 */
70 multiClusterRouting?: MultiClusterRouting;
71 /**
72 * Standard isolation (request priority).
73 */
74 standardIsolation?: StandardIsolation;
75 /**
76 * Ignore safety checks on create, update, and delete.
77 * @default true
78 */
79 ignoreWarnings?: boolean;
80 };
81
82 export type AppProfile = Resource<
83 "GCP.Bigtable.AppProfile",
84 AppProfileProps,
85 {
86 /** Full resource name `projects/{project}/instances/{instance}/appProfiles/{appProfile}`. */
87 name: string;
88 /** App profile id (last path segment). */
89 appProfileId: string;
90 /** Parent instance resource name. */
91 instance: string;
92 /** Instance id. */
93 instanceId: string;
94 /** Project id. */
95 project: string;
96 /** Description. */
97 description: string | undefined;
98 /** Single-cluster routing, if set. */
99 singleClusterRouting: SingleClusterRouting | undefined;
100 /** Multi-cluster routing, if set. */
101 multiClusterRouting: MultiClusterRouting | undefined;
102 /** Standard isolation, if set. */
103 standardIsolation: StandardIsolation | undefined;
104 /** Server etag. */
105 etag: string | undefined;
106 },
107 never,
108 Providers
109 >;
110
111 /**
112 * A Cloud Bigtable app profile — how client traffic is routed across
113 * clusters in an instance.
114 *
115 * The parent instance must already exist. Every instance has a built-in
116 * `default` profile; this resource creates additional profiles.
117 * Changing `appProfileId` or `instance` replaces the profile.
118 * Description, routing, and isolation update in place.
119 *
120 * App profiles have no labels field. Alchemy treats a profile as owned
121 * when its parent instance carries Alchemy labels, so `list` /
122 * `pnpm nuke:gcp` can find it. The built-in `default` profile is never
123 * listed.
124 *
125 * ### Creating an App Profile
126 * **Example:** Multi-cluster routing
127 * ```typescript
128 * const instance = yield* GCP.Bigtable.Instance("Data", {});
129 * const profile = yield* GCP.Bigtable.AppProfile("Analytics", {
130 * instance: instance.name,
131 * description: "analytics reads",
132 * multiClusterRouting: {},
133 * });
134 * ```
135 *
136 * **Example:** Single-cluster routing
137 * ```typescript
138 * const profile = yield* GCP.Bigtable.AppProfile("Writes", {
139 * instance: instance.name,
140 * singleClusterRouting: {
141 * clusterId: "cluster",
142 * allowTransactionalWrites: true,
143 * },
144 * });
145 * ```
146 *
147 * @resource
148 * @category Bigtable
149 */
150 export const AppProfile = Resource<AppProfile>("GCP.Bigtable.AppProfile");
151
152 export class AppProfileNotResolved extends Data.TaggedError("GCP.Bigtable.AppProfileNotResolved")<{
153 resourceName: string;
154 }> {}
155
156 const DEFAULT_APP_PROFILE_ID = "default";
157
158 const toId = (id: string, appProfileId: string | undefined, existing?: string) =>
159 toPhysicalId(id, appProfileId, existing, MAX_APP_PROFILE_ID_LENGTH);
160
161 const routingOf = (profile: bigtable.AppProfile | AppProfileProps) => {
162 const single = "singleClusterRouting" in profile ? profile.singleClusterRouting : undefined;
163 const multi =
164 "multiClusterRoutingUseAny" in profile
165 ? profile.multiClusterRoutingUseAny
166 : "multiClusterRouting" in profile
167 ? profile.multiClusterRouting
168 : undefined;
169 return { single, multi };
170 };
171
172 const routingKey = (profile: bigtable.AppProfile | AppProfileProps) => {
173 const { single, multi } = routingOf(profile);
174 if (single) {
175 return JSON.stringify({
176 kind: "single",
177 clusterId: single.clusterId,
178 tx: single.allowTransactionalWrites === true,
179 });
180 }
181 return JSON.stringify({
182 kind: "multi",
183 clusterIds: [...(multi?.clusterIds ?? [])].sort(),
184 });
185 };
186
187 const isolationKey = (isolation: StandardIsolation | bigtable.StandardIsolation | undefined) =>
188 JSON.stringify({ priority: (isolation?.priority ?? "").toUpperCase() });
189
190 const toAttrs = (profile: bigtable.AppProfile, project: string) => {
191 const name = profile.name ?? "";
192 const parsed = parseResourceName(name);
193 const single = profile.singleClusterRouting
194 ? {
195 clusterId: profile.singleClusterRouting.clusterId ?? "",
196 allowTransactionalWrites: profile.singleClusterRouting.allowTransactionalWrites === true,
197 }
198 : undefined;
199 const multi = profile.multiClusterRoutingUseAny
200 ? { clusterIds: profile.multiClusterRoutingUseAny.clusterIds }
201 : undefined;
202 return {
203 name,
204 appProfileId: parsed.appProfileId,
205 instance: parsed.instance,
206 instanceId: parsed.instanceId,
207 project: parsed.project || project,
208 description: profile.description,
209 singleClusterRouting: single,
210 multiClusterRouting: multi,
211 standardIsolation: profile.standardIsolation
212 ? { priority: profile.standardIsolation.priority }
213 : undefined,
214 etag: profile.etag,
215 };
216 };
217
218 const getByName = (name: string) =>
219 bigtable
220 .getProjectsInstancesAppProfiles({ name })
221 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
222
223 const toBody = (news: AppProfileProps): bigtable.AppProfile => {
224 const body: bigtable.AppProfile = {
225 description: news.description,
226 standardIsolation: news.standardIsolation,
227 };
228 if (news.singleClusterRouting !== undefined) {
229 body.singleClusterRouting = news.singleClusterRouting;
230 } else {
231 body.multiClusterRoutingUseAny = {
232 clusterIds: news.multiClusterRouting?.clusterIds,
233 };
234 }
235 return body;
236 };
237
238 export const AppProfileProvider = () =>
239 Provider.succeed(AppProfile, {
240 stables: ["name", "appProfileId", "instance", "instanceId", "project"],
241
242 diff: Effect.fn(function* ({ news, olds, output }) {
243 if (!isResolved(news)) return undefined;
244 const previousId = olds?.appProfileId ?? output?.appProfileId;
245 const nextId = news.appProfileId ?? previousId;
246 const previousInstance = olds?.instance ?? output?.instance;
247 const previousInstanceId = previousInstance
248 ? parseResourceName(
249 previousInstance.includes("/instances/")
250 ? previousInstance
251 : `projects/_/instances/${previousInstance}`,
252 ).instanceId
253 : output?.instanceId;
254 const nextInstanceId = parseResourceName(
255 news.instance.includes("/instances/")
256 ? news.instance
257 : `projects/_/instances/${news.instance}`,
258 ).instanceId;
259 if (
260 (previousId !== undefined && nextId !== undefined && previousId !== nextId) ||
261 (previousInstanceId !== undefined && previousInstanceId !== nextInstanceId)
262 ) {
263 return { action: "replace" as const };
264 }
265 return undefined;
266 }),
267
268 read: Effect.fn(function* ({ id, olds, output }) {
269 const env = yield* GcpEnvironment.current;
270 const appProfileId = yield* toId(id, olds?.appProfileId, output?.appProfileId);
271 const instanceRef = olds?.instance ?? output?.instance;
272 const name =
273 output?.name ??
274 (instanceRef
275 ? `${instanceNameOf(env.project, instanceRef)}/appProfiles/${appProfileId}`
276 : undefined);
277 if (name === undefined) return undefined;
278 const existing = yield* getByName(name);
279 if (existing === undefined) return undefined;
280 const attrs = toAttrs(existing, env.project);
281 return (yield* parentOwned(attrs.instance)) ? attrs : Unowned(attrs);
282 }),
283
284 list: () =>
285 Effect.gen(function* () {
286 const env = yield* GcpEnvironment.current;
287 const owned = new Set(
288 (yield* listAlchemyInstances(env.project)).map((instance) => instance.name ?? ""),
289 );
290 const appProfiles = yield* collectPages(
291 bigtable.listProjectsInstancesAppProfiles.pages({
292 parent: `projects/${env.project}/instances/-`,
293 pageSize: 1000,
294 }),
295 (page) => page.appProfiles,
296 );
297 return appProfiles
298 .filter((profile) => {
299 const parsed = parseResourceName(profile.name ?? "");
300 return parsed.appProfileId !== DEFAULT_APP_PROFILE_ID && owned.has(parsed.instance);
301 })
302 .map((profile) => toAttrs(profile, env.project));
303 }),
304
305 reconcile: Effect.fn(function* ({ id, news, output }) {
306 const env = yield* GcpEnvironment.current;
307 const appProfileId = yield* toId(id, news.appProfileId, output?.appProfileId);
308 const parent = instanceNameOf(env.project, news.instance);
309 const name = `${parent}/appProfiles/${appProfileId}`;
310 const ignoreWarnings = news.ignoreWarnings ?? true;
311 const desired = toBody(news);
312
313 let current = yield* getByName(name);
314
315 if (current === undefined) {
316 const created = yield* bigtable
317 .createProjectsInstancesAppProfiles({
318 parent,
319 appProfileId,
320 ignoreWarnings,
321 body: desired,
322 })
323 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
324 current = created ?? undefined;
325 }
326
327 if (current === undefined) {
328 return yield* new AppProfileNotResolved({ resourceName: name });
329 }
330
331 const descriptionChanged = (news.description ?? "") !== (current.description ?? "");
332 const routingChanged = routingKey(news) !== routingKey(current);
333 const isolationChanged =
334 news.standardIsolation !== undefined &&
335 isolationKey(news.standardIsolation) !== isolationKey(current.standardIsolation);
336
337 if (descriptionChanged || routingChanged || isolationChanged) {
338 const mask = [
339 descriptionChanged ? "description" : undefined,
340 routingChanged
341 ? news.singleClusterRouting !== undefined
342 ? "single_cluster_routing"
343 : "multi_cluster_routing_use_any"
344 : undefined,
345 isolationChanged ? "standard_isolation" : undefined,
346 ].filter((field): field is string => field !== undefined);
347 const patched = yield* bigtable
348 .patchProjectsInstancesAppProfiles({
349 name,
350 updateMask: mask.join(","),
351 ignoreWarnings,
352 body: { ...desired, etag: current.etag },
353 })
354 .pipe(
355 Effect.retry({
356 while: (error) => error._tag === "Conflict",
357 times: 8,
358 schedule: Schedule.spaced("1 second"),
359 }),
360 );
361 yield* waitForOperation(patched);
362 current = yield* getByName(name);
363 if (current === undefined) {
364 return yield* new AppProfileNotResolved({ resourceName: name });
365 }
366 }
367
368 return toAttrs(current, env.project);
369 }),
370
371 delete: Effect.fn(function* ({ output, olds }) {
372 const ignoreWarnings = olds?.ignoreWarnings ?? true;
373 yield* bigtable
374 .deleteProjectsInstancesAppProfiles({
375 name: output.name,
376 ignoreWarnings,
377 })
378 .pipe(Effect.catchTag("NotFound", () => Effect.void));
379 }),
380 });