@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 352 lines 12.1 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 * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { GcpEnvironment } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 ApihubNotResolved,
13 DEFAULT_PLUGIN_ACTIONS,
14 encodeOwnership,
15 hasOwnershipMarker,
16 locationParent,
17 MAX_PLUGIN_DISPLAY_NAME_LENGTH,
18 normalizeLocation,
19 ownedByAlchemy,
20 ownershipLabels,
21 parseName,
22 parseOwnership,
23 replaceOnIdentity,
24 sameJson,
25 sameText,
26 toPhysicalId,
27 waitUntilGone,
28 } from "./internal.ts";
29 import { waitForDeleteOperation } from "./internal.ts";
30
31 type PluginActionConfig = apihub.GoogleCloudApihubV1PluginActionConfig;
32 type PluginCategory = apihub.GoogleCloudApihubV1PluginPluginCategoryEnum;
33 type PluginGatewayType = apihub.GoogleCloudApihubV1PluginGatewayTypeEnum;
34 type HostingService = apihub.GoogleCloudApihubV1HostingService;
35 type ConfigTemplate = apihub.GoogleCloudApihubV1ConfigTemplate;
36 type AttributeValues = apihub.GoogleCloudApihubV1AttributeValues;
37 type Documentation = apihub.GoogleCloudApihubV1Documentation;
38
39 export type PluginProps = {
40 /**
41 * Plugin id (the `{plugin}` segment of
42 * `projects/{project}/locations/{location}/plugins/{plugin}`). If
43 * omitted, a unique id is generated. Immutable — changing it replaces
44 * the plugin.
45 */
46 pluginId?: string;
47 /**
48 * Location of the API Hub instance (`us-central1`, …). Immutable —
49 * changing it replaces the plugin.
50 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
51 */
52 location?: string;
53 /**
54 * Display name. Max 50 characters.
55 */
56 displayName?: string;
57 /**
58 * Human-readable description. Plugins have no labels field, so Alchemy
59 * stamps ownership into a `[alchemy …]` prefix and strips it from
60 * attributes. The API has no patch for plugins, so changing description
61 * (or other body fields) replaces the plugin.
62 */
63 description?: string;
64 /**
65 * Documentation URI that explains how to set up the plugin.
66 */
67 documentation?: Documentation;
68 /**
69 * Category of the plugin.
70 * @default "API_PRODUCER"
71 */
72 pluginCategory?: PluginCategory | (string & {});
73 /**
74 * Gateway type for on-ramp plugins.
75 */
76 gatewayType?: PluginGatewayType | (string & {});
77 /**
78 * Actions supported by the plugin. Required by the API; a default
79 * on-demand `sync-metadata` action is used when omitted.
80 */
81 actionsConfig?: PluginActionConfig[];
82 /**
83 * Hosting service URI for user-defined plugins.
84 */
85 hostingService?: HostingService;
86 /**
87 * Configuration template (auth + additional variables).
88 */
89 configTemplate?: ConfigTemplate;
90 /**
91 * Plugin type (`system-plugin-type` attribute).
92 */
93 type?: AttributeValues;
94 /**
95 * When false, disable the plugin after it exists. User-owned plugins
96 * created via the plugin framework manage state at the instance level.
97 * @default true
98 */
99 enabled?: boolean;
100 };
101
102 export type Plugin = Resource<
103 "GCP.ApiHub.Plugin",
104 PluginProps,
105 {
106 /** Full resource name. */
107 name: string;
108 /** Plugin id (last path segment). */
109 pluginId: string;
110 /** Project id. */
111 project: string;
112 /** Location id. */
113 location: string;
114 /** Display name. */
115 displayName: string | undefined;
116 /** User description with the Alchemy ownership prefix stripped. */
117 description: string | undefined;
118 /** Documentation. */
119 documentation: Documentation | undefined;
120 /** Category. */
121 pluginCategory: string | undefined;
122 /** Gateway type. */
123 gatewayType: string | undefined;
124 /** Action configuration. */
125 actionsConfig: PluginActionConfig[] | undefined;
126 /** Hosting service. */
127 hostingService: HostingService | undefined;
128 /** Config template. */
129 configTemplate: ConfigTemplate | undefined;
130 /** Plugin type attribute. */
131 type: AttributeValues | undefined;
132 /** Ownership type (`SYSTEM_OWNED` or `USER_OWNED`). */
133 ownershipType: string | undefined;
134 /** Plugin state. */
135 state: string | undefined;
136 /** RFC3339 creation timestamp. */
137 createTime: string | undefined;
138 /** RFC3339 last-update timestamp. */
139 updateTime: string | undefined;
140 },
141 never,
142 Providers
143 >;
144
145 /**
146 * An API Hub plugin — a user-owned or system-owned connector that
147 * publishes API metadata into Hub.
148 *
149 * Plugins have no labels and no patch RPC, so Alchemy stamps ownership
150 * into the description and treats body-field changes as replacements.
151 * Enable/disable syncs in place. Location and plugin id are identity.
152 *
153 * ### Creating a Plugin
154 * **Example:** Generated id with the default action
155 * ```typescript
156 * const plugin = yield* GCP.ApiHub.Plugin("OnRamp", {
157 * displayName: "on-ramp",
158 * description: "custom collector",
159 * });
160 * ```
161 *
162 * **Example:** Named plugin with an explicit action
163 * ```typescript
164 * const plugin = yield* GCP.ApiHub.Plugin("OnRamp", {
165 * pluginId: "orders-onramp",
166 * displayName: "orders on-ramp",
167 * pluginCategory: "API_PRODUCER",
168 * actionsConfig: [
169 * {
170 * id: "sync-metadata",
171 * displayName: "Sync metadata",
172 * description: "pull specs",
173 * triggerMode: "API_HUB_ON_DEMAND_TRIGGER",
174 * },
175 * ],
176 * });
177 * ```
178 *
179 * @resource
180 * @category ApiHub
181 */
182 export const Plugin = Resource<Plugin>("GCP.ApiHub.Plugin");
183
184 const resourceName = (project: string, location: string, pluginId: string) =>
185 `${locationParent(project, location)}/plugins/${pluginId}`;
186
187 const toAttrs = (plugin: apihub.GoogleCloudApihubV1Plugin, project: string, region: string) => {
188 const name = plugin.name ?? "";
189 const parsed = parseName(name, "plugins", region);
190 const { text } = parseOwnership(plugin.description);
191 return {
192 name,
193 pluginId: parsed.id,
194 project: parsed.project || project,
195 location: parsed.location,
196 displayName: plugin.displayName,
197 description: text,
198 documentation: plugin.documentation,
199 pluginCategory: plugin.pluginCategory,
200 gatewayType: plugin.gatewayType,
201 actionsConfig: plugin.actionsConfig,
202 hostingService: plugin.hostingService,
203 configTemplate: plugin.configTemplate,
204 type: plugin.type,
205 ownershipType: plugin.ownershipType,
206 state: plugin.state,
207 createTime: plugin.createTime,
208 updateTime: plugin.updateTime,
209 };
210 };
211
212 const getByName = (name: string) =>
213 name.length === 0
214 ? Effect.undefined
215 : apihub
216 .getProjectsLocationsPlugins({ name })
217 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
218
219 const listAt = (parent: string, project: string, region: string) =>
220 apihub.listProjectsLocationsPlugins.pages({ parent, pageSize: 1000 }).pipe(
221 Stream.flatMap((page) => Stream.fromIterable(page.plugins ?? [])),
222 Stream.filter((item) => hasOwnershipMarker(item.description)),
223 Stream.map((item) => toAttrs(item, project, region)),
224 Stream.runCollect,
225 Effect.map((chunk) => Array.from(chunk)),
226 Effect.catchTag("NotFound", () => Effect.succeed([])),
227 );
228
229 const actionsOf = (news: PluginProps) => news.actionsConfig ?? DEFAULT_PLUGIN_ACTIONS;
230
231 const categoryOf = (news: PluginProps) => news.pluginCategory ?? "API_PRODUCER";
232
233 const displayNameOf = (news: PluginProps, pluginId: string) =>
234 (news.displayName ?? pluginId).slice(0, MAX_PLUGIN_DISPLAY_NAME_LENGTH);
235
236 export const PluginProvider = () =>
237 Provider.succeed(Plugin, {
238 stables: ["name", "pluginId", "project", "location", "createTime"],
239
240 diff: Effect.fn(function* ({ news, olds, output }) {
241 if (!isResolved(news)) return undefined;
242 const env = yield* GcpEnvironment.current;
243 const extra =
244 olds !== undefined &&
245 (!sameText(news.displayName, olds.displayName) ||
246 !sameText(news.description, olds.description) ||
247 !sameJson(news.documentation, olds.documentation) ||
248 !sameJson(news.actionsConfig, olds.actionsConfig) ||
249 !sameText(news.pluginCategory, olds.pluginCategory) ||
250 !sameText(news.gatewayType, olds.gatewayType) ||
251 !sameJson(news.hostingService, olds.hostingService) ||
252 !sameJson(news.configTemplate, olds.configTemplate) ||
253 !sameJson(news.type, olds.type));
254 return replaceOnIdentity({
255 previousId: olds?.pluginId ?? output?.pluginId,
256 nextId: news.pluginId ?? olds?.pluginId ?? output?.pluginId,
257 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
258 nextLocation: normalizeLocation(
259 news.location ?? olds?.location ?? output?.location,
260 env.region,
261 ),
262 extra,
263 });
264 }),
265
266 read: Effect.fn(function* ({ id, olds, output }) {
267 const env = yield* GcpEnvironment.current;
268 const pluginId = yield* toPhysicalId(id, olds?.pluginId, output?.pluginId);
269 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
270 const name = output?.name ?? resourceName(env.project, location, pluginId);
271 const existing = yield* getByName(name);
272 if (existing === undefined) return undefined;
273 const attrs = toAttrs(existing, env.project, env.region);
274 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
275 }),
276
277 list: () =>
278 Effect.gen(function* () {
279 const env = yield* GcpEnvironment.current;
280 return yield* listAt(locationParent(env.project, env.region), env.project, env.region);
281 }),
282
283 reconcile: Effect.fn(function* ({ id, news, output }) {
284 const env = yield* GcpEnvironment.current;
285 const location = normalizeLocation(news.location ?? output?.location, env.region);
286 const pluginId = yield* toPhysicalId(id, news.pluginId, output?.pluginId);
287 const name = resourceName(env.project, location, pluginId);
288 const ownership = yield* ownershipLabels(id);
289 const description = encodeOwnership(ownership, news.description);
290 const displayName = displayNameOf(news, pluginId);
291 const parent = locationParent(env.project, location);
292
293 let current = yield* getByName(output?.name ?? name);
294
295 if (current === undefined) {
296 const created = yield* apihub
297 .createProjectsLocationsPlugins({
298 parent,
299 pluginId,
300 body: {
301 displayName,
302 description,
303 documentation: news.documentation,
304 pluginCategory: categoryOf(news),
305 gatewayType: news.gatewayType,
306 actionsConfig: actionsOf(news),
307 hostingService: news.hostingService,
308 configTemplate: news.configTemplate,
309 type: news.type,
310 },
311 })
312 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
313 current = created ?? (yield* getByName(name));
314 }
315
316 if (current === undefined) {
317 return yield* new ApihubNotResolved({ resourceName: name });
318 }
319
320 const currentName = current.name ?? name;
321 const desiredEnabled = news.enabled !== false;
322 const currentlyEnabled = current.state !== "DISABLED";
323 if (desiredEnabled !== currentlyEnabled) {
324 current = desiredEnabled
325 ? yield* apihub.enableProjectsLocationsPlugins({
326 name: currentName,
327 body: {},
328 })
329 : yield* apihub.disableProjectsLocationsPlugins({
330 name: currentName,
331 body: {},
332 });
333 }
334
335 return toAttrs(current, env.project, env.region);
336 }),
337
338 delete: Effect.fn(function* ({ output }) {
339 const operation = yield* apihub.deleteProjectsLocationsPlugins({ name: output.name }).pipe(
340 Effect.retry({
341 while: (error) => error._tag === "Conflict",
342 times: 8,
343 schedule: Schedule.spaced("2 seconds"),
344 }),
345 Effect.catchTag("NotFound", () => Effect.undefined),
346 );
347 if (operation !== undefined) {
348 yield* waitForDeleteOperation(operation);
349 }
350 yield* waitUntilGone(getByName(output.name), output.name);
351 }),
352 });