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
| 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 | ApihubInstanceFailed, |
| 13 | ApihubNotResolved, |
| 14 | encodeOwnershipLine, |
| 15 | hasOwnershipMarker, |
| 16 | locationParent, |
| 17 | MAX_PLUGIN_INSTANCE_DISPLAY_NAME_LENGTH, |
| 18 | normalizeLocation, |
| 19 | ownedByAlchemy, |
| 20 | ownershipLabels, |
| 21 | parseName, |
| 22 | parseOwnership, |
| 23 | replaceOnIdentity, |
| 24 | sameJson, |
| 25 | sameText, |
| 26 | toPhysicalId, |
| 27 | updateMaskOf, |
| 28 | waitUntilExists, |
| 29 | waitUntilGone, |
| 30 | } from "./internal.ts"; |
| 31 | import { waitForDeleteOperation, waitForOperation } from "./internal.ts"; |
| 32 | |
| 33 | export type PluginInstanceAction = apihub.GoogleCloudApihubV1PluginInstanceAction; |
| 34 | export type AuthConfig = apihub.GoogleCloudApihubV1AuthConfig; |
| 35 | export type ConfigVariableMap = apihub.GoogleCloudApihubV1ConfigVariableMap; |
| 36 | export type SourceEnvironmentMap = apihub.GoogleCloudApihubV1SourceEnvironmentMap; |
| 37 | |
| 38 | export type PluginsInstanceProps = { |
| 39 | /** |
| 40 | * Parent plugin resource name |
| 41 | * `projects/{project}/locations/{location}/plugins/{plugin}`. |
| 42 | * Immutable — changing it replaces the instance. |
| 43 | */ |
| 44 | plugin: string; |
| 45 | /** |
| 46 | * Plugin instance id (the `{instance}` segment). If omitted, a unique |
| 47 | * id is generated. Immutable — changing it replaces the instance. |
| 48 | */ |
| 49 | pluginInstanceId?: string; |
| 50 | /** |
| 51 | * Location of the API Hub instance. Defaults to the parent plugin's |
| 52 | * location. Immutable — changing it replaces the instance. |
| 53 | */ |
| 54 | location?: string; |
| 55 | /** |
| 56 | * Display name. Max 255 characters. Plugin instances have no |
| 57 | * description, so Alchemy stamps ownership into a `[alchemy …]` prefix |
| 58 | * and strips it from attributes. |
| 59 | */ |
| 60 | displayName?: string; |
| 61 | /** |
| 62 | * Actions this instance should run. Each `actionId` must match an |
| 63 | * action on the parent plugin. Defaults to `{ actionId: "sync-metadata" }`. |
| 64 | */ |
| 65 | actions?: PluginInstanceAction[]; |
| 66 | /** |
| 67 | * Authentication configuration for this instance. |
| 68 | */ |
| 69 | authConfig?: AuthConfig; |
| 70 | /** |
| 71 | * Additional config variables keyed by template id. |
| 72 | */ |
| 73 | additionalConfig?: ConfigVariableMap; |
| 74 | /** |
| 75 | * Source project id (runtime project for Google Cloud plugins). |
| 76 | */ |
| 77 | sourceProjectId?: string; |
| 78 | /** |
| 79 | * Source environment config keyed by environment name. |
| 80 | */ |
| 81 | sourceEnvironmentsConfig?: SourceEnvironmentMap; |
| 82 | }; |
| 83 | |
| 84 | export type PluginsInstance = Resource< |
| 85 | "GCP.ApiHub.PluginsInstance", |
| 86 | PluginsInstanceProps, |
| 87 | { |
| 88 | /** Full resource name. */ |
| 89 | name: string; |
| 90 | /** Plugin instance id (last path segment). */ |
| 91 | pluginInstanceId: string; |
| 92 | /** Parent plugin resource name. */ |
| 93 | plugin: string; |
| 94 | /** Parent plugin id. */ |
| 95 | pluginId: string; |
| 96 | /** Project id. */ |
| 97 | project: string; |
| 98 | /** Location id. */ |
| 99 | location: string; |
| 100 | /** User display name with the Alchemy ownership prefix stripped. */ |
| 101 | displayName: string | undefined; |
| 102 | /** Actions. */ |
| 103 | actions: PluginInstanceAction[] | undefined; |
| 104 | /** Auth config. */ |
| 105 | authConfig: AuthConfig | undefined; |
| 106 | /** Additional config. */ |
| 107 | additionalConfig: ConfigVariableMap | undefined; |
| 108 | /** Source project id. */ |
| 109 | sourceProjectId: string | undefined; |
| 110 | /** Source environment config. */ |
| 111 | sourceEnvironmentsConfig: SourceEnvironmentMap | undefined; |
| 112 | /** Instance state. */ |
| 113 | state: string | undefined; |
| 114 | /** Error message when state is ERROR or FAILED. */ |
| 115 | errorMessage: string | undefined; |
| 116 | /** RFC3339 creation timestamp. */ |
| 117 | createTime: string | undefined; |
| 118 | /** RFC3339 last-update timestamp. */ |
| 119 | updateTime: string | undefined; |
| 120 | }, |
| 121 | never, |
| 122 | Providers |
| 123 | >; |
| 124 | |
| 125 | /** |
| 126 | * An API Hub plugin instance — a configured running copy of a plugin. |
| 127 | * |
| 128 | * Plugin instances have no labels or description, so Alchemy stamps |
| 129 | * ownership into the display name for `list` / nuke. Plugin, location, |
| 130 | * and instance id are identity. Display name (and schedule cron on |
| 131 | * actions) update in place; auth/additional config changes replace the |
| 132 | * instance because ApplyPluginInstanceConfig is not in the distilled SDK. |
| 133 | * |
| 134 | * ### Creating a Plugin Instance |
| 135 | * **Example:** Instance of a user-owned plugin |
| 136 | * ```typescript |
| 137 | * const plugin = yield* GCP.ApiHub.Plugin("OnRamp", { |
| 138 | * displayName: "on-ramp", |
| 139 | * }); |
| 140 | * const instance = yield* GCP.ApiHub.PluginsInstance("Collector", { |
| 141 | * plugin: plugin.name, |
| 142 | * displayName: "orders collector", |
| 143 | * }); |
| 144 | * ``` |
| 145 | * |
| 146 | * **Example:** Named instance with an explicit action |
| 147 | * ```typescript |
| 148 | * const instance = yield* GCP.ApiHub.PluginsInstance("Collector", { |
| 149 | * plugin: plugin.name, |
| 150 | * pluginInstanceId: "orders-collector", |
| 151 | * actions: [{ actionId: "sync-metadata" }], |
| 152 | * }); |
| 153 | * ``` |
| 154 | * |
| 155 | * @resource |
| 156 | * @category ApiHub |
| 157 | */ |
| 158 | export const PluginsInstance = Resource<PluginsInstance>("GCP.ApiHub.PluginsInstance"); |
| 159 | |
| 160 | const DEFAULT_ACTIONS: PluginInstanceAction[] = [{ actionId: "sync-metadata" }]; |
| 161 | |
| 162 | const resourceName = (plugin: string, pluginInstanceId: string) => |
| 163 | `${plugin}/instances/${pluginInstanceId}`; |
| 164 | |
| 165 | const toAttrs = ( |
| 166 | instance: apihub.GoogleCloudApihubV1PluginInstance, |
| 167 | project: string, |
| 168 | region: string, |
| 169 | ): PluginsInstance["Attributes"] => { |
| 170 | const name = instance.name ?? ""; |
| 171 | const parsed = parseName(name, "instances", region); |
| 172 | const { text } = parseOwnership(instance.displayName); |
| 173 | return { |
| 174 | name, |
| 175 | pluginInstanceId: parsed.id, |
| 176 | plugin: parsed.plugin ?? parsed.parent, |
| 177 | pluginId: parsed.pluginId, |
| 178 | project: parsed.project || project, |
| 179 | location: parsed.location, |
| 180 | displayName: text, |
| 181 | actions: instance.actions, |
| 182 | authConfig: instance.authConfig, |
| 183 | additionalConfig: instance.additionalConfig, |
| 184 | sourceProjectId: instance.sourceProjectId, |
| 185 | sourceEnvironmentsConfig: instance.sourceEnvironmentsConfig, |
| 186 | state: instance.state === undefined ? undefined : `${instance.state}`, |
| 187 | errorMessage: instance.errorMessage, |
| 188 | createTime: instance.createTime, |
| 189 | updateTime: instance.updateTime, |
| 190 | }; |
| 191 | }; |
| 192 | |
| 193 | const getByName = (name: string) => |
| 194 | name.length === 0 |
| 195 | ? Effect.undefined |
| 196 | : apihub |
| 197 | .getProjectsLocationsPluginsInstances({ name }) |
| 198 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 199 | |
| 200 | const listAt = (parent: string, project: string, region: string) => |
| 201 | apihub.listProjectsLocationsPluginsInstances.pages({ parent, pageSize: 1000 }).pipe( |
| 202 | Stream.flatMap((page) => Stream.fromIterable(page.pluginInstances ?? [])), |
| 203 | Stream.filter((item) => hasOwnershipMarker(item.displayName)), |
| 204 | Stream.map((item) => toAttrs(item, project, region)), |
| 205 | Stream.runCollect, |
| 206 | Effect.map((chunk) => Array.from(chunk)), |
| 207 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 208 | ); |
| 209 | |
| 210 | const waitUntilReady = (name: string) => |
| 211 | getByName(name).pipe( |
| 212 | Effect.filterOrFail( |
| 213 | (current): current is apihub.GoogleCloudApihubV1PluginInstance => |
| 214 | current !== undefined && |
| 215 | current.state !== "CREATING" && |
| 216 | current.state !== "APPLYING_CONFIG", |
| 217 | () => new ApihubNotResolved({ resourceName: name }), |
| 218 | ), |
| 219 | Effect.retry({ |
| 220 | while: (error) => error._tag === "GCP.ApiHub.ResourceNotResolved", |
| 221 | times: 10, |
| 222 | schedule: Schedule.spaced("3 seconds"), |
| 223 | }), |
| 224 | Effect.flatMap((current) => { |
| 225 | if (current.state === "ERROR" || current.state === "FAILED") { |
| 226 | return Effect.fail( |
| 227 | new ApihubInstanceFailed({ |
| 228 | resourceName: name, |
| 229 | state: current.state, |
| 230 | message: current.errorMessage, |
| 231 | }), |
| 232 | ); |
| 233 | } |
| 234 | return Effect.succeed(current); |
| 235 | }), |
| 236 | ); |
| 237 | |
| 238 | const scheduleOf = (actions: PluginInstanceAction[] | undefined) => |
| 239 | (actions ?? []).map((action) => ({ |
| 240 | actionId: action.actionId, |
| 241 | scheduleCronExpression: action.scheduleCronExpression ?? "", |
| 242 | scheduleTimeZone: action.scheduleTimeZone ?? "", |
| 243 | })); |
| 244 | |
| 245 | export const PluginsInstanceProvider = () => |
| 246 | Provider.succeed(PluginsInstance, { |
| 247 | stables: [ |
| 248 | "name", |
| 249 | "pluginInstanceId", |
| 250 | "plugin", |
| 251 | "pluginId", |
| 252 | "project", |
| 253 | "location", |
| 254 | "createTime", |
| 255 | ], |
| 256 | |
| 257 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 258 | if (!isResolved(news)) return undefined; |
| 259 | const env = yield* GcpEnvironment.current; |
| 260 | const extra = |
| 261 | olds !== undefined && |
| 262 | (!sameJson(news.authConfig, olds.authConfig) || |
| 263 | !sameJson(news.additionalConfig, olds.additionalConfig) || |
| 264 | !sameText(news.sourceProjectId, olds.sourceProjectId) || |
| 265 | !sameJson(news.sourceEnvironmentsConfig, olds.sourceEnvironmentsConfig) || |
| 266 | !sameJson( |
| 267 | (news.actions ?? DEFAULT_ACTIONS).map((action) => action.actionId), |
| 268 | (olds.actions ?? DEFAULT_ACTIONS).map((action) => action.actionId), |
| 269 | )); |
| 270 | const previousPlugin = olds?.plugin ?? output?.plugin; |
| 271 | const pluginChanged = |
| 272 | previousPlugin !== undefined && news.plugin !== undefined && news.plugin !== previousPlugin; |
| 273 | const identity = replaceOnIdentity({ |
| 274 | previousId: olds?.pluginInstanceId ?? output?.pluginInstanceId, |
| 275 | nextId: news.pluginInstanceId ?? olds?.pluginInstanceId ?? output?.pluginInstanceId, |
| 276 | previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region), |
| 277 | nextLocation: normalizeLocation( |
| 278 | news.location ?? olds?.location ?? output?.location, |
| 279 | env.region, |
| 280 | ), |
| 281 | extra: extra || pluginChanged, |
| 282 | }); |
| 283 | if (identity !== undefined) return identity; |
| 284 | if (pluginChanged) { |
| 285 | return { action: "replace" as const, deleteFirst: false }; |
| 286 | } |
| 287 | return undefined; |
| 288 | }), |
| 289 | |
| 290 | read: Effect.fn(function* ({ id, olds, output }) { |
| 291 | const env = yield* GcpEnvironment.current; |
| 292 | const plugin = olds?.plugin ?? output?.plugin ?? ""; |
| 293 | const pluginInstanceId = yield* toPhysicalId( |
| 294 | id, |
| 295 | olds?.pluginInstanceId, |
| 296 | output?.pluginInstanceId, |
| 297 | ); |
| 298 | const name = |
| 299 | output?.name ?? (plugin.length > 0 ? resourceName(plugin, pluginInstanceId) : ""); |
| 300 | const existing = yield* getByName(name); |
| 301 | if (existing === undefined) return undefined; |
| 302 | const attrs = toAttrs(existing, env.project, env.region); |
| 303 | return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs); |
| 304 | }), |
| 305 | |
| 306 | list: () => |
| 307 | Effect.gen(function* () { |
| 308 | const env = yield* GcpEnvironment.current; |
| 309 | return yield* listAt( |
| 310 | `${locationParent(env.project, env.region)}/plugins/-`, |
| 311 | env.project, |
| 312 | env.region, |
| 313 | ); |
| 314 | }), |
| 315 | |
| 316 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 317 | const env = yield* GcpEnvironment.current; |
| 318 | const plugin = news.plugin; |
| 319 | const parsedPlugin = parseName(plugin, "plugins", env.region); |
| 320 | const location = normalizeLocation( |
| 321 | news.location ?? parsedPlugin.location ?? output?.location, |
| 322 | env.region, |
| 323 | ); |
| 324 | const pluginName = plugin.includes("/") |
| 325 | ? plugin |
| 326 | : `${locationParent(env.project, location)}/plugins/${plugin}`; |
| 327 | const pluginInstanceId = yield* toPhysicalId( |
| 328 | id, |
| 329 | news.pluginInstanceId, |
| 330 | output?.pluginInstanceId, |
| 331 | ); |
| 332 | const name = resourceName(pluginName, pluginInstanceId); |
| 333 | const ownership = yield* ownershipLabels(id); |
| 334 | const displayName = encodeOwnershipLine( |
| 335 | ownership, |
| 336 | news.displayName, |
| 337 | MAX_PLUGIN_INSTANCE_DISPLAY_NAME_LENGTH, |
| 338 | ); |
| 339 | const actions = news.actions ?? DEFAULT_ACTIONS; |
| 340 | |
| 341 | let current = yield* getByName(output?.name ?? name); |
| 342 | |
| 343 | if (current === undefined) { |
| 344 | const created = yield* apihub |
| 345 | .createProjectsLocationsPluginsInstances({ |
| 346 | parent: pluginName, |
| 347 | pluginInstanceId, |
| 348 | body: { |
| 349 | displayName, |
| 350 | actions, |
| 351 | authConfig: news.authConfig, |
| 352 | additionalConfig: news.additionalConfig, |
| 353 | sourceProjectId: news.sourceProjectId, |
| 354 | sourceEnvironmentsConfig: news.sourceEnvironmentsConfig, |
| 355 | }, |
| 356 | }) |
| 357 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 358 | if (created !== undefined) { |
| 359 | yield* waitForOperation(created); |
| 360 | current = yield* waitUntilExists(getByName(name), name); |
| 361 | } |
| 362 | if (current === undefined) { |
| 363 | current = yield* waitUntilExists(getByName(name), name).pipe( |
| 364 | Effect.catchTag("GCP.ApiHub.ResourceNotResolved", () => Effect.undefined), |
| 365 | ); |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | if (current === undefined) { |
| 370 | return yield* new ApihubNotResolved({ resourceName: name }); |
| 371 | } |
| 372 | |
| 373 | const currentName = current.name ?? name; |
| 374 | let ready = yield* waitUntilReady(currentName); |
| 375 | |
| 376 | const observedDisplay = parseOwnership(ready.displayName).text; |
| 377 | const displayChanged = !sameText(observedDisplay, news.displayName); |
| 378 | const scheduleChanged = !sameJson(scheduleOf(ready.actions), scheduleOf(actions)); |
| 379 | const updateMask = updateMaskOf( |
| 380 | displayChanged ? "display_name" : undefined, |
| 381 | scheduleChanged ? "actions" : undefined, |
| 382 | ); |
| 383 | |
| 384 | if (updateMask.length > 0) { |
| 385 | ready = yield* apihub.patchProjectsLocationsPluginsInstances({ |
| 386 | name: currentName, |
| 387 | updateMask, |
| 388 | body: { |
| 389 | name: currentName, |
| 390 | displayName, |
| 391 | actions, |
| 392 | }, |
| 393 | }); |
| 394 | } |
| 395 | |
| 396 | return toAttrs(ready, env.project, env.region); |
| 397 | }), |
| 398 | |
| 399 | delete: Effect.fn(function* ({ output }) { |
| 400 | const operation = yield* apihub |
| 401 | .deleteProjectsLocationsPluginsInstances({ name: output.name }) |
| 402 | .pipe( |
| 403 | Effect.retry({ |
| 404 | while: (error) => error._tag === "Conflict", |
| 405 | times: 8, |
| 406 | schedule: Schedule.spaced("2 seconds"), |
| 407 | }), |
| 408 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 409 | ); |
| 410 | if (operation !== undefined) { |
| 411 | yield* waitForDeleteOperation(operation); |
| 412 | } |
| 413 | yield* waitUntilGone(getByName(output.name), output.name); |
| 414 | }), |
| 415 | }); |