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

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