The best way to control Claude Code, Codex and more from any computer or phone
| 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 | canonicalizeLink, |
| 14 | changedFields, |
| 15 | collectPages, |
| 16 | hasAlchemyLabelKeys, |
| 17 | normalizeLocation, |
| 18 | parentOf, |
| 19 | parseName, |
| 20 | resourceName, |
| 21 | rfc1035, |
| 22 | sameJson, |
| 23 | sameStringList, |
| 24 | toPhysicalId, |
| 25 | userLabels, |
| 26 | waitForOperation, |
| 27 | waitUntilGone, |
| 28 | waitUntilPresent, |
| 29 | } from "./internal.ts"; |
| 30 | import type { |
| 31 | ExtensionChain, |
| 32 | ExtensionChainExtension, |
| 33 | ExtensionChainMatchCondition, |
| 34 | } from "./LbEdgeExtension.ts"; |
| 35 | |
| 36 | const COLLECTION = "lbTrafficExtensions"; |
| 37 | |
| 38 | export type LbTrafficExtensionLoadBalancingScheme = |
| 39 | | networkservices.LbTrafficExtensionLoadBalancingSchemeEnum |
| 40 | | (string & {}); |
| 41 | |
| 42 | export type ExtensionEvent = |
| 43 | | networkservices.ExtensionChainExtensionSupportedEventsItemEnum |
| 44 | | (string & {}); |
| 45 | |
| 46 | export type ExtensionBodySendMode = |
| 47 | | networkservices.ExtensionChainExtensionRequestBodySendModeEnum |
| 48 | | (string & {}); |
| 49 | |
| 50 | export type { ExtensionChain, ExtensionChainExtension, ExtensionChainMatchCondition }; |
| 51 | |
| 52 | export type LbTrafficExtensionProps = { |
| 53 | /** |
| 54 | * Extension id (the `{lbTrafficExtension}` segment of |
| 55 | * `projects/{project}/locations/{location}/lbTrafficExtensions/{lbTrafficExtension}`). |
| 56 | * If omitted, a unique name is generated from the stack, stage, and |
| 57 | * logical id. Immutable — changing it replaces the extension. |
| 58 | */ |
| 59 | lbTrafficExtensionId?: string; |
| 60 | /** |
| 61 | * Location matching the forwarding rules (`global` or a region). |
| 62 | * Immutable — changing it replaces the extension. `US-CENTRAL1` is |
| 63 | * accepted and normalized to `us-central1`. |
| 64 | * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`) |
| 65 | */ |
| 66 | location?: string; |
| 67 | /** |
| 68 | * Human-readable description. |
| 69 | */ |
| 70 | description?: string; |
| 71 | /** |
| 72 | * Forwarding-rule resource names this extension attaches to. At least |
| 73 | * one is required. A forwarding rule may have only one traffic |
| 74 | * extension. |
| 75 | */ |
| 76 | forwardingRules: string[]; |
| 77 | /** |
| 78 | * Ordered extension chains. The first matching chain runs. Limited to |
| 79 | * 5 chains. |
| 80 | */ |
| 81 | extensionChains: ExtensionChain[]; |
| 82 | /** |
| 83 | * Load balancing scheme shared by every referenced backend and |
| 84 | * forwarding rule (`INTERNAL_MANAGED` or `EXTERNAL_MANAGED`). |
| 85 | * Immutable — changing it replaces the extension. |
| 86 | */ |
| 87 | loadBalancingScheme: LbTrafficExtensionLoadBalancingScheme; |
| 88 | /** |
| 89 | * Resource-level metadata included in `ProcessingRequest`. Invalid |
| 90 | * when any chain uses a plugin extension. |
| 91 | */ |
| 92 | metadata?: Record<string, unknown>; |
| 93 | /** |
| 94 | * User labels. Alchemy ownership labels are merged in automatically. |
| 95 | */ |
| 96 | labels?: Record<string, string>; |
| 97 | }; |
| 98 | |
| 99 | export type LbTrafficExtension = Resource< |
| 100 | "GCP.NetworkServices.LbTrafficExtension", |
| 101 | LbTrafficExtensionProps, |
| 102 | { |
| 103 | /** Full resource name `projects/{project}/locations/{location}/lbTrafficExtensions/{lbTrafficExtension}`. */ |
| 104 | name: string; |
| 105 | /** Extension id (last path segment). */ |
| 106 | lbTrafficExtensionId: string; |
| 107 | /** Project id. */ |
| 108 | project: string; |
| 109 | /** Location id (`global`, `us-central1`, …). */ |
| 110 | location: string; |
| 111 | /** User-provided description. */ |
| 112 | description: string | undefined; |
| 113 | /** Attached forwarding-rule resource names. */ |
| 114 | forwardingRules: string[]; |
| 115 | /** Configured extension chains. */ |
| 116 | extensionChains: ExtensionChain[]; |
| 117 | /** Load balancing scheme. */ |
| 118 | loadBalancingScheme: string | undefined; |
| 119 | /** Resource-level metadata. */ |
| 120 | metadata: Record<string, unknown> | undefined; |
| 121 | /** User labels (Alchemy ownership labels stripped). */ |
| 122 | labels: Record<string, string>; |
| 123 | /** RFC3339 creation timestamp. */ |
| 124 | createTime: string | undefined; |
| 125 | /** RFC3339 last-update timestamp. */ |
| 126 | updateTime: string | undefined; |
| 127 | }, |
| 128 | never, |
| 129 | Providers |
| 130 | >; |
| 131 | |
| 132 | /** |
| 133 | * An LbTrafficExtension lets a Service Extension modify request and |
| 134 | * response headers and payloads without changing backend selection. |
| 135 | * |
| 136 | * Changing `lbTrafficExtensionId`, `location`, or `loadBalancingScheme` |
| 137 | * replaces the resource. Description, labels, forwarding rules, chains, |
| 138 | * and metadata update in place. |
| 139 | * |
| 140 | * ### Creating an LbTrafficExtension |
| 141 | * **Example:** Callout on an internal managed load balancer |
| 142 | * ```typescript |
| 143 | * const extension = yield* GCP.NetworkServices.LbTrafficExtension("Inspect", { |
| 144 | * location: "us-central1", |
| 145 | * loadBalancingScheme: "INTERNAL_MANAGED", |
| 146 | * forwardingRules: [rule.selfLink ?? rule.name], |
| 147 | * extensionChains: [ |
| 148 | * { |
| 149 | * name: "all-traffic", |
| 150 | * matchCondition: { celExpression: "true" }, |
| 151 | * extensions: [ |
| 152 | * { |
| 153 | * name: "header-rewriter", |
| 154 | * service: callout.selfLink ?? callout.name, |
| 155 | * authority: "ext.example.com", |
| 156 | * timeout: "0.1s", |
| 157 | * failOpen: true, |
| 158 | * supportedEvents: ["REQUEST_HEADERS", "RESPONSE_HEADERS"], |
| 159 | * }, |
| 160 | * ], |
| 161 | * }, |
| 162 | * ], |
| 163 | * }); |
| 164 | * ``` |
| 165 | * |
| 166 | * @resource |
| 167 | * @category NetworkServices |
| 168 | */ |
| 169 | export const LbTrafficExtension = Resource<LbTrafficExtension>( |
| 170 | "GCP.NetworkServices.LbTrafficExtension", |
| 171 | ); |
| 172 | |
| 173 | const toExtension = ( |
| 174 | extension: ExtensionChainExtension | networkservices.ExtensionChainExtension, |
| 175 | ): ExtensionChainExtension => ({ |
| 176 | name: extension.name, |
| 177 | authority: extension.authority, |
| 178 | service: extension.service ? canonicalizeLink(extension.service) : undefined, |
| 179 | supportedEvents: [...(extension.supportedEvents ?? [])], |
| 180 | timeout: extension.timeout, |
| 181 | failOpen: extension.failOpen, |
| 182 | forwardHeaders: [...(extension.forwardHeaders ?? [])], |
| 183 | forwardAttributes: [...(extension.forwardAttributes ?? [])], |
| 184 | metadata: extension.metadata ? { ...(extension.metadata as Record<string, unknown>) } : undefined, |
| 185 | requestBodySendMode: extension.requestBodySendMode, |
| 186 | responseBodySendMode: extension.responseBodySendMode, |
| 187 | observabilityMode: extension.observabilityMode, |
| 188 | }); |
| 189 | |
| 190 | const toChain = (chain: ExtensionChain | networkservices.ExtensionChain): ExtensionChain => ({ |
| 191 | name: chain.name, |
| 192 | matchCondition: chain.matchCondition |
| 193 | ? { celExpression: chain.matchCondition.celExpression } |
| 194 | : undefined, |
| 195 | extensions: (chain.extensions ?? []).map(toExtension), |
| 196 | }); |
| 197 | |
| 198 | const toForwardingRules = (rules: readonly string[] | undefined) => |
| 199 | (rules ?? []).map((rule) => canonicalizeLink(rule)).filter(Boolean); |
| 200 | |
| 201 | const toAttrs = ( |
| 202 | extension: networkservices.LbTrafficExtension, |
| 203 | project: string, |
| 204 | region: string, |
| 205 | ) => { |
| 206 | const name = extension.name ?? ""; |
| 207 | const parsed = parseName(name, COLLECTION, region); |
| 208 | return { |
| 209 | name, |
| 210 | lbTrafficExtensionId: parsed.id, |
| 211 | project: parsed.project || project, |
| 212 | location: parsed.location || region, |
| 213 | description: extension.description, |
| 214 | forwardingRules: toForwardingRules(extension.forwardingRules), |
| 215 | extensionChains: (extension.extensionChains ?? []).map(toChain), |
| 216 | loadBalancingScheme: extension.loadBalancingScheme, |
| 217 | metadata: extension.metadata |
| 218 | ? { ...(extension.metadata as Record<string, unknown>) } |
| 219 | : undefined, |
| 220 | labels: userLabels(extension.labels), |
| 221 | createTime: extension.createTime, |
| 222 | updateTime: extension.updateTime, |
| 223 | }; |
| 224 | }; |
| 225 | |
| 226 | const getByName = (name: string) => |
| 227 | networkservices |
| 228 | .getProjectsLocationsLbTrafficExtensions({ name }) |
| 229 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 230 | |
| 231 | export const LbTrafficExtensionProvider = () => |
| 232 | Provider.succeed(LbTrafficExtension, { |
| 233 | stables: [ |
| 234 | "name", |
| 235 | "lbTrafficExtensionId", |
| 236 | "project", |
| 237 | "location", |
| 238 | "loadBalancingScheme", |
| 239 | "createTime", |
| 240 | ], |
| 241 | |
| 242 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 243 | if (!isResolved(news)) return undefined; |
| 244 | const env = yield* GcpEnvironment.current; |
| 245 | const previousId = olds?.lbTrafficExtensionId ?? output?.lbTrafficExtensionId; |
| 246 | const nextId = news.lbTrafficExtensionId |
| 247 | ? rfc1035(news.lbTrafficExtensionId, "lb-traffic-extension") |
| 248 | : previousId; |
| 249 | const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 250 | const nextLocation = normalizeLocation( |
| 251 | news.location ?? olds?.location ?? output?.location, |
| 252 | env.region, |
| 253 | ); |
| 254 | const previousScheme = ( |
| 255 | olds?.loadBalancingScheme ?? |
| 256 | output?.loadBalancingScheme ?? |
| 257 | "" |
| 258 | ).toUpperCase(); |
| 259 | const nextScheme = news.loadBalancingScheme.toUpperCase(); |
| 260 | if ( |
| 261 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 262 | previousLocation !== nextLocation || |
| 263 | (previousScheme.length > 0 && previousScheme !== nextScheme) |
| 264 | ) { |
| 265 | return { action: "replace" as const }; |
| 266 | } |
| 267 | return undefined; |
| 268 | }), |
| 269 | |
| 270 | read: Effect.fn(function* ({ id, olds, output }) { |
| 271 | const env = yield* GcpEnvironment.current; |
| 272 | const lbTrafficExtensionId = yield* toPhysicalId( |
| 273 | id, |
| 274 | olds?.lbTrafficExtensionId, |
| 275 | output?.lbTrafficExtensionId, |
| 276 | "lb-traffic-extension", |
| 277 | ); |
| 278 | const location = normalizeLocation(olds?.location ?? output?.location, env.region); |
| 279 | const name = |
| 280 | output?.name ?? resourceName(env.project, location, COLLECTION, lbTrafficExtensionId); |
| 281 | const existing = yield* getByName(name); |
| 282 | if (existing === undefined) return undefined; |
| 283 | const attrs = toAttrs(existing, env.project, env.region); |
| 284 | return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs); |
| 285 | }), |
| 286 | |
| 287 | list: () => |
| 288 | Effect.gen(function* () { |
| 289 | const env = yield* GcpEnvironment.current; |
| 290 | const items = yield* collectPages( |
| 291 | networkservices.listProjectsLocationsLbTrafficExtensions.pages({ |
| 292 | parent: parentOf(env.project, "-"), |
| 293 | pageSize: 1000, |
| 294 | }), |
| 295 | (page) => page.lbTrafficExtensions, |
| 296 | ); |
| 297 | return items |
| 298 | .filter((item) => hasAlchemyLabelKeys(item.labels)) |
| 299 | .map((item) => toAttrs(item, env.project, env.region)); |
| 300 | }), |
| 301 | |
| 302 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 303 | const env = yield* GcpEnvironment.current; |
| 304 | const lbTrafficExtensionId = yield* toPhysicalId( |
| 305 | id, |
| 306 | news.lbTrafficExtensionId, |
| 307 | output?.lbTrafficExtensionId, |
| 308 | "lb-traffic-extension", |
| 309 | ); |
| 310 | const location = normalizeLocation(news.location ?? output?.location, env.region); |
| 311 | const name = resourceName(env.project, location, COLLECTION, lbTrafficExtensionId); |
| 312 | const desiredLabels = { |
| 313 | ...toLabels(news.labels), |
| 314 | ...(yield* createInternalLabels(id)), |
| 315 | }; |
| 316 | const desiredRules = toForwardingRules(news.forwardingRules); |
| 317 | const desiredChains = news.extensionChains.map(toChain); |
| 318 | const desiredMetadata = news.metadata ? { ...news.metadata } : undefined; |
| 319 | |
| 320 | let current = yield* getByName(name); |
| 321 | |
| 322 | if (current === undefined) { |
| 323 | const created = yield* networkservices |
| 324 | .createProjectsLocationsLbTrafficExtensions({ |
| 325 | parent: parentOf(env.project, location), |
| 326 | lbTrafficExtensionId, |
| 327 | body: { |
| 328 | description: news.description, |
| 329 | labels: desiredLabels, |
| 330 | forwardingRules: desiredRules, |
| 331 | extensionChains: desiredChains, |
| 332 | loadBalancingScheme: news.loadBalancingScheme, |
| 333 | metadata: desiredMetadata, |
| 334 | }, |
| 335 | }) |
| 336 | .pipe( |
| 337 | Effect.retry({ |
| 338 | while: (error) => error._tag === "Conflict", |
| 339 | times: 5, |
| 340 | schedule: Schedule.spaced("2 seconds"), |
| 341 | }), |
| 342 | Effect.catchTag("Conflict", () => Effect.undefined), |
| 343 | ); |
| 344 | if (created !== undefined) { |
| 345 | yield* waitForOperation(created); |
| 346 | } |
| 347 | current = yield* waitUntilPresent(getByName(name), name); |
| 348 | } |
| 349 | |
| 350 | const observed = toAttrs(current, env.project, env.region); |
| 351 | const observedLabels = tagRecord(current.labels); |
| 352 | const { upsert, removed } = diffLabels(observedLabels, desiredLabels); |
| 353 | const labelsChanged = upsert.length > 0 || removed.length > 0; |
| 354 | const updateMask = changedFields([ |
| 355 | ["labels", labelsChanged], |
| 356 | ["description", (current.description ?? "") !== (news.description ?? "")], |
| 357 | ["forwardingRules", !sameStringList(observed.forwardingRules, desiredRules)], |
| 358 | ["extensionChains", !sameJson(observed.extensionChains, desiredChains)], |
| 359 | ["metadata", !sameJson(observed.metadata, desiredMetadata)], |
| 360 | ]); |
| 361 | |
| 362 | if (updateMask.length > 0) { |
| 363 | const operation = yield* networkservices.patchProjectsLocationsLbTrafficExtensions({ |
| 364 | name: current.name ?? name, |
| 365 | updateMask: updateMask.join(","), |
| 366 | body: { |
| 367 | name: current.name ?? name, |
| 368 | labels: desiredLabels, |
| 369 | description: news.description, |
| 370 | forwardingRules: desiredRules, |
| 371 | extensionChains: desiredChains, |
| 372 | loadBalancingScheme: news.loadBalancingScheme, |
| 373 | metadata: desiredMetadata, |
| 374 | }, |
| 375 | }); |
| 376 | yield* waitForOperation(operation); |
| 377 | current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name); |
| 378 | } |
| 379 | |
| 380 | return toAttrs(current, env.project, env.region); |
| 381 | }), |
| 382 | |
| 383 | delete: Effect.fn(function* ({ output }) { |
| 384 | const operation = yield* networkservices |
| 385 | .deleteProjectsLocationsLbTrafficExtensions({ name: output.name }) |
| 386 | .pipe( |
| 387 | Effect.retry({ |
| 388 | while: (error) => error._tag === "Conflict", |
| 389 | times: 8, |
| 390 | schedule: Schedule.spaced("2 seconds"), |
| 391 | }), |
| 392 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 393 | ); |
| 394 | if (operation !== undefined) { |
| 395 | yield* waitForOperation(operation, { notFoundOk: true }); |
| 396 | } |
| 397 | yield* waitUntilGone(getByName(output.name), output.name); |
| 398 | }), |
| 399 | }); |