@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.5 KB
Raw
1 import * as beyondcorp from "@distilled.cloud/gcp/beyondcorp_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 * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 DEFAULT_GLOBAL,
13 ResourceNotResolved,
14 collectPages,
15 encodeOwnershipLine,
16 expandName,
17 fieldMask,
18 fingerprint,
19 hasOwnershipMarker,
20 listAtLocation,
21 normalizeLocation,
22 ownedByAlchemy,
23 parseName,
24 parseOwnership,
25 replaceOnIdentity,
26 rfc1035,
27 toPhysicalId,
28 waitForDeleteOperation,
29 waitForOperation,
30 waitUntilExists,
31 waitUntilGone,
32 } from "./internal.ts";
33
34 const COLLECTION = "applications";
35
36 export type SecurityGatewaysApplicationEndpointMatcher = {
37 /** Hostname pattern (`example.com`, `*.example.com`). */
38 hostname?: string;
39 /** Ports that match this hostname. */
40 ports?: number[];
41 };
42
43 export type SecurityGatewaysApplicationUpstream = {
44 /** VPC network to forward traffic to. */
45 network?: { name?: string };
46 /** External endpoints to forward traffic to. */
47 external?: {
48 endpoints?: Array<{ hostname?: string; port?: number }>;
49 };
50 /** Optional proxy-protocol configuration for the upstream. */
51 proxyProtocol?: beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1ProxyProtocolConfig;
52 /** Regions where the application sends traffic. */
53 egressPolicy?: { regions?: string[] };
54 };
55
56 export type SecurityGatewaysApplicationProps = {
57 /**
58 * Parent SecurityGateway resource name
59 * (`projects/{project}/locations/{location}/securityGateways/{securityGateway}`)
60 * or gateway id. Immutable — changing it replaces the application.
61 */
62 securityGateway: string;
63 /**
64 * Application id (the `{application}` segment of
65 * `.../securityGateways/{securityGateway}/applications/{application}`).
66 * If omitted, a unique RFC1035 name is generated. Immutable —
67 * changing it replaces the application.
68 */
69 applicationId?: string;
70 /**
71 * Location of the parent gateway. Inferred from `securityGateway`
72 * when that value is a full resource name. Defaults to `global`.
73 * Immutable — changing it replaces the application.
74 * @default "global"
75 */
76 location?: string;
77 /**
78 * Endpoint matchers. The application matches when any matcher is
79 * satisfied.
80 */
81 endpointMatchers: SecurityGatewaysApplicationEndpointMatcher[];
82 /**
83 * External application schema (`PROXY_GATEWAY`, `API_GATEWAY`).
84 */
85 schema?: beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1ApplicationSchemaEnum | (string & {});
86 /**
87 * Upstream resources that receive matched traffic.
88 */
89 upstreams?: SecurityGatewaysApplicationUpstream[];
90 /**
91 * Human-readable name. Cannot exceed 64 characters. Application has
92 * no labels field, so Alchemy stamps ownership into this value and
93 * strips it from attributes.
94 */
95 displayName?: string;
96 };
97
98 export type SecurityGatewaysApplication = Resource<
99 "GCP.BeyondCorp.SecurityGatewaysApplication",
100 SecurityGatewaysApplicationProps,
101 {
102 /** Full resource name `.../securityGateways/{securityGateway}/applications/{application}`. */
103 name: string;
104 /** Application id (last path segment). */
105 applicationId: string;
106 /** Parent SecurityGateway resource name. */
107 securityGateway: string;
108 /** Project id. */
109 project: string;
110 /** Location id (`global`). */
111 location: string;
112 /** Endpoint matchers. */
113 endpointMatchers: SecurityGatewaysApplicationEndpointMatcher[];
114 /** External application schema. */
115 schema: string | undefined;
116 /** Upstream resources. */
117 upstreams: SecurityGatewaysApplicationUpstream[];
118 /** User display name with the Alchemy ownership prefix stripped. */
119 displayName: string | undefined;
120 /** RFC3339 creation timestamp. */
121 createTime: string | undefined;
122 /** RFC3339 last-update timestamp. */
123 updateTime: string | undefined;
124 },
125 never,
126 Providers
127 >;
128
129 /**
130 * A BeyondCorp Security Gateway application that matches host and
131 * port combinations and forwards traffic to upstreams.
132 *
133 * The API has no labels field, so Alchemy stamps ownership into
134 * `displayName` for `list` / nuke. Changing the parent gateway,
135 * application id, or location replaces the application. Display
136 * name, endpoint matchers, schema, and upstreams update in place.
137 *
138 * ### Creating a SecurityGatewaysApplication
139 * **Example:** Match HTTPS for a hostname
140 * ```typescript
141 * const app = yield* GCP.BeyondCorp.SecurityGatewaysApplication("Web", {
142 * securityGateway: gateway.name,
143 * endpointMatchers: [{ hostname: "app.example.com", ports: [443] }],
144 * });
145 * ```
146 *
147 * **Example:** External upstreams
148 * ```typescript
149 * const app = yield* GCP.BeyondCorp.SecurityGatewaysApplication("Web", {
150 * securityGateway: gateway.name,
151 * applicationId: "app-web",
152 * displayName: "prod web",
153 * endpointMatchers: [{ hostname: "app.example.com", ports: [80, 443] }],
154 * upstreams: [
155 * {
156 * external: {
157 * endpoints: [{ hostname: "origin.example.com", port: 443 }],
158 * },
159 * },
160 * ],
161 * });
162 * ```
163 *
164 * @resource
165 * @category BeyondCorp
166 */
167 export const SecurityGatewaysApplication = Resource<SecurityGatewaysApplication>(
168 "GCP.BeyondCorp.SecurityGatewaysApplication",
169 );
170
171 const parentGatewayName = (project: string, location: string, securityGateway: string) =>
172 expandName(securityGateway, project, location, "securityGateways");
173
174 const resourceNameOf = (parent: string, applicationId: string) =>
175 `${parent}/applications/${applicationId}`;
176
177 const parentFromName = (name: string) => {
178 const index = name.lastIndexOf("/applications/");
179 return index >= 0 ? name.slice(0, index) : name;
180 };
181
182 const locationFromParent = (securityGateway: string, fallback: string) => {
183 if (!securityGateway.includes("/locations/")) return fallback;
184 return parseName(securityGateway, "securityGateways", fallback).location;
185 };
186
187 const toMatchers = (
188 matchers: beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1EndpointMatcherList | undefined,
189 ): SecurityGatewaysApplicationEndpointMatcher[] =>
190 (matchers ?? []).map((matcher) => ({
191 hostname: matcher.hostname,
192 ports: matcher.ports ? [...matcher.ports] : undefined,
193 }));
194
195 const toUpstreams = (
196 upstreams: beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1ApplicationUpstreamList | undefined,
197 ): SecurityGatewaysApplicationUpstream[] =>
198 (upstreams ?? []).map((upstream) => ({
199 network: upstream.network ? { name: upstream.network.name } : undefined,
200 external: upstream.external
201 ? {
202 endpoints: (upstream.external.endpoints ?? []).map((endpoint) => ({
203 hostname: endpoint.hostname,
204 port: endpoint.port,
205 })),
206 }
207 : undefined,
208 proxyProtocol: upstream.proxyProtocol,
209 egressPolicy: upstream.egressPolicy
210 ? {
211 regions: upstream.egressPolicy.regions ? [...upstream.egressPolicy.regions] : undefined,
212 }
213 : undefined,
214 }));
215
216 const toAttrs = (
217 item: beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1Application,
218 project: string,
219 ) => {
220 const name = item.name ?? "";
221 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
222 const ownership = parseOwnership(item.displayName);
223 const parent = parentFromName(name);
224 return {
225 name,
226 applicationId: parsed.id,
227 securityGateway: parent,
228 project: parsed.project || project,
229 location: parsed.location,
230 endpointMatchers: toMatchers(item.endpointMatchers),
231 schema: item.schema === undefined ? undefined : `${item.schema}`,
232 upstreams: toUpstreams(item.upstreams),
233 displayName: ownership.text,
234 createTime: item.createTime,
235 updateTime: item.updateTime,
236 };
237 };
238
239 const getByName = (name: string) =>
240 beyondcorp
241 .getProjectsLocationsSecurityGatewaysApplications({ name })
242 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
243
244 const listOwned = (project: string) =>
245 Effect.gen(function* () {
246 const gateways = yield* listAtLocation(project, (parent) =>
247 collectPages(
248 beyondcorp.listProjectsLocationsSecurityGateways.pages({
249 parent,
250 pageSize: 1000,
251 }),
252 (
253 page,
254 ):
255 | readonly beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1SecurityGateway[]
256 | undefined => page.securityGateways,
257 ),
258 );
259 const nested = yield* Effect.forEach(
260 gateways.filter((gateway) => (gateway.name ?? "").length > 0),
261 (gateway) =>
262 collectPages(
263 beyondcorp.listProjectsLocationsSecurityGatewaysApplications.pages({
264 parent: gateway.name!,
265 pageSize: 1000,
266 }),
267 (
268 page,
269 ): readonly beyondcorp.GoogleCloudBeyondcorpSecuritygatewaysV1Application[] | undefined =>
270 page.applications,
271 ),
272 { concurrency: 4 },
273 );
274 return nested.flat().filter((item) => hasOwnershipMarker(item.displayName));
275 });
276
277 export const SecurityGatewaysApplicationProvider = () =>
278 Provider.succeed(SecurityGatewaysApplication, {
279 stables: ["name", "applicationId", "securityGateway", "project", "location", "createTime"],
280
281 diff: Effect.fn(function* ({ news, olds, output }) {
282 if (!isResolved(news)) return undefined;
283 const previousLocation = normalizeLocation(
284 olds?.location ?? output?.location,
285 DEFAULT_GLOBAL,
286 );
287 return replaceOnIdentity({
288 previousId: olds?.applicationId ?? output?.applicationId,
289 nextId: news.applicationId
290 ? rfc1035(news.applicationId, "application")
291 : (olds?.applicationId ?? output?.applicationId),
292 previousLocation,
293 nextLocation: normalizeLocation(
294 news.location ?? locationFromParent(news.securityGateway, previousLocation),
295 DEFAULT_GLOBAL,
296 ),
297 previousParent: olds?.securityGateway ?? output?.securityGateway,
298 nextParent: news.securityGateway,
299 });
300 }),
301
302 read: Effect.fn(function* ({ id, olds, output }) {
303 const env = yield* GcpEnvironment.current;
304 const location = normalizeLocation(
305 olds?.location ??
306 output?.location ??
307 (olds?.securityGateway
308 ? locationFromParent(olds.securityGateway, DEFAULT_GLOBAL)
309 : undefined),
310 DEFAULT_GLOBAL,
311 );
312 const applicationId = yield* toPhysicalId(
313 id,
314 olds?.applicationId,
315 output?.applicationId,
316 "application",
317 );
318 const parent = olds?.securityGateway
319 ? parentGatewayName(env.project, location, olds.securityGateway)
320 : output?.securityGateway;
321 const name = output?.name ?? (parent ? resourceNameOf(parent, applicationId) : undefined);
322 if (name === undefined) return undefined;
323 const existing = yield* getByName(name);
324 if (existing === undefined) return undefined;
325 const attrs = toAttrs(existing, env.project);
326 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
327 }),
328
329 list: () =>
330 Effect.gen(function* () {
331 const env = yield* GcpEnvironment.current;
332 const items = yield* listOwned(env.project);
333 return items.map((item) => toAttrs(item, env.project));
334 }),
335
336 reconcile: Effect.fn(function* ({ id, news, output }) {
337 const env = yield* GcpEnvironment.current;
338 const location = normalizeLocation(
339 news.location ??
340 output?.location ??
341 locationFromParent(news.securityGateway, DEFAULT_GLOBAL),
342 DEFAULT_GLOBAL,
343 );
344 const applicationId = yield* toPhysicalId(
345 id,
346 news.applicationId,
347 output?.applicationId,
348 "application",
349 );
350 const parent = parentGatewayName(env.project, location, news.securityGateway);
351 const name = resourceNameOf(parent, applicationId);
352 const ownership = yield* createInternalLabels(id);
353 const desiredDisplayName = encodeOwnershipLine(ownership, news.displayName);
354 const endpointMatchers = news.endpointMatchers.map((matcher) => ({
355 hostname: matcher.hostname,
356 ports: matcher.ports,
357 }));
358 const upstreams = news.upstreams;
359
360 let current = yield* getByName(output?.name ?? name);
361
362 if (current === undefined) {
363 const created = yield* beyondcorp
364 .createProjectsLocationsSecurityGatewaysApplications({
365 parent,
366 applicationId,
367 body: {
368 displayName: desiredDisplayName,
369 endpointMatchers,
370 schema: news.schema,
371 upstreams,
372 },
373 })
374 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
375 if (created !== undefined) {
376 yield* waitForOperation(created);
377 }
378 current = yield* waitUntilExists(getByName(name), name);
379 }
380
381 if (current === undefined) {
382 return yield* new ResourceNotResolved({ resourceName: name });
383 }
384
385 const mask = fieldMask([
386 (current.displayName ?? "") !== desiredDisplayName && "display_name",
387 fingerprint(toMatchers(current.endpointMatchers)) !== fingerprint(endpointMatchers) &&
388 "endpoint_matchers",
389 (current.schema ?? "") !== (news.schema ?? "") && "schema",
390 fingerprint(toUpstreams(current.upstreams)) !== fingerprint(upstreams) && "upstreams",
391 ]);
392
393 if (mask.length > 0) {
394 const operation = yield* beyondcorp.patchProjectsLocationsSecurityGatewaysApplications({
395 name: current.name ?? name,
396 updateMask: mask,
397 body: {
398 displayName: desiredDisplayName,
399 endpointMatchers,
400 schema: news.schema,
401 upstreams,
402 },
403 });
404 yield* waitForOperation(operation);
405 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
406 }
407
408 return toAttrs(current, env.project);
409 }),
410
411 delete: Effect.fn(function* ({ output }) {
412 const operation = yield* beyondcorp
413 .deleteProjectsLocationsSecurityGatewaysApplications({
414 name: output.name,
415 })
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* waitForDeleteOperation(operation);
426 }
427 yield* waitUntilGone(getByName(output.name), output.name);
428 }),
429 });