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 networkservices from "@distilled.cloud/gcp/networkservices_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 | DEFAULT_GLOBAL, |
| 14 | changedFields, |
| 15 | collectPages, |
| 16 | hasAlchemyLabelKeys, |
| 17 | normalizeLocation, |
| 18 | parentOf, |
| 19 | parseName, |
| 20 | resourceName, |
| 21 | rfc1035, |
| 22 | sameJson, |
| 23 | toPhysicalId, |
| 24 | userLabels, |
| 25 | waitForOperation, |
| 26 | waitUntilGone, |
| 27 | waitUntilPresent, |
| 28 | } from "./internal.ts"; |
| 29 | |
| 30 | const COLLECTION = "serviceLbPolicies"; |
| 31 | |
| 32 | export type ServiceLbPolicyLoadBalancingAlgorithm = |
| 33 | | networkservices.ServiceLbPolicyLoadBalancingAlgorithmEnum |
| 34 | | (string & {}); |
| 35 | |
| 36 | export type ServiceLbPolicyIsolationGranularity = |
| 37 | | networkservices.ServiceLbPolicyIsolationConfigIsolationGranularityEnum |
| 38 | | (string & {}); |
| 39 | |
| 40 | export type ServiceLbPolicyIsolationMode = |
| 41 | | networkservices.ServiceLbPolicyIsolationConfigIsolationModeEnum |
| 42 | | (string & {}); |
| 43 | |
| 44 | export type ServiceLbPolicyAutoCapacityDrain = { |
| 45 | /** |
| 46 | * When true, an unhealthy IG/NEG is drained. An IG/NEG is unhealthy |
| 47 | * if fewer than 25% of its endpoints are healthy. Never drains more |
| 48 | * than 50% of configured backends. |
| 49 | */ |
| 50 | enable?: boolean; |
| 51 | }; |
| 52 | |
| 53 | export type ServiceLbPolicyFailoverConfig = { |
| 54 | /** |
| 55 | * Percentage of healthy endpoints below which traffic is sent to |
| 56 | * failover backends. Range 1-99. Defaults to 50 for classic global |
| 57 | * external HTTP(S) and proxyless mesh, 70 otherwise. |
| 58 | */ |
| 59 | failoverHealthThreshold?: number; |
| 60 | }; |
| 61 | |
| 62 | export type ServiceLbPolicyIsolationConfig = { |
| 63 | /** Isolation granularity (`REGION`). */ |
| 64 | isolationGranularity?: ServiceLbPolicyIsolationGranularity; |
| 65 | /** Isolation mode (`NEAREST` or `STRICT`). */ |
| 66 | isolationMode?: ServiceLbPolicyIsolationMode; |
| 67 | }; |
| 68 | |
| 69 | export type ServiceLbPolicyProps = { |
| 70 | /** |
| 71 | * Policy id (the `{serviceLbPolicy}` segment of |
| 72 | * `projects/{project}/locations/{location}/serviceLbPolicies/{serviceLbPolicy}`). |
| 73 | * If omitted, a unique name is generated from the stack, stage, and |
| 74 | * logical id. Immutable — changing it replaces the policy. |
| 75 | */ |
| 76 | serviceLbPolicyId?: string; |
| 77 | /** |
| 78 | * Location (`global`, `us-central1`, …). Immutable — changing it |
| 79 | * replaces the policy. `US-CENTRAL1` is accepted and normalized to |
| 80 | * `us-central1`. |
| 81 | * @default "global" |
| 82 | */ |
| 83 | location?: string; |
| 84 | /** |
| 85 | * Human-readable description. Max 1024 characters. |
| 86 | */ |
| 87 | description?: string; |
| 88 | /** |
| 89 | * Load balancing algorithm. Defaults to `WATERFALL_BY_REGION`. |
| 90 | */ |
| 91 | loadBalancingAlgorithm?: ServiceLbPolicyLoadBalancingAlgorithm; |
| 92 | /** |
| 93 | * Automatically drain traffic from unhealthy instance groups or NEGs. |
| 94 | */ |
| 95 | autoCapacityDrain?: ServiceLbPolicyAutoCapacityDrain; |
| 96 | /** |
| 97 | * Health-based failover threshold. |
| 98 | */ |
| 99 | failoverConfig?: ServiceLbPolicyFailoverConfig; |
| 100 | /** |
| 101 | * Backend isolation for the associated backend service. |
| 102 | */ |
| 103 | isolationConfig?: ServiceLbPolicyIsolationConfig; |
| 104 | /** |
| 105 | * User labels. Alchemy ownership labels are merged in automatically. |
| 106 | */ |
| 107 | labels?: Record<string, string>; |
| 108 | }; |
| 109 | |
| 110 | export type ServiceLbPolicy = Resource< |
| 111 | "GCP.NetworkServices.ServiceLbPolicy", |
| 112 | ServiceLbPolicyProps, |
| 113 | { |
| 114 | /** Full resource name `projects/{project}/locations/{location}/serviceLbPolicies/{serviceLbPolicy}`. */ |
| 115 | name: string; |
| 116 | /** Policy id (last path segment). */ |
| 117 | serviceLbPolicyId: string; |
| 118 | /** Project id. */ |
| 119 | project: string; |
| 120 | /** Location id (`global`, `us-central1`, …). */ |
| 121 | location: string; |
| 122 | /** User-provided description. */ |
| 123 | description: string | undefined; |
| 124 | /** Configured load balancing algorithm. */ |
| 125 | loadBalancingAlgorithm: string | undefined; |
| 126 | /** Auto capacity drain settings. */ |
| 127 | autoCapacityDrain: ServiceLbPolicyAutoCapacityDrain | undefined; |
| 128 | /** Failover configuration. */ |
| 129 | failoverConfig: ServiceLbPolicyFailoverConfig | undefined; |
| 130 | /** Isolation configuration. */ |
| 131 | isolationConfig: ServiceLbPolicyIsolationConfig | undefined; |
| 132 | /** User labels (Alchemy ownership labels stripped). */ |
| 133 | labels: Record<string, string>; |
| 134 | /** RFC3339 creation timestamp. */ |
| 135 | createTime: string | undefined; |
| 136 | /** RFC3339 last-update timestamp. */ |
| 137 | updateTime: string | undefined; |
| 138 | }, |
| 139 | never, |
| 140 | Providers |
| 141 | >; |
| 142 | |
| 143 | /** |
| 144 | * A ServiceLbPolicy holds global load-balancing and traffic-distribution |
| 145 | * settings that can be attached to a BackendService. |
| 146 | * |
| 147 | * Changing `serviceLbPolicyId` or `location` replaces the policy. |
| 148 | * Description, labels, algorithm, drain, failover, and isolation update |
| 149 | * in place. |
| 150 | * |
| 151 | * ### Creating a ServiceLbPolicy |
| 152 | * **Example:** Generated name |
| 153 | * ```typescript |
| 154 | * const policy = yield* GCP.NetworkServices.ServiceLbPolicy("Spread", {}); |
| 155 | * ``` |
| 156 | * |
| 157 | * **Example:** Spray-to-region with failover |
| 158 | * ```typescript |
| 159 | * const policy = yield* GCP.NetworkServices.ServiceLbPolicy("Spread", { |
| 160 | * serviceLbPolicyId: "app-lb-policy", |
| 161 | * loadBalancingAlgorithm: "SPRAY_TO_REGION", |
| 162 | * autoCapacityDrain: { enable: true }, |
| 163 | * failoverConfig: { failoverHealthThreshold: 70 }, |
| 164 | * labels: { env: "prod" }, |
| 165 | * }); |
| 166 | * ``` |
| 167 | * |
| 168 | * @resource |
| 169 | * @category NetworkServices |
| 170 | */ |
| 171 | export const ServiceLbPolicy = Resource<ServiceLbPolicy>("GCP.NetworkServices.ServiceLbPolicy"); |
| 172 | |
| 173 | const toDrain = ( |
| 174 | drain: |
| 175 | | ServiceLbPolicyAutoCapacityDrain |
| 176 | | networkservices.ServiceLbPolicyAutoCapacityDrain |
| 177 | | undefined, |
| 178 | ): ServiceLbPolicyAutoCapacityDrain | undefined => { |
| 179 | if (drain === undefined) return undefined; |
| 180 | return { enable: drain.enable }; |
| 181 | }; |
| 182 | |
| 183 | const toFailover = ( |
| 184 | failover: |
| 185 | | ServiceLbPolicyFailoverConfig |
| 186 | | networkservices.ServiceLbPolicyFailoverConfig |
| 187 | | undefined, |
| 188 | ): ServiceLbPolicyFailoverConfig | undefined => { |
| 189 | if (failover === undefined) return undefined; |
| 190 | return { failoverHealthThreshold: failover.failoverHealthThreshold }; |
| 191 | }; |
| 192 | |
| 193 | const toIsolation = ( |
| 194 | isolation: |
| 195 | | ServiceLbPolicyIsolationConfig |
| 196 | | networkservices.ServiceLbPolicyIsolationConfig |
| 197 | | undefined, |
| 198 | ): ServiceLbPolicyIsolationConfig | undefined => { |
| 199 | if (isolation === undefined) return undefined; |
| 200 | return { |
| 201 | isolationGranularity: isolation.isolationGranularity, |
| 202 | isolationMode: isolation.isolationMode, |
| 203 | }; |
| 204 | }; |
| 205 | |
| 206 | const toAttrs = (policy: networkservices.ServiceLbPolicy, project: string) => { |
| 207 | const name = policy.name ?? ""; |
| 208 | const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL); |
| 209 | return { |
| 210 | name, |
| 211 | serviceLbPolicyId: parsed.id, |
| 212 | project: parsed.project || project, |
| 213 | location: parsed.location || DEFAULT_GLOBAL, |
| 214 | description: policy.description, |
| 215 | loadBalancingAlgorithm: policy.loadBalancingAlgorithm, |
| 216 | autoCapacityDrain: toDrain(policy.autoCapacityDrain), |
| 217 | failoverConfig: toFailover(policy.failoverConfig), |
| 218 | isolationConfig: toIsolation(policy.isolationConfig), |
| 219 | labels: userLabels(policy.labels), |
| 220 | createTime: policy.createTime, |
| 221 | updateTime: policy.updateTime, |
| 222 | }; |
| 223 | }; |
| 224 | |
| 225 | const getByName = (name: string) => |
| 226 | networkservices |
| 227 | .getProjectsLocationsServiceLbPolicies({ name }) |
| 228 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 229 | |
| 230 | export const ServiceLbPolicyProvider = () => |
| 231 | Provider.succeed(ServiceLbPolicy, { |
| 232 | stables: ["name", "serviceLbPolicyId", "project", "location", "createTime"], |
| 233 | |
| 234 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 235 | if (!isResolved(news)) return undefined; |
| 236 | const previousId = olds?.serviceLbPolicyId ?? output?.serviceLbPolicyId; |
| 237 | const nextId = news.serviceLbPolicyId |
| 238 | ? rfc1035(news.serviceLbPolicyId, "service-lb-policy") |
| 239 | : previousId; |
| 240 | const previousLocation = normalizeLocation( |
| 241 | olds?.location ?? output?.location, |
| 242 | DEFAULT_GLOBAL, |
| 243 | ); |
| 244 | const nextLocation = normalizeLocation( |
| 245 | news.location ?? olds?.location ?? output?.location, |
| 246 | DEFAULT_GLOBAL, |
| 247 | ); |
| 248 | if ( |
| 249 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 250 | previousLocation !== nextLocation |
| 251 | ) { |
| 252 | return { action: "replace" as const }; |
| 253 | } |
| 254 | return undefined; |
| 255 | }), |
| 256 | |
| 257 | read: Effect.fn(function* ({ id, olds, output }) { |
| 258 | const env = yield* GcpEnvironment.current; |
| 259 | const serviceLbPolicyId = yield* toPhysicalId( |
| 260 | id, |
| 261 | olds?.serviceLbPolicyId, |
| 262 | output?.serviceLbPolicyId, |
| 263 | "service-lb-policy", |
| 264 | ); |
| 265 | const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL); |
| 266 | const name = |
| 267 | output?.name ?? resourceName(env.project, location, COLLECTION, serviceLbPolicyId); |
| 268 | const existing = yield* getByName(name); |
| 269 | if (existing === undefined) return undefined; |
| 270 | const attrs = toAttrs(existing, env.project); |
| 271 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 272 | }), |
| 273 | |
| 274 | list: () => |
| 275 | Effect.gen(function* () { |
| 276 | const env = yield* GcpEnvironment.current; |
| 277 | const items = yield* collectPages( |
| 278 | networkservices.listProjectsLocationsServiceLbPolicies.pages({ |
| 279 | parent: parentOf(env.project, "-"), |
| 280 | pageSize: 1000, |
| 281 | }), |
| 282 | (page) => page.serviceLbPolicies, |
| 283 | ); |
| 284 | return items |
| 285 | .filter((item) => hasAlchemyLabelKeys(item.labels)) |
| 286 | .map((item) => toAttrs(item, env.project)); |
| 287 | }), |
| 288 | |
| 289 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 290 | const env = yield* GcpEnvironment.current; |
| 291 | const serviceLbPolicyId = yield* toPhysicalId( |
| 292 | id, |
| 293 | news.serviceLbPolicyId, |
| 294 | output?.serviceLbPolicyId, |
| 295 | "service-lb-policy", |
| 296 | ); |
| 297 | const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL); |
| 298 | const name = resourceName(env.project, location, COLLECTION, serviceLbPolicyId); |
| 299 | const desiredLabels = { |
| 300 | ...toLabels(news.labels), |
| 301 | ...(yield* createInternalLabels(id)), |
| 302 | }; |
| 303 | const desiredDrain = toDrain(news.autoCapacityDrain); |
| 304 | const desiredFailover = toFailover(news.failoverConfig); |
| 305 | const desiredIsolation = toIsolation(news.isolationConfig); |
| 306 | |
| 307 | let current = yield* getByName(name); |
| 308 | |
| 309 | if (current === undefined) { |
| 310 | const created = yield* networkservices |
| 311 | .createProjectsLocationsServiceLbPolicies({ |
| 312 | parent: parentOf(env.project, location), |
| 313 | serviceLbPolicyId, |
| 314 | body: { |
| 315 | description: news.description, |
| 316 | labels: desiredLabels, |
| 317 | loadBalancingAlgorithm: news.loadBalancingAlgorithm, |
| 318 | autoCapacityDrain: desiredDrain, |
| 319 | failoverConfig: desiredFailover, |
| 320 | isolationConfig: desiredIsolation, |
| 321 | }, |
| 322 | }) |
| 323 | .pipe( |
| 324 | Effect.retry({ |
| 325 | while: (error) => error._tag === "Conflict", |
| 326 | times: 5, |
| 327 | schedule: Schedule.spaced("2 seconds"), |
| 328 | }), |
| 329 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 330 | ); |
| 331 | if (created !== undefined) { |
| 332 | yield* waitForOperation(created); |
| 333 | } |
| 334 | current = yield* waitUntilPresent(getByName(name), name); |
| 335 | } |
| 336 | |
| 337 | const observedLabels = tagRecord(current.labels); |
| 338 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 339 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 340 | const updateMask = changedFields([ |
| 341 | ["labels", labelsChanged], |
| 342 | ["description", (current.description ?? "") !== (news.description ?? "")], |
| 343 | [ |
| 344 | "loadBalancingAlgorithm", |
| 345 | (current.loadBalancingAlgorithm ?? "") !== (news.loadBalancingAlgorithm ?? ""), |
| 346 | ], |
| 347 | ["autoCapacityDrain", !sameJson(toDrain(current.autoCapacityDrain), desiredDrain)], |
| 348 | ["failoverConfig", !sameJson(toFailover(current.failoverConfig), desiredFailover)], |
| 349 | ["isolationConfig", !sameJson(toIsolation(current.isolationConfig), desiredIsolation)], |
| 350 | ]); |
| 351 | |
| 352 | if (updateMask.length > 0) { |
| 353 | const operation = yield* networkservices.patchProjectsLocationsServiceLbPolicies({ |
| 354 | name: current.name ?? name, |
| 355 | updateMask: updateMask.join(","), |
| 356 | body: { |
| 357 | name: current.name ?? name, |
| 358 | labels: desiredLabels, |
| 359 | description: news.description, |
| 360 | loadBalancingAlgorithm: news.loadBalancingAlgorithm, |
| 361 | autoCapacityDrain: desiredDrain, |
| 362 | failoverConfig: desiredFailover, |
| 363 | isolationConfig: desiredIsolation, |
| 364 | }, |
| 365 | }); |
| 366 | yield* waitForOperation(operation); |
| 367 | current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name); |
| 368 | } |
| 369 | |
| 370 | return toAttrs(current, env.project); |
| 371 | }), |
| 372 | |
| 373 | delete: Effect.fn(function* ({ output }) { |
| 374 | const operation = yield* networkservices |
| 375 | .deleteProjectsLocationsServiceLbPolicies({ name: output.name }) |
| 376 | .pipe( |
| 377 | Effect.retry({ |
| 378 | while: (error) => error._tag === "Conflict", |
| 379 | times: 8, |
| 380 | schedule: Schedule.spaced("2 seconds"), |
| 381 | }), |
| 382 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 383 | ); |
| 384 | if (operation !== undefined) { |
| 385 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 386 | } |
| 387 | yield* waitUntilGone(getByName(output.name), output.name); |
| 388 | }), |
| 389 | }); |