@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 386 lines 13.1 KB
Raw
1 import * as networkconnectivity from "@distilled.cloud/gcp/networkconnectivity_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 NetworkConnectivityNotResolved,
14 canonicalizeLink,
15 collectPages,
16 hasAlchemyLabelKeys,
17 lastSegment,
18 normalizeLocation,
19 parentOf,
20 parseName,
21 rfc1035,
22 toNetworkResource,
23 toPhysicalId,
24 toSubnetworkResource,
25 userLabels,
26 waitForOperation,
27 waitUntilGone,
28 waitUntilPresent,
29 } from "./internal.ts";
30
31 const COLLECTION = "regionalEndpoints";
32 const MAX_ID_LENGTH = 46;
33
34 export type RegionalEndpointAccessType =
35 | networkconnectivity.RegionalEndpointAccessTypeEnum
36 | (string & {});
37
38 export type RegionalEndpointProps = {
39 /**
40 * RegionalEndpoint id (the `{regional_endpoint}` segment of
41 * `projects/{project}/locations/{location}/regionalEndpoints/{regional_endpoint}`).
42 * If omitted, a unique name is generated. Must match
43 * `[-a-z0-9]([-a-z0-9]{0,44})[a-z0-9]`. Immutable — changing it
44 * replaces the endpoint.
45 */
46 regionalEndpointId?: string;
47 /**
48 * Location (`us-central1`, …). Immutable — changing it replaces the
49 * endpoint. `US-CENTRAL1` is accepted and normalized to `us-central1`.
50 * @default the stack's GCP region (`GCP.Region`, else the profile
51 * region, else `us-central1`)
52 */
53 location?: string;
54 /**
55 * Service endpoint this private regional endpoint connects to, e.g.
56 * `"storage.us-central1.p.rep.googleapis.com"`. Immutable — changing
57 * it replaces the endpoint.
58 */
59 targetGoogleApi: string;
60 /**
61 * Access type reflected on the PSC forwarding rule (`REGIONAL` or
62 * `GLOBAL`). Immutable — changing it replaces the endpoint.
63 */
64 accessType: RegionalEndpointAccessType;
65 /**
66 * VPC network
67 * (`projects/{project}/global/networks/{network}` or a Compute
68 * self-link). Immutable — changing it replaces the endpoint.
69 */
70 network?: string;
71 /**
72 * Subnetwork used to allocate the IP
73 * (`projects/{project}/regions/{region}/subnetworks/{subnetwork}` or a
74 * Compute self-link). Immutable — changing it replaces the endpoint.
75 */
76 subnetwork?: string;
77 /**
78 * IP address or Address resource URI. When omitted, an IP is allocated
79 * from `subnetwork`. Immutable — changing it replaces the endpoint.
80 */
81 address?: string;
82 /**
83 * Human-readable description. Set at create; the API has no update.
84 */
85 description?: string;
86 /**
87 * User labels. Alchemy ownership labels are merged in automatically.
88 */
89 labels?: Record<string, string>;
90 };
91
92 export type RegionalEndpoint = Resource<
93 "GCP.NetworkConnectivity.RegionalEndpoint",
94 RegionalEndpointProps,
95 {
96 /** Full resource name `projects/{project}/locations/{location}/regionalEndpoints/{regional_endpoint}`. */
97 name: string;
98 /** RegionalEndpoint id (last path segment). */
99 regionalEndpointId: string;
100 /** Project id. */
101 project: string;
102 /** Location id. */
103 location: string;
104 /** Target Google API hostname. */
105 targetGoogleApi: string | undefined;
106 /** Access type (`REGIONAL` or `GLOBAL`). */
107 accessType: string | undefined;
108 /** VPC network resource path. */
109 network: string | undefined;
110 /** Subnetwork resource path. */
111 subnetwork: string | undefined;
112 /** Allocated address or Address resource URI. */
113 address: string | undefined;
114 /** Literal IP of the PSC forwarding rule (deprecated; prefer `address`). */
115 ipAddress: string | undefined;
116 /** PSC forwarding rule created on behalf of the customer. */
117 pscForwardingRule: string | undefined;
118 /** User-provided description. */
119 description: string | undefined;
120 /** User labels (Alchemy ownership labels stripped). */
121 labels: Record<string, string>;
122 /** RFC3339 creation timestamp. */
123 createTime: string | undefined;
124 /** RFC3339 last-update timestamp. */
125 updateTime: string | undefined;
126 },
127 never,
128 Providers
129 >;
130
131 /**
132 * A Private Service Connect regional endpoint for a Google API.
133 *
134 * Identity fields (`regionalEndpointId`, `location`, `targetGoogleApi`,
135 * `accessType`, `network`, `subnetwork`, `address`) replace the
136 * endpoint. The API has no patch method.
137 *
138 * ### Creating a RegionalEndpoint
139 * **Example:** Regional access to Cloud Storage
140 * ```typescript
141 * const network = yield* GCP.Compute.Network("AppVpc", {
142 * autoCreateSubnetworks: false,
143 * });
144 * const subnet = yield* GCP.Compute.Subnetwork("AppSubnet", {
145 * network: network.selfLink ?? network.networkName,
146 * ipCidrRange: "10.20.0.0/24",
147 * privateIpGoogleAccess: true,
148 * });
149 * const endpoint = yield* GCP.NetworkConnectivity.RegionalEndpoint("Storage", {
150 * targetGoogleApi: "storage.us-central1.p.rep.googleapis.com",
151 * accessType: "REGIONAL",
152 * network: network.selfLink ?? network.networkName,
153 * subnetwork: subnet.selfLink ?? subnet.subnetworkName,
154 * labels: { env: "prod" },
155 * });
156 * ```
157 *
158 * @resource
159 * @category NetworkConnectivity
160 */
161 export const RegionalEndpoint = Resource<RegionalEndpoint>(
162 "GCP.NetworkConnectivity.RegionalEndpoint",
163 );
164
165 const resourceName = (project: string, location: string, regionalEndpointId: string) =>
166 `projects/${project}/locations/${location}/regionalEndpoints/${regionalEndpointId}`;
167
168 const identityKey = (props: {
169 targetGoogleApi?: string;
170 accessType?: string;
171 network?: string;
172 subnetwork?: string;
173 address?: string;
174 }) =>
175 JSON.stringify({
176 targetGoogleApi: (props.targetGoogleApi ?? "").toLowerCase(),
177 accessType: (props.accessType ?? "").toUpperCase(),
178 network: lastSegment(canonicalizeLink(props.network)),
179 subnetwork: lastSegment(canonicalizeLink(props.subnetwork)),
180 address: canonicalizeLink(props.address),
181 });
182
183 const toAttrs = (
184 endpoint: networkconnectivity.RegionalEndpoint,
185 project: string,
186 region: string,
187 ) => {
188 const name = endpoint.name ?? "";
189 const parsed = parseName(name, COLLECTION, region);
190 return {
191 name,
192 regionalEndpointId: parsed.id,
193 project: parsed.project || project,
194 location: parsed.location || region,
195 targetGoogleApi: endpoint.targetGoogleApi,
196 accessType: endpoint.accessType,
197 network: endpoint.network,
198 subnetwork: endpoint.subnetwork,
199 address: endpoint.address,
200 ipAddress: endpoint.ipAddress,
201 pscForwardingRule: endpoint.pscForwardingRule,
202 description: endpoint.description,
203 labels: userLabels(endpoint.labels),
204 createTime: endpoint.createTime,
205 updateTime: endpoint.updateTime,
206 };
207 };
208
209 const getByName = (name: string) =>
210 networkconnectivity
211 .getProjectsLocationsRegionalEndpoints({ name })
212 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
213
214 export const RegionalEndpointProvider = () =>
215 Provider.succeed(RegionalEndpoint, {
216 stables: [
217 "name",
218 "regionalEndpointId",
219 "project",
220 "location",
221 "targetGoogleApi",
222 "accessType",
223 "createTime",
224 ],
225
226 diff: Effect.fn(function* ({ news, olds, output }) {
227 if (!isResolved(news)) return undefined;
228 const env = yield* GcpEnvironment.current;
229 const previousId = olds?.regionalEndpointId ?? output?.regionalEndpointId;
230 const nextId = news.regionalEndpointId
231 ? rfc1035(news.regionalEndpointId, "regional-endpoint", MAX_ID_LENGTH)
232 : previousId;
233 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
234 const nextLocation = normalizeLocation(
235 news.location ?? olds?.location ?? output?.location,
236 env.region,
237 );
238 const previousKey = identityKey({
239 targetGoogleApi: olds?.targetGoogleApi ?? output?.targetGoogleApi,
240 accessType: olds?.accessType ?? output?.accessType,
241 network: olds?.network ?? output?.network,
242 subnetwork: olds?.subnetwork ?? output?.subnetwork,
243 address: olds?.address ?? output?.address,
244 });
245 const nextKey = identityKey({
246 targetGoogleApi: news.targetGoogleApi,
247 accessType: news.accessType,
248 network: news.network,
249 subnetwork: news.subnetwork,
250 address: news.address,
251 });
252 if (
253 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
254 previousLocation !== nextLocation ||
255 previousKey !== nextKey
256 ) {
257 return { action: "replace" as const };
258 }
259 return undefined;
260 }),
261
262 read: Effect.fn(function* ({ id, olds, output }) {
263 const env = yield* GcpEnvironment.current;
264 const regionalEndpointId = yield* toPhysicalId(
265 id,
266 olds?.regionalEndpointId,
267 output?.regionalEndpointId,
268 "regional-endpoint",
269 MAX_ID_LENGTH,
270 );
271 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
272 const name = output?.name ?? resourceName(env.project, location, regionalEndpointId);
273 const existing = yield* getByName(name);
274 if (existing === undefined) return undefined;
275 const attrs = toAttrs(existing, env.project, env.region);
276 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
277 }),
278
279 list: () =>
280 Effect.gen(function* () {
281 const env = yield* GcpEnvironment.current;
282 const items = yield* collectPages(
283 networkconnectivity.listProjectsLocationsRegionalEndpoints.pages({
284 parent: parentOf(env.project, "-"),
285 pageSize: 1000,
286 }),
287 (page) => page.regionalEndpoints,
288 );
289 return items
290 .filter((item) => hasAlchemyLabelKeys(item.labels))
291 .map((item) => toAttrs(item, env.project, env.region));
292 }),
293
294 reconcile: Effect.fn(function* ({ id, news, output }) {
295 const env = yield* GcpEnvironment.current;
296 const regionalEndpointId = yield* toPhysicalId(
297 id,
298 news.regionalEndpointId,
299 output?.regionalEndpointId,
300 "regional-endpoint",
301 MAX_ID_LENGTH,
302 );
303 const location = normalizeLocation(news.location ?? output?.location, env.region);
304 const name = resourceName(env.project, location, regionalEndpointId);
305 const desiredLabels = {
306 ...toLabels(news.labels),
307 ...(yield* createInternalLabels(id)),
308 };
309 const network =
310 news.network !== undefined ? toNetworkResource(env.project, news.network) : undefined;
311 const subnetwork =
312 news.subnetwork !== undefined
313 ? toSubnetworkResource(env.project, location, news.subnetwork)
314 : undefined;
315
316 let current = yield* getByName(name);
317
318 if (current === undefined) {
319 const created = yield* networkconnectivity
320 .createProjectsLocationsRegionalEndpoints({
321 parent: parentOf(env.project, location),
322 regionalEndpointId,
323 body: {
324 targetGoogleApi: news.targetGoogleApi,
325 accessType: news.accessType,
326 network,
327 subnetwork,
328 address: news.address,
329 description: news.description,
330 labels: desiredLabels,
331 },
332 })
333 .pipe(
334 Effect.retry({
335 while: (error) => error._tag === "Conflict",
336 times: 5,
337 schedule: Schedule.spaced("2 seconds"),
338 }),
339 Effect.catchTag("Conflict", () => Effect.undefined),
340 );
341 if (created !== undefined) {
342 yield* waitForOperation(created);
343 }
344 current = yield* waitUntilPresent(getByName(name), name);
345 }
346
347 if (current === undefined) {
348 return yield* new NetworkConnectivityNotResolved({ resourceName: name });
349 }
350
351 current = yield* getByName(current.name ?? name).pipe(
352 Effect.filterOrFail(
353 (value): value is networkconnectivity.RegionalEndpoint =>
354 value !== undefined &&
355 (value.pscForwardingRule !== undefined ||
356 value.address !== undefined ||
357 value.ipAddress !== undefined),
358 () => new NetworkConnectivityNotResolved({ resourceName: name }),
359 ),
360 Effect.retry({
361 while: (error) => error._tag === "GCP.NetworkConnectivity.NotResolved",
362 times: 10,
363 schedule: Schedule.spaced("4 seconds"),
364 }),
365 );
366
367 return toAttrs(current, env.project, env.region);
368 }),
369
370 delete: Effect.fn(function* ({ output }) {
371 const operation = yield* networkconnectivity
372 .deleteProjectsLocationsRegionalEndpoints({ name: output.name })
373 .pipe(
374 Effect.retry({
375 while: (error) => error._tag === "Conflict",
376 times: 8,
377 schedule: Schedule.spaced("2 seconds"),
378 }),
379 Effect.catchTag("NotFound", () => Effect.undefined),
380 );
381 if (operation !== undefined) {
382 yield* waitForOperation(operation, { notFoundOk: true });
383 }
384 yield* waitUntilGone(getByName(output.name), output.name);
385 }),
386 });