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 rma from "@distilled.cloud/gcp/rapidmigrationassessment_v1"; |
| 2 | import { Retry as GcpRetry } from "@distilled.cloud/gcp/Retry"; |
| 3 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 4 | import { tagRecord } from "alchemy/Tags"; |
| 5 | import * as Data from "effect/Data"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { stripInternalLabels } from "../Labels.ts"; |
| 11 | import { waitForOperation as waitForGcpOperation } from "../Operation.ts"; |
| 12 | |
| 13 | const noRetryLayer = Layer.succeed(GcpRetry, { while: () => false }); |
| 14 | |
| 15 | export const MAX_NAME_LENGTH = 63; |
| 16 | |
| 17 | export class ResourceNotResolved extends Data.TaggedError( |
| 18 | "GCP.RapidMigrationAssessment.ResourceNotResolved", |
| 19 | )<{ |
| 20 | resourceName: string; |
| 21 | }> {} |
| 22 | |
| 23 | export class ResourceStillExists extends Data.TaggedError( |
| 24 | "GCP.RapidMigrationAssessment.ResourceStillExists", |
| 25 | )<{ |
| 26 | resourceName: string; |
| 27 | }> {} |
| 28 | |
| 29 | export class ResourceNotReady extends Data.TaggedError( |
| 30 | "GCP.RapidMigrationAssessment.ResourceNotReady", |
| 31 | )<{ |
| 32 | resourceName: string; |
| 33 | state: string; |
| 34 | }> {} |
| 35 | |
| 36 | export class ResourceFailed extends Data.TaggedError( |
| 37 | "GCP.RapidMigrationAssessment.ResourceFailed", |
| 38 | )<{ |
| 39 | resourceName: string; |
| 40 | state: string; |
| 41 | }> {} |
| 42 | |
| 43 | export const lastSegment = (value: string) => { |
| 44 | const trimmed = value.replace(/\/+$/, ""); |
| 45 | const parts = trimmed.split("/"); |
| 46 | return parts[parts.length - 1] || trimmed; |
| 47 | }; |
| 48 | |
| 49 | export const rfc1035 = (name: string, fallback = "collector"): string => { |
| 50 | let next = name |
| 51 | .toLowerCase() |
| 52 | .replace(/[^a-z0-9-]/g, "-") |
| 53 | .replace(/-+/g, "-") |
| 54 | .replace(/^-+|-+$/g, ""); |
| 55 | if (!/^[a-z]/.test(next)) next = `c${next}`; |
| 56 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 57 | if (next.length === 0) return fallback; |
| 58 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; |
| 59 | return next.slice(0, MAX_NAME_LENGTH); |
| 60 | }; |
| 61 | |
| 62 | export const normalizeLocation = (location: string | undefined, defaultLocation: string) => |
| 63 | lastSegment(location ?? defaultLocation).toLowerCase(); |
| 64 | |
| 65 | export const locationParent = (project: string, location: string) => |
| 66 | `projects/${project}/locations/${lastSegment(location).toLowerCase()}`; |
| 67 | |
| 68 | export const toPhysicalId = ( |
| 69 | id: string, |
| 70 | explicit: string | undefined, |
| 71 | existing: string | undefined, |
| 72 | fallback = "collector", |
| 73 | ) => |
| 74 | Effect.gen(function* () { |
| 75 | if (explicit !== undefined) return rfc1035(explicit, fallback); |
| 76 | if (existing !== undefined) return existing; |
| 77 | return rfc1035( |
| 78 | yield* createPhysicalName({ |
| 79 | id, |
| 80 | maxLength: MAX_NAME_LENGTH, |
| 81 | lowercase: true, |
| 82 | }), |
| 83 | fallback, |
| 84 | ); |
| 85 | }); |
| 86 | |
| 87 | export const parseName = (name: string, collection = "collectors") => { |
| 88 | const parts = name.split("/").filter((part) => part.length > 0); |
| 89 | const collectionAt = parts.lastIndexOf(collection); |
| 90 | const locationsAt = parts.lastIndexOf("locations"); |
| 91 | const projectsAt = parts.lastIndexOf("projects"); |
| 92 | return { |
| 93 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 94 | location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "", |
| 95 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 96 | }; |
| 97 | }; |
| 98 | |
| 99 | export const userLabels = ( |
| 100 | labels: Record<string, string | undefined> | null | undefined, |
| 101 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 102 | |
| 103 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 104 | Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 105 | |
| 106 | export const expectedAssetCountOf = (value: number | string | undefined): string | undefined => |
| 107 | value === undefined ? undefined : String(value); |
| 108 | |
| 109 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 110 | (left ?? "") === (right ?? ""); |
| 111 | |
| 112 | export const sameNumber = (left: number | undefined, right: number | undefined) => |
| 113 | (left ?? 0) === (right ?? 0); |
| 114 | |
| 115 | export const fieldMask = (fields: Array<string | false | undefined>) => |
| 116 | fields.filter((field): field is string => typeof field === "string").join(","); |
| 117 | |
| 118 | export const replaceOnIdentity = (input: { |
| 119 | previousId: string | undefined; |
| 120 | nextId: string | undefined; |
| 121 | previousLocation: string; |
| 122 | nextLocation: string; |
| 123 | }) => { |
| 124 | const replace = |
| 125 | (input.previousId !== undefined && |
| 126 | input.nextId !== undefined && |
| 127 | input.nextId !== input.previousId) || |
| 128 | input.previousLocation !== input.nextLocation; |
| 129 | if (!replace) return undefined; |
| 130 | const samePhysical = |
| 131 | input.previousLocation === input.nextLocation && |
| 132 | input.previousId !== undefined && |
| 133 | input.nextId === input.previousId; |
| 134 | return { |
| 135 | action: "replace" as const, |
| 136 | deleteFirst: samePhysical, |
| 137 | }; |
| 138 | }; |
| 139 | |
| 140 | const READY_STATES = new Set([ |
| 141 | "STATE_READY_TO_USE", |
| 142 | "STATE_REGISTERED", |
| 143 | "STATE_ACTIVE", |
| 144 | "STATE_PAUSED", |
| 145 | ]); |
| 146 | |
| 147 | const FAILED_STATES = new Set(["STATE_ERROR"]); |
| 148 | |
| 149 | const GONE_STATES = new Set(["STATE_DECOMMISSIONED"]); |
| 150 | |
| 151 | export const isReadyState = (state: string | undefined) => |
| 152 | READY_STATES.has((state ?? "").toUpperCase()); |
| 153 | |
| 154 | export const isFailedState = (state: string | undefined) => |
| 155 | FAILED_STATES.has((state ?? "").toUpperCase()); |
| 156 | |
| 157 | export const isGoneState = (state: string | undefined) => |
| 158 | GONE_STATES.has((state ?? "").toUpperCase()); |
| 159 | |
| 160 | export const isPausedState = (state: string | undefined) => |
| 161 | (state ?? "").toUpperCase() === "STATE_PAUSED"; |
| 162 | |
| 163 | export const isRegisteredState = (state: string | undefined) => { |
| 164 | const next = (state ?? "").toUpperCase(); |
| 165 | return next === "STATE_REGISTERED" || next === "STATE_ACTIVE" || next === "STATE_PAUSED"; |
| 166 | }; |
| 167 | |
| 168 | /** |
| 169 | * Wait for a Rapid Migration Assessment collector operation. An operation |
| 170 | * that finished with `ALREADY_EXISTS` (6) is a lost create race; |
| 171 | * `notFoundOk` also accepts `NOT_FOUND` (5). |
| 172 | */ |
| 173 | export const waitForOperation = (operation: rma.Operation, options?: { notFoundOk?: boolean }) => |
| 174 | waitForGcpOperation( |
| 175 | operation, |
| 176 | (name) => |
| 177 | rma |
| 178 | .getProjectsLocationsOperations({ name }) |
| 179 | .pipe( |
| 180 | Effect.catchTag("NotFound", (error) => |
| 181 | options?.notFoundOk === true |
| 182 | ? Effect.succeed<rma.Operation>({ name, done: true }) |
| 183 | : Effect.fail(error), |
| 184 | ), |
| 185 | ), |
| 186 | { budget: "10 minutes" }, |
| 187 | ).pipe( |
| 188 | Effect.catchIf( |
| 189 | (error) => |
| 190 | error._tag === "GCP.OperationFailed" && |
| 191 | (error.code === 6 || (options?.notFoundOk === true && error.code === 5)), |
| 192 | () => Effect.void, |
| 193 | ), |
| 194 | Effect.asVoid, |
| 195 | ); |
| 196 | |
| 197 | export const waitUntilExists = <A, E extends { readonly _tag: string }, R>( |
| 198 | get: Effect.Effect<A | undefined, E, R>, |
| 199 | name: string, |
| 200 | ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved, R> => |
| 201 | get.pipe( |
| 202 | Effect.filterOrFail( |
| 203 | (value): value is NonNullable<A> => value != null, |
| 204 | () => new ResourceNotResolved({ resourceName: name }), |
| 205 | ), |
| 206 | Effect.retry({ |
| 207 | while: (error) => error._tag === "GCP.RapidMigrationAssessment.ResourceNotResolved", |
| 208 | times: 8, |
| 209 | schedule: Schedule.spaced("1 second"), |
| 210 | }), |
| 211 | ); |
| 212 | |
| 213 | export const waitUntilGone = <A, E extends { readonly _tag: string }, R>( |
| 214 | get: Effect.Effect<A | undefined, E, R>, |
| 215 | name: string, |
| 216 | ): Effect.Effect<void, E | ResourceStillExists, R> => |
| 217 | get.pipe( |
| 218 | Effect.filterOrFail( |
| 219 | (value) => value === undefined, |
| 220 | () => new ResourceStillExists({ resourceName: name }), |
| 221 | ), |
| 222 | Effect.retry({ |
| 223 | while: (error) => error._tag === "GCP.RapidMigrationAssessment.ResourceStillExists", |
| 224 | times: 10, |
| 225 | schedule: Schedule.spaced("5 seconds"), |
| 226 | }), |
| 227 | Effect.asVoid, |
| 228 | ); |
| 229 | |
| 230 | export const waitUntilReady = <A, E extends { readonly _tag: string }, R>( |
| 231 | get: Effect.Effect<A | undefined, E, R>, |
| 232 | name: string, |
| 233 | stateOf: (value: NonNullable<A>) => string | undefined, |
| 234 | ): Effect.Effect<NonNullable<A>, E | ResourceNotResolved | ResourceFailed | ResourceNotReady, R> => |
| 235 | get.pipe( |
| 236 | Effect.filterOrFail( |
| 237 | (value): value is NonNullable<A> => value != null, |
| 238 | () => new ResourceNotResolved({ resourceName: name }), |
| 239 | ), |
| 240 | Effect.filterOrFail( |
| 241 | (value) => !isFailedState(stateOf(value)), |
| 242 | (value) => |
| 243 | new ResourceFailed({ |
| 244 | resourceName: name, |
| 245 | state: stateOf(value) ?? "", |
| 246 | }), |
| 247 | ), |
| 248 | Effect.filterOrFail( |
| 249 | (value) => { |
| 250 | const state = stateOf(value) ?? ""; |
| 251 | return isReadyState(state) || state.length === 0; |
| 252 | }, |
| 253 | (value) => new ResourceNotReady({ resourceName: name, state: stateOf(value) ?? "" }), |
| 254 | ), |
| 255 | Effect.retry({ |
| 256 | while: (error) => |
| 257 | error._tag === "GCP.RapidMigrationAssessment.ResourceNotReady" || |
| 258 | error._tag === "GCP.RapidMigrationAssessment.ResourceNotResolved", |
| 259 | times: 10, |
| 260 | schedule: Schedule.spaced("3 seconds"), |
| 261 | }), |
| 262 | ); |
| 263 | |
| 264 | const emptyCollectors = Effect.succeed<rma.Collector[]>([]); |
| 265 | |
| 266 | export const listCollectors = (parent: string) => |
| 267 | parent.length === 0 |
| 268 | ? emptyCollectors |
| 269 | : rma.listProjectsLocationsCollectors.pages({ parent, pageSize: 1000 }).pipe( |
| 270 | Stream.flatMap((page) => Stream.fromIterable(page.collectors ?? [])), |
| 271 | Stream.filter((item) => hasAlchemyLabelMap(item.labels)), |
| 272 | Stream.runCollect, |
| 273 | Effect.map((chunk) => Array.from(chunk)), |
| 274 | Effect.provide(noRetryLayer), |
| 275 | Effect.catchTag("NotFound", () => emptyCollectors), |
| 276 | ); |
| 277 | |
| 278 | export const listOwnedCollectors = (project: string, _region: string) => |
| 279 | listCollectors(`projects/${project}/locations/-`); |