@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 429 lines 14.4 KB
Raw
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 sameStringList,
24 toPhysicalId,
25 userLabels,
26 waitForOperation,
27 waitUntilGone,
28 waitUntilPresent,
29 } from "./internal.ts";
30
31 const COLLECTION = "lbEdgeExtensions";
32 const DEFAULT_SCHEME = "EXTERNAL_MANAGED";
33
34 export type LbEdgeExtensionLoadBalancingScheme =
35 | networkservices.LbEdgeExtensionLoadBalancingSchemeEnum
36 | (string & {});
37
38 export type ExtensionChainMatchCondition = {
39 /**
40 * CEL expression used to select requests. See the Service Extensions
41 * CEL matcher language reference.
42 */
43 celExpression?: string;
44 };
45
46 export type ExtensionChainExtension = {
47 /**
48 * Extension name logged in HTTP request logs. RFC1034, 1-63
49 * characters. Required except on AuthzExtension.
50 */
51 name?: string;
52 /**
53 * `:authority` header sent from Envoy to the callout. Required for
54 * callout extensions; forbidden for plugin extensions.
55 */
56 authority?: string;
57 /**
58 * Backend service URL (callout) or WasmPlugin resource name (plugin).
59 */
60 service?: string;
61 /**
62 * Events that invoke this extension. `LbEdgeExtension` must list only
63 * `REQUEST_HEADERS`.
64 */
65 supportedEvents?: string[];
66 /**
67 * Per-message timeout between 10ms and 10000ms. Required for callouts.
68 */
69 timeout?: string;
70 /**
71 * Continue request processing if the callout fails or times out.
72 * @default false
73 */
74 failOpen?: boolean;
75 /** HTTP headers forwarded to the extension. Omitted sends every header. */
76 forwardHeaders?: string[];
77 /** Envoy attributes forwarded to the extension. Omitted sends none. */
78 forwardAttributes?: string[];
79 /**
80 * Metadata included in `ProcessingRequest.metadata_context`. Must not
81 * be set for plugin extensions.
82 */
83 metadata?: Record<string, unknown>;
84 /** Request body send mode (`STREAMED` or `FULL_DUPLEX_STREAMED`). */
85 requestBodySendMode?: string;
86 /** Response body send mode. */
87 responseBodySendMode?: string;
88 /**
89 * Run the callout asynchronously without pausing the request.
90 * @default false
91 */
92 observabilityMode?: boolean;
93 };
94
95 export type ExtensionChain = {
96 /** Chain name logged in HTTP request logs. RFC1034, 1-63 characters. */
97 name?: string;
98 /** Conditions under which this chain runs. */
99 matchCondition?: ExtensionChainMatchCondition;
100 /**
101 * Extensions executed for a matching request. `LbEdgeExtension` and
102 * `LbRouteExtension` allow one extension per chain.
103 */
104 extensions?: ExtensionChainExtension[];
105 };
106
107 export type LbEdgeExtensionProps = {
108 /**
109 * LbEdgeExtension id (the `{lbEdgeExtension}` segment of
110 * `projects/{project}/locations/{location}/lbEdgeExtensions/{lbEdgeExtension}`).
111 * If omitted, a unique name is generated from the stack, stage, and
112 * logical id. Must be 1-63 characters and not start with a number.
113 * Immutable — changing it replaces the extension.
114 */
115 lbEdgeExtensionId?: string;
116 /**
117 * Location (`global`, `us-central1`, …). Immutable — changing it
118 * replaces the extension. `US-CENTRAL1` is accepted and normalized to
119 * `us-central1`.
120 * @default "global"
121 */
122 location?: string;
123 /**
124 * Forwarding rule resource names this extension attaches to. At least
125 * one is required. Only one LbEdgeExtension may attach to a given
126 * forwarding rule.
127 */
128 forwardingRules: string[];
129 /**
130 * Ordered extension chains. The first matching chain runs. Limited to
131 * 5 chains.
132 */
133 extensionChains: ExtensionChain[];
134 /**
135 * Load balancing scheme shared by referenced forwarding rules.
136 * Immutable — changing it replaces the extension.
137 * @default "EXTERNAL_MANAGED"
138 */
139 loadBalancingScheme?: LbEdgeExtensionLoadBalancingScheme;
140 /**
141 * Human-readable description.
142 */
143 description?: string;
144 /**
145 * User labels. Alchemy ownership labels are merged in automatically.
146 */
147 labels?: Record<string, string>;
148 };
149
150 export type LbEdgeExtension = Resource<
151 "GCP.NetworkServices.LbEdgeExtension",
152 LbEdgeExtensionProps,
153 {
154 /** Full resource name `projects/{project}/locations/{location}/lbEdgeExtensions/{lbEdgeExtension}`. */
155 name: string;
156 /** LbEdgeExtension id (last path segment). */
157 lbEdgeExtensionId: string;
158 /** Project id. */
159 project: string;
160 /** Location id (`global`, `us-central1`, …). */
161 location: string;
162 /** Attached forwarding rule resource names. */
163 forwardingRules: string[];
164 /** Extension chains. */
165 extensionChains: ExtensionChain[];
166 /** Load balancing scheme. */
167 loadBalancingScheme: string | undefined;
168 /** User-provided description. */
169 description: string | undefined;
170 /** User labels (Alchemy ownership labels stripped). */
171 labels: Record<string, string>;
172 /** RFC3339 creation timestamp. */
173 createTime: string | undefined;
174 /** RFC3339 last-update timestamp. */
175 updateTime: string | undefined;
176 },
177 never,
178 Providers
179 >;
180
181 /**
182 * A Network Services LbEdgeExtension — a Service Extension that
183 * rewrites request headers so an Application Load Balancer can change
184 * backend selection and Cloud CDN cache keys.
185 *
186 * Changing `lbEdgeExtensionId`, `location`, or `loadBalancingScheme`
187 * replaces the extension. Description, labels, forwarding rules, and
188 * extension chains update in place.
189 *
190 * ### Creating an LbEdgeExtension
191 * **Example:** Attach to a global forwarding rule
192 * ```typescript
193 * const ext = yield* GCP.NetworkServices.LbEdgeExtension("Edge", {
194 * loadBalancingScheme: "EXTERNAL_MANAGED",
195 * forwardingRules: [rule.selfLink],
196 * extensionChains: [
197 * {
198 * name: "chain1",
199 * matchCondition: { celExpression: "true" },
200 * extensions: [
201 * {
202 * name: "ext1",
203 * authority: "ext1.example.com",
204 * service: backend.selfLink,
205 * timeout: "0.1s",
206 * supportedEvents: ["REQUEST_HEADERS"],
207 * },
208 * ],
209 * },
210 * ],
211 * });
212 * ```
213 *
214 * @resource
215 * @category NetworkServices
216 */
217 export const LbEdgeExtension = Resource<LbEdgeExtension>("GCP.NetworkServices.LbEdgeExtension");
218
219 export const toExtension = (
220 value: ExtensionChainExtension | networkservices.ExtensionChainExtension,
221 ): ExtensionChainExtension => ({
222 name: value.name,
223 authority: value.authority,
224 service: value.service,
225 supportedEvents: value.supportedEvents ?? [],
226 timeout: value.timeout,
227 failOpen: value.failOpen,
228 forwardHeaders: value.forwardHeaders ?? [],
229 forwardAttributes: value.forwardAttributes ?? [],
230 metadata: value.metadata,
231 requestBodySendMode: value.requestBodySendMode,
232 responseBodySendMode: value.responseBodySendMode,
233 observabilityMode: value.observabilityMode,
234 });
235
236 export const toChain = (
237 value: ExtensionChain | networkservices.ExtensionChain,
238 ): ExtensionChain => ({
239 name: value.name,
240 matchCondition: value.matchCondition
241 ? { celExpression: value.matchCondition.celExpression }
242 : undefined,
243 extensions: (value.extensions ?? []).map(toExtension),
244 });
245
246 const toAttrs = (extension: networkservices.LbEdgeExtension, project: string) => {
247 const name = extension.name ?? "";
248 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
249 return {
250 name,
251 lbEdgeExtensionId: parsed.id,
252 project: parsed.project || project,
253 location: parsed.location || DEFAULT_GLOBAL,
254 forwardingRules: extension.forwardingRules ?? [],
255 extensionChains: (extension.extensionChains ?? []).map(toChain),
256 loadBalancingScheme: extension.loadBalancingScheme,
257 description: extension.description,
258 labels: userLabels(extension.labels),
259 createTime: extension.createTime,
260 updateTime: extension.updateTime,
261 };
262 };
263
264 const getByName = (name: string) =>
265 networkservices
266 .getProjectsLocationsLbEdgeExtensions({ name })
267 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
268
269 export const LbEdgeExtensionProvider = () =>
270 Provider.succeed(LbEdgeExtension, {
271 stables: ["name", "lbEdgeExtensionId", "project", "location", "createTime"],
272
273 diff: Effect.fn(function* ({ news, olds, output }) {
274 if (!isResolved(news)) return undefined;
275 const previousId = olds?.lbEdgeExtensionId ?? output?.lbEdgeExtensionId;
276 const nextId = news.lbEdgeExtensionId
277 ? rfc1035(news.lbEdgeExtensionId, "lb-edge-extension")
278 : previousId;
279 const previousLocation = normalizeLocation(
280 olds?.location ?? output?.location,
281 DEFAULT_GLOBAL,
282 );
283 const nextLocation = normalizeLocation(
284 news.location ?? olds?.location ?? output?.location,
285 DEFAULT_GLOBAL,
286 );
287 const previousScheme =
288 olds?.loadBalancingScheme ?? output?.loadBalancingScheme ?? DEFAULT_SCHEME;
289 const nextScheme = news.loadBalancingScheme ?? previousScheme;
290 if (
291 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
292 previousLocation !== nextLocation ||
293 previousScheme !== nextScheme
294 ) {
295 return { action: "replace" as const };
296 }
297 return undefined;
298 }),
299
300 read: Effect.fn(function* ({ id, olds, output }) {
301 const env = yield* GcpEnvironment.current;
302 const lbEdgeExtensionId = yield* toPhysicalId(
303 id,
304 olds?.lbEdgeExtensionId,
305 output?.lbEdgeExtensionId,
306 "lb-edge-extension",
307 );
308 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
309 const name =
310 output?.name ?? resourceName(env.project, location, COLLECTION, lbEdgeExtensionId);
311 const existing = yield* getByName(name);
312 if (existing === undefined) return undefined;
313 const attrs = toAttrs(existing, env.project);
314 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
315 }),
316
317 list: () =>
318 Effect.gen(function* () {
319 const env = yield* GcpEnvironment.current;
320 const items = yield* collectPages(
321 networkservices.listProjectsLocationsLbEdgeExtensions.pages({
322 parent: parentOf(env.project, "-"),
323 pageSize: 1000,
324 }),
325 (page) => page.lbEdgeExtensions,
326 );
327 return items
328 .filter((item) => hasAlchemyLabelKeys(item.labels))
329 .map((item) => toAttrs(item, env.project));
330 }),
331
332 reconcile: Effect.fn(function* ({ id, news, output }) {
333 const env = yield* GcpEnvironment.current;
334 const lbEdgeExtensionId = yield* toPhysicalId(
335 id,
336 news.lbEdgeExtensionId,
337 output?.lbEdgeExtensionId,
338 "lb-edge-extension",
339 );
340 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
341 const name = resourceName(env.project, location, COLLECTION, lbEdgeExtensionId);
342 const desiredLabels = {
343 ...toLabels(news.labels),
344 ...(yield* createInternalLabels(id)),
345 };
346 const loadBalancingScheme = news.loadBalancingScheme ?? DEFAULT_SCHEME;
347 const desiredRules = news.forwardingRules;
348 const desiredChains = news.extensionChains.map(toChain);
349
350 let current = yield* getByName(name);
351
352 if (current === undefined) {
353 const created = yield* networkservices
354 .createProjectsLocationsLbEdgeExtensions({
355 parent: parentOf(env.project, location),
356 lbEdgeExtensionId,
357 body: {
358 labels: desiredLabels,
359 description: news.description,
360 forwardingRules: desiredRules,
361 extensionChains: desiredChains,
362 loadBalancingScheme,
363 },
364 })
365 .pipe(
366 Effect.retry({
367 while: (error) => error._tag === "Conflict",
368 times: 5,
369 schedule: Schedule.spaced("2 seconds"),
370 }),
371 Effect.catchTag("Conflict", () => Effect.undefined),
372 );
373 if (created !== undefined) {
374 yield* waitForOperation(created);
375 }
376 current = yield* waitUntilPresent(getByName(name), name);
377 }
378
379 const observedLabels = tagRecord(current.labels);
380 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
381 const labelsChanged = upsert.length > 0 || removed.length > 0;
382 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
383 const rulesChanged = !sameStringList(current.forwardingRules, desiredRules);
384 const chainsChanged = !sameJson((current.extensionChains ?? []).map(toChain), desiredChains);
385
386 const updateMask = changedFields([
387 ["labels", labelsChanged],
388 ["description", descriptionChanged],
389 ["forwardingRules", rulesChanged],
390 ["extensionChains", chainsChanged],
391 ]);
392
393 if (updateMask.length > 0) {
394 const operation = yield* networkservices.patchProjectsLocationsLbEdgeExtensions({
395 name: current.name ?? name,
396 updateMask: updateMask.join(","),
397 body: {
398 name: current.name ?? name,
399 labels: desiredLabels,
400 description: news.description,
401 forwardingRules: desiredRules,
402 extensionChains: desiredChains,
403 loadBalancingScheme,
404 },
405 });
406 yield* waitForOperation(operation);
407 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
408 }
409
410 return toAttrs(current, env.project);
411 }),
412
413 delete: Effect.fn(function* ({ output }) {
414 const operation = yield* networkservices
415 .deleteProjectsLocationsLbEdgeExtensions({ name: output.name })
416 .pipe(
417 Effect.retry({
418 while: (error) => error._tag === "Conflict",
419 times: 8,
420 schedule: Schedule.spaced("2 seconds"),
421 }),
422 Effect.catchTag("NotFound", () => Effect.undefined),
423 );
424 if (operation !== undefined) {
425 yield* waitForOperation(operation, { notFoundOk: true });
426 }
427 yield* waitUntilGone(getByName(output.name), output.name);
428 }),
429 });