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 artifactregistry from "@distilled.cloud/gcp/artifactregistry_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 { alchemyLabelKeys, hasAlchemyLabels, stripInternalLabels } from "../Labels.ts"; |
| 9 | import { waitForOperation as waitForLongRunning, type LongRunningOperation } from "../Operation.ts"; |
| 10 | |
| 11 | export const MAX_NAME_LENGTH = 63; |
| 12 | export const PAGE_SIZE = 1000; |
| 13 | |
| 14 | export class ResourceNotResolved extends Data.TaggedError( |
| 15 | "GCP.ArtifactRegistry.ResourceNotResolved", |
| 16 | )<{ |
| 17 | resourceName: string; |
| 18 | }> {} |
| 19 | |
| 20 | export class ResourceStillExists extends Data.TaggedError( |
| 21 | "GCP.ArtifactRegistry.ResourceStillExists", |
| 22 | )<{ |
| 23 | resourceName: string; |
| 24 | }> {} |
| 25 | |
| 26 | export const lastSegment = (value: string) => { |
| 27 | const trimmed = value.replace(/\/+$/, ""); |
| 28 | const parts = trimmed.split("/"); |
| 29 | return parts[parts.length - 1] || trimmed; |
| 30 | }; |
| 31 | |
| 32 | export const rfc1035 = (name: string, fallback = "artifact"): string => { |
| 33 | let next = name |
| 34 | .toLowerCase() |
| 35 | .replace(/[^a-z0-9-]/g, "-") |
| 36 | .replace(/-+/g, "-") |
| 37 | .replace(/^-+|-+$/g, ""); |
| 38 | if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "a"}${next}`; |
| 39 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 40 | if (next.length === 0) next = fallback; |
| 41 | if (!/[a-z0-9]$/.test(next)) { |
| 42 | next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; |
| 43 | } |
| 44 | return next.slice(0, MAX_NAME_LENGTH); |
| 45 | }; |
| 46 | |
| 47 | export const normalizeLocation = (location: string | undefined, fallback: string) => |
| 48 | lastSegment(location ?? fallback).toLowerCase(); |
| 49 | |
| 50 | export const parseName = (name: string, collection: string, fallbackLocation: string) => { |
| 51 | const parts = name.split("/").filter((part) => part.length > 0); |
| 52 | const collectionAt = parts.lastIndexOf(collection); |
| 53 | const locationsAt = parts.lastIndexOf("locations"); |
| 54 | const projectsAt = parts.lastIndexOf("projects"); |
| 55 | return { |
| 56 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 57 | location: |
| 58 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation, |
| 59 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 60 | parent: |
| 61 | collectionAt > 0 |
| 62 | ? parts.slice(0, collectionAt).join("/") |
| 63 | : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), |
| 64 | }; |
| 65 | }; |
| 66 | |
| 67 | export const expandRepository = (value: string, project: string, location: string) => { |
| 68 | const next = value.replace(/\/+$/, ""); |
| 69 | if (next.includes("/repositories/")) return next; |
| 70 | if (next.includes("/")) return next; |
| 71 | return `projects/${project}/locations/${location}/repositories/${next}`; |
| 72 | }; |
| 73 | |
| 74 | export const locationFromRepository = (repository: string | undefined, fallback: string) => { |
| 75 | if (repository === undefined || !repository.includes("/locations/")) { |
| 76 | return fallback; |
| 77 | } |
| 78 | return parseName(repository, "repositories", fallback).location; |
| 79 | }; |
| 80 | |
| 81 | export const toPhysicalId = ( |
| 82 | id: string, |
| 83 | explicit: string | undefined, |
| 84 | existing: string | undefined, |
| 85 | fallback = "artifact", |
| 86 | ) => |
| 87 | Effect.gen(function* () { |
| 88 | if (explicit !== undefined) return explicit; |
| 89 | if (existing !== undefined) return existing; |
| 90 | return rfc1035( |
| 91 | yield* createPhysicalName({ |
| 92 | id, |
| 93 | maxLength: MAX_NAME_LENGTH, |
| 94 | lowercase: true, |
| 95 | }), |
| 96 | fallback, |
| 97 | ); |
| 98 | }); |
| 99 | |
| 100 | export const userLabels = ( |
| 101 | labels: Record<string, string | undefined> | null | undefined, |
| 102 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 103 | |
| 104 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 105 | Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 106 | |
| 107 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 108 | (left ?? "") === (right ?? ""); |
| 109 | |
| 110 | export const fingerprint = (value: unknown): string => JSON.stringify(value ?? null); |
| 111 | |
| 112 | export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right); |
| 113 | |
| 114 | export const sortedStrings = (values: readonly string[] | undefined) => |
| 115 | [...(values ?? [])].slice().sort(); |
| 116 | |
| 117 | export const fieldMask = (fields: Array<string | false | undefined>) => |
| 118 | fields.filter((field): field is string => typeof field === "string").join(","); |
| 119 | |
| 120 | export const replaceOnIdentity = (input: { |
| 121 | previousId: string | undefined; |
| 122 | nextId: string | undefined; |
| 123 | previousLocation: string; |
| 124 | nextLocation: string; |
| 125 | extra?: boolean; |
| 126 | previousParent?: string; |
| 127 | nextParent?: string; |
| 128 | }) => { |
| 129 | const parentChanged = |
| 130 | (input.previousParent ?? "") !== "" && |
| 131 | (input.nextParent ?? "") !== "" && |
| 132 | lastSegment(input.previousParent ?? "") !== lastSegment(input.nextParent ?? ""); |
| 133 | const replace = |
| 134 | (input.extra ?? false) || |
| 135 | parentChanged || |
| 136 | (input.previousId !== undefined && |
| 137 | input.nextId !== undefined && |
| 138 | input.nextId !== input.previousId) || |
| 139 | input.previousLocation !== input.nextLocation; |
| 140 | if (!replace) return undefined; |
| 141 | const samePhysical = |
| 142 | input.previousLocation === input.nextLocation && |
| 143 | !parentChanged && |
| 144 | input.previousId !== undefined && |
| 145 | input.nextId === input.previousId; |
| 146 | return { |
| 147 | action: "replace" as const, |
| 148 | deleteFirst: samePhysical, |
| 149 | }; |
| 150 | }; |
| 151 | |
| 152 | const markerOf = (stack: string, stage: string, id: string) => |
| 153 | `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`; |
| 154 | |
| 155 | export const encodeOwnership = ( |
| 156 | labels: Record<string, string>, |
| 157 | text: string | undefined, |
| 158 | ): string => { |
| 159 | const marker = markerOf( |
| 160 | labels[alchemyLabelKeys.stack] ?? "x", |
| 161 | labels[alchemyLabelKeys.stage] ?? "x", |
| 162 | labels[alchemyLabelKeys.id] ?? "x", |
| 163 | ); |
| 164 | return text && text.length > 0 ? `${marker}\n${text}` : marker; |
| 165 | }; |
| 166 | |
| 167 | export const parseOwnership = ( |
| 168 | text: string | undefined, |
| 169 | ): { |
| 170 | labels: Record<string, string>; |
| 171 | text: string | undefined; |
| 172 | } => { |
| 173 | if (!text?.startsWith("[alchemy ")) { |
| 174 | return { labels: {}, text }; |
| 175 | } |
| 176 | const end = text.indexOf("]"); |
| 177 | if (end < 0) return { labels: {}, text }; |
| 178 | const labels: Record<string, string> = {}; |
| 179 | for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) { |
| 180 | const eq = part.indexOf("="); |
| 181 | if (eq > 0) { |
| 182 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 183 | } |
| 184 | } |
| 185 | const rest = text.slice(end + 1).replace(/^\n/, ""); |
| 186 | return { labels, text: rest.length > 0 ? rest : undefined }; |
| 187 | }; |
| 188 | |
| 189 | export const hasOwnershipMarker = (text: string | undefined) => |
| 190 | Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-")); |
| 191 | |
| 192 | export const ownedByAlchemy = (id: string, text: string | undefined) => |
| 193 | Effect.gen(function* () { |
| 194 | const { labels } = parseOwnership(text); |
| 195 | return yield* hasAlchemyLabels(id, labels); |
| 196 | }); |
| 197 | |
| 198 | export const waitUntilExists = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) => |
| 199 | get.pipe( |
| 200 | Effect.flatMap((value) => |
| 201 | value ? Effect.succeed(value) : Effect.fail(new ResourceNotResolved({ resourceName: name })), |
| 202 | ), |
| 203 | Effect.retry({ |
| 204 | while: (error) => error instanceof ResourceNotResolved, |
| 205 | times: 8, |
| 206 | schedule: Schedule.spaced("1 second"), |
| 207 | }), |
| 208 | ); |
| 209 | |
| 210 | export const waitUntilGone = <A, E, R>(get: Effect.Effect<A | undefined, E, R>, name: string) => |
| 211 | get.pipe( |
| 212 | Effect.flatMap((value) => |
| 213 | value === undefined |
| 214 | ? Effect.void |
| 215 | : Effect.fail(new ResourceStillExists({ resourceName: name })), |
| 216 | ), |
| 217 | Effect.retry({ |
| 218 | while: (error) => error instanceof ResourceStillExists, |
| 219 | times: 10, |
| 220 | schedule: Schedule.spaced("1 second"), |
| 221 | }), |
| 222 | ); |
| 223 | |
| 224 | const emptyList = <A>() => Effect.succeed<A[]>([]); |
| 225 | |
| 226 | export const collectPages = <Page, Item, E extends { readonly _tag: string }, R>( |
| 227 | pages: Stream.Stream<Page, E, R>, |
| 228 | items: (page: Page) => readonly Item[] | null | undefined, |
| 229 | ) => |
| 230 | pages.pipe( |
| 231 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 232 | Stream.runCollect, |
| 233 | Effect.map((chunk) => Array.from(chunk) as Item[]), |
| 234 | Effect.catchIf( |
| 235 | (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound", |
| 236 | () => emptyList<Item>(), |
| 237 | ), |
| 238 | ); |
| 239 | |
| 240 | export const listChildResources = <A, E, R>( |
| 241 | parents: readonly { name?: string }[], |
| 242 | list: (name: string) => Effect.Effect<A[], E, R>, |
| 243 | ) => |
| 244 | Effect.forEach( |
| 245 | parents.filter((parent) => (parent.name ?? "").length > 0), |
| 246 | (parent) => list(parent.name!), |
| 247 | { concurrency: 4 }, |
| 248 | ).pipe(Effect.map((groups) => groups.flat())); |
| 249 | |
| 250 | export const listAlchemyRepositories = (project: string) => |
| 251 | collectPages( |
| 252 | artifactregistry.listProjectsLocationsRepositories.pages({ |
| 253 | parent: `projects/${project}/locations/-`, |
| 254 | pageSize: PAGE_SIZE, |
| 255 | }), |
| 256 | (page) => page.repositories, |
| 257 | ).pipe(Effect.map((repos) => repos.filter((repo) => hasAlchemyLabelMap(repo.labels)))); |
| 258 | |
| 259 | export const listPackages = (parent: string) => |
| 260 | parent.length === 0 |
| 261 | ? emptyList<artifactregistry.Package>() |
| 262 | : collectPages( |
| 263 | artifactregistry.listProjectsLocationsRepositoriesPackages.pages({ |
| 264 | parent, |
| 265 | pageSize: PAGE_SIZE, |
| 266 | }), |
| 267 | (page) => page.packages, |
| 268 | ); |
| 269 | |
| 270 | export const listTags = (parent: string) => |
| 271 | parent.length === 0 |
| 272 | ? emptyList<artifactregistry.Tag>() |
| 273 | : collectPages( |
| 274 | artifactregistry.listProjectsLocationsRepositoriesPackagesTags.pages({ |
| 275 | parent, |
| 276 | pageSize: PAGE_SIZE, |
| 277 | }), |
| 278 | (page) => page.tags, |
| 279 | ); |
| 280 | |
| 281 | export const listRules = (parent: string) => |
| 282 | parent.length === 0 |
| 283 | ? emptyList<artifactregistry.GoogleDevtoolsArtifactregistryV1Rule>() |
| 284 | : collectPages( |
| 285 | artifactregistry.listProjectsLocationsRepositoriesRules.pages({ |
| 286 | parent, |
| 287 | pageSize: PAGE_SIZE, |
| 288 | }), |
| 289 | (page) => page.rules, |
| 290 | ); |
| 291 | |
| 292 | export const listAttachments = (parent: string) => |
| 293 | parent.length === 0 |
| 294 | ? emptyList<artifactregistry.Attachment>() |
| 295 | : collectPages( |
| 296 | artifactregistry.listProjectsLocationsRepositoriesAttachments.pages({ |
| 297 | parent, |
| 298 | pageSize: PAGE_SIZE, |
| 299 | }), |
| 300 | (page) => page.attachments, |
| 301 | ); |
| 302 | |
| 303 | export const missingGet = |
| 304 | <A, E extends { readonly _tag: string }, R>( |
| 305 | effect: (input: { name: string }) => Effect.Effect<A, E, R>, |
| 306 | ) => |
| 307 | (name: string) => |
| 308 | name.length === 0 |
| 309 | ? Effect.undefined |
| 310 | : effect({ name }).pipe( |
| 311 | Effect.catchIf( |
| 312 | (error): error is E & { readonly _tag: "NotFound" } => error._tag === "NotFound", |
| 313 | () => Effect.undefined, |
| 314 | ), |
| 315 | ); |
| 316 | |
| 317 | /** Repository and package operations finish within a few minutes. */ |
| 318 | const OPERATION_BUDGET = "10 minutes"; |
| 319 | |
| 320 | /** |
| 321 | * Wait for a long-running operation. ALREADY_EXISTS (code 6) means a |
| 322 | * concurrent create won the race; reconcile observes the resource next. |
| 323 | */ |
| 324 | export const waitForOperation = (operation: LongRunningOperation) => |
| 325 | waitForLongRunning( |
| 326 | operation, |
| 327 | (name) => artifactregistry.getProjectsLocationsOperations({ name }), |
| 328 | { |
| 329 | budget: OPERATION_BUDGET, |
| 330 | }, |
| 331 | ).pipe( |
| 332 | Effect.catchIf( |
| 333 | (error) => error._tag === "GCP.OperationFailed" && error.code === 6, |
| 334 | () => Effect.succeed(operation), |
| 335 | ), |
| 336 | ); |
| 337 | |
| 338 | /** |
| 339 | * Wait for a delete operation. A vanished operation or NOT_FOUND (code 5) |
| 340 | * means the resource is already gone. |
| 341 | */ |
| 342 | export const waitForDeleteOperation = (operation: LongRunningOperation) => |
| 343 | waitForOperation(operation).pipe( |
| 344 | Effect.catchIf( |
| 345 | (error) => |
| 346 | error._tag === "NotFound" || (error._tag === "GCP.OperationFailed" && error.code === 5), |
| 347 | () => Effect.succeed(operation), |
| 348 | ), |
| 349 | ); |