The best way to control Claude Code, Codex and more from any computer or phone

main
ts 537 lines 16.6 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 = "grpcRoutes";
32
33 export type GrpcRouteMethodMatch = {
34 /** How to match the method name. Defaults to `EXACT`. */
35 type?: string;
36 /** gRPC service name. Omitted matches every service. */
37 grpcService?: string;
38 /** gRPC method name. Omitted matches every method. */
39 grpcMethod?: string;
40 /**
41 * Case-sensitive matching. Defaults to true. Must not be set with
42 * `REGULAR_EXPRESSION`.
43 */
44 caseSensitive?: boolean;
45 };
46
47 export type GrpcRouteHeaderMatch = {
48 /** How to match the header value. Defaults to `EXACT`. */
49 type?: string;
50 /** Header key. */
51 key?: string;
52 /** Header value. */
53 value?: string;
54 };
55
56 export type GrpcRouteRouteMatch = {
57 /** gRPC method matcher. Omitted matches every method. */
58 method?: GrpcRouteMethodMatch;
59 /** Header matchers. */
60 headers?: GrpcRouteHeaderMatch[];
61 };
62
63 export type GrpcRouteDestination = {
64 /** BackendService or Service Directory service URL. */
65 serviceName?: string;
66 /** Traffic weight relative to other destinations. */
67 weight?: number;
68 };
69
70 export type GrpcRouteFaultInjectionDelay = {
71 /** Fixed delay before forwarding (duration string). */
72 fixedDelay?: string;
73 /** Percentage of traffic delayed, 0-100. */
74 percentage?: number;
75 };
76
77 export type GrpcRouteFaultInjectionAbort = {
78 /** HTTP status used to abort, 200-599. */
79 httpStatus?: number;
80 /** Percentage of traffic aborted, 0-100. */
81 percentage?: number;
82 };
83
84 export type GrpcRouteFaultInjectionPolicy = {
85 /** Delay injection. */
86 delay?: GrpcRouteFaultInjectionDelay;
87 /** Abort injection. */
88 abort?: GrpcRouteFaultInjectionAbort;
89 };
90
91 export type GrpcRouteRetryPolicy = {
92 /**
93 * Conditions that trigger a retry (`connect-failure`, `unavailable`,
94 * `cancelled`, …).
95 */
96 retryConditions?: string[];
97 /** Allowed retry count. Defaults to 1. */
98 numRetries?: number;
99 };
100
101 export type GrpcRouteStatefulSessionAffinityPolicy = {
102 /** Cookie TTL for the `GSSA` session cookie (`0s` is a session cookie). */
103 cookieTtl?: string;
104 };
105
106 export type GrpcRouteRouteAction = {
107 /** Destinations that receive matched traffic. */
108 destinations?: GrpcRouteDestination[];
109 /** Fault injection. */
110 faultInjectionPolicy?: GrpcRouteFaultInjectionPolicy;
111 /** End-to-end timeout including retries. */
112 timeout?: string;
113 /** Retry policy. */
114 retryPolicy?: GrpcRouteRetryPolicy;
115 /** Cookie-based session affinity. */
116 statefulSessionAffinity?: GrpcRouteStatefulSessionAffinityPolicy;
117 /** Idle timeout. `0s` disables it. */
118 idleTimeout?: string;
119 };
120
121 export type GrpcRouteRouteRule = {
122 /**
123 * Matchers. The rule matches if any matcher matches. Omitted matches
124 * every request.
125 */
126 matches?: GrpcRouteRouteMatch[];
127 /** How to route matched traffic. */
128 action?: GrpcRouteRouteAction;
129 };
130
131 export type GrpcRouteProps = {
132 /**
133 * GrpcRoute id (the `{grpcRoute}` segment of
134 * `projects/{project}/locations/{location}/grpcRoutes/{grpcRoute}`).
135 * If omitted, a unique name is generated from the stack, stage, and
136 * logical id. Must be 1-63 characters and not start with a number.
137 * Immutable — changing it replaces the route.
138 */
139 grpcRouteId?: string;
140 /**
141 * Location (`global`, `us-central1`, …). Immutable — changing it
142 * replaces the route. `US-CENTRAL1` is accepted and normalized to
143 * `us-central1`.
144 * @default "global"
145 */
146 location?: string;
147 /**
148 * Service hostnames (with optional port) this route matches, e.g.
149 * `foo.example.com` or `*.example.com`.
150 */
151 hostnames: string[];
152 /**
153 * Routing rules. The first matching rule is executed. At least one
154 * rule is required.
155 */
156 rules: GrpcRouteRouteRule[];
157 /**
158 * Mesh resource names this route attaches to
159 * (`projects/{project}/locations/{location}/meshes/{mesh}`).
160 */
161 meshes?: string[];
162 /**
163 * Gateway resource names this route attaches to
164 * (`projects/{project}/locations/{location}/gateways/{gateway}`).
165 */
166 gateways?: string[];
167 /**
168 * Human-readable description. Max length 1024 characters.
169 */
170 description?: string;
171 /**
172 * User labels. Alchemy ownership labels are merged in automatically.
173 */
174 labels?: Record<string, string>;
175 };
176
177 export type GrpcRoute = Resource<
178 "GCP.NetworkServices.GrpcRoute",
179 GrpcRouteProps,
180 {
181 /** Full resource name `projects/{project}/locations/{location}/grpcRoutes/{grpcRoute}`. */
182 name: string;
183 /** GrpcRoute id (last path segment). */
184 grpcRouteId: string;
185 /** Project id. */
186 project: string;
187 /** Location id (`global`, `us-central1`, …). */
188 location: string;
189 /** Server-defined resource URL. */
190 selfLink: string | undefined;
191 /** Hostnames this route matches. */
192 hostnames: string[];
193 /** Routing rules. */
194 rules: GrpcRouteRouteRule[];
195 /** Attached Mesh resource names. */
196 meshes: string[];
197 /** Attached Gateway resource names. */
198 gateways: string[];
199 /** User-provided description. */
200 description: string | undefined;
201 /** User labels (Alchemy ownership labels stripped). */
202 labels: Record<string, string>;
203 /** RFC3339 creation timestamp. */
204 createTime: string | undefined;
205 /** RFC3339 last-update timestamp. */
206 updateTime: string | undefined;
207 },
208 never,
209 Providers
210 >;
211
212 /**
213 * A Network Services GrpcRoute — how a Mesh or Gateway routes gRPC
214 * traffic for a set of hostnames.
215 *
216 * Changing `grpcRouteId` or `location` replaces the route. Hostnames,
217 * rules, mesh/gateway attachments, description, and labels update in
218 * place.
219 *
220 * ### Creating a GrpcRoute
221 * **Example:** Hostname with a retry policy
222 * ```typescript
223 * const route = yield* GCP.NetworkServices.GrpcRoute("Api", {
224 * hostnames: ["api.example.com"],
225 * rules: [
226 * {
227 * action: {
228 * retryPolicy: { retryConditions: ["unavailable"], numRetries: 2 },
229 * },
230 * },
231 * ],
232 * });
233 * ```
234 *
235 * **Example:** Attach to a gateway
236 * ```typescript
237 * const route = yield* GCP.NetworkServices.GrpcRoute("Api", {
238 * grpcRouteId: "app-grpc",
239 * hostnames: ["api.example.com"],
240 * gateways: [gateway.name],
241 * labels: { env: "prod" },
242 * rules: [
243 * {
244 * matches: [{ method: { grpcService: "api.v1.Orders", grpcMethod: "Get" } }],
245 * action: { destinations: [{ serviceName: backend.selfLink }] },
246 * },
247 * ],
248 * });
249 * ```
250 *
251 * @resource
252 * @category NetworkServices
253 */
254 export const GrpcRoute = Resource<GrpcRoute>("GCP.NetworkServices.GrpcRoute");
255
256 const toMethod = (
257 value: GrpcRouteMethodMatch | networkservices.GrpcRouteMethodMatch | undefined,
258 ): GrpcRouteMethodMatch | undefined => {
259 if (value === undefined) return undefined;
260 return {
261 type: value.type,
262 grpcService: value.grpcService,
263 grpcMethod: value.grpcMethod,
264 caseSensitive: value.caseSensitive,
265 };
266 };
267
268 const toHeader = (
269 value: GrpcRouteHeaderMatch | networkservices.GrpcRouteHeaderMatch,
270 ): GrpcRouteHeaderMatch => ({
271 type: value.type,
272 key: value.key,
273 value: value.value,
274 });
275
276 const toMatch = (
277 value: GrpcRouteRouteMatch | networkservices.GrpcRouteRouteMatch,
278 ): GrpcRouteRouteMatch => ({
279 method: toMethod(value.method),
280 headers: (value.headers ?? []).map(toHeader),
281 });
282
283 const toDestination = (
284 value: GrpcRouteDestination | networkservices.GrpcRouteDestination,
285 ): GrpcRouteDestination => ({
286 serviceName: value.serviceName,
287 weight: value.weight,
288 });
289
290 const toFault = (
291 value: GrpcRouteFaultInjectionPolicy | networkservices.GrpcRouteFaultInjectionPolicy | undefined,
292 ): GrpcRouteFaultInjectionPolicy | undefined => {
293 if (value === undefined) return undefined;
294 return {
295 delay: value.delay
296 ? {
297 fixedDelay: value.delay.fixedDelay,
298 percentage: value.delay.percentage,
299 }
300 : undefined,
301 abort: value.abort
302 ? {
303 httpStatus: value.abort.httpStatus,
304 percentage: value.abort.percentage,
305 }
306 : undefined,
307 };
308 };
309
310 const toRetry = (
311 value: GrpcRouteRetryPolicy | networkservices.GrpcRouteRetryPolicy | undefined,
312 ): GrpcRouteRetryPolicy | undefined => {
313 if (value === undefined) return undefined;
314 return {
315 retryConditions: value.retryConditions ?? [],
316 numRetries: value.numRetries,
317 };
318 };
319
320 const toAffinity = (
321 value:
322 | GrpcRouteStatefulSessionAffinityPolicy
323 | networkservices.GrpcRouteStatefulSessionAffinityPolicy
324 | undefined,
325 ): GrpcRouteStatefulSessionAffinityPolicy | undefined => {
326 if (value === undefined) return undefined;
327 return { cookieTtl: value.cookieTtl };
328 };
329
330 const toAction = (
331 value: GrpcRouteRouteAction | networkservices.GrpcRouteRouteAction | undefined,
332 ): GrpcRouteRouteAction | undefined => {
333 if (value === undefined) return undefined;
334 return {
335 destinations: (value.destinations ?? []).map(toDestination),
336 faultInjectionPolicy: toFault(value.faultInjectionPolicy),
337 timeout: value.timeout,
338 retryPolicy: toRetry(value.retryPolicy),
339 statefulSessionAffinity: toAffinity(value.statefulSessionAffinity),
340 idleTimeout: value.idleTimeout,
341 };
342 };
343
344 const toRule = (
345 value: GrpcRouteRouteRule | networkservices.GrpcRouteRouteRule,
346 ): GrpcRouteRouteRule => ({
347 matches: (value.matches ?? []).map(toMatch),
348 action: toAction(value.action),
349 });
350
351 const toAttrs = (route: networkservices.GrpcRoute, project: string) => {
352 const name = route.name ?? "";
353 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
354 return {
355 name,
356 grpcRouteId: parsed.id,
357 project: parsed.project || project,
358 location: parsed.location || DEFAULT_GLOBAL,
359 selfLink: route.selfLink,
360 hostnames: route.hostnames ?? [],
361 rules: (route.rules ?? []).map(toRule),
362 meshes: route.meshes ?? [],
363 gateways: route.gateways ?? [],
364 description: route.description,
365 labels: userLabels(route.labels),
366 createTime: route.createTime,
367 updateTime: route.updateTime,
368 };
369 };
370
371 const getByName = (name: string) =>
372 networkservices
373 .getProjectsLocationsGrpcRoutes({ name })
374 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
375
376 export const GrpcRouteProvider = () =>
377 Provider.succeed(GrpcRoute, {
378 stables: ["name", "grpcRouteId", "project", "location", "selfLink", "createTime"],
379
380 diff: Effect.fn(function* ({ news, olds, output }) {
381 if (!isResolved(news)) return undefined;
382 const previousId = olds?.grpcRouteId ?? output?.grpcRouteId;
383 const nextId = news.grpcRouteId ? rfc1035(news.grpcRouteId, "grpc-route") : previousId;
384 const previousLocation = normalizeLocation(
385 olds?.location ?? output?.location,
386 DEFAULT_GLOBAL,
387 );
388 const nextLocation = normalizeLocation(
389 news.location ?? olds?.location ?? output?.location,
390 DEFAULT_GLOBAL,
391 );
392 if (
393 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
394 previousLocation !== nextLocation
395 ) {
396 return { action: "replace" as const };
397 }
398 return undefined;
399 }),
400
401 read: Effect.fn(function* ({ id, olds, output }) {
402 const env = yield* GcpEnvironment.current;
403 const grpcRouteId = yield* toPhysicalId(
404 id,
405 olds?.grpcRouteId,
406 output?.grpcRouteId,
407 "grpc-route",
408 );
409 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
410 const name = output?.name ?? resourceName(env.project, location, COLLECTION, grpcRouteId);
411 const existing = yield* getByName(name);
412 if (existing === undefined) return undefined;
413 const attrs = toAttrs(existing, env.project);
414 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
415 }),
416
417 list: () =>
418 Effect.gen(function* () {
419 const env = yield* GcpEnvironment.current;
420 const items = yield* collectPages(
421 networkservices.listProjectsLocationsGrpcRoutes.pages({
422 parent: parentOf(env.project, "-"),
423 pageSize: 1000,
424 returnPartialSuccess: true,
425 }),
426 (page) => page.grpcRoutes,
427 );
428 return items
429 .filter((item) => hasAlchemyLabelKeys(item.labels))
430 .map((item) => toAttrs(item, env.project));
431 }),
432
433 reconcile: Effect.fn(function* ({ id, news, output }) {
434 const env = yield* GcpEnvironment.current;
435 const grpcRouteId = yield* toPhysicalId(
436 id,
437 news.grpcRouteId,
438 output?.grpcRouteId,
439 "grpc-route",
440 );
441 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
442 const name = resourceName(env.project, location, COLLECTION, grpcRouteId);
443 const desiredLabels = {
444 ...toLabels(news.labels),
445 ...(yield* createInternalLabels(id)),
446 };
447 const desiredRules = news.rules.map(toRule);
448 const desiredHostnames = news.hostnames;
449 const desiredMeshes = news.meshes ?? [];
450 const desiredGateways = news.gateways ?? [];
451
452 let current = yield* getByName(name);
453
454 if (current === undefined) {
455 const created = yield* networkservices
456 .createProjectsLocationsGrpcRoutes({
457 parent: parentOf(env.project, location),
458 grpcRouteId,
459 body: {
460 labels: desiredLabels,
461 description: news.description,
462 hostnames: desiredHostnames,
463 rules: desiredRules,
464 meshes: desiredMeshes,
465 gateways: desiredGateways,
466 },
467 })
468 .pipe(
469 Effect.retry({
470 while: (error) => error._tag === "Conflict",
471 times: 5,
472 schedule: Schedule.spaced("2 seconds"),
473 }),
474 Effect.catchTag("Conflict", () => Effect.undefined),
475 );
476 if (created !== undefined) {
477 yield* waitForOperation(created);
478 }
479 current = yield* waitUntilPresent(getByName(name), name);
480 }
481
482 const observedLabels = tagRecord(current.labels);
483 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
484 const labelsChanged = upsert.length > 0 || removed.length > 0;
485 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
486 const hostnamesChanged = !sameStringList(current.hostnames, desiredHostnames);
487 const rulesChanged = !sameJson((current.rules ?? []).map(toRule), desiredRules);
488 const meshesChanged = !sameStringList(current.meshes, desiredMeshes);
489 const gatewaysChanged = !sameStringList(current.gateways, desiredGateways);
490
491 const updateMask = changedFields([
492 ["labels", labelsChanged],
493 ["description", descriptionChanged],
494 ["hostnames", hostnamesChanged],
495 ["rules", rulesChanged],
496 ["meshes", meshesChanged],
497 ["gateways", gatewaysChanged],
498 ]);
499
500 if (updateMask.length > 0) {
501 const operation = yield* networkservices.patchProjectsLocationsGrpcRoutes({
502 name: current.name ?? name,
503 updateMask: updateMask.join(","),
504 body: {
505 name: current.name ?? name,
506 labels: desiredLabels,
507 description: news.description,
508 hostnames: desiredHostnames,
509 rules: desiredRules,
510 meshes: desiredMeshes,
511 gateways: desiredGateways,
512 },
513 });
514 yield* waitForOperation(operation);
515 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
516 }
517
518 return toAttrs(current, env.project);
519 }),
520
521 delete: Effect.fn(function* ({ output }) {
522 const operation = yield* networkservices
523 .deleteProjectsLocationsGrpcRoutes({ name: output.name })
524 .pipe(
525 Effect.retry({
526 while: (error) => error._tag === "Conflict",
527 times: 8,
528 schedule: Schedule.spaced("2 seconds"),
529 }),
530 Effect.catchTag("NotFound", () => Effect.undefined),
531 );
532 if (operation !== undefined) {
533 yield* waitForOperation(operation, { notFoundOk: true });
534 }
535 yield* waitUntilGone(getByName(output.name), output.name);
536 }),
537 });