The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as dm from "@distilled.cloud/gcp/datamigration_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 { |
| 9 | alchemyLabelKeys, |
| 10 | createInternalLabels, |
| 11 | hasAlchemyLabels, |
| 12 | stripInternalLabels, |
| 13 | } from "../Labels.ts"; |
| 14 | import { waitForOperation as waitForLongRunning } from "../Operation.ts"; |
| 15 | |
| 16 | export const MAX_NAME_LENGTH = 63; |
| 17 | export const MAX_DISPLAY_NAME_LENGTH = 63; |
| 18 | |
| 19 | export class ResourceNotResolved extends Data.TaggedError("GCP.DataMigration.ResourceNotResolved")<{ |
| 20 | resourceName: string; |
| 21 | }> {} |
| 22 | |
| 23 | export class ResourceStillExists extends Data.TaggedError("GCP.DataMigration.ResourceStillExists")<{ |
| 24 | resourceName: string; |
| 25 | }> {} |
| 26 | |
| 27 | export const lastSegment = (value: string) => { |
| 28 | const trimmed = value.replace(/\/+$/, ""); |
| 29 | const parts = trimmed.split("/"); |
| 30 | return parts[parts.length - 1] || trimmed; |
| 31 | }; |
| 32 | |
| 33 | export const rfc1035 = (name: string, fallback = "dm"): string => { |
| 34 | let next = name |
| 35 | .toLowerCase() |
| 36 | .replace(/[^a-z0-9-]/g, "-") |
| 37 | .replace(/-+/g, "-") |
| 38 | .replace(/^-+|-+$/g, ""); |
| 39 | if (!/^[a-z]/.test(next)) next = `d${next}`; |
| 40 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 41 | if (next.length === 0) return fallback; |
| 42 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; |
| 43 | return next.slice(0, MAX_NAME_LENGTH); |
| 44 | }; |
| 45 | |
| 46 | export const normalizeLocation = (location: string | undefined, defaultLocation: string) => |
| 47 | lastSegment(location ?? defaultLocation).toLowerCase(); |
| 48 | |
| 49 | export const locationParent = (project: string, location: string) => |
| 50 | `projects/${project}/locations/${lastSegment(location).toLowerCase()}`; |
| 51 | |
| 52 | export const parentOfName = (name: string) => { |
| 53 | const parts = name.split("/").filter((part) => part.length > 0); |
| 54 | return parts.slice(0, -2).join("/"); |
| 55 | }; |
| 56 | |
| 57 | export const toPhysicalId = ( |
| 58 | id: string, |
| 59 | explicit: string | undefined, |
| 60 | existing: string | undefined, |
| 61 | fallback = "dm", |
| 62 | ) => |
| 63 | Effect.gen(function* () { |
| 64 | if (explicit !== undefined) return rfc1035(explicit, fallback); |
| 65 | if (existing !== undefined) return existing; |
| 66 | return rfc1035( |
| 67 | yield* createPhysicalName({ |
| 68 | id, |
| 69 | maxLength: MAX_NAME_LENGTH, |
| 70 | lowercase: true, |
| 71 | }), |
| 72 | fallback, |
| 73 | ); |
| 74 | }); |
| 75 | |
| 76 | export const parseName = (name: string, collection: string) => { |
| 77 | const parts = name.split("/").filter((part) => part.length > 0); |
| 78 | const collectionAt = parts.lastIndexOf(collection); |
| 79 | const locationsAt = parts.lastIndexOf("locations"); |
| 80 | const projectsAt = parts.lastIndexOf("projects"); |
| 81 | return { |
| 82 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 83 | location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "", |
| 84 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 85 | parent: |
| 86 | collectionAt > 0 |
| 87 | ? parts.slice(0, collectionAt).join("/") |
| 88 | : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), |
| 89 | }; |
| 90 | }; |
| 91 | |
| 92 | export const expandParent = ( |
| 93 | value: string, |
| 94 | project: string, |
| 95 | location: string, |
| 96 | collection: string, |
| 97 | ) => { |
| 98 | if (value.includes("/")) return value.replace(/\/+$/, ""); |
| 99 | return `projects/${project}/locations/${location}/${collection}/${value}`; |
| 100 | }; |
| 101 | |
| 102 | export const connectionProfileOf = (value: string, project: string, location: string) => |
| 103 | expandParent(value, project, location, "connectionProfiles"); |
| 104 | |
| 105 | export const conversionWorkspaceOf = (value: string, project: string, location: string) => |
| 106 | expandParent(value, project, location, "conversionWorkspaces"); |
| 107 | |
| 108 | export const networkOf = (value: string, project: string) => { |
| 109 | const trimmed = value.replace(/\/+$/, ""); |
| 110 | const projectsAt = trimmed.indexOf("projects/"); |
| 111 | if (projectsAt >= 0) return trimmed.slice(projectsAt); |
| 112 | return `projects/${project}/global/networks/${trimmed}`; |
| 113 | }; |
| 114 | |
| 115 | export const userLabels = ( |
| 116 | labels: Record<string, string | undefined> | null | undefined, |
| 117 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 118 | |
| 119 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 120 | Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 121 | |
| 122 | export const canonical = (value: unknown): unknown => { |
| 123 | if (value === undefined || value === null) return undefined; |
| 124 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 125 | if (typeof value === "string") { |
| 126 | return value.length === 0 ? undefined : value; |
| 127 | } |
| 128 | if (Array.isArray(value)) { |
| 129 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 130 | return items.length === 0 ? undefined : items; |
| 131 | } |
| 132 | if (typeof value === "object") { |
| 133 | const entries = Object.entries(value as Record<string, unknown>) |
| 134 | .map(([key, item]) => [key, canonical(item)] as const) |
| 135 | .filter(([, item]) => item !== undefined) |
| 136 | .sort(([left], [right]) => left.localeCompare(right)); |
| 137 | if (entries.length === 0) return undefined; |
| 138 | return Object.fromEntries(entries); |
| 139 | } |
| 140 | return undefined; |
| 141 | }; |
| 142 | |
| 143 | export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); |
| 144 | |
| 145 | export const fieldMask = (fields: Array<string | false | undefined>) => |
| 146 | fields.filter((field): field is string => typeof field === "string").join(","); |
| 147 | |
| 148 | export const replaceOnIdentity = (input: { |
| 149 | previousId: string | undefined; |
| 150 | nextId: string | undefined; |
| 151 | previousLocation: string; |
| 152 | nextLocation: string; |
| 153 | extra?: boolean; |
| 154 | previousParent?: string; |
| 155 | nextParent?: string; |
| 156 | }) => { |
| 157 | const parentChanged = |
| 158 | (input.previousParent ?? "") !== "" && |
| 159 | (input.nextParent ?? "") !== "" && |
| 160 | (input.previousParent ?? "") !== (input.nextParent ?? ""); |
| 161 | const replace = |
| 162 | (input.extra ?? false) || |
| 163 | parentChanged || |
| 164 | (input.previousId !== undefined && |
| 165 | input.nextId !== undefined && |
| 166 | input.nextId !== input.previousId) || |
| 167 | input.previousLocation !== input.nextLocation; |
| 168 | if (!replace) return undefined; |
| 169 | const samePhysical = |
| 170 | input.previousLocation === input.nextLocation && |
| 171 | !parentChanged && |
| 172 | input.previousId !== undefined && |
| 173 | input.nextId === input.previousId; |
| 174 | return { |
| 175 | action: "replace" as const, |
| 176 | deleteFirst: samePhysical, |
| 177 | }; |
| 178 | }; |
| 179 | |
| 180 | /** |
| 181 | * Wait for a Database Migration Service long-running operation. Cloud SQL / |
| 182 | * AlloyDB destination connection profiles provision a database instance |
| 183 | * (20–40 minutes). |
| 184 | * `ALREADY_EXISTS` (a concurrent create won) always succeeds; |
| 185 | * `notFoundOk` also accepts a `NOT_FOUND` result or an operation that has |
| 186 | * already been garbage-collected (deletes). |
| 187 | */ |
| 188 | export const waitForOperation = (operation: dm.Operation, options?: { notFoundOk?: boolean }) => |
| 189 | waitForLongRunning(operation, (name) => dm.getProjectsLocationsOperations({ name }), { |
| 190 | budget: "45 minutes", |
| 191 | }).pipe( |
| 192 | Effect.catchIf( |
| 193 | (error) => |
| 194 | error._tag === "GCP.OperationFailed" && |
| 195 | (error.code === 6 || (options?.notFoundOk === true && error.code === 5)), |
| 196 | () => Effect.void, |
| 197 | ), |
| 198 | Effect.catchIf( |
| 199 | (error) => options?.notFoundOk === true && error._tag === "NotFound", |
| 200 | () => Effect.void, |
| 201 | ), |
| 202 | ); |
| 203 | |
| 204 | export const waitUntilExists = <A, E extends { readonly _tag: string }, R>( |
| 205 | get: Effect.Effect<A | undefined, E, R>, |
| 206 | name: string, |
| 207 | ) => |
| 208 | get.pipe( |
| 209 | Effect.flatMap((value) => |
| 210 | value ? Effect.succeed(value) : Effect.fail(new ResourceNotResolved({ resourceName: name })), |
| 211 | ), |
| 212 | Effect.retry({ |
| 213 | while: (error) => error._tag === "GCP.DataMigration.ResourceNotResolved", |
| 214 | times: 8, |
| 215 | schedule: Schedule.spaced("1 second"), |
| 216 | }), |
| 217 | ); |
| 218 | |
| 219 | export const waitUntilGone = <A, E extends { readonly _tag: string }, R>( |
| 220 | get: Effect.Effect<A | undefined, E, R>, |
| 221 | name: string, |
| 222 | ) => |
| 223 | get.pipe( |
| 224 | Effect.flatMap((value) => |
| 225 | value === undefined |
| 226 | ? Effect.void |
| 227 | : Effect.fail(new ResourceStillExists({ resourceName: name })), |
| 228 | ), |
| 229 | Effect.retry({ |
| 230 | while: (error) => error._tag === "GCP.DataMigration.ResourceStillExists", |
| 231 | times: 10, |
| 232 | schedule: Schedule.spaced("4 seconds"), |
| 233 | }), |
| 234 | ); |
| 235 | |
| 236 | export const collectPages = <Page, A, E, R>( |
| 237 | pages: Stream.Stream<Page, E, R>, |
| 238 | items: (page: Page) => readonly A[] | undefined, |
| 239 | ) => |
| 240 | pages.pipe( |
| 241 | Stream.flatMap((page) => Stream.fromIterable(items(page) ?? [])), |
| 242 | Stream.runCollect, |
| 243 | Effect.map((chunk) => Array.from(chunk)), |
| 244 | ); |
| 245 | |
| 246 | /** |
| 247 | * List across every location via the `locations/-` wildcard, falling back to |
| 248 | * the default region where the API rejects the wildcard. A missing parent |
| 249 | * (`NotFound`) lists as empty; any other error fails. |
| 250 | */ |
| 251 | export const listAtLocation = <A, E extends { readonly _tag: string }, R>( |
| 252 | project: string, |
| 253 | region: string, |
| 254 | list: (parent: string) => Effect.Effect<A[], E, R>, |
| 255 | ) => |
| 256 | list(`projects/${project}/locations/-`).pipe( |
| 257 | Effect.catchIf( |
| 258 | (error) => error._tag === "NotFound" || error._tag === "BadRequest", |
| 259 | () => |
| 260 | list(`projects/${project}/locations/${region}`).pipe( |
| 261 | Effect.catchIf( |
| 262 | (error) => error._tag === "NotFound", |
| 263 | () => Effect.succeed<A[]>([]), |
| 264 | ), |
| 265 | ), |
| 266 | ), |
| 267 | ); |
| 268 | |
| 269 | export const listConversionWorkspaces = (project: string, region: string) => |
| 270 | collectPages( |
| 271 | dm.listProjectsLocationsConversionWorkspaces.pages({ |
| 272 | parent: `projects/${project}/locations/-`, |
| 273 | pageSize: 1000, |
| 274 | }), |
| 275 | (page) => page.conversionWorkspaces, |
| 276 | ).pipe( |
| 277 | Effect.catchTag("NotFound", () => |
| 278 | collectPages( |
| 279 | dm.listProjectsLocationsConversionWorkspaces.pages({ |
| 280 | parent: locationParent(project, region), |
| 281 | pageSize: 1000, |
| 282 | }), |
| 283 | (page) => page.conversionWorkspaces, |
| 284 | ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as dm.ConversionWorkspace[]))), |
| 285 | ), |
| 286 | ); |
| 287 | |
| 288 | const markerOf = (labels: Record<string, string>, stack: string, stage: string, id: string) => |
| 289 | `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`; |
| 290 | |
| 291 | // `[alc stack stage id]` keeps all three ownership fields when a short |
| 292 | // display name leaves no room for the keyed `[alchemy ...]` form. |
| 293 | const compactMarkerOf = (stack: string, stage: string, id: string) => |
| 294 | `[alc ${stack} ${stage} ${id}]`; |
| 295 | |
| 296 | const COMPACT_BELOW = 54; |
| 297 | |
| 298 | const fitMarker = (labels: Record<string, string>, maxLength: number) => { |
| 299 | const build = (stack: string, stage: string, id: string) => |
| 300 | maxLength < COMPACT_BELOW |
| 301 | ? compactMarkerOf(stack, stage, id) |
| 302 | : markerOf(labels, stack, stage, id); |
| 303 | let stack = labels[alchemyLabelKeys.stack] ?? "x"; |
| 304 | let stage = labels[alchemyLabelKeys.stage] ?? "x"; |
| 305 | let id = labels[alchemyLabelKeys.id] ?? "x"; |
| 306 | let marker = build(stack, stage, id); |
| 307 | while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) { |
| 308 | if (stack.length >= stage.length && stack.length >= id.length) { |
| 309 | stack = stack.slice(0, -1); |
| 310 | } else if (stage.length >= id.length) { |
| 311 | stage = stage.slice(0, -1); |
| 312 | } else { |
| 313 | id = id.slice(0, -1); |
| 314 | } |
| 315 | marker = build(stack, stage, id); |
| 316 | } |
| 317 | return marker.length <= maxLength ? marker : `${marker.slice(0, maxLength - 1)}]`; |
| 318 | }; |
| 319 | |
| 320 | export const encodeOwnership = ( |
| 321 | labels: Record<string, string>, |
| 322 | text: string | undefined, |
| 323 | ): string => { |
| 324 | const marker = fitMarker(labels, 8000); |
| 325 | const trimmed = text?.trim(); |
| 326 | return trimmed && trimmed.length > 0 ? `${marker}\n${trimmed}` : marker; |
| 327 | }; |
| 328 | |
| 329 | export const encodeOwnershipLine = ( |
| 330 | labels: Record<string, string>, |
| 331 | text: string | undefined, |
| 332 | maxLength = MAX_DISPLAY_NAME_LENGTH, |
| 333 | ): string => { |
| 334 | const trimmed = text?.replace(/[\r\n]+/g, " ").trim(); |
| 335 | if (!trimmed) return fitMarker(labels, maxLength); |
| 336 | const minMarker = 16; |
| 337 | const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker)); |
| 338 | const marker = fitMarker(labels, maxLength - reserved); |
| 339 | return `${marker} ${trimmed}`.slice(0, maxLength); |
| 340 | }; |
| 341 | |
| 342 | export const parseOwnership = ( |
| 343 | text: string | undefined, |
| 344 | ): { |
| 345 | labels: Record<string, string>; |
| 346 | text: string | undefined; |
| 347 | } => { |
| 348 | if (text?.startsWith("[alc ")) { |
| 349 | const end = text.indexOf("]"); |
| 350 | if (end < 0) return { labels: {}, text }; |
| 351 | const [stack, stage, id] = text.slice("[alc ".length, end).trim().split(/\s+/); |
| 352 | const labels: Record<string, string> = {}; |
| 353 | if (stack) labels[alchemyLabelKeys.stack] = stack; |
| 354 | if (stage) labels[alchemyLabelKeys.stage] = stage; |
| 355 | if (id) labels[alchemyLabelKeys.id] = id; |
| 356 | const rest = text.slice(end + 1).replace(/^[\s\n]+/, ""); |
| 357 | return { labels, text: rest.length > 0 ? rest : undefined }; |
| 358 | } |
| 359 | if (!text?.startsWith("[alchemy ")) { |
| 360 | return { labels: {}, text }; |
| 361 | } |
| 362 | const end = text.indexOf("]"); |
| 363 | if (end < 0) return { labels: {}, text }; |
| 364 | const labels: Record<string, string> = {}; |
| 365 | for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) { |
| 366 | const eq = part.indexOf("="); |
| 367 | if (eq > 0) { |
| 368 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 369 | } |
| 370 | } |
| 371 | const rest = text.slice(end + 1).replace(/^[\s\n]+/, ""); |
| 372 | return { labels, text: rest.length > 0 ? rest : undefined }; |
| 373 | }; |
| 374 | |
| 375 | export const hasOwnershipMarker = (text: string | undefined) => |
| 376 | Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-")); |
| 377 | |
| 378 | const prefixMatch = (expected: string, observed: string) => |
| 379 | expected === observed || expected.startsWith(observed) || observed.startsWith(expected); |
| 380 | |
| 381 | export const ownedByAlchemy = (id: string, text: string | undefined) => |
| 382 | Effect.gen(function* () { |
| 383 | const expected = yield* createInternalLabels(id); |
| 384 | const { labels } = parseOwnership(text); |
| 385 | if (!hasOwnershipMarker(text)) return false; |
| 386 | const exact = yield* hasAlchemyLabels(id, labels); |
| 387 | if (exact) return true; |
| 388 | return ( |
| 389 | prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") && |
| 390 | prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") && |
| 391 | prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "") |
| 392 | ); |
| 393 | }); |