The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as parametermanager from "@distilled.cloud/gcp/parametermanager_v1"; |
| 2 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 3 | import { tagRecord } from "alchemy/Tags"; |
| 4 | import * as Data from "effect/Data"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Schedule from "effect/Schedule"; |
| 7 | import * as Stream from "effect/Stream"; |
| 8 | import { DeleteNotConfirmed } from "../Errors.ts"; |
| 9 | import { ALCHEMY_LABEL_PREFIX, stripInternalLabels } from "../Labels.ts"; |
| 10 | |
| 11 | export const DEFAULT_LOCATION = "global"; |
| 12 | export const DEFAULT_FORMAT: parametermanager.ParameterFormatEnum = "UNFORMATTED"; |
| 13 | export const MAX_NAME_LENGTH = 63; |
| 14 | |
| 15 | export class ParameterNotResolved extends Data.TaggedError( |
| 16 | "GCP.ParameterManager.ParameterNotResolved", |
| 17 | )<{ |
| 18 | resourceName: string; |
| 19 | }> {} |
| 20 | |
| 21 | export class ParameterVersionNotResolved extends Data.TaggedError( |
| 22 | "GCP.ParameterManager.ParameterVersionNotResolved", |
| 23 | )<{ |
| 24 | resourceName: string; |
| 25 | }> {} |
| 26 | |
| 27 | export class ParameterVersionPayloadRequired extends Data.TaggedError( |
| 28 | "GCP.ParameterManager.ParameterVersionPayloadRequired", |
| 29 | )<{ |
| 30 | resourceName: string; |
| 31 | }> {} |
| 32 | |
| 33 | export const lastSegment = (value: string) => { |
| 34 | const trimmed = value.replace(/\/+$/, ""); |
| 35 | const parts = trimmed.split("/"); |
| 36 | return parts[parts.length - 1] || trimmed; |
| 37 | }; |
| 38 | |
| 39 | export const normalizeLocation = (location: string | undefined) => |
| 40 | lastSegment(location ?? DEFAULT_LOCATION).toLowerCase(); |
| 41 | |
| 42 | export const normalizeFormat = ( |
| 43 | format: string | undefined, |
| 44 | ): parametermanager.ParameterFormatEnum => { |
| 45 | const value = (format ?? DEFAULT_FORMAT).toUpperCase(); |
| 46 | if (value === "YAML" || value === "JSON" || value === "UNFORMATTED") { |
| 47 | return value; |
| 48 | } |
| 49 | return DEFAULT_FORMAT; |
| 50 | }; |
| 51 | |
| 52 | export const rfc1035 = (name: string, fallback: string): string => { |
| 53 | let next = name |
| 54 | .toLowerCase() |
| 55 | .replace(/[^a-z0-9-]/g, "-") |
| 56 | .replace(/-+/g, "-") |
| 57 | .replace(/^-+/, "") |
| 58 | .replace(/-+$/, ""); |
| 59 | if (!/^[a-z]/.test(next)) { |
| 60 | next = `p${next}`; |
| 61 | } |
| 62 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, ""); |
| 63 | return next.length > 0 ? next : fallback; |
| 64 | }; |
| 65 | |
| 66 | export const toPhysicalId = ( |
| 67 | id: string, |
| 68 | explicit: string | undefined, |
| 69 | existing: string | undefined, |
| 70 | fallback: string, |
| 71 | ) => |
| 72 | Effect.gen(function* () { |
| 73 | if (explicit !== undefined) return explicit; |
| 74 | if (existing !== undefined) return existing; |
| 75 | return rfc1035( |
| 76 | yield* createPhysicalName({ |
| 77 | id, |
| 78 | maxLength: MAX_NAME_LENGTH, |
| 79 | lowercase: true, |
| 80 | }), |
| 81 | fallback, |
| 82 | ); |
| 83 | }); |
| 84 | |
| 85 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 86 | (left ?? "") === (right ?? ""); |
| 87 | |
| 88 | export const userLabels = ( |
| 89 | labels: Record<string, string | undefined> | null | undefined, |
| 90 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 91 | |
| 92 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 93 | Object.keys(labels ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX)); |
| 94 | |
| 95 | export const parseParameterName = (name: string) => { |
| 96 | const parts = name.split("/").filter((part) => part.length > 0); |
| 97 | const parametersAt = parts.lastIndexOf("parameters"); |
| 98 | const locationsAt = parts.lastIndexOf("locations"); |
| 99 | const projectsAt = parts.lastIndexOf("projects"); |
| 100 | return { |
| 101 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 102 | location: |
| 103 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION, |
| 104 | parameterId: |
| 105 | parametersAt >= 0 && parts[parametersAt + 1] ? parts[parametersAt + 1]! : lastSegment(name), |
| 106 | parent: parametersAt > 0 ? parts.slice(0, parametersAt).join("/") : "", |
| 107 | }; |
| 108 | }; |
| 109 | |
| 110 | export const parseVersionName = (name: string) => { |
| 111 | const parts = name.split("/").filter((part) => part.length > 0); |
| 112 | const versionsAt = parts.lastIndexOf("versions"); |
| 113 | const parsed = parseParameterName(versionsAt > 0 ? parts.slice(0, versionsAt).join("/") : name); |
| 114 | return { |
| 115 | ...parsed, |
| 116 | parameter: versionsAt > 0 ? parts.slice(0, versionsAt).join("/") : parsed.parent, |
| 117 | parameterVersionId: |
| 118 | versionsAt >= 0 && parts[versionsAt + 1] ? parts[versionsAt + 1]! : lastSegment(name), |
| 119 | }; |
| 120 | }; |
| 121 | |
| 122 | export const parameterResourceName = (project: string, location: string, parameterId: string) => |
| 123 | `projects/${project}/locations/${location}/parameters/${parameterId}`; |
| 124 | |
| 125 | export const expandParameter = (parameter: string, project: string, location: string) => { |
| 126 | const next = parameter.replace(/\/+$/, ""); |
| 127 | if (next.includes("/parameters/")) return next; |
| 128 | const id = lastSegment(next); |
| 129 | if (id.length === 0) { |
| 130 | return parameterResourceName(project, location, "parameter"); |
| 131 | } |
| 132 | if (next.startsWith("projects/")) { |
| 133 | return `${next}/parameters/${id}`; |
| 134 | } |
| 135 | return parameterResourceName(project, location, id); |
| 136 | }; |
| 137 | |
| 138 | export const versionResourceName = (parameter: string, versionId: string) => |
| 139 | `${parameter}/versions/${versionId}`; |
| 140 | |
| 141 | export const locationFromParameter = (parameter: string | undefined, fallback: string) => { |
| 142 | if (parameter === undefined || parameter.length === 0) return fallback; |
| 143 | if (!parameter.includes("/locations/")) return fallback; |
| 144 | return parseParameterName(parameter).location || fallback; |
| 145 | }; |
| 146 | |
| 147 | export const encodeUtf8Base64 = (value: string) => |
| 148 | Effect.sync(() => Buffer.from(value, "utf8").toString("base64")); |
| 149 | |
| 150 | export const desiredPayloadData = (props: { data?: string; payload?: { data?: string } }) => |
| 151 | Effect.gen(function* () { |
| 152 | if (props.payload?.data !== undefined) return props.payload.data; |
| 153 | if (props.data !== undefined) return yield* encodeUtf8Base64(props.data); |
| 154 | return undefined; |
| 155 | }); |
| 156 | |
| 157 | export const samePayload = (left: string | undefined, right: string | undefined) => { |
| 158 | const a = left ?? ""; |
| 159 | const b = right ?? ""; |
| 160 | if (a === b) return true; |
| 161 | if (a.length === 0 || b.length === 0) return false; |
| 162 | try { |
| 163 | return Buffer.from(a, "base64").compare(Buffer.from(b, "base64")) === 0; |
| 164 | } catch { |
| 165 | return false; |
| 166 | } |
| 167 | }; |
| 168 | |
| 169 | export const getParameter = (name: string) => |
| 170 | parametermanager |
| 171 | .getProjectsLocationsParameters({ name }) |
| 172 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 173 | |
| 174 | export const getVersion = (name: string) => |
| 175 | parametermanager |
| 176 | .getProjectsLocationsParametersVersions({ name, view: "FULL" }) |
| 177 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 178 | |
| 179 | export const waitUntilParameterGone = (name: string) => |
| 180 | getParameter(name).pipe( |
| 181 | Effect.repeat({ |
| 182 | schedule: Schedule.spaced("1 second"), |
| 183 | until: (parameter): boolean => parameter === undefined, |
| 184 | times: 30, |
| 185 | }), |
| 186 | Effect.flatMap((parameter): Effect.Effect<void, DeleteNotConfirmed> => |
| 187 | parameter === undefined |
| 188 | ? Effect.void |
| 189 | : Effect.fail(new DeleteNotConfirmed({ resource: name })), |
| 190 | ), |
| 191 | ); |
| 192 | |
| 193 | export const waitUntilVersionGone = (name: string) => |
| 194 | getVersion(name).pipe( |
| 195 | Effect.repeat({ |
| 196 | schedule: Schedule.spaced("1 second"), |
| 197 | until: (version): boolean => version === undefined, |
| 198 | times: 30, |
| 199 | }), |
| 200 | Effect.flatMap((version): Effect.Effect<void, DeleteNotConfirmed> => |
| 201 | version === undefined ? Effect.void : Effect.fail(new DeleteNotConfirmed({ resource: name })), |
| 202 | ), |
| 203 | ); |
| 204 | |
| 205 | const emptyParameters = () => Effect.succeed([] as parametermanager.Parameter[]); |
| 206 | |
| 207 | const collectParameterPages = (parent: string) => |
| 208 | parametermanager.listProjectsLocationsParameters |
| 209 | .pages({ |
| 210 | parent, |
| 211 | pageSize: 1000, |
| 212 | }) |
| 213 | .pipe( |
| 214 | Stream.runCollect, |
| 215 | Effect.map((pages) => Array.from(pages).flatMap((page) => page.parameters ?? [])), |
| 216 | Effect.catchTag("NotFound", () => emptyParameters()), |
| 217 | ); |
| 218 | |
| 219 | export const listAlchemyParameters = (project: string) => |
| 220 | Effect.gen(function* () { |
| 221 | const aggregated = yield* collectParameterPages(`projects/${project}/locations/-`); |
| 222 | const parameters = |
| 223 | aggregated.length > 0 |
| 224 | ? aggregated |
| 225 | : yield* collectParameterPages(`projects/${project}/locations/${DEFAULT_LOCATION}`); |
| 226 | return parameters.filter((parameter) => hasAlchemyLabelMap(parameter.labels)); |
| 227 | }); |
| 228 | |
| 229 | const emptyVersions = () => Effect.succeed([] as parametermanager.ParameterVersion[]); |
| 230 | |
| 231 | export const listVersions = (parent: string) => |
| 232 | parent.length === 0 |
| 233 | ? emptyVersions() |
| 234 | : parametermanager.listProjectsLocationsParametersVersions |
| 235 | .pages({ |
| 236 | parent, |
| 237 | pageSize: 1000, |
| 238 | }) |
| 239 | .pipe( |
| 240 | Stream.runCollect, |
| 241 | Effect.map((pages) => Array.from(pages).flatMap((page) => page.parameterVersions ?? [])), |
| 242 | // A missing parameter has no versions. |
| 243 | Effect.catchTag("NotFound", () => emptyVersions()), |
| 244 | ); |
| 245 | |
| 246 | export const deleteVersions = (parent: string) => |
| 247 | Effect.gen(function* () { |
| 248 | const versions = yield* listVersions(parent); |
| 249 | yield* Effect.forEach( |
| 250 | versions, |
| 251 | (version) => |
| 252 | version.name |
| 253 | ? parametermanager |
| 254 | .deleteProjectsLocationsParametersVersions({ |
| 255 | name: version.name, |
| 256 | }) |
| 257 | .pipe(Effect.catchTag("NotFound", () => Effect.void)) |
| 258 | : Effect.void, |
| 259 | { concurrency: 4 }, |
| 260 | ); |
| 261 | }); |