@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 367 lines 12.1 KB
Raw
1 import * as cnr from "@distilled.cloud/gcp/cloudnumberregistry_v1alpha";
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_LOCATION,
14 ResourceNotResolved,
15 expandName,
16 fieldMask,
17 listAtLocation,
18 listLabeledPages,
19 normalizeLocation,
20 parentOf,
21 parseName,
22 replaceOnIdentity,
23 resourceName,
24 sameRef,
25 toPhysicalId,
26 userLabels,
27 waitForDeleteOperation,
28 waitForOperation,
29 waitUntilExists,
30 waitUntilGone,
31 } from "./internal.ts";
32
33 const COLLECTION = "realms";
34 const DEFAULT_TRAFFIC: cnr.RealmTrafficTypeEnum = "PRIVATE";
35 const DEFAULT_MANAGEMENT: cnr.RealmManagementTypeEnum = "USER";
36 const DEFAULT_IP_VERSION: cnr.RealmIpVersionEnum = "IPV4";
37
38 export type RealmDiscoveryMetadata = {
39 eventTime: string | undefined;
40 createTime: string | undefined;
41 state: string | undefined;
42 updateTime: string | undefined;
43 resourceUri: string | undefined;
44 resource: string | undefined;
45 sourceId: string | undefined;
46 sourceSubId: string | undefined;
47 };
48
49 export type RealmAggregatedData = {
50 customRangesCount: number | undefined;
51 discoveredRangesCount: number | undefined;
52 };
53
54 export type RealmProps = {
55 /**
56 * Realm id (the `{realm}` segment of
57 * `projects/{project}/locations/{location}/realms/{realm}`). If omitted,
58 * a unique RFC1035 name is generated. Immutable — changing it
59 * replaces the realm.
60 */
61 realmId?: string;
62 /**
63 * Location of the realm. Cloud Number Registry is global — `global`
64 * is the only supported value. Immutable — changing it replaces the
65 * realm.
66 * @default "global"
67 */
68 location?: string;
69 /**
70 * Registry book that claims this realm. Accepts a book id or a full
71 * resource name. Immutable — changing it replaces the realm.
72 */
73 registryBook: string;
74 /**
75 * Traffic type of the realm (`PRIVATE`, `INTERNET`, `LINKLOCAL`,
76 * `UNSET`). Immutable — changing it replaces the realm.
77 * @default "PRIVATE"
78 */
79 trafficType?: cnr.RealmTrafficTypeEnum | (string & {});
80 /**
81 * Who manages the realm (`USER` for custom ranges, `CNR` for
82 * discovered resources). Immutable — changing it replaces the realm.
83 * @default "USER"
84 */
85 managementType?: cnr.RealmManagementTypeEnum | (string & {});
86 /**
87 * IP version (`IPV4` or `IPV6`). Immutable — changing it replaces
88 * the realm.
89 * @default "IPV4"
90 */
91 ipVersion?: cnr.RealmIpVersionEnum | (string & {});
92 /**
93 * User labels. Alchemy ownership labels are merged in automatically.
94 */
95 labels?: Record<string, string>;
96 };
97
98 export type Realm = Resource<
99 "GCP.CloudNumberRegistry.Realm",
100 RealmProps,
101 {
102 /** Full resource name `projects/{project}/locations/{location}/realms/{realm}`. */
103 name: string;
104 /** Realm id (last path segment). */
105 realmId: string;
106 /** Project id. */
107 project: string;
108 /** Location id of the resource. */
109 location: string;
110 /** Registry book that claims this realm. */
111 registryBook: string | undefined;
112 /** Traffic type. */
113 trafficType: string | undefined;
114 /** Management type. */
115 managementType: string | undefined;
116 /** IP version. */
117 ipVersion: string | undefined;
118 /** User labels (Alchemy ownership labels stripped). */
119 labels: Record<string, string>;
120 /** Discovery metadata, when the realm was imported from Compute Engine. */
121 discoveryMetadata: RealmDiscoveryMetadata | undefined;
122 /** Aggregated counts, populated when the view is AGGREGATE. */
123 aggregatedData: RealmAggregatedData | undefined;
124 /** RFC3339 creation timestamp. */
125 createTime: string | undefined;
126 /** RFC3339 last-update timestamp. */
127 updateTime: string | undefined;
128 },
129 never,
130 Providers
131 >;
132
133 /**
134 * A Cloud Number Registry realm — a routing domain of IP ranges that
135 * must not overlap (unless one range is the parent of another). Custom
136 * ranges can only be added to user-managed realms.
137 *
138 * `realmId`, `location`, `registryBook`, `trafficType`,
139 * `managementType`, and `ipVersion` replace the resource. Labels
140 * update in place.
141 *
142 * ### Creating a Realm
143 * **Example:** User-managed IPv4 realm
144 * ```typescript
145 * const book = yield* GCP.CloudNumberRegistry.RegistryBook("Inventory", {});
146 * const realm = yield* GCP.CloudNumberRegistry.Realm("Private", {
147 * registryBook: book.name,
148 * trafficType: "PRIVATE",
149 * managementType: "USER",
150 * ipVersion: "IPV4",
151 * });
152 * ```
153 *
154 * ### Updating a Realm
155 * **Example:** Labels
156 * ```typescript
157 * const realm = yield* GCP.CloudNumberRegistry.Realm("Private", {
158 * registryBook: book.name,
159 * labels: { env: "prod" },
160 * });
161 * ```
162 *
163 * @resource
164 * @category CloudNumberRegistry
165 */
166 export const Realm = Resource<Realm>("GCP.CloudNumberRegistry.Realm");
167
168 const toDiscovery = (
169 metadata: cnr.DiscoveryMetadata | undefined,
170 ): RealmDiscoveryMetadata | undefined =>
171 metadata === undefined
172 ? undefined
173 : {
174 eventTime: metadata.eventTime,
175 createTime: metadata.createTime,
176 state: metadata.state,
177 updateTime: metadata.updateTime,
178 resourceUri: metadata.resourceUri,
179 resource: metadata.resource,
180 sourceId: metadata.sourceId,
181 sourceSubId: metadata.sourceSubId,
182 };
183
184 const toAttrs = (item: cnr.Realm, project: string) => {
185 const name = item.name ?? "";
186 const parsed = parseName(name, COLLECTION);
187 return {
188 name,
189 realmId: parsed.id,
190 project: parsed.project || project,
191 location: parsed.location || DEFAULT_LOCATION,
192 registryBook: item.registryBook,
193 trafficType: item.trafficType,
194 managementType: item.managementType,
195 ipVersion: item.ipVersion,
196 labels: userLabels(item.labels),
197 discoveryMetadata: toDiscovery(item.discoveryMetadata),
198 aggregatedData: item.aggregatedData
199 ? {
200 customRangesCount: item.aggregatedData.customRangesCount,
201 discoveredRangesCount: item.aggregatedData.discoveredRangesCount,
202 }
203 : undefined,
204 createTime: item.createTime,
205 updateTime: item.updateTime,
206 };
207 };
208
209 const getByName = (name: string) =>
210 name.length === 0
211 ? Effect.undefined
212 : cnr
213 .getProjectsLocationsRealms({ name })
214 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
215
216 const listOwned = (project: string) =>
217 listAtLocation(project, (parent) =>
218 listLabeledPages(
219 cnr.listProjectsLocationsRealms.pages({
220 parent,
221 pageSize: 1000,
222 }),
223 (page) => page.realms,
224 (item) => item.labels,
225 ),
226 );
227
228 export const RealmProvider = () =>
229 Provider.succeed(Realm, {
230 stables: [
231 "name",
232 "realmId",
233 "project",
234 "location",
235 "registryBook",
236 "trafficType",
237 "managementType",
238 "ipVersion",
239 "createTime",
240 ],
241
242 diff: Effect.fn(function* ({ news, olds, output }) {
243 if (!isResolved(news)) return undefined;
244 const previousBook = olds?.registryBook ?? output?.registryBook;
245 const previousTraffic = olds?.trafficType ?? output?.trafficType;
246 const nextTraffic = news.trafficType ?? previousTraffic;
247 const previousManagement = olds?.managementType ?? output?.managementType;
248 const nextManagement = news.managementType ?? previousManagement;
249 const previousVersion = olds?.ipVersion ?? output?.ipVersion;
250 const nextVersion = news.ipVersion ?? previousVersion;
251 return replaceOnIdentity({
252 previousId: olds?.realmId ?? output?.realmId,
253 nextId: news.realmId ?? olds?.realmId ?? output?.realmId,
254 previousLocation: normalizeLocation(olds?.location ?? output?.location),
255 nextLocation: normalizeLocation(news.location ?? olds?.location ?? output?.location),
256 extra:
257 (previousBook !== undefined && !sameRef(previousBook, news.registryBook)) ||
258 (previousTraffic !== undefined &&
259 nextTraffic !== undefined &&
260 previousTraffic !== nextTraffic) ||
261 (previousManagement !== undefined &&
262 nextManagement !== undefined &&
263 previousManagement !== nextManagement) ||
264 (previousVersion !== undefined &&
265 nextVersion !== undefined &&
266 previousVersion !== nextVersion),
267 });
268 }),
269
270 read: Effect.fn(function* ({ id, olds, output }) {
271 const env = yield* GcpEnvironment.current;
272 const realmId = yield* toPhysicalId(id, olds?.realmId, output?.realmId, "realm");
273 const location = normalizeLocation(olds?.location ?? output?.location);
274 const name = output?.name ?? resourceName(env.project, location, COLLECTION, realmId);
275 const existing = yield* getByName(name);
276 if (existing === undefined) return undefined;
277 const attrs = toAttrs(existing, env.project);
278 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
279 }),
280
281 list: () =>
282 Effect.gen(function* () {
283 const env = yield* GcpEnvironment.current;
284 const items = yield* listOwned(env.project);
285 return items.map((item) => toAttrs(item, env.project));
286 }),
287
288 reconcile: Effect.fn(function* ({ id, news, output }) {
289 const env = yield* GcpEnvironment.current;
290 const realmId = yield* toPhysicalId(id, news.realmId, output?.realmId, "realm");
291 const location = normalizeLocation(news.location ?? output?.location);
292 const name = resourceName(env.project, location, COLLECTION, realmId);
293 const desiredLabels = {
294 ...toLabels(news.labels),
295 ...(yield* createInternalLabels(id)),
296 };
297 const registryBook = expandName(news.registryBook, env.project, location, "registryBooks");
298 const trafficType = news.trafficType ?? DEFAULT_TRAFFIC;
299 const managementType = news.managementType ?? DEFAULT_MANAGEMENT;
300 const ipVersion = news.ipVersion ?? DEFAULT_IP_VERSION;
301
302 let current = yield* getByName(output?.name ?? name);
303
304 if (current === undefined) {
305 const created = yield* cnr
306 .createProjectsLocationsRealms({
307 parent: parentOf(env.project, location),
308 realmId,
309 body: {
310 registryBook,
311 trafficType,
312 managementType,
313 ipVersion,
314 labels: desiredLabels,
315 },
316 })
317 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
318 if (created !== undefined) {
319 yield* waitForOperation(created);
320 }
321 current = yield* waitUntilExists(getByName(name), name);
322 }
323
324 if (current === undefined) {
325 return yield* new ResourceNotResolved({ resourceName: name });
326 }
327
328 const observedLabels = tagRecord(current.labels);
329 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
330 const mask = fieldMask([(upsert.length > 0 || removed.length > 0) && "labels"]);
331
332 if (mask.length > 0) {
333 const operation = yield* cnr.patchProjectsLocationsRealms({
334 name: current.name ?? name,
335 updateMask: mask,
336 body: {
337 name: current.name ?? name,
338 labels: desiredLabels,
339 },
340 });
341 yield* waitForOperation(operation);
342 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
343 }
344
345 return toAttrs(current, env.project);
346 }),
347
348 delete: Effect.fn(function* ({ output }) {
349 const operation = yield* cnr
350 .deleteProjectsLocationsRealms({
351 name: output.name,
352 force: true,
353 })
354 .pipe(
355 Effect.retry({
356 while: (error) => error._tag === "Conflict",
357 times: 8,
358 schedule: Schedule.spaced("2 seconds"),
359 }),
360 Effect.catchTag("NotFound", () => Effect.undefined),
361 );
362 if (operation !== undefined) {
363 yield* waitForDeleteOperation(operation);
364 }
365 yield* waitUntilGone(getByName(output.name), output.name);
366 }),
367 });