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 networkconnectivity from "@distilled.cloud/gcp/networkconnectivity_v1"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import { tagRecord } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import { GcpEnvironment } from "../Environment.ts"; |
| 10 | import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts"; |
| 11 | import type { Providers } from "../Providers.ts"; |
| 12 | import { |
| 13 | NetworkConnectivityNotResolved, |
| 14 | canonicalizeLink, |
| 15 | changedFields, |
| 16 | collectPages, |
| 17 | hasAlchemyLabelKeys, |
| 18 | lastSegment, |
| 19 | normalizeLocation, |
| 20 | parentOf, |
| 21 | parseName, |
| 22 | rfc1035, |
| 23 | sameJson, |
| 24 | toNetworkResource, |
| 25 | toPhysicalId, |
| 26 | toSubnetworkResource, |
| 27 | userLabels, |
| 28 | waitForOperation, |
| 29 | waitUntilGone, |
| 30 | waitUntilPresent, |
| 31 | } from "./internal.ts"; |
| 32 | |
| 33 | const COLLECTION = "serviceConnectionPolicies"; |
| 34 | |
| 35 | export type ServiceConnectionPolicySubnetworkMode = |
| 36 | | networkconnectivity.CreateProjectsLocationsServiceConnectionPoliciesSubnetworkModeEnum |
| 37 | | (string & {}); |
| 38 | export type ServiceConnectionPolicyIpStack = |
| 39 | | networkconnectivity.CreateProjectsLocationsServiceConnectionPoliciesAutoSubnetworkConfig_ipStackEnum |
| 40 | | (string & {}); |
| 41 | export type PscConfigProducerInstanceLocation = |
| 42 | | networkconnectivity.PscConfigProducerInstanceLocationEnum |
| 43 | | (string & {}); |
| 44 | |
| 45 | export type PscConfig = { |
| 46 | /** |
| 47 | * Subnetwork resource paths used for IPAM |
| 48 | * (`projects/{project}/regions/{region}/subnetworks/{subnetwork}`). |
| 49 | */ |
| 50 | subnetworks?: string[]; |
| 51 | /** |
| 52 | * Max number of PSC connections for this policy (int64 string). |
| 53 | */ |
| 54 | limit?: string; |
| 55 | /** |
| 56 | * Authorization mechanism for producer instance location. |
| 57 | */ |
| 58 | producerInstanceLocation?: PscConfigProducerInstanceLocation; |
| 59 | /** |
| 60 | * Projects, folders, or organizations the producer instance may live |
| 61 | * in, e.g. `"projects/my-project"`. |
| 62 | */ |
| 63 | allowedGoogleProducersResourceHierarchyLevel?: string[]; |
| 64 | }; |
| 65 | |
| 66 | export type AutoSubnetworkConfig = { |
| 67 | /** Requested IP stack. */ |
| 68 | ipStack?: ServiceConnectionPolicyIpStack; |
| 69 | /** Desired prefix length for the auto-created subnet. */ |
| 70 | prefixLength?: number; |
| 71 | /** CIDR spaces to search for a free range. */ |
| 72 | allocRangeSpace?: string[]; |
| 73 | }; |
| 74 | |
| 75 | export type AutoCreatedSubnetworkInfo = { |
| 76 | internalRange?: string; |
| 77 | internalRangeRef?: string; |
| 78 | subnetwork?: string; |
| 79 | subnetworkRef?: string; |
| 80 | delinked?: boolean; |
| 81 | }; |
| 82 | |
| 83 | export type ServiceConnectionPolicyProps = { |
| 84 | /** |
| 85 | * Policy id (the `{service_connection_policy}` segment). If omitted, a |
| 86 | * unique name is generated. Immutable — changing it replaces the |
| 87 | * policy. |
| 88 | */ |
| 89 | serviceConnectionPolicyId?: string; |
| 90 | /** |
| 91 | * Location (`us-central1`, …). Immutable — changing it replaces the |
| 92 | * policy. `US-CENTRAL1` is accepted and normalized to `us-central1`. |
| 93 | * @default the stack's GCP region (`GCP.Region`, else the profile |
| 94 | * region, else `us-central1`) |
| 95 | */ |
| 96 | location?: string; |
| 97 | /** |
| 98 | * Consumer VPC |
| 99 | * (`projects/{project}/global/networks/{network}` or a Compute |
| 100 | * self-link). Immutable — changing it replaces the policy. |
| 101 | */ |
| 102 | network: string; |
| 103 | /** |
| 104 | * Service class identifier, e.g. `"gcp-memorystore-redis"` or |
| 105 | * `"gcp-cloud-sql"`. |
| 106 | */ |
| 107 | serviceClass: string; |
| 108 | /** |
| 109 | * PSC connection configuration (subnets, connection limit, …). |
| 110 | */ |
| 111 | pscConfig?: PscConfig; |
| 112 | /** |
| 113 | * Subnetwork mode. `USER_PROVIDED` uses `pscConfig.subnetworks`; |
| 114 | * `AUTO_CREATED` allocates a subnet from `autoSubnetworkConfig`. |
| 115 | * Create-only. |
| 116 | */ |
| 117 | subnetworkMode?: ServiceConnectionPolicySubnetworkMode; |
| 118 | /** |
| 119 | * Auto-created subnet options. Create-only; used when |
| 120 | * `subnetworkMode` is `AUTO_CREATED`. |
| 121 | */ |
| 122 | autoSubnetworkConfig?: AutoSubnetworkConfig; |
| 123 | /** |
| 124 | * Human-readable description. |
| 125 | */ |
| 126 | description?: string; |
| 127 | /** |
| 128 | * User labels. Alchemy ownership labels are merged in automatically. |
| 129 | */ |
| 130 | labels?: Record<string, string>; |
| 131 | }; |
| 132 | |
| 133 | export type ServiceConnectionPolicy = Resource< |
| 134 | "GCP.NetworkConnectivity.ServiceConnectionPolicy", |
| 135 | ServiceConnectionPolicyProps, |
| 136 | { |
| 137 | /** Full resource name `projects/{project}/locations/{location}/serviceConnectionPolicies/{id}`. */ |
| 138 | name: string; |
| 139 | /** Policy id (last path segment). */ |
| 140 | serviceConnectionPolicyId: string; |
| 141 | /** Project id. */ |
| 142 | project: string; |
| 143 | /** Location id. */ |
| 144 | location: string; |
| 145 | /** Consumer VPC resource path. */ |
| 146 | network: string | undefined; |
| 147 | /** Service class identifier. */ |
| 148 | serviceClass: string | undefined; |
| 149 | /** PSC configuration. */ |
| 150 | pscConfig: PscConfig | undefined; |
| 151 | /** Infrastructure used for connections (`PSC`, …). */ |
| 152 | infrastructure: string | undefined; |
| 153 | /** Auto-created subnet info, if any. */ |
| 154 | autoCreatedSubnetInfo: AutoCreatedSubnetworkInfo | undefined; |
| 155 | /** User-provided description. */ |
| 156 | description: string | undefined; |
| 157 | /** User labels (Alchemy ownership labels stripped). */ |
| 158 | labels: Record<string, string>; |
| 159 | /** Server etag. */ |
| 160 | etag: string | undefined; |
| 161 | /** RFC3339 creation timestamp. */ |
| 162 | createTime: string | undefined; |
| 163 | /** RFC3339 last-update timestamp. */ |
| 164 | updateTime: string | undefined; |
| 165 | }, |
| 166 | never, |
| 167 | Providers |
| 168 | >; |
| 169 | |
| 170 | /** |
| 171 | * A PSC Service Connection Policy that allows a consumer VPC to connect |
| 172 | * to a producer service class (Cloud SQL, Memorystore, …). |
| 173 | * |
| 174 | * Changing `serviceConnectionPolicyId`, `location`, or `network` |
| 175 | * replaces the policy. Description, labels, `serviceClass`, and |
| 176 | * `pscConfig` update in place. |
| 177 | * |
| 178 | * ### Creating a ServiceConnectionPolicy |
| 179 | * **Example:** User-provided subnet |
| 180 | * ```typescript |
| 181 | * const network = yield* GCP.Compute.Network("AppVpc", { |
| 182 | * autoCreateSubnetworks: false, |
| 183 | * }); |
| 184 | * const subnet = yield* GCP.Compute.Subnetwork("PscSubnet", { |
| 185 | * network: network.selfLink ?? network.networkName, |
| 186 | * ipCidrRange: "10.20.0.0/24", |
| 187 | * }); |
| 188 | * const policy = yield* GCP.NetworkConnectivity.ServiceConnectionPolicy( |
| 189 | * "Redis", |
| 190 | * { |
| 191 | * serviceClass: "gcp-memorystore-redis", |
| 192 | * network: network.selfLink ?? network.networkName, |
| 193 | * pscConfig: { |
| 194 | * subnetworks: [subnet.selfLink ?? subnet.subnetworkName], |
| 195 | * }, |
| 196 | * labels: { env: "prod" }, |
| 197 | * }, |
| 198 | * ); |
| 199 | * ``` |
| 200 | * |
| 201 | * ### Updating a ServiceConnectionPolicy |
| 202 | * **Example:** Description, labels, and connection limit |
| 203 | * ```typescript |
| 204 | * const policy = yield* GCP.NetworkConnectivity.ServiceConnectionPolicy( |
| 205 | * "Redis", |
| 206 | * { |
| 207 | * serviceClass: "gcp-memorystore-redis", |
| 208 | * network: network.selfLink ?? network.networkName, |
| 209 | * description: "redis psc v2", |
| 210 | * pscConfig: { |
| 211 | * subnetworks: [subnet.selfLink ?? subnet.subnetworkName], |
| 212 | * limit: "4", |
| 213 | * }, |
| 214 | * labels: { env: "prod", role: "psc" }, |
| 215 | * }, |
| 216 | * ); |
| 217 | * ``` |
| 218 | * |
| 219 | * @resource |
| 220 | * @category NetworkConnectivity |
| 221 | */ |
| 222 | export const ServiceConnectionPolicy = Resource<ServiceConnectionPolicy>( |
| 223 | "GCP.NetworkConnectivity.ServiceConnectionPolicy", |
| 224 | ); |
| 225 | |
| 226 | const resourceName = (project: string, location: string, serviceConnectionPolicyId: string) => |
| 227 | `projects/${project}/locations/${location}/serviceConnectionPolicies/${serviceConnectionPolicyId}`; |
| 228 | |
| 229 | const toPscConfig = ( |
| 230 | config: PscConfig | networkconnectivity.PscConfig | undefined, |
| 231 | project: string, |
| 232 | location: string, |
| 233 | ): PscConfig | undefined => { |
| 234 | if (config === undefined) return undefined; |
| 235 | return { |
| 236 | subnetworks: (config.subnetworks ?? []).map((subnetwork) => |
| 237 | toSubnetworkResource(project, location, subnetwork), |
| 238 | ), |
| 239 | limit: config.limit, |
| 240 | producerInstanceLocation: config.producerInstanceLocation, |
| 241 | allowedGoogleProducersResourceHierarchyLevel: |
| 242 | config.allowedGoogleProducersResourceHierarchyLevel |
| 243 | ? [...config.allowedGoogleProducersResourceHierarchyLevel] |
| 244 | : undefined, |
| 245 | }; |
| 246 | }; |
| 247 | |
| 248 | const toAutoCreated = ( |
| 249 | info: networkconnectivity.AutoCreatedSubnetworkInfo | undefined, |
| 250 | ): AutoCreatedSubnetworkInfo | undefined => { |
| 251 | if (info === undefined) return undefined; |
| 252 | return { |
| 253 | internalRange: info.internalRange, |
| 254 | internalRangeRef: info.internalRangeRef, |
| 255 | subnetwork: info.subnetwork, |
| 256 | subnetworkRef: info.subnetworkRef, |
| 257 | delinked: info.delinked, |
| 258 | }; |
| 259 | }; |
| 260 | |
| 261 | const toAttrs = ( |
| 262 | policy: networkconnectivity.ServiceConnectionPolicy, |
| 263 | project: string, |
| 264 | region: string, |
| 265 | ) => { |
| 266 | const name = policy.name ?? ""; |
| 267 | const parsed = parseName(name, COLLECTION, region); |
| 268 | const location = parsed.location || region; |
| 269 | return { |
| 270 | name, |
| 271 | serviceConnectionPolicyId: parsed.id, |
| 272 | project: parsed.project || project, |
| 273 | location, |
| 274 | network: policy.network, |
| 275 | serviceClass: policy.serviceClass, |
| 276 | pscConfig: toPscConfig(policy.pscConfig, parsed.project || project, location), |
| 277 | infrastructure: policy.infrastructure, |
| 278 | autoCreatedSubnetInfo: toAutoCreated(policy.autoCreatedSubnetInfo), |
| 279 | description: policy.description, |
| 280 | labels: userLabels(policy.labels), |
| 281 | etag: policy.etag, |
| 282 | createTime: policy.createTime, |
| 283 | updateTime: policy.updateTime, |
| 284 | }; |
| 285 | }; |
| 286 | |
| 287 | const getByName = (name: string) => |
| 288 | networkconnectivity |
| 289 | .getProjectsLocationsServiceConnectionPolicies({ name }) |
| 290 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 291 | |
| 292 | export const ServiceConnectionPolicyProvider = () => |
| 293 | Provider.succeed(ServiceConnectionPolicy, { |
| 294 | stables: ["name", "serviceConnectionPolicyId", "project", "location", "network", "createTime"], |
| 295 | |
| 296 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 297 | if (!isResolved(news)) return undefined; |
| 298 | const env = yield* GcpEnvironment.current; |
| 299 | const previousId = olds?.serviceConnectionPolicyId ?? output?.serviceConnectionPolicyId; |
| 300 | const nextId = news.serviceConnectionPolicyId |
| 301 | ? rfc1035(news.serviceConnectionPolicyId, "service-connection-policy") |
| 302 | : previousId; |
| 303 | const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 304 | const nextLocation = normalizeLocation( |
| 305 | news.location ?? olds?.location ?? output?.location, |
| 306 | env.region, |
| 307 | ); |
| 308 | const previousNetwork = lastSegment(canonicalizeLink(olds?.network ?? output?.network)); |
| 309 | const nextNetwork = lastSegment(canonicalizeLink(news.network)); |
| 310 | if ( |
| 311 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 312 | previousLocation !== nextLocation || |
| 313 | (previousNetwork.length > 0 && previousNetwork !== nextNetwork) |
| 314 | ) { |
| 315 | return { action: "replace" as const }; |
| 316 | } |
| 317 | return undefined; |
| 318 | }), |
| 319 | |
| 320 | read: Effect.fn(function* ({ id, olds, output }) { |
| 321 | const env = yield* GcpEnvironment.current; |
| 322 | const serviceConnectionPolicyId = yield* toPhysicalId( |
| 323 | id, |
| 324 | olds?.serviceConnectionPolicyId, |
| 325 | output?.serviceConnectionPolicyId, |
| 326 | "service-connection-policy", |
| 327 | ); |
| 328 | const location = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 329 | const name = output?.name ?? resourceName(env.project, location, serviceConnectionPolicyId); |
| 330 | const existing = yield* getByName(name); |
| 331 | if (existing === undefined) return undefined; |
| 332 | const attrs = toAttrs(existing, env.project, env.region); |
| 333 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 334 | }), |
| 335 | |
| 336 | list: () => |
| 337 | Effect.gen(function* () { |
| 338 | const env = yield* GcpEnvironment.current; |
| 339 | const items = yield* collectPages( |
| 340 | networkconnectivity.listProjectsLocationsServiceConnectionPolicies.pages({ |
| 341 | parent: parentOf(env.project, "-"), |
| 342 | pageSize: 1000, |
| 343 | }), |
| 344 | (page) => page.serviceConnectionPolicies, |
| 345 | ); |
| 346 | return items |
| 347 | .filter((item) => hasAlchemyLabelKeys(item.labels)) |
| 348 | .map((item) => toAttrs(item, env.project, env.region)); |
| 349 | }), |
| 350 | |
| 351 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 352 | const env = yield* GcpEnvironment.current; |
| 353 | const serviceConnectionPolicyId = yield* toPhysicalId( |
| 354 | id, |
| 355 | news.serviceConnectionPolicyId, |
| 356 | output?.serviceConnectionPolicyId, |
| 357 | "service-connection-policy", |
| 358 | ); |
| 359 | const location = normalizeLocation(news.location ?? output?.location, env.region); |
| 360 | const name = resourceName(env.project, location, serviceConnectionPolicyId); |
| 361 | const desiredLabels = { |
| 362 | ...toLabels(news.labels), |
| 363 | ...(yield* createInternalLabels(id)), |
| 364 | }; |
| 365 | const network = toNetworkResource(env.project, news.network); |
| 366 | const pscConfig = toPscConfig(news.pscConfig, env.project, location); |
| 367 | |
| 368 | let current = yield* getByName(name); |
| 369 | |
| 370 | if (current === undefined) { |
| 371 | const created = yield* networkconnectivity |
| 372 | .createProjectsLocationsServiceConnectionPolicies({ |
| 373 | parent: parentOf(env.project, location), |
| 374 | serviceConnectionPolicyId, |
| 375 | subnetworkMode: news.subnetworkMode, |
| 376 | "autoSubnetworkConfig.ipStack": news.autoSubnetworkConfig?.ipStack, |
| 377 | "autoSubnetworkConfig.prefixLength": news.autoSubnetworkConfig?.prefixLength, |
| 378 | "autoSubnetworkConfig.allocRangeSpace": news.autoSubnetworkConfig?.allocRangeSpace |
| 379 | ? [...news.autoSubnetworkConfig.allocRangeSpace] |
| 380 | : undefined, |
| 381 | body: { |
| 382 | network, |
| 383 | serviceClass: news.serviceClass, |
| 384 | pscConfig, |
| 385 | description: news.description, |
| 386 | labels: desiredLabels, |
| 387 | }, |
| 388 | }) |
| 389 | .pipe( |
| 390 | Effect.retry({ |
| 391 | while: (error) => error._tag === "Conflict", |
| 392 | times: 5, |
| 393 | schedule: Schedule.spaced("2 seconds"), |
| 394 | }), |
| 395 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 396 | ); |
| 397 | if (created !== undefined) { |
| 398 | yield* waitForOperation(created); |
| 399 | } |
| 400 | current = yield* waitUntilPresent(getByName(name), name); |
| 401 | } |
| 402 | |
| 403 | if (current === undefined) { |
| 404 | return yield* new NetworkConnectivityNotResolved({ resourceName: name }); |
| 405 | } |
| 406 | |
| 407 | const observedLabels = tagRecord(current.labels); |
| 408 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 409 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 410 | const descriptionChanged = (current.description ?? "") !== (news.description ?? ""); |
| 411 | const serviceClassChanged = (current.serviceClass ?? "") !== news.serviceClass; |
| 412 | const observedPsc = toPscConfig(current.pscConfig, env.project, location); |
| 413 | const pscChanged = !sameJson( |
| 414 | { |
| 415 | subnetworks: [...(observedPsc?.subnetworks ?? [])] |
| 416 | .map((value) => lastSegment(canonicalizeLink(value))) |
| 417 | .sort(), |
| 418 | limit: observedPsc?.limit ?? "", |
| 419 | producerInstanceLocation: observedPsc?.producerInstanceLocation ?? "", |
| 420 | allowedGoogleProducersResourceHierarchyLevel: [ |
| 421 | ...(observedPsc?.allowedGoogleProducersResourceHierarchyLevel ?? []), |
| 422 | ].sort(), |
| 423 | }, |
| 424 | { |
| 425 | subnetworks: [...(pscConfig?.subnetworks ?? [])] |
| 426 | .map((value) => lastSegment(canonicalizeLink(value))) |
| 427 | .sort(), |
| 428 | limit: pscConfig?.limit ?? "", |
| 429 | producerInstanceLocation: pscConfig?.producerInstanceLocation ?? "", |
| 430 | allowedGoogleProducersResourceHierarchyLevel: [ |
| 431 | ...(pscConfig?.allowedGoogleProducersResourceHierarchyLevel ?? []), |
| 432 | ].sort(), |
| 433 | }, |
| 434 | ); |
| 435 | const updateMask = changedFields([ |
| 436 | ["labels", labelsChanged], |
| 437 | ["description", descriptionChanged], |
| 438 | ["serviceClass", serviceClassChanged], |
| 439 | ["pscConfig", pscChanged], |
| 440 | ]); |
| 441 | |
| 442 | if (updateMask.length > 0) { |
| 443 | const operation = |
| 444 | yield* networkconnectivity.patchProjectsLocationsServiceConnectionPolicies({ |
| 445 | name: current.name ?? name, |
| 446 | updateMask: updateMask.join(","), |
| 447 | body: { |
| 448 | name: current.name ?? name, |
| 449 | labels: desiredLabels, |
| 450 | description: news.description, |
| 451 | serviceClass: news.serviceClass, |
| 452 | pscConfig, |
| 453 | etag: current.etag, |
| 454 | }, |
| 455 | }); |
| 456 | yield* waitForOperation(operation); |
| 457 | current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name); |
| 458 | } |
| 459 | |
| 460 | return toAttrs(current, env.project, env.region); |
| 461 | }), |
| 462 | |
| 463 | delete: Effect.fn(function* ({ output }) { |
| 464 | const operation = yield* networkconnectivity |
| 465 | .deleteProjectsLocationsServiceConnectionPolicies({ |
| 466 | name: output.name, |
| 467 | etag: output.etag, |
| 468 | }) |
| 469 | .pipe( |
| 470 | Effect.retry({ |
| 471 | while: (error) => error._tag === "Conflict", |
| 472 | times: 8, |
| 473 | schedule: Schedule.spaced("2 seconds"), |
| 474 | }), |
| 475 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 476 | ); |
| 477 | if (operation !== undefined) { |
| 478 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 479 | } |
| 480 | yield* waitUntilGone(getByName(output.name), output.name); |
| 481 | }), |
| 482 | }); |