@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 405 lines 13.5 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 toBackendServiceResource,
25 toNamedResource,
26 toPhysicalId,
27 userLabels,
28 waitForOperation,
29 waitUntilGone,
30 waitUntilPresent,
31 } from "./internal.ts";
32
33 const COLLECTION = "tlsRoutes";
34
35 export type TlsRouteRouteMatch = {
36 /**
37 * SNI hosts to match, including wildcards (`*.example.com`). At least
38 * one of `sniHost` or `alpn` is required. Up to 100 SNI hosts across
39 * all matches.
40 */
41 sniHost?: string[];
42 /**
43 * ALPN values to match (`http/1.1`, `h2`). At least one of `sniHost`
44 * or `alpn` is required. Up to 5 ALPNs across all matches.
45 */
46 alpn?: string[];
47 };
48
49 export type TlsRouteRouteDestination = {
50 /**
51 * BackendService resource name to route to, e.g.
52 * `projects/{project}/locations/global/backendServices/{service}`.
53 */
54 serviceName?: string;
55 /**
56 * Relative weight of this destination. Weights do not need to sum to
57 * 100.
58 */
59 weight?: number;
60 };
61
62 export type TlsRouteRouteAction = {
63 /** Destination services. At least one is required. */
64 destinations?: TlsRouteRouteDestination[];
65 /**
66 * Idle timeout (e.g. `"3600s"`). Default 1 hour; `"0s"` disables it.
67 */
68 idleTimeout?: string;
69 };
70
71 export type TlsRouteRouteRule = {
72 /** Match predicates, OR-ed. At least one match is required. */
73 matches?: TlsRouteRouteMatch[];
74 /** Routing action applied when a match succeeds. */
75 action?: TlsRouteRouteAction;
76 };
77
78 export type TlsRouteProps = {
79 /**
80 * Route id (the `{tlsRoute}` segment of
81 * `projects/{project}/locations/{location}/tlsRoutes/{tlsRoute}`). If
82 * omitted, a unique name is generated from the stack, stage, and
83 * logical id. Immutable — changing it replaces the route.
84 */
85 tlsRouteId?: string;
86 /**
87 * Location (`global`, `us-central1`, …). Immutable — changing it
88 * replaces the route. `US-CENTRAL1` is accepted and normalized to
89 * `us-central1`.
90 * @default "global"
91 */
92 location?: string;
93 /**
94 * Human-readable description. Max 1024 characters.
95 */
96 description?: string;
97 /**
98 * Routing rules evaluated in order. At least one rule is required.
99 */
100 rules: TlsRouteRouteRule[];
101 /**
102 * Mesh resource names this route attaches to
103 * (`projects/{project}/locations/{location}/meshes/{mesh}`). Attached
104 * meshes must be sidecar type.
105 */
106 meshes?: string[];
107 /**
108 * Gateway resource names this route attaches to
109 * (`projects/{project}/locations/{location}/gateways/{gateway}`).
110 */
111 gateways?: string[];
112 /**
113 * TargetTcpProxy resource names this route attaches to
114 * (`projects/{project}/locations/{location}/targetTcpProxies/{proxy}`).
115 */
116 targetProxies?: string[];
117 /**
118 * User labels. Alchemy ownership labels are merged in automatically.
119 */
120 labels?: Record<string, string>;
121 };
122
123 export type TlsRoute = Resource<
124 "GCP.NetworkServices.TlsRoute",
125 TlsRouteProps,
126 {
127 /** Full resource name `projects/{project}/locations/{location}/tlsRoutes/{tlsRoute}`. */
128 name: string;
129 /** Route id (last path segment). */
130 tlsRouteId: string;
131 /** Project id. */
132 project: string;
133 /** Location id (`global`, `us-central1`, …). */
134 location: string;
135 /** User-provided description. */
136 description: string | undefined;
137 /** Configured routing rules. */
138 rules: TlsRouteRouteRule[];
139 /** Attached mesh resource names. */
140 meshes: string[];
141 /** Attached gateway resource names. */
142 gateways: string[];
143 /** Attached TargetTcpProxy resource names. */
144 targetProxies: string[];
145 /** User labels (Alchemy ownership labels stripped). */
146 labels: Record<string, string>;
147 /** Server-defined resource URL. */
148 selfLink: string | undefined;
149 /** RFC3339 creation timestamp. */
150 createTime: string | undefined;
151 /** RFC3339 last-update timestamp. */
152 updateTime: string | undefined;
153 },
154 never,
155 Providers
156 >;
157
158 /**
159 * A TlsRoute routes TLS traffic based on SNI and ALPN for a Mesh,
160 * Gateway, or TargetTcpProxy.
161 *
162 * Changing `tlsRouteId` or `location` replaces the route. Description,
163 * labels, rules, meshes, gateways, and target proxies update in place.
164 *
165 * ### Creating a TlsRoute
166 * **Example:** SNI-based sidecar route
167 * ```typescript
168 * const route = yield* GCP.NetworkServices.TlsRoute("Secure", {
169 * meshes: [mesh.name],
170 * rules: [
171 * {
172 * matches: [{ sniHost: ["api.example.com"], alpn: ["h2"] }],
173 * action: {
174 * destinations: [{ serviceName: backend.name, weight: 1 }],
175 * },
176 * },
177 * ],
178 * });
179 * ```
180 *
181 * @resource
182 * @category NetworkServices
183 */
184 export const TlsRoute = Resource<TlsRoute>("GCP.NetworkServices.TlsRoute");
185
186 const toDestination = (
187 project: string,
188 destination: TlsRouteRouteDestination | networkservices.TlsRouteRouteDestination,
189 ): TlsRouteRouteDestination => ({
190 serviceName: destination.serviceName
191 ? toBackendServiceResource(project, destination.serviceName)
192 : undefined,
193 weight: destination.weight,
194 });
195
196 const toAction = (
197 project: string,
198 action: TlsRouteRouteAction | networkservices.TlsRouteRouteAction | undefined,
199 ): TlsRouteRouteAction | undefined => {
200 if (action === undefined) return undefined;
201 return {
202 destinations: (action.destinations ?? []).map((destination) =>
203 toDestination(project, destination),
204 ),
205 idleTimeout: action.idleTimeout,
206 };
207 };
208
209 const toRule = (
210 project: string,
211 rule: TlsRouteRouteRule | networkservices.TlsRouteRouteRule,
212 ): TlsRouteRouteRule => ({
213 matches: (rule.matches ?? []).map((match) => ({
214 sniHost: [...(match.sniHost ?? [])],
215 alpn: [...(match.alpn ?? [])],
216 })),
217 action: toAction(project, rule.action),
218 });
219
220 const toMeshes = (project: string, location: string, meshes: readonly string[] | undefined) =>
221 (meshes ?? []).map((mesh) => toNamedResource(project, location, "meshes", mesh));
222
223 const toGateways = (project: string, location: string, gateways: readonly string[] | undefined) =>
224 (gateways ?? []).map((gateway) => toNamedResource(project, location, "gateways", gateway));
225
226 const toTargetProxies = (
227 project: string,
228 location: string,
229 proxies: readonly string[] | undefined,
230 ) => (proxies ?? []).map((proxy) => toNamedResource(project, location, "targetTcpProxies", proxy));
231
232 const toAttrs = (route: networkservices.TlsRoute, project: string) => {
233 const name = route.name ?? "";
234 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
235 const location = parsed.location || DEFAULT_GLOBAL;
236 const proj = parsed.project || project;
237 return {
238 name,
239 tlsRouteId: parsed.id,
240 project: proj,
241 location,
242 description: route.description,
243 rules: (route.rules ?? []).map((rule) => toRule(proj, rule)),
244 meshes: toMeshes(proj, location, route.meshes),
245 gateways: toGateways(proj, location, route.gateways),
246 targetProxies: toTargetProxies(proj, location, route.targetProxies),
247 labels: userLabels(route.labels),
248 selfLink: route.selfLink,
249 createTime: route.createTime,
250 updateTime: route.updateTime,
251 };
252 };
253
254 const getByName = (name: string) =>
255 networkservices
256 .getProjectsLocationsTlsRoutes({ name })
257 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
258
259 export const TlsRouteProvider = () =>
260 Provider.succeed(TlsRoute, {
261 stables: ["name", "tlsRouteId", "project", "location", "createTime", "selfLink"],
262
263 diff: Effect.fn(function* ({ news, olds, output }) {
264 if (!isResolved(news)) return undefined;
265 const previousId = olds?.tlsRouteId ?? output?.tlsRouteId;
266 const nextId = news.tlsRouteId ? rfc1035(news.tlsRouteId, "tls-route") : previousId;
267 const previousLocation = normalizeLocation(
268 olds?.location ?? output?.location,
269 DEFAULT_GLOBAL,
270 );
271 const nextLocation = normalizeLocation(
272 news.location ?? olds?.location ?? output?.location,
273 DEFAULT_GLOBAL,
274 );
275 if (
276 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
277 previousLocation !== nextLocation
278 ) {
279 return { action: "replace" as const };
280 }
281 return undefined;
282 }),
283
284 read: Effect.fn(function* ({ id, olds, output }) {
285 const env = yield* GcpEnvironment.current;
286 const tlsRouteId = yield* toPhysicalId(id, olds?.tlsRouteId, output?.tlsRouteId, "tls-route");
287 const location = normalizeLocation(olds?.location ?? output?.location, DEFAULT_GLOBAL);
288 const name = output?.name ?? resourceName(env.project, location, COLLECTION, tlsRouteId);
289 const existing = yield* getByName(name);
290 if (existing === undefined) return undefined;
291 const attrs = toAttrs(existing, env.project);
292 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
293 }),
294
295 list: () =>
296 Effect.gen(function* () {
297 const env = yield* GcpEnvironment.current;
298 const items = yield* collectPages(
299 networkservices.listProjectsLocationsTlsRoutes.pages({
300 parent: parentOf(env.project, "-"),
301 pageSize: 1000,
302 returnPartialSuccess: true,
303 }),
304 (page) => page.tlsRoutes,
305 );
306 return items
307 .filter((item) => hasAlchemyLabelKeys(item.labels))
308 .map((item) => toAttrs(item, env.project));
309 }),
310
311 reconcile: Effect.fn(function* ({ id, news, output }) {
312 const env = yield* GcpEnvironment.current;
313 const tlsRouteId = yield* toPhysicalId(id, news.tlsRouteId, output?.tlsRouteId, "tls-route");
314 const location = normalizeLocation(news.location ?? output?.location, DEFAULT_GLOBAL);
315 const name = resourceName(env.project, location, COLLECTION, tlsRouteId);
316 const desiredLabels = {
317 ...toLabels(news.labels),
318 ...(yield* createInternalLabels(id)),
319 };
320 const desiredRules = news.rules.map((rule) => toRule(env.project, rule));
321 const desiredMeshes = toMeshes(env.project, location, news.meshes);
322 const desiredGateways = toGateways(env.project, location, news.gateways);
323 const desiredProxies = toTargetProxies(env.project, location, news.targetProxies);
324
325 let current = yield* getByName(name);
326
327 if (current === undefined) {
328 const created = yield* networkservices
329 .createProjectsLocationsTlsRoutes({
330 parent: parentOf(env.project, location),
331 tlsRouteId,
332 body: {
333 description: news.description,
334 labels: desiredLabels,
335 rules: desiredRules,
336 meshes: desiredMeshes,
337 gateways: desiredGateways,
338 targetProxies: desiredProxies,
339 },
340 })
341 .pipe(
342 Effect.retry({
343 while: (error) => error._tag === "Conflict",
344 times: 5,
345 schedule: Schedule.spaced("2 seconds"),
346 }),
347 Effect.catchTag("Conflict", () => Effect.undefined),
348 );
349 if (created !== undefined) {
350 yield* waitForOperation(created);
351 }
352 current = yield* waitUntilPresent(getByName(name), name);
353 }
354
355 const observed = toAttrs(current, env.project);
356 const observedLabels = tagRecord(current.labels);
357 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
358 const labelsChanged = upsert.length > 0 || removed.length > 0;
359 const updateMask = changedFields([
360 ["labels", labelsChanged],
361 ["description", (current.description ?? "") !== (news.description ?? "")],
362 ["rules", !sameJson(observed.rules, desiredRules)],
363 ["meshes", !sameStringList(observed.meshes, desiredMeshes)],
364 ["gateways", !sameStringList(observed.gateways, desiredGateways)],
365 ["targetProxies", !sameStringList(observed.targetProxies, desiredProxies)],
366 ]);
367
368 if (updateMask.length > 0) {
369 const operation = yield* networkservices.patchProjectsLocationsTlsRoutes({
370 name: current.name ?? name,
371 updateMask: updateMask.join(","),
372 body: {
373 name: current.name ?? name,
374 labels: desiredLabels,
375 description: news.description,
376 rules: desiredRules,
377 meshes: desiredMeshes,
378 gateways: desiredGateways,
379 targetProxies: desiredProxies,
380 },
381 });
382 yield* waitForOperation(operation);
383 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
384 }
385
386 return toAttrs(current, env.project);
387 }),
388
389 delete: Effect.fn(function* ({ output }) {
390 const operation = yield* networkservices
391 .deleteProjectsLocationsTlsRoutes({ name: output.name })
392 .pipe(
393 Effect.retry({
394 while: (error) => error._tag === "Conflict",
395 times: 8,
396 schedule: Schedule.spaced("2 seconds"),
397 }),
398 Effect.catchTag("NotFound", () => Effect.undefined),
399 );
400 if (operation !== undefined) {
401 yield* waitForOperation(operation, { notFoundOk: true });
402 }
403 yield* waitUntilGone(getByName(output.name), output.name);
404 }),
405 });