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 dataproc from "@distilled.cloud/gcp/dataproc_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 { stripInternalLabels } from "../Labels.ts"; |
| 9 | import { waitForOperation as waitForGcpOperation } from "../Operation.ts"; |
| 10 | |
| 11 | export const DEFAULT_ZONE = "us-central1-a"; |
| 12 | export const MAX_POLICY_ID_LENGTH = 50; |
| 13 | // Cluster, batch, and session operations run for minutes; poll for up to ~10 |
| 14 | // minutes (at 5-8s spacing) before giving up. |
| 15 | export const MAX_POLLS = 120; |
| 16 | export const MAX_WORKLOAD_ID_LENGTH = 63; |
| 17 | export const MIN_WORKLOAD_ID_LENGTH = 4; |
| 18 | // Session template ids match `[a-zA-Z0-9][-_a-zA-Z0-9]{1,48}[a-zA-Z0-9]`. |
| 19 | export const MAX_SESSION_TEMPLATE_ID_LENGTH = 50; |
| 20 | // Managed cluster name prefixes match `[a-z]([-a-z0-9]{0,34}[a-z0-9])?`. |
| 21 | export const MAX_MANAGED_CLUSTER_PREFIX_LENGTH = 36; |
| 22 | |
| 23 | export const LIST_LOCATIONS = [ |
| 24 | "us-central1", |
| 25 | "us-east1", |
| 26 | "us-east4", |
| 27 | "us-west1", |
| 28 | "europe-west1", |
| 29 | "asia-east1", |
| 30 | ] as const; |
| 31 | |
| 32 | export class DataprocNotResolved extends Data.TaggedError("GCP.Dataproc.ResourceNotResolved")<{ |
| 33 | resourceName: string; |
| 34 | }> {} |
| 35 | |
| 36 | export class DataprocStillExists extends Data.TaggedError("GCP.Dataproc.ResourceStillExists")<{ |
| 37 | resourceName: string; |
| 38 | }> {} |
| 39 | |
| 40 | export const lastSegment = (value: string) => { |
| 41 | const trimmed = value.replace(/\/+$/, ""); |
| 42 | const parts = trimmed.split("/"); |
| 43 | return parts[parts.length - 1] || trimmed; |
| 44 | }; |
| 45 | |
| 46 | export const normalizeLocation = (location: string | undefined, fallback: string) => |
| 47 | lastSegment(location ?? fallback).toLowerCase(); |
| 48 | |
| 49 | export const locationParent = (project: string, location: string) => |
| 50 | `projects/${project}/locations/${location}`; |
| 51 | |
| 52 | export const regionParent = (project: string, region: string) => |
| 53 | `projects/${project}/regions/${region}`; |
| 54 | |
| 55 | export const parseResourceName = (name: string, collection: string, fallbackLocation: string) => { |
| 56 | const parts = name.split("/").filter((part) => part.length > 0); |
| 57 | const collectionAt = parts.lastIndexOf(collection); |
| 58 | const locationsAt = parts.lastIndexOf("locations"); |
| 59 | const regionsAt = parts.lastIndexOf("regions"); |
| 60 | const projectsAt = parts.lastIndexOf("projects"); |
| 61 | const placeAt = locationsAt >= 0 ? locationsAt : regionsAt; |
| 62 | return { |
| 63 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 64 | location: placeAt >= 0 && parts[placeAt + 1] ? parts[placeAt + 1]! : fallbackLocation, |
| 65 | id: collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 66 | parent: |
| 67 | collectionAt > 0 |
| 68 | ? parts.slice(0, collectionAt).join("/") |
| 69 | : parts.slice(0, Math.max(0, parts.length - 1)).join("/"), |
| 70 | }; |
| 71 | }; |
| 72 | |
| 73 | export const rfc1035 = (name: string, maxLength: number, fallback: string): string => { |
| 74 | let next = name |
| 75 | .toLowerCase() |
| 76 | .replace(/[^a-z0-9-]/g, "-") |
| 77 | .replace(/-+/g, "-") |
| 78 | .replace(/^-+|-+$/g, ""); |
| 79 | if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "d"}${next}`; |
| 80 | next = next.slice(0, maxLength).replace(/-+$/g, ""); |
| 81 | if (next.length === 0) next = fallback; |
| 82 | if (next.length < MIN_WORKLOAD_ID_LENGTH) { |
| 83 | next = `${next}${fallback}xxxx`.slice(0, MIN_WORKLOAD_ID_LENGTH); |
| 84 | } |
| 85 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, maxLength - 1)}0`; |
| 86 | return next.slice(0, maxLength); |
| 87 | }; |
| 88 | |
| 89 | export const toPhysicalId = ( |
| 90 | id: string, |
| 91 | explicit: string | undefined, |
| 92 | existing: string | undefined, |
| 93 | maxLength: number, |
| 94 | fallback: string, |
| 95 | ) => |
| 96 | Effect.gen(function* () { |
| 97 | if (explicit !== undefined) return rfc1035(explicit, maxLength, fallback); |
| 98 | if (existing !== undefined) return existing; |
| 99 | return rfc1035( |
| 100 | yield* createPhysicalName({ |
| 101 | id, |
| 102 | maxLength, |
| 103 | lowercase: true, |
| 104 | }), |
| 105 | maxLength, |
| 106 | fallback, |
| 107 | ); |
| 108 | }); |
| 109 | |
| 110 | export const userLabels = ( |
| 111 | labels: Record<string, string | undefined> | null | undefined, |
| 112 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 113 | |
| 114 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 115 | Object.keys(labels ?? {}).some((key) => key.startsWith("alchemy-")); |
| 116 | |
| 117 | export const canonical = (value: unknown): unknown => { |
| 118 | if (value === undefined || value === null) return undefined; |
| 119 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 120 | if (typeof value === "string") { |
| 121 | return value.length === 0 ? undefined : value; |
| 122 | } |
| 123 | if (Array.isArray(value)) { |
| 124 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 125 | return items.length === 0 ? undefined : items; |
| 126 | } |
| 127 | if (typeof value === "object") { |
| 128 | const entries = Object.entries(value as Record<string, unknown>) |
| 129 | .map(([key, item]) => [key, canonical(item)] as const) |
| 130 | .filter(([, item]) => item !== undefined) |
| 131 | .sort(([left], [right]) => left.localeCompare(right)); |
| 132 | if (entries.length === 0) return undefined; |
| 133 | return Object.fromEntries(entries); |
| 134 | } |
| 135 | return undefined; |
| 136 | }; |
| 137 | |
| 138 | export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); |
| 139 | |
| 140 | export const sameJson = (left: unknown, right: unknown) => fingerprint(left) === fingerprint(right); |
| 141 | |
| 142 | export const collectPages = <Page, Item, E, R>( |
| 143 | stream: Stream.Stream<Page, E, R>, |
| 144 | pick: (page: Page) => readonly Item[] | undefined, |
| 145 | ) => |
| 146 | stream.pipe( |
| 147 | Stream.flatMap((page) => Stream.fromIterable(pick(page) ?? [])), |
| 148 | Stream.runCollect, |
| 149 | Effect.map((chunk) => Array.from(chunk)), |
| 150 | ); |
| 151 | |
| 152 | export const emptyOnMissing = <A, E extends { readonly _tag: string }, R>( |
| 153 | effect: Effect.Effect<A[], E, R>, |
| 154 | ) => |
| 155 | effect.pipe( |
| 156 | Effect.catchIf( |
| 157 | (error) => error._tag === "NotFound", |
| 158 | () => Effect.succeed([] as A[]), |
| 159 | ), |
| 160 | ); |
| 161 | |
| 162 | /** |
| 163 | * Wait for a Dataproc operation. Cluster creates and batch/session |
| 164 | * startups take several minutes (clusters up to ~20). An operation that |
| 165 | * finished with `ALREADY_EXISTS` (6) is a lost create race; `notFoundOk` |
| 166 | * also accepts `NOT_FOUND` (5). |
| 167 | */ |
| 168 | export const waitForOperation = ( |
| 169 | operation: dataproc.Operation, |
| 170 | options?: { notFoundOk?: boolean }, |
| 171 | ) => |
| 172 | waitForGcpOperation( |
| 173 | operation, |
| 174 | (name) => |
| 175 | (name.includes("/regions/") |
| 176 | ? dataproc.getProjectsRegionsOperations({ name }) |
| 177 | : dataproc.getProjectsLocationsOperations({ name }) |
| 178 | ).pipe( |
| 179 | Effect.catchTag("NotFound", (error) => |
| 180 | options?.notFoundOk === true |
| 181 | ? Effect.succeed<dataproc.Operation>({ name, done: true }) |
| 182 | : Effect.fail(error), |
| 183 | ), |
| 184 | ), |
| 185 | { budget: "30 minutes" }, |
| 186 | ).pipe( |
| 187 | Effect.catchIf( |
| 188 | (error) => |
| 189 | error._tag === "GCP.OperationFailed" && |
| 190 | (error.code === 6 || (options?.notFoundOk === true && error.code === 5)), |
| 191 | () => Effect.void, |
| 192 | ), |
| 193 | Effect.asVoid, |
| 194 | ); |
| 195 | |
| 196 | export const waitUntilExists = <A, E extends { readonly _tag: string }, R>( |
| 197 | get: Effect.Effect<A | undefined, E, R>, |
| 198 | name: string, |
| 199 | ) => |
| 200 | get.pipe( |
| 201 | Effect.flatMap((value) => |
| 202 | value ? Effect.succeed(value) : Effect.fail(new DataprocNotResolved({ resourceName: name })), |
| 203 | ), |
| 204 | Effect.retry({ |
| 205 | while: (error) => error._tag === "GCP.Dataproc.ResourceNotResolved", |
| 206 | times: 8, |
| 207 | schedule: Schedule.spaced("1 second"), |
| 208 | }), |
| 209 | ); |
| 210 | |
| 211 | export const waitUntilGone = <A, E extends { readonly _tag: string }, R>( |
| 212 | get: Effect.Effect<A | undefined, E, R>, |
| 213 | name: string, |
| 214 | ) => |
| 215 | get.pipe( |
| 216 | Effect.flatMap((value) => |
| 217 | value === undefined |
| 218 | ? Effect.void |
| 219 | : Effect.fail(new DataprocStillExists({ resourceName: name })), |
| 220 | ), |
| 221 | Effect.retry({ |
| 222 | while: (error) => error._tag === "GCP.Dataproc.ResourceStillExists", |
| 223 | times: MAX_POLLS, |
| 224 | schedule: Schedule.spaced("5 seconds"), |
| 225 | }), |
| 226 | ); |
| 227 | |
| 228 | export const defaultYarnConfig = (): dataproc.BasicYarnAutoscalingConfig => ({ |
| 229 | gracefulDecommissionTimeout: "3600s", |
| 230 | scaleUpFactor: 0.5, |
| 231 | scaleDownFactor: 0, |
| 232 | scaleUpMinWorkerFraction: 0, |
| 233 | scaleDownMinWorkerFraction: 0, |
| 234 | }); |
| 235 | |
| 236 | export const defaultWorkerConfig = (): dataproc.InstanceGroupAutoscalingPolicyConfig => ({ |
| 237 | minInstances: 2, |
| 238 | maxInstances: 3, |
| 239 | weight: 1, |
| 240 | }); |
| 241 | |
| 242 | export const defaultSparkBatch = (): dataproc.SparkBatch => ({ |
| 243 | mainClass: "org.apache.spark.examples.SparkPi", |
| 244 | jarFileUris: ["file:///usr/lib/spark/examples/jars/spark-examples.jar"], |
| 245 | args: ["1"], |
| 246 | }); |
| 247 | |
| 248 | export const defaultWorkflowJobs = (): dataproc.OrderedJobList => [ |
| 249 | { |
| 250 | stepId: "spark-pi", |
| 251 | sparkJob: defaultSparkBatch(), |
| 252 | }, |
| 253 | ]; |
| 254 | |
| 255 | export const defaultWorkflowPlacement = ( |
| 256 | clusterName: string, |
| 257 | ): dataproc.WorkflowTemplatePlacement => ({ |
| 258 | managedCluster: { |
| 259 | clusterName, |
| 260 | config: { |
| 261 | gceClusterConfig: { zoneUri: DEFAULT_ZONE }, |
| 262 | masterConfig: { |
| 263 | numInstances: 1, |
| 264 | machineTypeUri: "n1-standard-2", |
| 265 | diskConfig: { bootDiskSizeGb: 30 }, |
| 266 | }, |
| 267 | workerConfig: { numInstances: 2 }, |
| 268 | softwareConfig: { imageVersion: "2.2-debian12" }, |
| 269 | }, |
| 270 | }, |
| 271 | }); |