@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, 04:45 UTC

main
ts 348 lines 12.3 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_v1";
2 import { unownedUnlessPrevious } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import { waitGlobalOperation } from "./operations.ts";
14
15 export type TargetGrpcProxyProps = {
16 /**
17 * TargetGrpcProxy name (RFC1035, 1-63 characters). If omitted, a unique
18 * name is generated from the stack, stage, and logical id. Changing it
19 * replaces the resource.
20 */
21 targetGrpcProxyName?: string;
22 /**
23 * Optional description. Alchemy ownership is stored in a `[alchemy …]`
24 * prefix so `list` / nuke can find resources (Compute TargetGrpcProxy has
25 * no labels field).
26 */
27 description?: string;
28 /**
29 * URL map this proxy routes to. Accepts a UrlMap self-link, a
30 * `projects/{project}/global/urlMaps/{name}` path, or the UrlMap name.
31 * The referenced backend services must use protocol `GRPC`. Changing
32 * this replaces the resource.
33 */
34 urlMap: string;
35 /**
36 * If true, BackendServices on the URL map may be reached by proxyless
37 * gRPC clients using the `xds:///` target URI (Traffic Director
38 * configuration checks apply). If false, clients use a sidecar proxy
39 * and must not use `xds:///`. Changing this replaces the resource.
40 * @default false
41 */
42 validateForProxyless?: boolean;
43 };
44
45 export type TargetGrpcProxy = Resource<
46 "GCP.Compute.TargetGrpcProxy",
47 TargetGrpcProxyProps,
48 {
49 /** TargetGrpcProxy name. */
50 targetGrpcProxyName: string;
51 /** Project id. */
52 project: string;
53 /** User description with the Alchemy ownership prefix stripped. */
54 description: string | undefined;
55 /** URL of the attached UrlMap. */
56 urlMap: string;
57 /** Whether proxyless gRPC clients are allowed. */
58 validateForProxyless: boolean;
59 /** Server-defined URL. */
60 selfLink: string | undefined;
61 /** Server-defined URL that includes the numeric id. */
62 selfLinkWithId: string | undefined;
63 /** Server-assigned numeric id. */
64 targetGrpcProxyId: string | undefined;
65 /** Optimistic-locking fingerprint. */
66 fingerprint: string | undefined;
67 /** RFC3339 creation timestamp. */
68 creationTimestamp: string | undefined;
69 /** Resource kind. */
70 kind: string | undefined;
71 },
72 never,
73 Providers
74 >;
75
76 /**
77 * A global Compute Engine target gRPC proxy.
78 *
79 * Target gRPC proxies are referenced by global forwarding rules with
80 * load-balancing scheme `INTERNAL_SELF_MANAGED` (Traffic Director) and
81 * point at a URL map whose backend services use protocol `GRPC`. This
82 * resource maps to the global `targetGrpcProxies` collection. Compute
83 * TargetGrpcProxy has no labels field — Alchemy ownership is stored in
84 * the description so nuke can find leaked proxies.
85 *
86 * ### Creating a Target gRPC Proxy
87 * **Example:** Generated name in front of a gRPC URL map
88 * ```typescript
89 * const backend = yield* GCP.Compute.BackendService("grpc", {
90 * protocol: "GRPC",
91 * loadBalancingScheme: "INTERNAL_SELF_MANAGED",
92 * });
93 * const map = yield* GCP.Compute.UrlMap("grpc", {
94 * defaultService: backend.selfLink,
95 * });
96 * const proxy = yield* GCP.Compute.TargetGrpcProxy("grpc", {
97 * urlMap: map.urlMapName,
98 * });
99 * ```
100 *
101 * **Example:** Explicit name, description, and proxyless validation
102 * ```typescript
103 * const proxy = yield* GCP.Compute.TargetGrpcProxy("grpc", {
104 * targetGrpcProxyName: "app-grpc",
105 * description: "traffic director frontend",
106 * urlMap: map.selfLink,
107 * validateForProxyless: true,
108 * });
109 * ```
110 *
111 * @resource
112 * @category Compute
113 */
114 export const TargetGrpcProxy = Resource<TargetGrpcProxy>("GCP.Compute.TargetGrpcProxy");
115
116 export class TargetGrpcProxyNotResolved extends Data.TaggedError(
117 "GCP.Compute.TargetGrpcProxyNotResolved",
118 )<{
119 targetGrpcProxyName: string;
120 }> {}
121
122 const toName = (id: string, name: string | undefined, existing?: string) =>
123 Effect.gen(function* () {
124 if (name !== undefined) return name;
125 if (existing !== undefined) return existing;
126 const generated = yield* createPhysicalName({
127 id,
128 maxLength: 63,
129 lowercase: true,
130 });
131 return /^[a-z]/.test(generated) ? generated : `g${generated}`.slice(0, 63);
132 });
133
134 const encodeDescription = (
135 labels: Record<string, string>,
136 description: string | undefined,
137 ): string => {
138 const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`;
139 return description ? `${marker}\n${description}` : marker;
140 };
141
142 const parseDescription = (
143 description: string | undefined,
144 ): {
145 labels: Record<string, string>;
146 description: string | undefined;
147 } => {
148 if (!description?.startsWith("[alchemy ")) {
149 return { labels: {}, description };
150 }
151 const end = description.indexOf("]");
152 if (end < 0) return { labels: {}, description };
153 const labels: Record<string, string> = {};
154 for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) {
155 const eq = part.indexOf("=");
156 if (eq > 0) {
157 labels[part.slice(0, eq)] = part.slice(eq + 1);
158 }
159 }
160 const rest = description.slice(end + 1).replace(/^\n/, "");
161 return { labels, description: rest.length > 0 ? rest : undefined };
162 };
163
164 const resourceTail = (value: string | undefined): string => {
165 if (value === undefined || value.length === 0) return "";
166 const parts = value.split("/").filter((part) => part.length > 0);
167 return parts[parts.length - 1] ?? "";
168 };
169
170 const toUrlMapRef = (project: string, urlMap: string): string => {
171 if (urlMap.includes("/")) return urlMap;
172 return `projects/${project}/global/urlMaps/${urlMap}`;
173 };
174
175 const toAttrs = (proxy: compute.TargetGrpcProxy, project: string) => {
176 const parsed = parseDescription(proxy.description);
177 return {
178 targetGrpcProxyName: proxy.name ?? proxy.id ?? "",
179 project,
180 description: parsed.description,
181 urlMap: proxy.urlMap ?? "",
182 validateForProxyless: proxy.validateForProxyless === true,
183 selfLink: proxy.selfLink,
184 selfLinkWithId: proxy.selfLinkWithId,
185 targetGrpcProxyId: proxy.id,
186 fingerprint: proxy.fingerprint,
187 creationTimestamp: proxy.creationTimestamp,
188 kind: proxy.kind,
189 };
190 };
191
192 const getByName = (project: string, targetGrpcProxy: string) =>
193 compute
194 .getTargetGrpcProxies({ project, targetGrpcProxy })
195 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
196
197 export const TargetGrpcProxyProvider = () =>
198 Provider.succeed(TargetGrpcProxy, {
199 stables: [
200 "targetGrpcProxyName",
201 "project",
202 "targetGrpcProxyId",
203 "selfLink",
204 "selfLinkWithId",
205 "creationTimestamp",
206 ],
207
208 diff: Effect.fn(function* ({ news, olds, output }) {
209 if (!isResolved(news)) return undefined;
210 const previous = olds?.targetGrpcProxyName ?? output?.targetGrpcProxyName;
211 const next = news.targetGrpcProxyName;
212 if (previous !== undefined && next !== undefined && previous !== next) {
213 return { action: "replace" as const, deleteFirst: true };
214 }
215 const previousUrlMap = olds?.urlMap ?? output?.urlMap;
216 if (
217 previousUrlMap !== undefined &&
218 resourceTail(previousUrlMap) !== resourceTail(news.urlMap)
219 ) {
220 return { action: "replace" as const, deleteFirst: true };
221 }
222 const previousProxyless = olds?.validateForProxyless ?? output?.validateForProxyless ?? false;
223 const nextProxyless = news.validateForProxyless ?? false;
224 if (previousProxyless !== nextProxyless) {
225 return { action: "replace" as const, deleteFirst: true };
226 }
227 return undefined;
228 }),
229
230 read: Effect.fn(function* ({ id, olds, output, previous }) {
231 const env = yield* GcpEnvironment.current;
232 const targetGrpcProxyName = yield* toName(
233 id,
234 olds?.targetGrpcProxyName,
235 output?.targetGrpcProxyName,
236 );
237 const existing = yield* getByName(env.project, targetGrpcProxyName);
238 if (existing === undefined) return undefined;
239 const attrs = toAttrs(existing, env.project);
240 const { labels } = parseDescription(existing.description);
241 return (yield* hasAlchemyLabels(id, labels))
242 ? attrs
243 : unownedUnlessPrevious(attrs, previous, "targetGrpcProxyName");
244 }),
245
246 list: () =>
247 Effect.gen(function* () {
248 const env = yield* GcpEnvironment.current;
249 return yield* compute.listTargetGrpcProxies
250 .items({ project: env.project, maxResults: 500 })
251 .pipe(
252 Stream.filter((proxy) => {
253 const { labels } = parseDescription(proxy.description);
254 return Object.keys(labels).some((key) => key.startsWith("alchemy-"));
255 }),
256 Stream.map((proxy) => toAttrs(proxy, env.project)),
257 Stream.runCollect,
258 Effect.map((chunk) => Array.from(chunk)),
259 );
260 }),
261
262 reconcile: Effect.fn(function* ({ id, news, output }) {
263 const env = yield* GcpEnvironment.current;
264 const targetGrpcProxyName = yield* toName(
265 id,
266 news.targetGrpcProxyName,
267 output?.targetGrpcProxyName,
268 );
269 const ownership = yield* createInternalLabels(id);
270 const desiredDescription = encodeDescription(ownership, news.description);
271 const desiredUrlMap = toUrlMapRef(env.project, news.urlMap);
272 const desiredProxyless = news.validateForProxyless === true;
273
274 let current = yield* getByName(env.project, targetGrpcProxyName);
275
276 if (current === undefined) {
277 const body: compute.TargetGrpcProxy = {
278 name: targetGrpcProxyName,
279 description: desiredDescription,
280 urlMap: desiredUrlMap,
281 };
282 if (news.validateForProxyless !== undefined) {
283 body.validateForProxyless = news.validateForProxyless;
284 }
285 yield* compute
286 .insertTargetGrpcProxies({
287 project: env.project,
288 body,
289 })
290 .pipe(
291 Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)),
292 Effect.catchTag("Conflict", () => Effect.undefined),
293 );
294 current = yield* getByName(env.project, targetGrpcProxyName);
295 }
296
297 if (current === undefined) {
298 return yield* new TargetGrpcProxyNotResolved({ targetGrpcProxyName });
299 }
300
301 const descriptionChanged = (current.description ?? "") !== desiredDescription;
302 const urlMapChanged = resourceTail(current.urlMap) !== resourceTail(desiredUrlMap);
303 const proxylessChanged = (current.validateForProxyless === true) !== desiredProxyless;
304
305 if (descriptionChanged || urlMapChanged || proxylessChanged) {
306 const body: compute.TargetGrpcProxy = {
307 fingerprint: current.fingerprint,
308 description: desiredDescription,
309 };
310 if (urlMapChanged) {
311 body.urlMap = desiredUrlMap;
312 }
313 if (proxylessChanged) {
314 body.validateForProxyless = desiredProxyless;
315 }
316 yield* compute
317 .patchTargetGrpcProxies({
318 project: env.project,
319 targetGrpcProxy: targetGrpcProxyName,
320 body,
321 })
322 .pipe(Effect.flatMap((operation) => waitGlobalOperation(env.project, operation)));
323 current = yield* getByName(env.project, targetGrpcProxyName);
324 if (current === undefined) {
325 return yield* new TargetGrpcProxyNotResolved({
326 targetGrpcProxyName,
327 });
328 }
329 }
330
331 return toAttrs(current, env.project);
332 }),
333
334 delete: Effect.fn(function* ({ output }) {
335 const env = yield* GcpEnvironment.current;
336 const operation = yield* compute
337 .deleteTargetGrpcProxies({
338 project: env.project,
339 targetGrpcProxy: output.targetGrpcProxyName,
340 })
341 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
342 if (operation !== undefined) {
343 yield* waitGlobalOperation(env.project, operation).pipe(
344 Effect.catchTag("NotFound", () => Effect.void),
345 );
346 }
347 }),
348 });