@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 301 lines 10.1 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, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 DEFAULT_GATEWAY_TYPE,
14 DEFAULT_HOST_TYPE,
15 ResourceNotResolved,
16 collectPages,
17 hasAlchemyLabelMap,
18 listAtLocation,
19 normalizeLocation,
20 parentOf,
21 parseName,
22 replaceOnIdentity,
23 rfc1035,
24 toPhysicalId,
25 userLabels,
26 waitForDeleteOperation,
27 waitForOperation,
28 waitUntilGone,
29 waitUntilReady,
30 } from "./internal.ts";
31
32 const COLLECTION = "appGateways";
33
34 export type AppGatewayAllocatedConnection = {
35 /** PSC URI of an allocated connection. */
36 pscUri?: string;
37 /** Ingress port of an allocated connection. */
38 ingressPort?: number;
39 };
40
41 export type AppGatewayProps = {
42 /**
43 * AppGateway id (the `{appGateway}` segment of
44 * `projects/{project}/locations/{location}/appGateways/{appGateway}`).
45 * If omitted, a unique RFC1035 name is generated. Must be 4-63
46 * characters matching `[a-z]([a-z0-9-]{0,61}[a-z0-9])?`. Immutable —
47 * changing it replaces the gateway.
48 */
49 appGatewayId?: string;
50 /**
51 * Region (`us-central1`, …). Immutable — changing it replaces the
52 * gateway. `US-CENTRAL1` is accepted and normalized to `us-central1`.
53 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
54 */
55 location?: string;
56 /**
57 * Network connectivity type. Immutable — changing it replaces the
58 * gateway.
59 * @default "TCP_PROXY"
60 */
61 type?: beyondcorp.AppGatewayTypeEnum | (string & {});
62 /**
63 * Hosting type. Immutable — changing it replaces the gateway.
64 * @default "GCP_REGIONAL_MIG"
65 */
66 hostType?: beyondcorp.AppGatewayHostTypeEnum | (string & {});
67 /**
68 * Human-readable name. Cannot exceed 64 characters. AppGateway has no
69 * update API, so this is set at create only.
70 */
71 displayName?: string;
72 /**
73 * User labels. Alchemy ownership labels are merged in automatically.
74 * AppGateway has no update API, so labels are set at create only.
75 */
76 labels?: Record<string, string>;
77 };
78
79 export type AppGateway = Resource<
80 "GCP.BeyondCorp.AppGateway",
81 AppGatewayProps,
82 {
83 /** Full resource name `projects/{project}/locations/{location}/appGateways/{appGateway}`. */
84 name: string;
85 /** AppGateway id (last path segment). */
86 appGatewayId: string;
87 /** Project id. */
88 project: string;
89 /** Location id. */
90 location: string;
91 /** Network connectivity type. */
92 type: string | undefined;
93 /** Hosting type. */
94 hostType: string | undefined;
95 /** Human-readable name. */
96 displayName: string | undefined;
97 /** User labels (Alchemy ownership labels stripped). */
98 labels: Record<string, string>;
99 /** Server-reported state (`CREATED`, `CREATING`, …). */
100 state: string | undefined;
101 /** Server-defined URI. */
102 uri: string | undefined;
103 /** Allocated PSC connections. */
104 allocatedConnections: AppGatewayAllocatedConnection[];
105 /** Server-generated resource uid. */
106 uid: string | undefined;
107 /** RFC3339 creation timestamp. */
108 createTime: string | undefined;
109 /** RFC3339 last-update timestamp. */
110 updateTime: string | undefined;
111 },
112 never,
113 Providers
114 >;
115
116 /**
117 * A BeyondCorp AppGateway that provisions the GCP components used to
118 * reach a remote application.
119 *
120 * Changing `appGatewayId`, `location`, `type`, or `hostType` replaces
121 * the gateway. The API has no patch method — display name and labels
122 * are applied at create only.
123 *
124 * ### Creating an AppGateway
125 * **Example:** Generated name
126 * ```typescript
127 * const gateway = yield* GCP.BeyondCorp.AppGateway("Edge", {});
128 * ```
129 *
130 * **Example:** Explicit id, type, and labels
131 * ```typescript
132 * const gateway = yield* GCP.BeyondCorp.AppGateway("Edge", {
133 * appGatewayId: "app-edge",
134 * location: "us-central1",
135 * type: "TCP_PROXY",
136 * hostType: "GCP_REGIONAL_MIG",
137 * displayName: "edge gateway",
138 * labels: { env: "prod" },
139 * });
140 * ```
141 *
142 * @resource
143 * @category BeyondCorp
144 */
145 export const AppGateway = Resource<AppGateway>("GCP.BeyondCorp.AppGateway");
146
147 const resourceName = (project: string, location: string, appGatewayId: string) =>
148 `projects/${project}/locations/${location}/appGateways/${appGatewayId}`;
149
150 const toAttrs = (item: beyondcorp.AppGateway, project: string, region: string) => {
151 const name = item.name ?? "";
152 const parsed = parseName(name, COLLECTION, region);
153 return {
154 name,
155 appGatewayId: parsed.id,
156 project: parsed.project || project,
157 location: parsed.location,
158 type: item.type === undefined ? undefined : `${item.type}`,
159 hostType: item.hostType === undefined ? undefined : `${item.hostType}`,
160 displayName: item.displayName,
161 labels: userLabels(item.labels),
162 state: item.state === undefined ? undefined : `${item.state}`,
163 uri: item.uri,
164 allocatedConnections: (item.allocatedConnections ?? []).map((connection) => ({
165 pscUri: connection.pscUri,
166 ingressPort: connection.ingressPort,
167 })),
168 uid: item.uid,
169 createTime: item.createTime,
170 updateTime: item.updateTime,
171 };
172 };
173
174 const getByName = (name: string) =>
175 beyondcorp
176 .getProjectsLocationsAppGateways({ name })
177 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
178
179 const listOwned = (project: string) =>
180 listAtLocation(project, (parent) =>
181 collectPages(
182 beyondcorp.listProjectsLocationsAppGateways.pages({
183 parent,
184 pageSize: 1000,
185 }),
186 (page): readonly beyondcorp.AppGateway[] | undefined => page.appGateways,
187 ),
188 ).pipe(Effect.map((items) => items.filter((item) => hasAlchemyLabelMap(item.labels))));
189
190 export const AppGatewayProvider = () =>
191 Provider.succeed(AppGateway, {
192 stables: ["name", "appGatewayId", "project", "location", "uid", "createTime"],
193
194 diff: Effect.fn(function* ({ news, olds, output }) {
195 if (!isResolved(news)) return undefined;
196 const env = yield* GcpEnvironment.current;
197 const previousType = olds?.type ?? output?.type ?? DEFAULT_GATEWAY_TYPE;
198 const nextType = news.type ?? previousType;
199 const previousHost = olds?.hostType ?? output?.hostType ?? DEFAULT_HOST_TYPE;
200 const nextHost = news.hostType ?? previousHost;
201 return replaceOnIdentity({
202 previousId: olds?.appGatewayId ?? output?.appGatewayId,
203 nextId: news.appGatewayId
204 ? rfc1035(news.appGatewayId, "appgateway")
205 : (olds?.appGatewayId ?? output?.appGatewayId),
206 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
207 nextLocation: normalizeLocation(
208 news.location ?? olds?.location ?? output?.location,
209 env.region,
210 ),
211 extra: previousType !== nextType || previousHost !== nextHost,
212 });
213 }),
214
215 read: Effect.fn(function* ({ id, olds, output }) {
216 const env = yield* GcpEnvironment.current;
217 const appGatewayId = yield* toPhysicalId(
218 id,
219 olds?.appGatewayId,
220 output?.appGatewayId,
221 "appgateway",
222 );
223 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
224 const name = output?.name ?? resourceName(env.project, location, appGatewayId);
225 const existing = yield* getByName(name);
226 if (existing === undefined) return undefined;
227 const attrs = toAttrs(existing, env.project, env.region);
228 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
229 }),
230
231 list: () =>
232 Effect.gen(function* () {
233 const env = yield* GcpEnvironment.current;
234 const items = yield* listOwned(env.project);
235 return items.map((item) => toAttrs(item, env.project, env.region));
236 }),
237
238 reconcile: Effect.fn(function* ({ id, news, output }) {
239 const env = yield* GcpEnvironment.current;
240 const appGatewayId = yield* toPhysicalId(
241 id,
242 news.appGatewayId,
243 output?.appGatewayId,
244 "appgateway",
245 );
246 const location = normalizeLocation(news.location ?? output?.location, env.region);
247 const name = resourceName(env.project, location, appGatewayId);
248 const desiredLabels = {
249 ...toLabels(news.labels),
250 ...(yield* createInternalLabels(id)),
251 };
252 const type = news.type ?? DEFAULT_GATEWAY_TYPE;
253 const hostType = news.hostType ?? DEFAULT_HOST_TYPE;
254
255 let current = yield* getByName(output?.name ?? name);
256
257 if (current === undefined) {
258 const created = yield* beyondcorp
259 .createProjectsLocationsAppGateways({
260 parent: parentOf(env.project, location),
261 appGatewayId,
262 body: {
263 type,
264 hostType,
265 displayName: news.displayName,
266 labels: desiredLabels,
267 },
268 })
269 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
270 if (created !== undefined) {
271 yield* waitForOperation(created);
272 }
273 current = yield* waitUntilReady(getByName(name), name, (item) =>
274 item.state === undefined ? undefined : `${item.state}`,
275 );
276 }
277
278 if (current === undefined) {
279 return yield* new ResourceNotResolved({ resourceName: name });
280 }
281
282 return toAttrs(current, env.project, env.region);
283 }),
284
285 delete: Effect.fn(function* ({ output }) {
286 const operation = yield* beyondcorp
287 .deleteProjectsLocationsAppGateways({ name: output.name })
288 .pipe(
289 Effect.retry({
290 while: (error) => error._tag === "Conflict",
291 times: 8,
292 schedule: Schedule.spaced("2 seconds"),
293 }),
294 Effect.catchTag("NotFound", () => Effect.undefined),
295 );
296 if (operation !== undefined) {
297 yield* waitForDeleteOperation(operation);
298 }
299 yield* waitUntilGone(getByName(output.name), output.name);
300 }),
301 });