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

main
ts 431 lines 14.3 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 { 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_CONNECTION_TYPE,
14 DEFAULT_GATEWAY_KIND,
15 ResourceNotResolved,
16 collectPages,
17 expandName,
18 fieldMask,
19 fingerprint,
20 hasAlchemyLabelMap,
21 lastSegment,
22 listAtLocation,
23 normalizeLocation,
24 parentOf,
25 parseName,
26 replaceOnIdentity,
27 rfc1035,
28 sameStringList,
29 sameText,
30 toPhysicalId,
31 userLabels,
32 waitForDeleteOperation,
33 waitForOperation,
34 waitUntilExists,
35 waitUntilGone,
36 waitUntilReady,
37 } from "./internal.ts";
38
39 const COLLECTION = "appConnections";
40
41 export type AppConnectionApplicationEndpoint = {
42 /** Hostname or IP of the remote application. */
43 host?: string;
44 /** Port of the remote application. */
45 port?: number;
46 };
47
48 export type AppConnectionGateway = {
49 /**
50 * Hosting type of the gateway.
51 * @default "GCP_REGIONAL_MIG"
52 */
53 type?:
54 | beyondcorp.GoogleCloudBeyondcorpAppconnectionsV1AppConnectionGatewayTypeEnum
55 | (string & {});
56 /**
57 * AppGateway resource name
58 * (`projects/{project}/locations/{location}/appGateways/{appGateway}`)
59 * or gateway id.
60 */
61 appGateway?: string;
62 /** Ingress port reserved on the gateway. Output only. */
63 ingressPort?: number;
64 /** Server-defined URI. Output only. */
65 uri?: string;
66 /** L7 private service connection. Output only. */
67 l7psc?: string;
68 };
69
70 export type AppConnectionProps = {
71 /**
72 * AppConnection id (the `{appConnection}` segment of
73 * `projects/{project}/locations/{location}/appConnections/{appConnection}`).
74 * If omitted, a unique RFC1035 name is generated. Must be 4-63
75 * characters matching `[a-z]([a-z0-9-]{0,61}[a-z0-9])?`. Immutable —
76 * changing it replaces the connection.
77 */
78 appConnectionId?: string;
79 /**
80 * Region (`us-central1`, …). Immutable — changing it replaces the
81 * connection. `US-CENTRAL1` is accepted and normalized to `us-central1`.
82 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
83 */
84 location?: string;
85 /**
86 * Network connectivity type. Immutable — changing it replaces the
87 * connection.
88 * @default "TCP_PROXY"
89 */
90 type?: beyondcorp.GoogleCloudBeyondcorpAppconnectionsV1AppConnectionTypeEnum | (string & {});
91 /**
92 * Remote application endpoint. Host and port are required.
93 */
94 applicationEndpoint: AppConnectionApplicationEndpoint;
95 /**
96 * Gateway used by the connection. The nested `appGateway` is
97 * immutable — changing it replaces the connection.
98 */
99 gateway?: AppConnectionGateway;
100 /**
101 * AppConnector resource names authorized to associate with this
102 * connection.
103 */
104 connectors?: string[];
105 /**
106 * Human-readable name. Cannot exceed 64 characters.
107 */
108 displayName?: string;
109 /**
110 * User labels. Alchemy ownership labels are merged in automatically.
111 */
112 labels?: Record<string, string>;
113 };
114
115 export type AppConnection = Resource<
116 "GCP.BeyondCorp.AppConnection",
117 AppConnectionProps,
118 {
119 /** Full resource name `projects/{project}/locations/{location}/appConnections/{appConnection}`. */
120 name: string;
121 /** AppConnection id (last path segment). */
122 appConnectionId: string;
123 /** Project id. */
124 project: string;
125 /** Location id. */
126 location: string;
127 /** Network connectivity type. */
128 type: string | undefined;
129 /** Remote application endpoint. */
130 applicationEndpoint: AppConnectionApplicationEndpoint | undefined;
131 /** Gateway used by the connection. */
132 gateway: AppConnectionGateway | undefined;
133 /** Authorized AppConnector names. */
134 connectors: string[];
135 /** Human-readable name. */
136 displayName: string | undefined;
137 /** User labels (Alchemy ownership labels stripped). */
138 labels: Record<string, string>;
139 /** Server-reported state (`CREATED`, `CREATING`, …). */
140 state: string | undefined;
141 /** Server-generated resource uid. */
142 uid: string | undefined;
143 /** RFC3339 creation timestamp. */
144 createTime: string | undefined;
145 /** RFC3339 last-update timestamp. */
146 updateTime: string | undefined;
147 },
148 never,
149 Providers
150 >;
151
152 /**
153 * A BeyondCorp AppConnection that links a remote application endpoint
154 * to an AppGateway and optional AppConnectors.
155 *
156 * Changing `appConnectionId`, `location`, `type`, or
157 * `gateway.appGateway` replaces the connection. Display name, labels,
158 * application endpoint, and connectors update in place.
159 *
160 * ### Creating an AppConnection
161 * **Example:** TCP proxy through an AppGateway
162 * ```typescript
163 * const connection = yield* GCP.BeyondCorp.AppConnection("App", {
164 * applicationEndpoint: { host: "10.0.0.4", port: 8080 },
165 * gateway: { appGateway: gateway.name },
166 * connectors: [connector.name],
167 * });
168 * ```
169 *
170 * **Example:** Explicit id and labels
171 * ```typescript
172 * const connection = yield* GCP.BeyondCorp.AppConnection("App", {
173 * appConnectionId: "app-tcp",
174 * type: "TCP_PROXY",
175 * applicationEndpoint: { host: "app.internal", port: 443 },
176 * gateway: { appGateway: gateway.name },
177 * displayName: "prod app",
178 * labels: { env: "prod" },
179 * });
180 * ```
181 *
182 * @resource
183 * @category BeyondCorp
184 */
185 export const AppConnection = Resource<AppConnection>("GCP.BeyondCorp.AppConnection");
186
187 const resourceName = (project: string, location: string, appConnectionId: string) =>
188 `projects/${project}/locations/${location}/appConnections/${appConnectionId}`;
189
190 const expandConnectors = (
191 connectors: readonly string[] | undefined,
192 project: string,
193 location: string,
194 ) =>
195 (connectors ?? []).map((connector) => expandName(connector, project, location, "appConnectors"));
196
197 const expandGateway = (
198 gateway: AppConnectionGateway | undefined,
199 project: string,
200 location: string,
201 ): AppConnectionGateway | undefined => {
202 if (gateway === undefined) return undefined;
203 const appGateway = gateway.appGateway
204 ? expandName(gateway.appGateway, project, location, "appGateways")
205 : undefined;
206 return {
207 type: gateway.type ?? DEFAULT_GATEWAY_KIND,
208 appGateway,
209 ingressPort: gateway.ingressPort,
210 uri: gateway.uri,
211 l7psc: gateway.l7psc,
212 };
213 };
214
215 const toGateway = (
216 gateway: beyondcorp.GoogleCloudBeyondcorpAppconnectionsV1AppConnectionGateway | undefined,
217 ): AppConnectionGateway | undefined => {
218 if (gateway === undefined) return undefined;
219 return {
220 type: gateway.type === undefined ? undefined : `${gateway.type}`,
221 appGateway: gateway.appGateway,
222 ingressPort: gateway.ingressPort,
223 uri: gateway.uri,
224 l7psc: gateway.l7psc,
225 };
226 };
227
228 const toAttrs = (
229 item: beyondcorp.GoogleCloudBeyondcorpAppconnectionsV1AppConnection,
230 project: string,
231 region: string,
232 ) => {
233 const name = item.name ?? "";
234 const parsed = parseName(name, COLLECTION, region);
235 return {
236 name,
237 appConnectionId: parsed.id,
238 project: parsed.project || project,
239 location: parsed.location,
240 type: item.type === undefined ? undefined : `${item.type}`,
241 applicationEndpoint: item.applicationEndpoint
242 ? {
243 host: item.applicationEndpoint.host,
244 port: item.applicationEndpoint.port,
245 }
246 : undefined,
247 gateway: toGateway(item.gateway),
248 connectors: item.connectors ? [...item.connectors] : [],
249 displayName: item.displayName,
250 labels: userLabels(item.labels),
251 state: item.state === undefined ? undefined : `${item.state}`,
252 uid: item.uid,
253 createTime: item.createTime,
254 updateTime: item.updateTime,
255 };
256 };
257
258 const getByName = (name: string) =>
259 beyondcorp
260 .getProjectsLocationsAppConnections({ name })
261 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
262
263 const listOwned = (project: string) =>
264 listAtLocation(project, (parent) =>
265 collectPages(
266 beyondcorp.listProjectsLocationsAppConnections.pages({
267 parent,
268 pageSize: 1000,
269 }),
270 (
271 page,
272 ): readonly beyondcorp.GoogleCloudBeyondcorpAppconnectionsV1AppConnection[] | undefined =>
273 page.appConnections,
274 ),
275 ).pipe(Effect.map((items) => items.filter((item) => hasAlchemyLabelMap(item.labels))));
276
277 export const AppConnectionProvider = () =>
278 Provider.succeed(AppConnection, {
279 stables: ["name", "appConnectionId", "project", "location", "uid", "createTime"],
280
281 diff: Effect.fn(function* ({ news, olds, output }) {
282 if (!isResolved(news)) return undefined;
283 const env = yield* GcpEnvironment.current;
284 const previousType = olds?.type ?? output?.type ?? DEFAULT_CONNECTION_TYPE;
285 const nextType = news.type ?? previousType;
286 const previousGateway = lastSegment(
287 olds?.gateway?.appGateway ?? output?.gateway?.appGateway ?? "",
288 );
289 const nextGateway = lastSegment(news.gateway?.appGateway ?? "");
290 return replaceOnIdentity({
291 previousId: olds?.appConnectionId ?? output?.appConnectionId,
292 nextId: news.appConnectionId
293 ? rfc1035(news.appConnectionId, "appconnection")
294 : (olds?.appConnectionId ?? output?.appConnectionId),
295 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
296 nextLocation: normalizeLocation(
297 news.location ?? olds?.location ?? output?.location,
298 env.region,
299 ),
300 extra:
301 previousType !== nextType ||
302 (previousGateway.length > 0 && nextGateway.length > 0 && previousGateway !== nextGateway),
303 });
304 }),
305
306 read: Effect.fn(function* ({ id, olds, output }) {
307 const env = yield* GcpEnvironment.current;
308 const appConnectionId = yield* toPhysicalId(
309 id,
310 olds?.appConnectionId,
311 output?.appConnectionId,
312 "appconnection",
313 );
314 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
315 const name = output?.name ?? resourceName(env.project, location, appConnectionId);
316 const existing = yield* getByName(name);
317 if (existing === undefined) return undefined;
318 const attrs = toAttrs(existing, env.project, env.region);
319 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
320 }),
321
322 list: () =>
323 Effect.gen(function* () {
324 const env = yield* GcpEnvironment.current;
325 const items = yield* listOwned(env.project);
326 return items.map((item) => toAttrs(item, env.project, env.region));
327 }),
328
329 reconcile: Effect.fn(function* ({ id, news, output }) {
330 const env = yield* GcpEnvironment.current;
331 const appConnectionId = yield* toPhysicalId(
332 id,
333 news.appConnectionId,
334 output?.appConnectionId,
335 "appconnection",
336 );
337 const location = normalizeLocation(news.location ?? output?.location, env.region);
338 const name = resourceName(env.project, location, appConnectionId);
339 const desiredLabels = {
340 ...toLabels(news.labels),
341 ...(yield* createInternalLabels(id)),
342 };
343 const type = news.type ?? DEFAULT_CONNECTION_TYPE;
344 const applicationEndpoint = {
345 host: news.applicationEndpoint.host,
346 port: news.applicationEndpoint.port,
347 };
348 const gateway = expandGateway(news.gateway, env.project, location);
349 const connectors = expandConnectors(news.connectors, env.project, location);
350
351 let current = yield* getByName(output?.name ?? name);
352
353 if (current === undefined) {
354 const created = yield* beyondcorp
355 .createProjectsLocationsAppConnections({
356 parent: parentOf(env.project, location),
357 appConnectionId,
358 body: {
359 type,
360 applicationEndpoint,
361 gateway: gateway
362 ? {
363 type: gateway.type,
364 appGateway: gateway.appGateway,
365 }
366 : undefined,
367 connectors,
368 displayName: news.displayName,
369 labels: desiredLabels,
370 },
371 })
372 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
373 if (created !== undefined) {
374 yield* waitForOperation(created);
375 }
376 current = yield* waitUntilReady(getByName(name), name, (item) =>
377 item.state === undefined ? undefined : `${item.state}`,
378 );
379 }
380
381 if (current === undefined) {
382 return yield* new ResourceNotResolved({ resourceName: name });
383 }
384
385 const observedLabels = tagRecord(current.labels);
386 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
387 const endpointChanged =
388 fingerprint(current.applicationEndpoint) !== fingerprint(applicationEndpoint);
389 const connectorsChanged = !sameStringList(current.connectors, connectors);
390 const mask = fieldMask([
391 (upsert.length > 0 || removed.length > 0) && "labels",
392 !sameText(current.displayName, news.displayName) && "display_name",
393 endpointChanged && "application_endpoint",
394 connectorsChanged && "connectors",
395 ]);
396
397 if (mask.length > 0) {
398 const operation = yield* beyondcorp.patchProjectsLocationsAppConnections({
399 name: current.name ?? name,
400 updateMask: mask,
401 body: {
402 displayName: news.displayName,
403 labels: desiredLabels,
404 applicationEndpoint,
405 connectors,
406 },
407 });
408 yield* waitForOperation(operation);
409 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
410 }
411
412 return toAttrs(current, env.project, env.region);
413 }),
414
415 delete: Effect.fn(function* ({ output }) {
416 const operation = yield* beyondcorp
417 .deleteProjectsLocationsAppConnections({ name: output.name })
418 .pipe(
419 Effect.retry({
420 while: (error) => error._tag === "Conflict",
421 times: 8,
422 schedule: Schedule.spaced("2 seconds"),
423 }),
424 Effect.catchTag("NotFound", () => Effect.undefined),
425 );
426 if (operation !== undefined) {
427 yield* waitForDeleteOperation(operation);
428 }
429 yield* waitUntilGone(getByName(output.name), output.name);
430 }),
431 });