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, 04:45 UTC
| 1 | import * as servicedirectory from "@distilled.cloud/gcp/servicedirectory_v1"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { tagRecord } from "alchemy/Tags"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import { GcpEnvironment } from "../Environment.ts"; |
| 12 | import { |
| 13 | createInternalLabels, |
| 14 | diffLabels, |
| 15 | hasAlchemyLabels, |
| 16 | stripInternalLabels, |
| 17 | toLabels, |
| 18 | } from "../Labels.ts"; |
| 19 | import type { Providers } from "../Providers.ts"; |
| 20 | |
| 21 | const MAX_NAMESPACE_ID_LENGTH = 63; |
| 22 | |
| 23 | export type NamespaceProps = { |
| 24 | /** |
| 25 | * Namespace id (the `{namespace}` segment of |
| 26 | * `projects/{project}/locations/{location}/namespaces/{namespace}`). |
| 27 | * If omitted, a unique name is generated from the stack, stage, and |
| 28 | * logical id. Must be 1-63 characters and match |
| 29 | * `[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`. Immutable — changing it |
| 30 | * replaces the namespace. |
| 31 | */ |
| 32 | namespaceId?: string; |
| 33 | /** |
| 34 | * Location of the namespace (e.g. `us-central1`). Immutable — changing |
| 35 | * it replaces the namespace. `US-CENTRAL1` is accepted and normalized |
| 36 | * to `us-central1`. |
| 37 | * @default the stack's GCP region (`GCP.Region`, else the profile |
| 38 | * region, else `us-central1`) |
| 39 | */ |
| 40 | location?: string; |
| 41 | /** |
| 42 | * User labels. Alchemy ownership labels are merged in automatically. |
| 43 | */ |
| 44 | labels?: Record<string, string>; |
| 45 | }; |
| 46 | |
| 47 | export type Namespace = Resource< |
| 48 | "GCP.ServiceDirectory.Namespace", |
| 49 | NamespaceProps, |
| 50 | { |
| 51 | /** Full resource name `projects/{project}/locations/{location}/namespaces/{namespace}`. */ |
| 52 | name: string; |
| 53 | /** Namespace id (last path segment). */ |
| 54 | namespaceId: string; |
| 55 | /** Project id. */ |
| 56 | project: string; |
| 57 | /** Location id (e.g. `us-central1`). */ |
| 58 | location: string; |
| 59 | /** User labels (Alchemy ownership labels stripped). */ |
| 60 | labels: Record<string, string>; |
| 61 | /** Server-assigned UUID4. */ |
| 62 | uid: string | undefined; |
| 63 | }, |
| 64 | never, |
| 65 | Providers |
| 66 | >; |
| 67 | |
| 68 | /** |
| 69 | * A Service Directory namespace — a location-scoped container for |
| 70 | * services. |
| 71 | * |
| 72 | * Changing `namespaceId` or `location` replaces the namespace. |
| 73 | * |
| 74 | * ### Creating a Namespace |
| 75 | * **Example:** Generated name |
| 76 | * ```typescript |
| 77 | * const services = yield* GCP.ServiceDirectory.Namespace("Services", {}); |
| 78 | * ``` |
| 79 | * |
| 80 | * **Example:** Explicit id, location, and labels |
| 81 | * ```typescript |
| 82 | * const services = yield* GCP.ServiceDirectory.Namespace("Services", { |
| 83 | * namespaceId: "app-services", |
| 84 | * location: "us-central1", |
| 85 | * labels: { env: "prod" }, |
| 86 | * }); |
| 87 | * ``` |
| 88 | * |
| 89 | * @resource |
| 90 | * @category ServiceDirectory |
| 91 | */ |
| 92 | export const Namespace = Resource<Namespace>("GCP.ServiceDirectory.Namespace"); |
| 93 | |
| 94 | export class NamespaceNotResolved extends Data.TaggedError( |
| 95 | "GCP.ServiceDirectory.NamespaceNotResolved", |
| 96 | )<{ |
| 97 | resourceName: string; |
| 98 | }> {} |
| 99 | |
| 100 | const lastSegment = (value: string) => { |
| 101 | const trimmed = value.replace(/\/+$/, ""); |
| 102 | const parts = trimmed.split("/"); |
| 103 | return parts[parts.length - 1] || trimmed; |
| 104 | }; |
| 105 | |
| 106 | const normalizeLocation = (location: string | undefined, defaultLocation: string) => |
| 107 | lastSegment(location ?? defaultLocation).toLowerCase(); |
| 108 | |
| 109 | const resourceName = (project: string, location: string, namespaceId: string) => |
| 110 | `projects/${project}/locations/${location}/namespaces/${namespaceId}`; |
| 111 | |
| 112 | const locationParent = (project: string, location: string) => |
| 113 | `projects/${project}/locations/${location}`; |
| 114 | |
| 115 | const parseName = (name: string, defaultLocation: string) => { |
| 116 | const parts = name.split("/").filter((part) => part.length > 0); |
| 117 | const namespacesAt = parts.lastIndexOf("namespaces"); |
| 118 | const locationsAt = parts.lastIndexOf("locations"); |
| 119 | const projectsAt = parts.lastIndexOf("projects"); |
| 120 | return { |
| 121 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 122 | location: |
| 123 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : defaultLocation, |
| 124 | namespaceId: |
| 125 | namespacesAt >= 0 && parts[namespacesAt + 1] ? parts[namespacesAt + 1]! : lastSegment(name), |
| 126 | }; |
| 127 | }; |
| 128 | |
| 129 | const userLabels = ( |
| 130 | labels: Record<string, string | undefined> | null | undefined, |
| 131 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 132 | |
| 133 | const toId = (id: string, namespaceId: string | undefined, existing?: string) => |
| 134 | Effect.gen(function* () { |
| 135 | if (namespaceId !== undefined) return namespaceId; |
| 136 | if (existing !== undefined) return existing; |
| 137 | const generated = yield* createPhysicalName({ |
| 138 | id, |
| 139 | maxLength: MAX_NAMESPACE_ID_LENGTH, |
| 140 | lowercase: true, |
| 141 | forbiddenPrefixes: ["gcp"], |
| 142 | }); |
| 143 | const named = /^[a-z]/.test(generated) ? generated : `n${generated}`; |
| 144 | return named.replace(/-+$/g, "").slice(0, MAX_NAMESPACE_ID_LENGTH).replace(/-+$/g, ""); |
| 145 | }); |
| 146 | |
| 147 | const toAttrs = (namespace: servicedirectory.Namespace, project: string, region: string) => { |
| 148 | const name = namespace.name ?? ""; |
| 149 | const parsed = parseName(name, region); |
| 150 | return { |
| 151 | name, |
| 152 | namespaceId: parsed.namespaceId, |
| 153 | project: parsed.project || project, |
| 154 | location: parsed.location, |
| 155 | labels: userLabels(namespace.labels), |
| 156 | uid: namespace.uid, |
| 157 | }; |
| 158 | }; |
| 159 | |
| 160 | const getByName = (name: string) => |
| 161 | servicedirectory |
| 162 | .getProjectsLocationsNamespaces({ name }) |
| 163 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 164 | |
| 165 | const listNamespacesAt = (parent: string, project: string, region: string) => |
| 166 | Effect.gen(function* () { |
| 167 | const found: ReturnType<typeof toAttrs>[] = []; |
| 168 | let pageToken: string | undefined; |
| 169 | do { |
| 170 | const response = yield* servicedirectory.listProjectsLocationsNamespaces({ |
| 171 | parent, |
| 172 | pageSize: 1000, |
| 173 | pageToken, |
| 174 | }); |
| 175 | for (const namespace of response.namespaces ?? []) { |
| 176 | if (Object.keys(namespace.labels ?? {}).some((key) => key.startsWith("alchemy-"))) { |
| 177 | found.push(toAttrs(namespace, project, region)); |
| 178 | } |
| 179 | } |
| 180 | pageToken = response.nextPageToken; |
| 181 | } while (pageToken !== undefined && pageToken !== ""); |
| 182 | return found; |
| 183 | }).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as ReturnType<typeof toAttrs>[]))); |
| 184 | |
| 185 | export const NamespaceProvider = () => |
| 186 | Provider.succeed(Namespace, { |
| 187 | stables: ["name", "namespaceId", "project", "location", "uid"], |
| 188 | |
| 189 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 190 | if (!isResolved(news)) return undefined; |
| 191 | const env = yield* GcpEnvironment.current; |
| 192 | const previousId = olds?.namespaceId ?? output?.namespaceId; |
| 193 | const nextId = news.namespaceId ?? previousId; |
| 194 | const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId; |
| 195 | |
| 196 | const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 197 | const nextLocation = normalizeLocation(news.location ?? output?.location, env.region); |
| 198 | if (idChanged || previousLocation !== nextLocation) { |
| 199 | return { action: "replace" as const }; |
| 200 | } |
| 201 | return undefined; |
| 202 | }), |
| 203 | |
| 204 | read: Effect.fn(function* ({ id, olds, output }) { |
| 205 | const env = yield* GcpEnvironment.current; |
| 206 | const namespaceId = yield* toId(id, olds?.namespaceId, output?.namespaceId); |
| 207 | const location = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 208 | const name = output?.name ?? resourceName(env.project, location, namespaceId); |
| 209 | const existing = yield* getByName(name); |
| 210 | if (existing === undefined) return undefined; |
| 211 | const attrs = toAttrs(existing, env.project, env.region); |
| 212 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 213 | }), |
| 214 | |
| 215 | list: () => |
| 216 | Effect.gen(function* () { |
| 217 | const env = yield* GcpEnvironment.current; |
| 218 | const fallback = [locationParent(env.project, env.region)]; |
| 219 | const found: ReturnType<typeof toAttrs>[] = []; |
| 220 | let pageToken: string | undefined; |
| 221 | do { |
| 222 | const response = yield* servicedirectory |
| 223 | .listProjectsLocations({ |
| 224 | name: `projects/${env.project}`, |
| 225 | pageSize: 100, |
| 226 | pageToken, |
| 227 | }) |
| 228 | .pipe( |
| 229 | Effect.catchTag("NotFound", () => |
| 230 | Effect.succeed({ |
| 231 | locations: [ |
| 232 | { |
| 233 | name: fallback[0], |
| 234 | locationId: env.region, |
| 235 | } satisfies servicedirectory.Location, |
| 236 | ], |
| 237 | nextPageToken: undefined as string | undefined, |
| 238 | }), |
| 239 | ), |
| 240 | ); |
| 241 | const parents = (response.locations ?? []) |
| 242 | .map((location) => location.name) |
| 243 | .filter((name): name is string => !!name); |
| 244 | const pages = yield* Effect.forEach( |
| 245 | parents.length > 0 ? parents : fallback, |
| 246 | (parent) => listNamespacesAt(parent, env.project, env.region), |
| 247 | { concurrency: 4 }, |
| 248 | ); |
| 249 | for (const namespaces of pages) { |
| 250 | found.push(...namespaces); |
| 251 | } |
| 252 | pageToken = response.nextPageToken; |
| 253 | } while (pageToken !== undefined && pageToken !== ""); |
| 254 | return found; |
| 255 | }), |
| 256 | |
| 257 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 258 | const env = yield* GcpEnvironment.current; |
| 259 | const namespaceId = yield* toId(id, news.namespaceId, output?.namespaceId); |
| 260 | const location = normalizeLocation(news.location ?? output?.location, env.region); |
| 261 | const name = resourceName(env.project, location, namespaceId); |
| 262 | const desiredLabels = { |
| 263 | ...toLabels(news.labels), |
| 264 | ...(yield* createInternalLabels(id)), |
| 265 | }; |
| 266 | |
| 267 | let current = yield* getByName(name); |
| 268 | |
| 269 | if (current === undefined) { |
| 270 | const created = yield* servicedirectory |
| 271 | .createProjectsLocationsNamespaces({ |
| 272 | parent: locationParent(env.project, location), |
| 273 | namespaceId, |
| 274 | body: { |
| 275 | labels: desiredLabels, |
| 276 | }, |
| 277 | }) |
| 278 | .pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 279 | current = created ?? undefined; |
| 280 | } |
| 281 | |
| 282 | if (current === undefined) { |
| 283 | return yield* new NamespaceNotResolved({ resourceName: name }); |
| 284 | } |
| 285 | |
| 286 | const observedLabels = tagRecord(current.labels); |
| 287 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 288 | if (upsert.length > 0 || removed.length > 0) { |
| 289 | current = yield* servicedirectory.patchProjectsLocationsNamespaces({ |
| 290 | name, |
| 291 | updateMask: "labels", |
| 292 | body: { |
| 293 | name, |
| 294 | labels: desiredLabels, |
| 295 | }, |
| 296 | }); |
| 297 | } |
| 298 | |
| 299 | return toAttrs(current, env.project, env.region); |
| 300 | }), |
| 301 | |
| 302 | delete: Effect.fn(function* ({ output }) { |
| 303 | yield* servicedirectory.deleteProjectsLocationsNamespaces({ name: output.name }).pipe( |
| 304 | Effect.retry({ |
| 305 | while: (error) => error._tag === "Conflict", |
| 306 | times: 8, |
| 307 | schedule: Schedule.spaced("1 second"), |
| 308 | }), |
| 309 | Effect.catchTag("NotFound", () => Effect.void), |
| 310 | ); |
| 311 | }), |
| 312 | }); |