@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 390 lines 12.5 KB
Raw
1 import * as vmwareengine from "@distilled.cloud/gcp/vmwareengine_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 type { Providers } from "../Providers.ts";
10 import {
11 DEFAULT_GLOBAL,
12 VmwareengineNotResolved,
13 changedFields,
14 collectPages,
15 createInternalLabels,
16 encodeOwnership,
17 hasAlchemyLabels,
18 hasOwnershipMarker,
19 listAcrossLocations,
20 normalizeLocation,
21 parentOf,
22 parseName,
23 parseOwnership,
24 replaceOnIdentity,
25 rfc1035,
26 toPhysicalId,
27 waitForOperation,
28 waitUntilGone,
29 waitUntilPresent,
30 waitUntilReady,
31 } from "./internal.ts";
32
33 const COLLECTION = "vmwareEngineNetworks";
34 const DEFAULT_TYPE = "STANDARD" satisfies vmwareengine.VmwareEngineNetworkTypeEnum;
35
36 export type VmwareEngineNetworkType = vmwareengine.VmwareEngineNetworkTypeEnum | (string & {});
37
38 export type VmwareEngineNetworkVpc = {
39 /** VPC network type (`INTRANET`, `INTERNET`, `GOOGLE_CLOUD`). */
40 type: string | undefined;
41 /** Service VPC resource name. */
42 network: string | undefined;
43 };
44
45 export type VmwareEngineNetworkProps = {
46 /**
47 * Network id (the `{vmwareEngineNetwork}` segment of
48 * `projects/{project}/locations/{location}/vmwareEngineNetworks/{id}`).
49 * If omitted, a unique RFC1035 name is generated. For `LEGACY`
50 * networks the API requires `{region}-default`. Immutable — changing
51 * it replaces the network.
52 */
53 vmwareEngineNetworkId?: string;
54 /**
55 * Location. `STANDARD` networks are global (`global`). `LEGACY`
56 * networks are regional (`us-central1`). Immutable — changing it
57 * replaces the network. `US-CENTRAL1` is accepted and normalized.
58 * @default "global" (`STANDARD`) or the stack's GCP region (`LEGACY`)
59 */
60 location?: string;
61 /**
62 * Network type. `STANDARD` is global; `LEGACY` is the per-region
63 * singleton `{region}-default`. Immutable — changing it replaces the
64 * network.
65 * @default "STANDARD"
66 */
67 type?: VmwareEngineNetworkType;
68 /**
69 * Human-readable description. VMware Engine networks have no labels
70 * field, so Alchemy ownership is stored in a `[alchemy …]` prefix and
71 * stripped from attributes.
72 */
73 description?: string;
74 };
75
76 export type VmwareEngineNetwork = Resource<
77 "GCP.VMwareEngine.VmwareEngineNetwork",
78 VmwareEngineNetworkProps,
79 {
80 /** Full resource name `projects/{project}/locations/{location}/vmwareEngineNetworks/{id}`. */
81 name: string;
82 /** Network id (last path segment). */
83 vmwareEngineNetworkId: string;
84 /** Project id. */
85 project: string;
86 /** Location id (`global` or a region). */
87 location: string;
88 /** Network type (`STANDARD`, `LEGACY`). */
89 type: string;
90 /** User description with the Alchemy ownership prefix stripped. */
91 description: string | undefined;
92 /** Server-reported state (`ACTIVE`, `CREATING`, …). */
93 state: string | undefined;
94 /** Server-generated uid. */
95 uid: string | undefined;
96 /** Server etag for update/delete. */
97 etag: string | undefined;
98 /** Attached service VPC networks. */
99 vpcNetworks: VmwareEngineNetworkVpc[];
100 /** RFC3339 creation timestamp. */
101 createTime: string | undefined;
102 /** RFC3339 last-update timestamp. */
103 updateTime: string | undefined;
104 },
105 never,
106 Providers
107 >;
108
109 /**
110 * A VMware Engine network that private clouds attach to for intranet,
111 * internet, and Google Cloud connectivity.
112 *
113 * `STANDARD` networks live at `locations/global`. `LEGACY` networks are
114 * regional singletons named `{region}-default`. Changing id, location,
115 * or type replaces the network. Description updates in place.
116 *
117 * ### Creating a Network
118 * **Example:** Generated STANDARD network
119 * ```typescript
120 * const network = yield* GCP.VMwareEngine.VmwareEngineNetwork("Ven", {
121 * type: "STANDARD",
122 * description: "app network",
123 * });
124 * ```
125 *
126 * **Example:** Named STANDARD network
127 * ```typescript
128 * const network = yield* GCP.VMwareEngine.VmwareEngineNetwork("Ven", {
129 * vmwareEngineNetworkId: "app-ven",
130 * location: "global",
131 * type: "STANDARD",
132 * description: "prod network",
133 * });
134 * ```
135 *
136 * ### Legacy regional network
137 * **Example:** `{region}-default` LEGACY network
138 * ```typescript
139 * const network = yield* GCP.VMwareEngine.VmwareEngineNetwork("Legacy", {
140 * location: "us-central1",
141 * type: "LEGACY",
142 * description: "legacy default",
143 * });
144 * ```
145 *
146 * ### Updating a Network
147 * Re-declare the same logical id with changed props; the engine keeps the
148 * physical resource and updates it in place.
149 *
150 * **Example:** Description
151 * ```typescript
152 * const network = yield* GCP.VMwareEngine.VmwareEngineNetwork("Ven", {
153 * location: "global",
154 * type: "STANDARD",
155 * description: "prod network v2",
156 * });
157 * ```
158 *
159 * @resource
160 * @category VMwareEngine
161 */
162 export const VmwareEngineNetwork = Resource<VmwareEngineNetwork>(
163 "GCP.VMwareEngine.VmwareEngineNetwork",
164 );
165
166 const resourceName = (project: string, location: string, networkId: string) =>
167 `${parentOf(project, location)}/${COLLECTION}/${networkId}`;
168
169 const typeOf = (value: string | undefined) => (value ?? DEFAULT_TYPE).toUpperCase();
170
171 const fallbackLocation = (type: string, region: string) =>
172 type === "LEGACY" ? region : DEFAULT_GLOBAL;
173
174 const toId = (
175 id: string,
176 networkId: string | undefined,
177 existing: string | undefined,
178 type: string,
179 location: string,
180 ) => {
181 if (networkId !== undefined) {
182 return Effect.succeed(rfc1035(networkId, "network"));
183 }
184 if (type === "LEGACY") {
185 return Effect.succeed(existing ?? `${location}-default`);
186 }
187 return toPhysicalId(id, undefined, existing, "network");
188 };
189
190 const toVpcs = (networks: vmwareengine.VpcNetworkList | undefined): VmwareEngineNetworkVpc[] =>
191 (networks ?? []).map((network) => ({
192 type: network.type,
193 network: network.network,
194 }));
195
196 const toAttrs = (network: vmwareengine.VmwareEngineNetwork, project: string) => {
197 const name = network.name ?? "";
198 const parsed = parseName(name, COLLECTION, DEFAULT_GLOBAL);
199 const ownership = parseOwnership(network.description);
200 return {
201 name,
202 vmwareEngineNetworkId: parsed.id,
203 project: parsed.project || project,
204 location: parsed.location,
205 type: typeOf(network.type),
206 description: ownership.text,
207 state: network.state,
208 uid: network.uid,
209 etag: network.etag,
210 vpcNetworks: toVpcs(network.vpcNetworks),
211 createTime: network.createTime,
212 updateTime: network.updateTime,
213 };
214 };
215
216 const getByName = (name: string) =>
217 name.length === 0
218 ? Effect.undefined
219 : vmwareengine
220 .getProjectsLocationsVmwareEngineNetworks({ name })
221 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
222
223 export const VmwareEngineNetworkProvider = () =>
224 Provider.succeed(VmwareEngineNetwork, {
225 stables: ["name", "vmwareEngineNetworkId", "project", "location", "type", "uid", "createTime"],
226
227 diff: Effect.fn(function* ({ news, olds, output }) {
228 if (!isResolved(news)) return undefined;
229 const env = yield* GcpEnvironment.current;
230 const previousType = typeOf(olds?.type ?? output?.type);
231 const nextType = typeOf(news.type ?? olds?.type ?? output?.type);
232 const previousLocation = normalizeLocation(
233 olds?.location ?? output?.location,
234 fallbackLocation(previousType, env.region),
235 );
236 const nextLocation = normalizeLocation(
237 news.location ?? olds?.location ?? output?.location,
238 fallbackLocation(nextType, env.region),
239 );
240 const previousId = olds?.vmwareEngineNetworkId ?? output?.vmwareEngineNetworkId;
241 const nextId = news.vmwareEngineNetworkId
242 ? rfc1035(news.vmwareEngineNetworkId, "network")
243 : nextType === "LEGACY"
244 ? `${nextLocation}-default`
245 : previousId;
246 return replaceOnIdentity({
247 previousId,
248 nextId,
249 previousLocation,
250 nextLocation,
251 extra: previousType !== nextType,
252 });
253 }),
254
255 read: Effect.fn(function* ({ id, olds, output }) {
256 const env = yield* GcpEnvironment.current;
257 const type = typeOf(olds?.type ?? output?.type);
258 const location = normalizeLocation(
259 olds?.location ?? output?.location,
260 fallbackLocation(type, env.region),
261 );
262 const networkId = yield* toId(
263 id,
264 olds?.vmwareEngineNetworkId,
265 output?.vmwareEngineNetworkId,
266 type,
267 location,
268 );
269 const name = output?.name ?? resourceName(env.project, location, networkId);
270 const existing = yield* getByName(name);
271 if (existing === undefined) return undefined;
272 const attrs = toAttrs(existing, env.project);
273 const { labels } = parseOwnership(existing.description);
274 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
275 }),
276
277 list: () =>
278 Effect.gen(function* () {
279 const env = yield* GcpEnvironment.current;
280 const items = yield* listAcrossLocations(env.project, env.region, (parent) =>
281 collectPages(
282 vmwareengine.listProjectsLocationsVmwareEngineNetworks.pages({
283 parent,
284 pageSize: 1000,
285 }),
286 (page) => page.vmwareEngineNetworks,
287 ),
288 );
289 return items
290 .filter((item) => hasOwnershipMarker(item.description))
291 .map((item) => toAttrs(item, env.project));
292 }),
293
294 reconcile: Effect.fn(function* ({ id, news, output }) {
295 const env = yield* GcpEnvironment.current;
296 const type = typeOf(news.type ?? output?.type);
297 const location = normalizeLocation(
298 news.location ?? output?.location,
299 fallbackLocation(type, env.region),
300 );
301 const networkId = yield* toId(
302 id,
303 news.vmwareEngineNetworkId,
304 output?.vmwareEngineNetworkId,
305 type,
306 location,
307 );
308 const name = resourceName(env.project, location, networkId);
309 const ownership = yield* createInternalLabels(id);
310 const desiredDescription = encodeOwnership(ownership, news.description);
311
312 let current = yield* getByName(output?.name ?? name);
313
314 if (current === undefined) {
315 const created = yield* vmwareengine
316 .createProjectsLocationsVmwareEngineNetworks({
317 parent: parentOf(env.project, location),
318 vmwareEngineNetworkId: networkId,
319 body: {
320 type,
321 description: desiredDescription,
322 },
323 })
324 .pipe(
325 Effect.retry({
326 while: (error) => error._tag === "Conflict",
327 times: 5,
328 schedule: Schedule.spaced("2 seconds"),
329 }),
330 Effect.catchTag("Conflict", () => Effect.undefined),
331 );
332 if (created !== undefined) {
333 yield* waitForOperation(created);
334 }
335 current = yield* waitUntilPresent(getByName(name), name);
336 }
337
338 if (current === undefined) {
339 return yield* new VmwareengineNotResolved({ resourceName: name });
340 }
341
342 current = yield* waitUntilReady(
343 getByName(current.name ?? name),
344 current.name ?? name,
345 (item) => item.state,
346 );
347
348 const updateMask = changedFields([
349 ["description", (current.description ?? "") !== desiredDescription],
350 ]);
351 if (updateMask.length > 0) {
352 const operation = yield* vmwareengine.patchProjectsLocationsVmwareEngineNetworks({
353 name: current.name ?? name,
354 updateMask: updateMask.join(","),
355 body: {
356 name: current.name ?? name,
357 description: desiredDescription,
358 },
359 });
360 yield* waitForOperation(operation);
361 current = yield* waitUntilReady(
362 getByName(current.name ?? name),
363 current.name ?? name,
364 (item) => item.state,
365 );
366 }
367
368 return toAttrs(current, env.project);
369 }),
370
371 delete: Effect.fn(function* ({ output }) {
372 const operation = yield* vmwareengine
373 .deleteProjectsLocationsVmwareEngineNetworks({
374 name: output.name,
375 etag: output.etag,
376 })
377 .pipe(
378 Effect.retry({
379 while: (error) => error._tag === "Conflict",
380 times: 8,
381 schedule: Schedule.spaced("2 seconds"),
382 }),
383 Effect.catchTag("NotFound", () => Effect.undefined),
384 );
385 if (operation !== undefined) {
386 yield* waitForOperation(operation, { notFoundOk: true });
387 }
388 yield* waitUntilGone(getByName(output.name), output.name);
389 }),
390 });