The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as apigee from "@distilled.cloud/gcp/apigee_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 Data from "effect/Data"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as HttpClient from "effect/http/HttpClient"; |
| 10 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import { GcpEnvironment } from "../Environment.ts"; |
| 13 | import { |
| 14 | createInternalLabels, |
| 15 | diffLabels, |
| 16 | hasAlchemyLabels, |
| 17 | stripInternalLabels, |
| 18 | toLabels, |
| 19 | } from "../Labels.ts"; |
| 20 | import type { Providers } from "../Providers.ts"; |
| 21 | import { |
| 22 | environmentIdOf, |
| 23 | environmentNameOf, |
| 24 | lastSegment, |
| 25 | listProjectEnvironments, |
| 26 | missingToUndefined, |
| 27 | organizationIdOf, |
| 28 | parseOrgEnv, |
| 29 | toResourceId, |
| 30 | } from "./common.ts"; |
| 31 | import { waitForOperation } from "./operations.ts"; |
| 32 | |
| 33 | const MAX_NAME_LENGTH = 63; |
| 34 | |
| 35 | export type EnvironmentsArchiveDeploymentProps = { |
| 36 | /** |
| 37 | * Apigee organization id or `organizations/{org}`. Defaults to the |
| 38 | * current GCP project id. Immutable — changing it replaces the |
| 39 | * deployment. |
| 40 | */ |
| 41 | organization?: string; |
| 42 | /** |
| 43 | * Environment id or `organizations/{org}/environments/{env}`. The |
| 44 | * environment must use archive deployment. Immutable — changing it |
| 45 | * replaces the deployment. |
| 46 | */ |
| 47 | environment: string; |
| 48 | /** |
| 49 | * Archive deployment id (last path segment). If omitted, a unique name |
| 50 | * is generated. Immutable — changing it replaces the deployment. |
| 51 | */ |
| 52 | archiveDeploymentId?: string; |
| 53 | /** |
| 54 | * Signed GCS URI from `generateUploadUrl`, or a `gs://` object that |
| 55 | * already holds the archive zip. Input-only. |
| 56 | */ |
| 57 | gcsUri?: string; |
| 58 | /** |
| 59 | * Base64-encoded archive zip. When `gcsUri` is omitted, Alchemy calls |
| 60 | * generateUploadUrl and PUTs these bytes to the signed URL. |
| 61 | */ |
| 62 | archiveZip?: string; |
| 63 | /** |
| 64 | * User labels. Alchemy ownership labels are merged in automatically. |
| 65 | */ |
| 66 | labels?: Record<string, string>; |
| 67 | }; |
| 68 | |
| 69 | export type EnvironmentsArchiveDeployment = Resource< |
| 70 | "GCP.Apigee.EnvironmentsArchiveDeployment", |
| 71 | EnvironmentsArchiveDeploymentProps, |
| 72 | { |
| 73 | /** Full resource name `organizations/{org}/environments/{env}/archiveDeployments/{id}`. */ |
| 74 | name: string; |
| 75 | /** Archive deployment id. */ |
| 76 | archiveDeploymentId: string; |
| 77 | /** Apigee organization id. */ |
| 78 | organizationId: string; |
| 79 | /** Environment id. */ |
| 80 | environmentId: string; |
| 81 | /** User labels (Alchemy ownership labels stripped). */ |
| 82 | labels: Record<string, string>; |
| 83 | /** Create LRO name, if still reported. */ |
| 84 | operation: string | undefined; |
| 85 | /** Create time in milliseconds since epoch. */ |
| 86 | createdAt: string | undefined; |
| 87 | /** Update time in milliseconds since epoch. */ |
| 88 | updatedAt: string | undefined; |
| 89 | }, |
| 90 | never, |
| 91 | Providers |
| 92 | >; |
| 93 | |
| 94 | /** |
| 95 | * An Apigee archive deployment — a zip of API proxies deployed as a unit |
| 96 | * to an archive-mode environment. |
| 97 | * |
| 98 | * Labels carry Alchemy ownership so `list` / nuke can find leaked rows. |
| 99 | * Name is identity; labels update in place. Creating an archive is a |
| 100 | * long-running operation. |
| 101 | * |
| 102 | * ### Creating an Archive Deployment |
| 103 | * **Example:** Upload a zip |
| 104 | * ```typescript |
| 105 | * const archive = yield* GCP.Apigee.EnvironmentsArchiveDeployment("Bundle", { |
| 106 | * environment: "eval", |
| 107 | * archiveZip: zipBase64, |
| 108 | * labels: { env: "test" }, |
| 109 | * }); |
| 110 | * ``` |
| 111 | * |
| 112 | * @resource |
| 113 | * @category Apigee |
| 114 | */ |
| 115 | export const EnvironmentsArchiveDeployment = Resource<EnvironmentsArchiveDeployment>( |
| 116 | "GCP.Apigee.EnvironmentsArchiveDeployment", |
| 117 | ); |
| 118 | |
| 119 | export class EnvironmentsArchiveDeploymentNotResolved extends Data.TaggedError( |
| 120 | "GCP.Apigee.EnvironmentsArchiveDeploymentNotResolved", |
| 121 | )<{ |
| 122 | resourceName: string; |
| 123 | }> {} |
| 124 | |
| 125 | const resourceName = (organizationId: string, environmentId: string, archiveDeploymentId: string) => |
| 126 | `${environmentNameOf(organizationId, environmentId)}/archiveDeployments/${archiveDeploymentId}`; |
| 127 | |
| 128 | const userLabels = ( |
| 129 | labels: Record<string, string | undefined> | null | undefined, |
| 130 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 131 | |
| 132 | const toAttrs = ( |
| 133 | archive: apigee.GoogleCloudApigeeV1ArchiveDeployment, |
| 134 | organizationId: string, |
| 135 | environmentId: string, |
| 136 | ) => { |
| 137 | const raw = archive.name ?? ""; |
| 138 | const parsed = parseOrgEnv(raw); |
| 139 | const archiveDeploymentId = lastSegment(raw); |
| 140 | return { |
| 141 | name: raw.includes("/") |
| 142 | ? raw |
| 143 | : resourceName(organizationId, environmentId, archiveDeploymentId || raw), |
| 144 | archiveDeploymentId: archiveDeploymentId || raw, |
| 145 | organizationId: parsed.organizationId || organizationId, |
| 146 | environmentId: parsed.environmentId || environmentId, |
| 147 | labels: userLabels(archive.labels), |
| 148 | operation: archive.operation, |
| 149 | createdAt: archive.createdAt, |
| 150 | updatedAt: archive.updatedAt, |
| 151 | }; |
| 152 | }; |
| 153 | |
| 154 | const getByName = (name: string) => |
| 155 | missingToUndefined(apigee.getOrganizationsEnvironmentsArchiveDeployments({ name })); |
| 156 | |
| 157 | const uploadZip = (uploadUri: string, archiveZip: string) => |
| 158 | Effect.gen(function* () { |
| 159 | const client = yield* HttpClient.HttpClient; |
| 160 | const bytes = yield* Effect.sync(() => Buffer.from(archiveZip, "base64")); |
| 161 | const response = yield* client.execute( |
| 162 | HttpClientRequest.put(uploadUri).pipe( |
| 163 | HttpClientRequest.bodyUint8Array(bytes, "application/zip"), |
| 164 | ), |
| 165 | ); |
| 166 | if (response.status >= 400) { |
| 167 | return yield* new EnvironmentsArchiveDeploymentNotResolved({ |
| 168 | resourceName: uploadUri, |
| 169 | }); |
| 170 | } |
| 171 | return uploadUri; |
| 172 | }); |
| 173 | |
| 174 | export const EnvironmentsArchiveDeploymentProvider = () => |
| 175 | Provider.succeed(EnvironmentsArchiveDeployment, { |
| 176 | stables: ["name", "archiveDeploymentId", "organizationId", "environmentId", "createdAt"], |
| 177 | |
| 178 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 179 | if (!isResolved(news)) return undefined; |
| 180 | const previousId = olds?.archiveDeploymentId ?? output?.archiveDeploymentId; |
| 181 | const previousOrg = olds?.organization ?? output?.organizationId; |
| 182 | const previousEnv = olds?.environment ?? output?.environmentId; |
| 183 | const idChanged = |
| 184 | previousId !== undefined && |
| 185 | news.archiveDeploymentId !== undefined && |
| 186 | news.archiveDeploymentId !== previousId; |
| 187 | const orgChanged = |
| 188 | previousOrg !== undefined && |
| 189 | news.organization !== undefined && |
| 190 | organizationIdOf(news.organization, "") !== organizationIdOf(previousOrg, ""); |
| 191 | const envChanged = |
| 192 | previousEnv !== undefined && |
| 193 | environmentIdOf(news.environment) !== environmentIdOf(previousEnv); |
| 194 | if (idChanged || orgChanged || envChanged) { |
| 195 | return { action: "replace" as const, deleteFirst: false }; |
| 196 | } |
| 197 | return undefined; |
| 198 | }), |
| 199 | |
| 200 | read: Effect.fn(function* ({ id, olds, output }) { |
| 201 | const { project } = yield* GcpEnvironment.current; |
| 202 | const organizationId = organizationIdOf( |
| 203 | olds?.organization ?? output?.organizationId, |
| 204 | project, |
| 205 | ); |
| 206 | const environmentId = environmentIdOf(olds?.environment ?? output?.environmentId ?? ""); |
| 207 | const archiveDeploymentId = yield* toResourceId( |
| 208 | id, |
| 209 | olds?.archiveDeploymentId, |
| 210 | output?.archiveDeploymentId, |
| 211 | { maxLength: MAX_NAME_LENGTH, rfc1035: true }, |
| 212 | ); |
| 213 | const name = output?.name ?? resourceName(organizationId, environmentId, archiveDeploymentId); |
| 214 | const existing = yield* getByName(name); |
| 215 | if (existing === undefined) return undefined; |
| 216 | const attrs = toAttrs(existing, organizationId, environmentId); |
| 217 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 218 | }), |
| 219 | |
| 220 | list: () => |
| 221 | Effect.gen(function* () { |
| 222 | const environments = yield* listProjectEnvironments(); |
| 223 | const found: EnvironmentsArchiveDeployment["Attributes"][] = []; |
| 224 | for (const item of environments) { |
| 225 | const archives = yield* apigee.listOrganizationsEnvironmentsArchiveDeployments |
| 226 | .pages({ parent: item.parent, pageSize: 100 }) |
| 227 | .pipe( |
| 228 | Stream.flatMap((page) => Stream.fromIterable(page.archiveDeployments ?? [])), |
| 229 | Stream.filter((archive) => |
| 230 | Object.keys(archive.labels ?? {}).some((key) => key.startsWith("alchemy-")), |
| 231 | ), |
| 232 | Stream.map((archive) => toAttrs(archive, item.organizationId, item.environmentId)), |
| 233 | Stream.runCollect, |
| 234 | Effect.map((chunk) => Array.from(chunk)), |
| 235 | Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => |
| 236 | Effect.succeed([] as EnvironmentsArchiveDeployment["Attributes"][]), |
| 237 | ), |
| 238 | ); |
| 239 | found.push(...archives); |
| 240 | } |
| 241 | return found; |
| 242 | }), |
| 243 | |
| 244 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 245 | const { project } = yield* GcpEnvironment.current; |
| 246 | const organizationId = organizationIdOf(news.organization, project); |
| 247 | const environmentId = environmentIdOf(news.environment); |
| 248 | const archiveDeploymentId = yield* toResourceId( |
| 249 | id, |
| 250 | news.archiveDeploymentId, |
| 251 | output?.archiveDeploymentId, |
| 252 | { maxLength: MAX_NAME_LENGTH, rfc1035: true }, |
| 253 | ); |
| 254 | const parent = environmentNameOf(organizationId, environmentId); |
| 255 | const name = resourceName(organizationId, environmentId, archiveDeploymentId); |
| 256 | const desiredLabels = { |
| 257 | ...toLabels(news.labels), |
| 258 | ...(yield* createInternalLabels(id)), |
| 259 | }; |
| 260 | |
| 261 | let current = yield* getByName(output?.name ?? name); |
| 262 | |
| 263 | if (current === undefined) { |
| 264 | let gcsUri = news.gcsUri; |
| 265 | if (gcsUri === undefined && news.archiveZip !== undefined) { |
| 266 | const upload = yield* apigee.generateUploadUrlOrganizationsEnvironmentsArchiveDeployments( |
| 267 | { parent, body: {} }, |
| 268 | ); |
| 269 | if (upload.uploadUri) { |
| 270 | gcsUri = yield* uploadZip(upload.uploadUri, news.archiveZip); |
| 271 | } |
| 272 | } |
| 273 | const operation = yield* apigee |
| 274 | .createOrganizationsEnvironmentsArchiveDeployments({ |
| 275 | parent, |
| 276 | body: { |
| 277 | name, |
| 278 | gcsUri, |
| 279 | labels: desiredLabels, |
| 280 | }, |
| 281 | }) |
| 282 | .pipe( |
| 283 | Effect.catchTag("Conflict", () => |
| 284 | Effect.succeed<apigee.GoogleLongrunningOperation>({ |
| 285 | done: true, |
| 286 | }), |
| 287 | ), |
| 288 | ); |
| 289 | if (operation.name || operation.done !== true) { |
| 290 | yield* waitForOperation(operation); |
| 291 | } |
| 292 | current = yield* getByName(name); |
| 293 | } |
| 294 | |
| 295 | if (current === undefined) { |
| 296 | return yield* new EnvironmentsArchiveDeploymentNotResolved({ resourceName: name }); |
| 297 | } |
| 298 | |
| 299 | const observedLabels = tagRecord(current.labels); |
| 300 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 301 | if (upsert.length > 0 || removed.length > 0) { |
| 302 | current = yield* apigee.patchOrganizationsEnvironmentsArchiveDeployments({ |
| 303 | name: current.name ?? name, |
| 304 | updateMask: "labels", |
| 305 | body: { labels: desiredLabels }, |
| 306 | }); |
| 307 | } |
| 308 | |
| 309 | return toAttrs(current, organizationId, environmentId); |
| 310 | }), |
| 311 | |
| 312 | delete: Effect.fn(function* ({ output }) { |
| 313 | yield* apigee |
| 314 | .deleteOrganizationsEnvironmentsArchiveDeployments({ |
| 315 | name: output.name, |
| 316 | }) |
| 317 | .pipe(Effect.catchTag(["NotFound", "ApigeeResourceNotFound"], () => Effect.void)); |
| 318 | }), |
| 319 | }); |