@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 514 lines 16.8 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, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 DEFAULT_GLOBAL,
14 changedFields,
15 collectPages,
16 hasAlchemyLabelKeys,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 resourceName,
21 rfc1035,
22 sameJson,
23 toPhysicalId,
24 userLabels,
25 waitForOperation,
26 waitUntilGone,
27 waitUntilPresent,
28 } from "./internal.ts";
29
30 const COLLECTION = "wasmPlugins";
31
32 export type WasmPluginLogLevel = networkservices.WasmPluginLogConfigMinLogLevelEnum | (string & {});
33
34 export type WasmPluginLogConfig = {
35 /**
36 * Whether plugin activity logs are exported to Cloud Logging.
37 * @default false
38 */
39 enable?: boolean;
40 /**
41 * Sampling rate in `[0.0, 1.0]` when logging is enabled. `1.0` reports
42 * every log statement.
43 * @default 1
44 */
45 sampleRate?: number;
46 /**
47 * Lowest plugin log level exported to Cloud Logging. Only set when
48 * logging is enabled.
49 * @default "INFO"
50 */
51 minLogLevel?: WasmPluginLogLevel;
52 };
53
54 export type WasmPluginVersionInput = {
55 /** Human-readable description of this version. */
56 description?: string;
57 /** User labels on this version. Alchemy ownership labels are merged in. */
58 labels?: Record<string, string>;
59 /**
60 * Artifact Registry URI of the image that contains `plugin.wasm`.
61 * Docker (`LOCATION-docker.pkg.dev/...`) or generic artifact
62 * (`projects/{project}/locations/{location}/repositories/{repository}/genericArtifacts/{package}:{version}`)
63 * forms are accepted. Immutable on the child version resource.
64 */
65 imageUri?: string;
66 /**
67 * Base64-encoded plugin configuration delivered through `ON_CONFIGURE`.
68 * Mutually exclusive with `pluginConfigUri`.
69 */
70 pluginConfigData?: string;
71 /**
72 * Artifact Registry URI of an image that contains `plugin.config`.
73 * Mutually exclusive with `pluginConfigData`.
74 */
75 pluginConfigUri?: string;
76 };
77
78 export type WasmPluginVersionDetails = {
79 /** User-provided description. */
80 description: string | undefined;
81 /** User labels (Alchemy ownership labels stripped). */
82 labels: Record<string, string>;
83 /** Image URI that supplied the Wasm module. */
84 imageUri: string | undefined;
85 /** Resolved image digest. */
86 imageDigest: string | undefined;
87 /** Plugin-config Artifact Registry URI, if set. */
88 pluginConfigUri: string | undefined;
89 /** Digest of plugin configuration. */
90 pluginConfigDigest: string | undefined;
91 /** RFC3339 creation timestamp. */
92 createTime: string | undefined;
93 /** RFC3339 last-update timestamp. */
94 updateTime: string | undefined;
95 };
96
97 export type WasmPluginProps = {
98 /**
99 * WasmPlugin id (the `{wasmPlugin}` segment of
100 * `projects/{project}/locations/{location}/wasmPlugins/{wasmPlugin}`).
101 * If omitted, a unique name is generated from the stack, stage, and
102 * logical id. Must be 1-63 characters and not start with a number.
103 * Immutable — changing it replaces the plugin.
104 */
105 wasmPluginId?: string;
106 /**
107 * Location. Wasm plugins live in `global`. Immutable — changing it
108 * replaces the plugin. `GLOBAL` is accepted and normalized to `global`.
109 * @default "global"
110 */
111 location?: string;
112 /**
113 * Human-readable description.
114 */
115 description?: string;
116 /**
117 * User labels. Alchemy ownership labels are merged in automatically.
118 */
119 labels?: Record<string, string>;
120 /**
121 * Id of the currently serving `WasmPluginVersion`. Must name a child
122 * version of this plugin. Omit until a version exists; updating this
123 * field does not replace the plugin.
124 */
125 mainVersionId?: string;
126 /**
127 * Logging options for statements emitted by the Wasm module.
128 */
129 logConfig?: WasmPluginLogConfig;
130 /**
131 * Inline versions keyed by version id. When set, this map is
132 * authoritative on create and update — omitted keys are deleted.
133 * Leave unset to manage versions through `WasmPluginsVersion` without
134 * the plugin wiping them on reconcile.
135 */
136 versions?: Record<string, WasmPluginVersionInput>;
137 };
138
139 export type WasmPlugin = Resource<
140 "GCP.NetworkServices.WasmPlugin",
141 WasmPluginProps,
142 {
143 /** Full resource name `projects/{project}/locations/{location}/wasmPlugins/{wasmPlugin}`. */
144 name: string;
145 /** WasmPlugin id (last path segment). */
146 wasmPluginId: string;
147 /** Project id. */
148 project: string;
149 /** Location id (`global`). */
150 location: string;
151 /** User-provided description. */
152 description: string | undefined;
153 /** User labels (Alchemy ownership labels stripped). */
154 labels: Record<string, string>;
155 /** Currently serving version id, if set. */
156 mainVersionId: string | undefined;
157 /** Logging configuration, if set. */
158 logConfig: WasmPluginLogConfig | undefined;
159 /** Inline versions from a full-view get. */
160 versions: Record<string, WasmPluginVersionDetails>;
161 /** Extension resource names that reference this plugin. */
162 usedBy: string[];
163 /** RFC3339 creation timestamp. */
164 createTime: string | undefined;
165 /** RFC3339 last-update timestamp. */
166 updateTime: string | undefined;
167 },
168 never,
169 Providers
170 >;
171
172 /**
173 * A Network Services WasmPlugin — a Service Extensions plugin that
174 * runs a customer-provided Wasm module.
175 *
176 * Changing `wasmPluginId` or `location` replaces the plugin.
177 * Description, labels, `mainVersionId`, `logConfig`, and an explicit
178 * `versions` map update in place. Child `WasmPluginsVersion` resources
179 * are preserved unless `versions` is set on this plugin.
180 *
181 * ### Creating a WasmPlugin
182 * **Example:** Generated name
183 * ```typescript
184 * const plugin = yield* GCP.NetworkServices.WasmPlugin("Edge", {
185 * description: "edge plugin",
186 * });
187 * ```
188 *
189 * **Example:** Named plugin with logging
190 * ```typescript
191 * const plugin = yield* GCP.NetworkServices.WasmPlugin("Edge", {
192 * wasmPluginId: "app-edge",
193 * description: "prod edge",
194 * labels: { env: "prod" },
195 * logConfig: { enable: true, sampleRate: 1, minLogLevel: "WARN" },
196 * });
197 * ```
198 *
199 * ### Inline versions
200 * **Example:** Plugin plus a serving version
201 * ```typescript
202 * const plugin = yield* GCP.NetworkServices.WasmPlugin("Edge", {
203 * mainVersionId: "v1",
204 * versions: {
205 * v1: {
206 * imageUri: "us-central1-docker.pkg.dev/my-project/plugins/edge:v1",
207 * },
208 * },
209 * });
210 * ```
211 *
212 * @resource
213 * @category NetworkServices
214 */
215 export const WasmPlugin = Resource<WasmPlugin>("GCP.NetworkServices.WasmPlugin");
216
217 const toLogConfig = (
218 value: WasmPluginLogConfig | networkservices.WasmPluginLogConfig | undefined,
219 ): WasmPluginLogConfig | undefined => {
220 if (value === undefined) return undefined;
221 if (
222 value.enable === undefined &&
223 value.sampleRate === undefined &&
224 value.minLogLevel === undefined
225 ) {
226 return undefined;
227 }
228 return {
229 enable: value.enable,
230 sampleRate: value.sampleRate,
231 minLogLevel: value.minLogLevel,
232 };
233 };
234
235 const toVersionDetails = (
236 details: networkservices.WasmPluginVersionDetails | undefined,
237 ): WasmPluginVersionDetails => ({
238 description: details?.description,
239 labels: userLabels(details?.labels),
240 imageUri: details?.imageUri,
241 imageDigest: details?.imageDigest,
242 pluginConfigUri: details?.pluginConfigUri,
243 pluginConfigDigest: details?.pluginConfigDigest,
244 createTime: details?.createTime,
245 updateTime: details?.updateTime,
246 });
247
248 const toVersionMap = (
249 versions: networkservices.WasmPluginVersionDetailsMap | undefined,
250 ): Record<string, WasmPluginVersionDetails> =>
251 Object.fromEntries(
252 Object.entries(versions ?? {}).map(([id, details]) => [id, toVersionDetails(details)]),
253 );
254
255 const versionFingerprint = (
256 versions: Record<string, WasmPluginVersionInput> | undefined,
257 ownership: Record<string, string>,
258 ) => {
259 if (versions === undefined) return undefined;
260 return Object.fromEntries(
261 Object.keys(versions)
262 .sort()
263 .map((id) => {
264 const version = versions[id] ?? {};
265 return [
266 id,
267 {
268 description: version.description ?? "",
269 imageUri: version.imageUri ?? "",
270 pluginConfigUri: version.pluginConfigUri ?? "",
271 labels: {
272 ...toLabels(version.labels),
273 ...ownership,
274 },
275 },
276 ];
277 }),
278 );
279 };
280
281 const observedVersionFingerprint = (
282 versions: networkservices.WasmPluginVersionDetailsMap | undefined,
283 ) =>
284 Object.fromEntries(
285 Object.keys(versions ?? {})
286 .sort()
287 .map((id) => {
288 const version = versions?.[id] ?? {};
289 return [
290 id,
291 {
292 description: version.description ?? "",
293 imageUri: version.imageUri ?? "",
294 pluginConfigUri: version.pluginConfigUri ?? "",
295 labels: tagRecord(version.labels),
296 },
297 ];
298 }),
299 );
300
301 const toVersionBodies = (
302 versions: Record<string, WasmPluginVersionInput> | undefined,
303 ownership: Record<string, string>,
304 ): networkservices.WasmPluginVersionDetailsMap | undefined => {
305 if (versions === undefined) return undefined;
306 return Object.fromEntries(
307 Object.entries(versions).map(([id, version]) => [
308 id,
309 {
310 description: version.description,
311 labels: { ...toLabels(version.labels), ...ownership },
312 imageUri: version.imageUri,
313 pluginConfigData: version.pluginConfigData,
314 pluginConfigUri: version.pluginConfigUri,
315 } satisfies networkservices.WasmPluginVersionDetails,
316 ]),
317 );
318 };
319
320 const toAttrs = (plugin: networkservices.WasmPlugin, project: string) => {
321 const name = plugin.name ?? "";
322 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
323 return {
324 name,
325 wasmPluginId: parsed.id,
326 project: parsed.project || project,
327 location: parsed.location || DEFAULT_GLOBAL,
328 description: plugin.description,
329 labels: userLabels(plugin.labels),
330 mainVersionId: plugin.mainVersionId,
331 logConfig: toLogConfig(plugin.logConfig),
332 versions: toVersionMap(plugin.versions),
333 usedBy: (plugin.usedBy ?? [])
334 .map((entry) => entry.name)
335 .filter((value): value is string => typeof value === "string"),
336 createTime: plugin.createTime,
337 updateTime: plugin.updateTime,
338 };
339 };
340
341 const getByName = (name: string) =>
342 networkservices
343 .getProjectsLocationsWasmPlugins({
344 name,
345 view: "WASM_PLUGIN_VIEW_FULL",
346 })
347 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
348
349 export const WasmPluginProvider = () =>
350 Provider.succeed(WasmPlugin, {
351 stables: ["name", "wasmPluginId", "project", "location", "createTime"],
352
353 diff: Effect.fn(function* ({ news, olds, output }) {
354 if (!isResolved(news)) return undefined;
355 const previousId = olds?.wasmPluginId ?? output?.wasmPluginId;
356 const nextId = news.wasmPluginId ? rfc1035(news.wasmPluginId, "wasm-plugin") : previousId;
357 const previousLocation = normalizeLocation(
358 olds?.location ?? output?.location,
359 DEFAULT_GLOBAL,
360 );
361 const nextLocation = normalizeLocation(
362 news.location ?? olds?.location ?? output?.location,
363 DEFAULT_GLOBAL,
364 );
365 if (
366 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
367 previousLocation !== nextLocation
368 ) {
369 return { action: "replace" as const };
370 }
371 return undefined;
372 }),
373
374 read: Effect.fn(function* ({ id, olds, output }) {
375 const env = yield* GcpEnvironment.current;
376 const wasmPluginId = yield* toPhysicalId(
377 id,
378 olds?.wasmPluginId,
379 output?.wasmPluginId,
380 "wasm-plugin",
381 );
382 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
383 const name = output?.name ?? resourceName(env.project, location, COLLECTION, wasmPluginId);
384 const existing = yield* getByName(name);
385 if (existing === undefined) return undefined;
386 const attrs = toAttrs(existing, env.project);
387 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
388 }),
389
390 list: () =>
391 Effect.gen(function* () {
392 const env = yield* GcpEnvironment.current;
393 const items = yield* collectPages(
394 networkservices.listProjectsLocationsWasmPlugins.pages({
395 parent: parentOf(env.project, DEFAULT_GLOBAL),
396 pageSize: 1000,
397 }),
398 (page) => page.wasmPlugins,
399 );
400 return items
401 .filter((item) => hasAlchemyLabelKeys(item.labels))
402 .map((item) => toAttrs(item, env.project));
403 }),
404
405 reconcile: Effect.fn(function* ({ id, news, output }) {
406 const env = yield* GcpEnvironment.current;
407 const wasmPluginId = yield* toPhysicalId(
408 id,
409 news.wasmPluginId,
410 output?.wasmPluginId,
411 "wasm-plugin",
412 );
413 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
414 const name = resourceName(env.project, location, COLLECTION, wasmPluginId);
415 const desiredLabels = {
416 ...toLabels(news.labels),
417 ...(yield* createInternalLabels(id)),
418 };
419 const desiredLogConfig = toLogConfig(news.logConfig);
420 const desiredVersions = toVersionBodies(news.versions, desiredLabels);
421
422 let current = yield* getByName(name);
423
424 if (current === undefined) {
425 const created = yield* networkservices
426 .createProjectsLocationsWasmPlugins({
427 parent: parentOf(env.project, location),
428 wasmPluginId,
429 body: {
430 labels: desiredLabels,
431 description: news.description,
432 mainVersionId: news.mainVersionId,
433 logConfig: desiredLogConfig,
434 versions: desiredVersions,
435 },
436 })
437 .pipe(
438 Effect.retry({
439 while: (error) => error._tag === "Conflict",
440 times: 5,
441 schedule: Schedule.spaced("2 seconds"),
442 }),
443 Effect.catchTag("Conflict", () => Effect.undefined),
444 );
445 if (created !== undefined) {
446 yield* waitForOperation(created);
447 }
448 current = yield* waitUntilPresent(getByName(name), name);
449 }
450
451 const observedLabels = tagRecord(current.labels);
452 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
453 const labelsChanged = upsert.length > 0 || removed.length > 0;
454 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
455 const mainVersionChanged =
456 news.mainVersionId !== undefined && (current.mainVersionId ?? "") !== news.mainVersionId;
457 const logConfigChanged =
458 news.logConfig !== undefined && !sameJson(toLogConfig(current.logConfig), desiredLogConfig);
459 const versionsChanged =
460 news.versions !== undefined &&
461 !sameJson(
462 observedVersionFingerprint(current.versions),
463 versionFingerprint(news.versions, desiredLabels),
464 );
465
466 const updateMask = changedFields([
467 ["labels", labelsChanged],
468 ["description", descriptionChanged],
469 ["mainVersionId", mainVersionChanged],
470 ["logConfig", logConfigChanged],
471 ["versions", versionsChanged],
472 ]);
473
474 if (updateMask.length > 0) {
475 const operation = yield* networkservices.patchProjectsLocationsWasmPlugins({
476 name: current.name ?? name,
477 updateMask: updateMask.join(","),
478 body: {
479 name: current.name ?? name,
480 labels: desiredLabels,
481 description: news.description,
482 mainVersionId: news.mainVersionId,
483 logConfig: desiredLogConfig,
484 versions: versionsChanged ? desiredVersions : undefined,
485 },
486 });
487 yield* waitForOperation(operation);
488 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
489 }
490
491 return toAttrs(current, env.project);
492 }),
493
494 delete: Effect.fn(function* ({ output }) {
495 yield* Effect.gen(function* () {
496 const operation = yield* networkservices
497 .deleteProjectsLocationsWasmPlugins({ name: output.name })
498 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
499 if (operation !== undefined) {
500 yield* waitForOperation(operation, { notFoundOk: true });
501 }
502 }).pipe(
503 Effect.retry({
504 while: (error) =>
505 error._tag === "Conflict" ||
506 // FAILED_PRECONDITION: still referenced by a route/extension.
507 (error._tag === "GCP.OperationFailed" && error.code === 9),
508 times: 8,
509 schedule: Schedule.spaced("2 seconds"),
510 }),
511 );
512 yield* waitUntilGone(getByName(output.name), output.name);
513 }),
514 });