@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 362 lines 12.6 KB
Raw
1 import * as apihub from "@distilled.cloud/gcp/apihub_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 { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 ApihubNotResolved,
13 MAX_INSTANCE_ID_LENGTH,
14 encodeOwnership,
15 hasAlchemyLabelMap,
16 hasOwnershipMarker,
17 locationParent,
18 normalizeLocation,
19 parseOwnership,
20 parseResourceName,
21 replaceOnIdentity,
22 sameText,
23 toPhysicalId,
24 updateMaskOf,
25 userLabels,
26 waitForDeleteOperation,
27 waitForOperation,
28 waitUntilExists,
29 waitUntilGone,
30 } from "./internal.ts";
31
32 export type ApiHubInstanceConfig = {
33 /** Disable search for the instance. */
34 disableSearch?: boolean;
35 /**
36 * Customer-managed encryption key
37 * `projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`.
38 * Immutable — changing it replaces the instance.
39 */
40 cmekKeyName?: string;
41 /**
42 * Encryption type. Immutable — changing it replaces the instance.
43 * @default "GMEK"
44 */
45 encryptionType?: "ENCRYPTION_TYPE_UNSPECIFIED" | "GMEK" | "CMEK" | (string & {});
46 /** Vertex AI location used for the data store. */
47 vertexLocation?: string;
48 /** When true, MCP data is not synced to Agent Registry. */
49 agentRegistrySyncDisabled?: boolean;
50 };
51
52 export type ApiHubInstanceProps = {
53 /**
54 * ApiHub instance id (the `{apiHubInstance}` segment of
55 * `projects/{project}/locations/{location}/apiHubInstances/{apiHubInstance}`).
56 * If omitted, a unique id is generated. Must be 4-40 characters matching
57 * `[a-z0-9-_]+`. Immutable — changing it replaces the instance.
58 */
59 apiHubInstanceId?: string;
60 /**
61 * Location (`us-central1`, …). Only one ApiHub instance is allowed per
62 * project. Immutable — changing it replaces the instance.
63 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
64 */
65 location?: string;
66 /**
67 * Human-readable description. Ownership is stored in labels; the
68 * description is also stamped with `[alchemy …]` so `list` / nuke can
69 * find instances that predate label updates.
70 */
71 description?: string;
72 /**
73 * User labels. Alchemy ownership labels are merged in automatically.
74 */
75 labels?: Record<string, string>;
76 /**
77 * Provisioning config. `cmekKeyName` and `encryptionType` are immutable.
78 * Search, Vertex location, and Agent Registry sync update in place.
79 */
80 config?: ApiHubInstanceConfig;
81 };
82
83 export type ApiHubInstance = Resource<
84 "GCP.ApiHub.ApiHubInstance",
85 ApiHubInstanceProps,
86 {
87 /** Full resource name. */
88 name: string;
89 /** Instance id (last path segment). */
90 apiHubInstanceId: string;
91 /** Project id. */
92 project: string;
93 /** Location id. */
94 location: string;
95 /** User description with the Alchemy ownership prefix stripped. */
96 description: string | undefined;
97 /** User labels (Alchemy ownership labels stripped). */
98 labels: Record<string, string>;
99 /** Server-reported instance state. */
100 state: string | undefined;
101 /** Extra information when `state` is `FAILED`. */
102 stateMessage: string | undefined;
103 /** Whether search is disabled. */
104 disableSearch: boolean;
105 /** Customer-managed encryption key, if any. */
106 cmekKeyName: string | undefined;
107 /** Encryption type. */
108 encryptionType: string | undefined;
109 /** Vertex AI location. */
110 vertexLocation: string | undefined;
111 /** Whether Agent Registry sync is disabled. */
112 agentRegistrySyncDisabled: boolean;
113 /** RFC3339 creation timestamp. */
114 createTime: string | undefined;
115 /** RFC3339 last-update timestamp. */
116 updateTime: string | undefined;
117 },
118 never,
119 Providers
120 >;
121
122 /**
123 * A Google Cloud API Hub instance. One instance is allowed per project.
124 *
125 * Location, instance id, CMEK, and encryption type are immutable. Search,
126 * Vertex location, and Agent Registry sync update in place.
127 *
128 * ### Creating an ApiHub Instance
129 * **Example:** Generated id in us-central1
130 * ```typescript
131 * const hub = yield* GCP.ApiHub.ApiHubInstance("Hub", {
132 * labels: { env: "test" },
133 * config: { disableSearch: false },
134 * });
135 * ```
136 *
137 * **Example:** Named instance with Vertex location
138 * ```typescript
139 * const hub = yield* GCP.ApiHub.ApiHubInstance("Hub", {
140 * apiHubInstanceId: "alchemy-hub",
141 * location: "us-central1",
142 * config: { vertexLocation: "us-central1" },
143 * });
144 * ```
145 *
146 * @resource
147 * @category ApiHub
148 */
149 export const ApiHubInstance = Resource<ApiHubInstance>("GCP.ApiHub.ApiHubInstance");
150
151 const resourceName = (project: string, location: string, apiHubInstanceId: string) =>
152 `${locationParent(project, location)}/apiHubInstances/${apiHubInstanceId}`;
153
154 const toAttrs = (
155 instance: apihub.GoogleCloudApihubV1ApiHubInstance,
156 project: string,
157 region: string,
158 ) => {
159 const name = instance.name ?? "";
160 const parsed = parseResourceName(name, "apiHubInstances", region);
161 const description = parseOwnership(instance.description).text;
162 return {
163 name,
164 apiHubInstanceId: parsed.id,
165 project: parsed.project || project,
166 location: parsed.location,
167 description,
168 labels: userLabels(instance.labels),
169 state: instance.state,
170 stateMessage: instance.stateMessage,
171 disableSearch: instance.config?.disableSearch === true,
172 cmekKeyName: instance.config?.cmekKeyName,
173 encryptionType: instance.config?.encryptionType,
174 vertexLocation: instance.config?.vertexLocation,
175 agentRegistrySyncDisabled: instance.config?.agentRegistrySyncConfig?.disabled === true,
176 createTime: instance.createTime,
177 updateTime: instance.updateTime,
178 };
179 };
180
181 const getByName = (name: string) =>
182 name.length === 0
183 ? Effect.undefined
184 : apihub
185 .getProjectsLocationsApiHubInstances({ name })
186 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
187
188 const lookupAt = (parent: string) =>
189 apihub.lookupProjectsLocationsApiHubInstances({ parent }).pipe(
190 Effect.map((response) => response.apiHubInstance),
191 Effect.catchTag("NotFound", () => Effect.undefined),
192 );
193
194 const configOf = (news: ApiHubInstanceProps): apihub.GoogleCloudApihubV1Config => ({
195 disableSearch: news.config?.disableSearch,
196 cmekKeyName: news.config?.cmekKeyName,
197 encryptionType: news.config?.encryptionType,
198 vertexLocation: news.config?.vertexLocation,
199 agentRegistrySyncConfig:
200 news.config?.agentRegistrySyncDisabled === undefined
201 ? undefined
202 : { disabled: news.config.agentRegistrySyncDisabled },
203 });
204
205 export const ApiHubInstanceProvider = () =>
206 Provider.succeed(ApiHubInstance, {
207 stables: ["name", "apiHubInstanceId", "project", "location", "createTime"],
208
209 diff: Effect.fn(function* ({ news, olds, output }) {
210 if (!isResolved(news)) return undefined;
211 const env = yield* GcpEnvironment.current;
212 return replaceOnIdentity({
213 previousId: olds?.apiHubInstanceId ?? output?.apiHubInstanceId,
214 nextId: news.apiHubInstanceId ?? olds?.apiHubInstanceId ?? output?.apiHubInstanceId,
215 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
216 nextLocation: normalizeLocation(
217 news.location ?? olds?.location ?? output?.location,
218 env.region,
219 ),
220 extra:
221 (news.config?.cmekKeyName ?? olds?.config?.cmekKeyName) !==
222 (olds?.config?.cmekKeyName ?? output?.cmekKeyName) ||
223 (news.config?.encryptionType ?? olds?.config?.encryptionType) !==
224 (olds?.config?.encryptionType ?? output?.encryptionType),
225 });
226 }),
227
228 read: Effect.fn(function* ({ id, olds, output }) {
229 const env = yield* GcpEnvironment.current;
230 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
231 const apiHubInstanceId = yield* toPhysicalId(
232 id,
233 olds?.apiHubInstanceId,
234 output?.apiHubInstanceId,
235 MAX_INSTANCE_ID_LENGTH,
236 );
237 const name = output?.name ?? resourceName(env.project, location, apiHubInstanceId);
238 let existing = yield* getByName(name);
239 if (existing === undefined) {
240 existing = yield* lookupAt(locationParent(env.project, location));
241 }
242 if (existing === undefined) return undefined;
243 const attrs = toAttrs(existing, env.project, env.region);
244 const labeled = yield* hasAlchemyLabels(id, tagRecord(existing.labels));
245 const described = yield* ownedByLabelsOrDescription(
246 id,
247 existing.labels,
248 existing.description,
249 );
250 return labeled || described ? attrs : Unowned(attrs);
251 }),
252
253 list: () =>
254 Effect.gen(function* () {
255 const env = yield* GcpEnvironment.current;
256 const existing = yield* lookupAt(locationParent(env.project, env.region));
257 if (existing === undefined) return [];
258 if (!hasAlchemyLabelMap(existing.labels) && !hasOwnershipMarker(existing.description)) {
259 return [];
260 }
261 return [toAttrs(existing, env.project, env.region)];
262 }),
263
264 reconcile: Effect.fn(function* ({ id, news, output }) {
265 const env = yield* GcpEnvironment.current;
266 const location = normalizeLocation(news.location ?? output?.location, env.region);
267 const parent = locationParent(env.project, location);
268 const apiHubInstanceId = yield* toPhysicalId(
269 id,
270 news.apiHubInstanceId,
271 output?.apiHubInstanceId,
272 MAX_INSTANCE_ID_LENGTH,
273 );
274 const name = resourceName(env.project, location, apiHubInstanceId);
275 const ownership = yield* createInternalLabels(id);
276 const desiredLabels = {
277 ...toLabels(news.labels),
278 ...ownership,
279 };
280 const description = encodeOwnership(ownership, news.description);
281 const config = configOf(news);
282
283 let current = yield* getByName(output?.name ?? name);
284 if (current === undefined) {
285 current = yield* lookupAt(parent);
286 }
287
288 if (current === undefined) {
289 const created = yield* apihub
290 .createProjectsLocationsApiHubInstances({
291 parent,
292 apiHubInstanceId,
293 body: {
294 description,
295 labels: desiredLabels,
296 config,
297 },
298 })
299 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
300 if (created !== undefined) {
301 yield* waitForOperation(created);
302 }
303 current = (yield* lookupAt(parent)) ?? (yield* waitUntilExists(getByName(name), name));
304 }
305
306 if (current === undefined) {
307 return yield* new ApihubNotResolved({ resourceName: name });
308 }
309
310 const currentName = current.name ?? name;
311 const disableChanged =
312 (current.config?.disableSearch === true) !== (news.config?.disableSearch === true);
313 const vertexChanged = !sameText(current.config?.vertexLocation, news.config?.vertexLocation);
314 const syncChanged =
315 (current.config?.agentRegistrySyncConfig?.disabled === true) !==
316 (news.config?.agentRegistrySyncDisabled === true);
317
318 if (disableChanged || vertexChanged || syncChanged) {
319 const operation = yield* apihub.patchProjectsLocationsApiHubInstances({
320 name: currentName,
321 updateMask: updateMaskOf(
322 disableChanged ? "config.disable_search" : undefined,
323 vertexChanged ? "config.vertex_location" : undefined,
324 syncChanged ? "config.agent_registry_sync_config" : undefined,
325 ),
326 body: {
327 name: currentName,
328 config,
329 },
330 });
331 yield* waitForOperation(operation);
332 current = yield* waitUntilExists(getByName(currentName), currentName);
333 }
334
335 if (current === undefined) {
336 return yield* new ApihubNotResolved({ resourceName: currentName });
337 }
338
339 return toAttrs(current, env.project, env.region);
340 }),
341
342 delete: Effect.fn(function* ({ output }) {
343 const operation = yield* apihub
344 .deleteProjectsLocationsApiHubInstances({ name: output.name })
345 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
346 if (operation !== undefined) {
347 yield* waitForDeleteOperation(operation);
348 }
349 yield* waitUntilGone(getByName(output.name), output.name);
350 }),
351 });
352
353 const ownedByLabelsOrDescription = (
354 id: string,
355 labels: Record<string, string | undefined> | null | undefined,
356 description: string | undefined,
357 ) =>
358 Effect.gen(function* () {
359 if (yield* hasAlchemyLabels(id, tagRecord(labels))) return true;
360 const parsed = parseOwnership(description);
361 return yield* hasAlchemyLabels(id, parsed.labels);
362 });