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

main
ts 421 lines 14.6 KB
Raw
1 import * as networkservices from "@distilled.cloud/gcp/networkservices_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 * as Schedule from "effect/Schedule";
9 import { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 DEFAULT_GLOBAL,
14 canonicalizeLink,
15 collectPages,
16 hasAlchemyLabelKeys,
17 lastSegment,
18 normalizeLocation,
19 parentOf,
20 parseName,
21 rfc1035,
22 toPhysicalId,
23 userLabels,
24 waitForOperation,
25 waitUntilGone,
26 waitUntilPresent,
27 } from "./internal.ts";
28
29 const COLLECTION = "versions";
30
31 export type WasmPluginsVersionProps = {
32 /**
33 * Parent WasmPlugin. Full name
34 * `projects/{project}/locations/{location}/wasmPlugins/{wasmPlugin}`
35 * or the plugin id (combined with `location`). Immutable — changing
36 * it replaces the version.
37 */
38 wasmPlugin: string;
39 /**
40 * Version id (the `{wasmPluginVersion}` segment of
41 * `.../wasmPlugins/{wasmPlugin}/versions/{wasmPluginVersion}`). If
42 * omitted, a unique name is generated from the stack, stage, and
43 * logical id. Must be 1-63 characters and not start with a number.
44 * Immutable — changing it replaces the version.
45 */
46 wasmPluginVersionId?: string;
47 /**
48 * Location of the parent plugin. Used when `wasmPlugin` is a bare
49 * id. Wasm plugins live in `global`. Immutable — changing it
50 * replaces the version. `GLOBAL` is accepted and normalized to
51 * `global`.
52 * @default "global"
53 */
54 location?: string;
55 /**
56 * Human-readable description. Versions have no update API, so
57 * changing this field replaces the version.
58 */
59 description?: string;
60 /**
61 * User labels. Alchemy ownership labels are merged in automatically.
62 * Versions have no update API, so changing labels replaces the version.
63 */
64 labels?: Record<string, string>;
65 /**
66 * Artifact Registry URI of the image that contains `plugin.wasm`.
67 * Docker (`LOCATION-docker.pkg.dev/...`) or generic artifact
68 * (`projects/{project}/locations/{location}/repositories/{repository}/genericArtifacts/{package}:{version}`)
69 * forms are accepted. Immutable — changing it replaces the version.
70 */
71 imageUri?: string;
72 /**
73 * Base64-encoded plugin configuration delivered through `ON_CONFIGURE`.
74 * Mutually exclusive with `pluginConfigUri`. Immutable — changing it
75 * replaces the version.
76 */
77 pluginConfigData?: string;
78 /**
79 * Artifact Registry URI of an image that contains `plugin.config`.
80 * Mutually exclusive with `pluginConfigData`. Immutable — changing it
81 * replaces the version.
82 */
83 pluginConfigUri?: string;
84 };
85
86 export type WasmPluginsVersion = Resource<
87 "GCP.NetworkServices.WasmPluginsVersion",
88 WasmPluginsVersionProps,
89 {
90 /** Full resource name `projects/{project}/locations/{location}/wasmPlugins/{wasmPlugin}/versions/{wasmPluginVersion}`. */
91 name: string;
92 /** Version id (last path segment). */
93 wasmPluginVersionId: string;
94 /** Parent WasmPlugin resource name. */
95 wasmPlugin: string;
96 /** Parent WasmPlugin id. */
97 wasmPluginId: string;
98 /** Project id. */
99 project: string;
100 /** Location id (`global`). */
101 location: string;
102 /** User-provided description. */
103 description: string | undefined;
104 /** User labels (Alchemy ownership labels stripped). */
105 labels: Record<string, string>;
106 /** Image URI that supplied the Wasm module. */
107 imageUri: string | undefined;
108 /** Resolved image digest. */
109 imageDigest: string | undefined;
110 /** Plugin-config Artifact Registry URI, if set. */
111 pluginConfigUri: string | undefined;
112 /** Digest of plugin configuration. */
113 pluginConfigDigest: string | undefined;
114 /** RFC3339 creation timestamp. */
115 createTime: string | undefined;
116 /** RFC3339 last-update timestamp. */
117 updateTime: string | undefined;
118 },
119 never,
120 Providers
121 >;
122
123 /**
124 * An immutable WasmPluginVersion nested under a WasmPlugin. Each
125 * version points at a Wasm module in Artifact Registry and optionally
126 * a runtime config.
127 *
128 * There is no patch API. Changing the parent plugin, version id,
129 * location, image URI, or plugin config replaces the version.
130 * Description and labels are applied at create time.
131 *
132 * ### Creating a WasmPluginsVersion
133 * **Example:** Version from a Docker image
134 * ```typescript
135 * const version = yield* GCP.NetworkServices.WasmPluginsVersion("V1", {
136 * wasmPlugin: plugin.name,
137 * imageUri: "us-central1-docker.pkg.dev/my-project/plugins/edge:v1",
138 * });
139 * ```
140 *
141 * **Example:** Named version with config
142 * ```typescript
143 * const version = yield* GCP.NetworkServices.WasmPluginsVersion("V1", {
144 * wasmPlugin: plugin.name,
145 * wasmPluginVersionId: "v1",
146 * description: "prod edge v1",
147 * labels: { env: "prod" },
148 * imageUri:
149 * "projects/my-project/locations/us-central1/repositories/plugins/genericArtifacts/edge:v1",
150 * pluginConfigData: "e30=",
151 * });
152 * ```
153 *
154 * @resource
155 * @category NetworkServices
156 */
157 export const WasmPluginsVersion = Resource<WasmPluginsVersion>(
158 "GCP.NetworkServices.WasmPluginsVersion",
159 );
160
161 const parentFromVersionName = (name: string) => {
162 const index = name.lastIndexOf("/versions/");
163 return index >= 0 ? name.slice(0, index) : name;
164 };
165
166 const locationFromParent = (wasmPlugin: string, fallback: string) => {
167 const canonical = canonicalizeLink(wasmPlugin);
168 if (!canonical.includes("/locations/")) return fallback;
169 return parseName(canonical, "wasmPlugins", fallback).location;
170 };
171
172 const parentPluginName = (project: string, location: string, wasmPlugin: string) => {
173 const canonical = canonicalizeLink(wasmPlugin);
174 if (canonical.includes("/wasmPlugins/")) return canonical;
175 const id = lastSegment(canonical);
176 return `projects/${project}/locations/${location}/wasmPlugins/${id}`;
177 };
178
179 const resourceNameOf = (parent: string, versionId: string) => `${parent}/versions/${versionId}`;
180
181 const linkKey = (value: string | undefined) => lastSegment(canonicalizeLink(value)).toLowerCase();
182
183 const toAttrs = (version: networkservices.WasmPluginVersion, project: string) => {
184 const name = version.name ?? "";
185 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
186 const parent = parentFromVersionName(name);
187 const pluginParsed = parseName(parent, "wasmPlugins", DEFAULT_GLOBAL);
188 return {
189 name,
190 wasmPluginVersionId: parsed.id,
191 wasmPlugin: parent,
192 wasmPluginId: pluginParsed.id,
193 project: parsed.project || project,
194 location: parsed.location || DEFAULT_GLOBAL,
195 description: version.description,
196 labels: userLabels(version.labels),
197 imageUri: version.imageUri,
198 imageDigest: version.imageDigest,
199 pluginConfigUri: version.pluginConfigUri,
200 pluginConfigDigest: version.pluginConfigDigest,
201 createTime: version.createTime,
202 updateTime: version.updateTime,
203 };
204 };
205
206 const getByName = (name: string) =>
207 name.length === 0 || !name.includes("/wasmPlugins/") || name.includes("/wasmPlugins//")
208 ? Effect.undefined
209 : networkservices
210 .getProjectsLocationsWasmPluginsVersions({ name })
211 .pipe(Effect.catchTag(["NotFound"], () => Effect.undefined));
212
213 const getPlugin = (name: string) =>
214 networkservices
215 .getProjectsLocationsWasmPlugins({ name })
216 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
217
218 const replaceIfChanged = (previous: string | undefined, next: string | undefined) =>
219 previous !== undefined &&
220 next !== undefined &&
221 previous.length > 0 &&
222 next.length > 0 &&
223 previous !== next;
224
225 export const WasmPluginsVersionProvider = () =>
226 Provider.succeed(WasmPluginsVersion, {
227 stables: [
228 "name",
229 "wasmPluginVersionId",
230 "wasmPlugin",
231 "wasmPluginId",
232 "project",
233 "location",
234 "createTime",
235 ],
236
237 diff: Effect.fn(function* ({ news, olds, output }) {
238 if (!isResolved(news)) return undefined;
239 const previousId = olds?.wasmPluginVersionId ?? output?.wasmPluginVersionId;
240 const nextId = news.wasmPluginVersionId
241 ? rfc1035(news.wasmPluginVersionId, "wasm-plugin-version")
242 : previousId;
243 const previousLocation = normalizeLocation(
244 olds?.location ?? output?.location,
245 DEFAULT_GLOBAL,
246 );
247 const nextLocation = normalizeLocation(
248 news.location ?? locationFromParent(news.wasmPlugin, previousLocation),
249 DEFAULT_GLOBAL,
250 );
251 const previousParent = linkKey(olds?.wasmPlugin ?? output?.wasmPlugin);
252 const nextParent = linkKey(news.wasmPlugin);
253 if (
254 replaceIfChanged(previousId, nextId) ||
255 previousLocation !== nextLocation ||
256 (previousParent.length > 0 && previousParent !== nextParent) ||
257 replaceIfChanged(olds?.imageUri ?? output?.imageUri, news.imageUri) ||
258 replaceIfChanged(olds?.pluginConfigUri ?? output?.pluginConfigUri, news.pluginConfigUri) ||
259 replaceIfChanged(olds?.pluginConfigData, news.pluginConfigData)
260 ) {
261 return { action: "replace" as const };
262 }
263 return undefined;
264 }),
265
266 read: Effect.fn(function* ({ id, olds, output }) {
267 const env = yield* GcpEnvironment.current;
268 const location = normalizeLocation(
269 olds?.location ??
270 output?.location ??
271 (olds?.wasmPlugin ? locationFromParent(olds.wasmPlugin, DEFAULT_GLOBAL) : undefined),
272 DEFAULT_GLOBAL,
273 );
274 const parent = parentPluginName(
275 env.project,
276 location,
277 olds?.wasmPlugin ?? output?.wasmPlugin ?? "",
278 );
279 const versionId = yield* toPhysicalId(
280 id,
281 olds?.wasmPluginVersionId,
282 output?.wasmPluginVersionId,
283 "wasm-plugin-version",
284 );
285 const name = output?.name ?? resourceNameOf(parent, versionId);
286 const existing = yield* getByName(name);
287 if (existing === undefined) return undefined;
288 const attrs = toAttrs(existing, env.project);
289 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
290 }),
291
292 list: () =>
293 Effect.gen(function* () {
294 const env = yield* GcpEnvironment.current;
295 const plugins = yield* collectPages(
296 networkservices.listProjectsLocationsWasmPlugins.pages({
297 parent: parentOf(env.project, DEFAULT_GLOBAL),
298 pageSize: 1000,
299 }),
300 (page) => page.wasmPlugins,
301 );
302 const nested = yield* Effect.forEach(
303 plugins.filter((plugin) => (plugin.name ?? "").length > 0),
304 (plugin) =>
305 collectPages(
306 networkservices.listProjectsLocationsWasmPluginsVersions.pages({
307 parent: plugin.name ?? "",
308 pageSize: 1000,
309 }),
310 (page) => page.wasmPluginVersions,
311 ),
312 { concurrency: 4 },
313 );
314 return nested
315 .flat()
316 .filter((item) => hasAlchemyLabelKeys(item.labels))
317 .map((item) => toAttrs(item, env.project));
318 }),
319
320 reconcile: Effect.fn(function* ({ id, news, output }) {
321 const env = yield* GcpEnvironment.current;
322 const location = normalizeLocation(
323 news.location ?? output?.location ?? locationFromParent(news.wasmPlugin, DEFAULT_GLOBAL),
324 DEFAULT_GLOBAL,
325 );
326 const parent = parentPluginName(env.project, location, news.wasmPlugin);
327 const versionId = yield* toPhysicalId(
328 id,
329 news.wasmPluginVersionId,
330 output?.wasmPluginVersionId,
331 "wasm-plugin-version",
332 );
333 const name = resourceNameOf(parent, versionId);
334 const desiredLabels = {
335 ...toLabels(news.labels),
336 ...(yield* createInternalLabels(id)),
337 };
338
339 let current = yield* getByName(name);
340
341 if (current === undefined) {
342 const created = yield* networkservices
343 .createProjectsLocationsWasmPluginsVersions({
344 parent,
345 wasmPluginVersionId: versionId,
346 body: {
347 labels: desiredLabels,
348 description: news.description,
349 imageUri: news.imageUri,
350 pluginConfigData: news.pluginConfigData,
351 pluginConfigUri: news.pluginConfigUri,
352 },
353 })
354 .pipe(
355 Effect.retry({
356 while: (error) => error._tag === "Conflict",
357 times: 5,
358 schedule: Schedule.spaced("2 seconds"),
359 }),
360 Effect.catchTag("Conflict", () => Effect.undefined),
361 );
362 if (created !== undefined) {
363 yield* waitForOperation(created);
364 }
365 current = yield* waitUntilPresent(getByName(name), name);
366 }
367
368 return toAttrs(current, env.project);
369 }),
370
371 delete: Effect.fn(function* ({ output }) {
372 const plugin = yield* getPlugin(output.wasmPlugin);
373 if (plugin !== undefined && (plugin.mainVersionId ?? "") === output.wasmPluginVersionId) {
374 const siblings = yield* collectPages(
375 networkservices.listProjectsLocationsWasmPluginsVersions.pages({
376 parent: output.wasmPlugin,
377 pageSize: 1000,
378 }),
379 (page) => page.wasmPluginVersions,
380 );
381 const other = siblings.find(
382 (version) => lastSegment(version.name ?? "") !== output.wasmPluginVersionId,
383 );
384 if (other !== undefined) {
385 const nextMain = lastSegment(other.name ?? "");
386 const switched = yield* networkservices
387 .patchProjectsLocationsWasmPlugins({
388 name: output.wasmPlugin,
389 updateMask: "mainVersionId",
390 body: {
391 name: output.wasmPlugin,
392 mainVersionId: nextMain,
393 },
394 })
395 .pipe(Effect.catchTag(["NotFound"], () => Effect.undefined));
396 if (switched !== undefined) {
397 yield* waitForOperation(switched, { notFoundOk: true });
398 }
399 }
400 }
401
402 yield* Effect.gen(function* () {
403 const operation = yield* networkservices
404 .deleteProjectsLocationsWasmPluginsVersions({ name: output.name })
405 .pipe(Effect.catchTag(["NotFound"], () => Effect.undefined));
406 if (operation !== undefined) {
407 yield* waitForOperation(operation, { notFoundOk: true });
408 }
409 }).pipe(
410 Effect.retry({
411 while: (error) =>
412 error._tag === "Conflict" ||
413 // FAILED_PRECONDITION: still referenced by a route/extension.
414 (error._tag === "GCP.OperationFailed" && error.code === 9),
415 times: 8,
416 schedule: Schedule.spaced("2 seconds"),
417 }),
418 );
419 yield* waitUntilGone(getByName(output.name), output.name);
420 }),
421 });