@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 454 lines 15.5 KB
Raw
1 import * as oracle from "@distilled.cloud/gcp/oracledatabase_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 { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 OracleDatabaseNotResolved,
13 collectPages,
14 hasAlchemyLabelMap,
15 listAtLocation,
16 normalizeLocation,
17 parentOf,
18 parseName,
19 replaceOnIdentity,
20 resourceNameOf,
21 retryConflict,
22 retryQuota,
23 specifiedEquals,
24 type TimeZone,
25 toPhysicalId,
26 userLabels,
27 waitUntilExists,
28 waitUntilGone,
29 waitUntilReady,
30 } from "./internal.ts";
31 import { waitForOperation } from "./operations.ts";
32
33 const COLLECTION = "exadbVmClusters";
34 const FALLBACK_ID = "exadbvm";
35
36 export type ExadbVmClusterStorageDetails = {
37 /** Storage per node in GB. */
38 sizeInGbsPerNode?: number;
39 };
40
41 export type DataCollectionOptionsCommon = {
42 /** Enable incident logs. */
43 isIncidentLogsEnabled?: boolean;
44 /** Enable health monitoring. */
45 isHealthMonitoringEnabled?: boolean;
46 /** Enable diagnostics events. */
47 isDiagnosticsEventsEnabled?: boolean;
48 };
49
50 export type ExadbVmClusterPropertiesInput = {
51 /** OCI cluster name. Immutable. */
52 clusterName?: string;
53 /** Grid image id. Immutable. Required on create. */
54 gridImageId?: string;
55 /** License model. Immutable. */
56 licenseModel?: oracle.ExadbVmClusterPropertiesLicenseModelEnum | (string & {});
57 /** VM file system storage. Immutable. Required on create. */
58 vmFileSystemStorage?: ExadbVmClusterStorageDetails;
59 /** Additional ECPUs per node. Immutable. */
60 additionalEcpuCountPerNode?: number;
61 /** Data collection options. Immutable. */
62 dataCollectionOptions?: DataCollectionOptionsCommon;
63 /** Shape attribute (`SMART_STORAGE`, `BLOCK_STORAGE`). Immutable. */
64 shapeAttribute?: oracle.ExadbVmClusterPropertiesShapeAttributeEnum | (string & {});
65 /** Node/VM count. Mutable via patch. */
66 nodeCount?: number;
67 /** Enabled ECPUs per node. Immutable. */
68 enabledEcpuCountPerNode?: number;
69 /** SCAN listener TCP port. Immutable. */
70 scanListenerPortTcp?: number;
71 /** SSH public keys. Immutable. */
72 sshPublicKeys?: string[];
73 /** Time zone. Immutable. */
74 timeZone?: TimeZone;
75 /** Exascale storage vault. Immutable. */
76 exascaleDbStorageVault?: string;
77 /** Hostname prefix. Immutable. */
78 hostnamePrefix?: string;
79 };
80
81 export type ExadbVmClusterProps = {
82 /**
83 * Exadb VM Cluster id. If omitted, a unique RFC1035 name is generated.
84 * Immutable.
85 */
86 exadbVmClusterId?: string;
87 /**
88 * Region. Immutable.
89 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
90 */
91 location?: string;
92 /**
93 * Display name. Immutable.
94 */
95 displayName?: string;
96 /**
97 * Client ODB Subnet. Immutable.
98 */
99 odbSubnet?: string;
100 /**
101 * Backup ODB Subnet. Immutable.
102 */
103 backupOdbSubnet?: string;
104 /**
105 * ODB Network. Immutable.
106 */
107 odbNetwork?: string;
108 /**
109 * User labels. Alchemy ownership labels are merged in automatically.
110 */
111 labels?: Record<string, string>;
112 /**
113 * Cluster properties.
114 */
115 properties?: ExadbVmClusterPropertiesInput;
116 /** Node count. Convenience alias for `properties.nodeCount`. */
117 nodeCount?: number;
118 /** Grid image id. Convenience alias for `properties.gridImageId`. */
119 gridImageId?: string;
120 /** Hostname prefix. Convenience alias for `properties.hostnamePrefix`. */
121 hostnamePrefix?: string;
122 /** SSH public keys. Convenience alias for `properties.sshPublicKeys`. */
123 sshPublicKeys?: string[];
124 /** Exascale vault. Convenience alias. */
125 exascaleDbStorageVault?: string;
126 /** Enabled ECPUs per node. Convenience alias. */
127 enabledEcpuCountPerNode?: number;
128 };
129
130 export type ExadbVmCluster = Resource<
131 "GCP.OracleDatabase.ExadbVmCluster",
132 ExadbVmClusterProps,
133 {
134 /** Full resource name. */
135 name: string;
136 /** Cluster id. */
137 exadbVmClusterId: string;
138 /** Project id. */
139 project: string;
140 /** Location id. */
141 location: string;
142 /** Display name. */
143 displayName: string | undefined;
144 /** Client ODB Subnet. */
145 odbSubnet: string | undefined;
146 /** Backup ODB Subnet. */
147 backupOdbSubnet: string | undefined;
148 /** ODB Network. */
149 odbNetwork: string | undefined;
150 /** User labels (Alchemy ownership labels stripped). */
151 labels: Record<string, string>;
152 /** GCP Oracle zone. */
153 gcpOracleZone: string | undefined;
154 /** Entitlement id. */
155 entitlementId: string | undefined;
156 /** Lifecycle state. */
157 lifecycleState: string | undefined;
158 /** Node count. */
159 nodeCount: number | undefined;
160 /** Hostname. */
161 hostname: string | undefined;
162 /** Grid Infrastructure version. */
163 giVersion: string | undefined;
164 /** RFC3339 creation timestamp. */
165 createTime: string | undefined;
166 },
167 never,
168 Providers
169 >;
170
171 /**
172 * An Oracle Exascale VM Cluster on Google Cloud.
173 *
174 * Changing `exadbVmClusterId`, `location`, ODB identity, `gridImageId`,
175 * or `exascaleDbStorageVault` replaces the cluster. Labels and
176 * `nodeCount` patch in place (adding VMs). Removing VMs uses a separate
177 * API and is not modeled here.
178 *
179 * ### Creating an Exadb VM Cluster
180 * **Example:** Generated name
181 * ```typescript
182 * const cluster = yield* GCP.OracleDatabase.ExadbVmCluster("ExaVm", {
183 * displayName: "exavm",
184 * odbSubnet: subnet.name,
185 * backupOdbSubnet: backupSubnet.name,
186 * gridImageId: "19.0.0.0",
187 * hostnamePrefix: "exavm",
188 * sshPublicKeys: [publicKey],
189 * exascaleDbStorageVault: vault.name,
190 * enabledEcpuCountPerNode: 8,
191 * nodeCount: 2,
192 * properties: {
193 * vmFileSystemStorage: { sizeInGbsPerNode: 180 },
194 * shapeAttribute: "SMART_STORAGE",
195 * },
196 * });
197 * ```
198 *
199 * @resource
200 * @category OracleDatabase
201 */
202 export const ExadbVmCluster = Resource<ExadbVmCluster>("GCP.OracleDatabase.ExadbVmCluster");
203
204 const mergedProperties = (news: ExadbVmClusterProps): ExadbVmClusterPropertiesInput => ({
205 ...news.properties,
206 nodeCount: news.nodeCount ?? news.properties?.nodeCount,
207 gridImageId: news.gridImageId ?? news.properties?.gridImageId,
208 hostnamePrefix: news.hostnamePrefix ?? news.properties?.hostnamePrefix,
209 sshPublicKeys: news.sshPublicKeys ?? news.properties?.sshPublicKeys,
210 exascaleDbStorageVault: news.exascaleDbStorageVault ?? news.properties?.exascaleDbStorageVault,
211 enabledEcpuCountPerNode: news.enabledEcpuCountPerNode ?? news.properties?.enabledEcpuCountPerNode,
212 });
213
214 const toCreateBody = (
215 news: ExadbVmClusterProps,
216 desiredLabels: Record<string, string>,
217 ): oracle.ExadbVmCluster => {
218 const props = mergedProperties(news);
219 const properties: oracle.ExadbVmClusterProperties = {};
220 if (props.clusterName !== undefined) properties.clusterName = props.clusterName;
221 if (props.gridImageId !== undefined) properties.gridImageId = props.gridImageId;
222 if (props.licenseModel !== undefined) {
223 properties.licenseModel = props.licenseModel;
224 }
225 if (props.vmFileSystemStorage !== undefined) {
226 properties.vmFileSystemStorage = props.vmFileSystemStorage;
227 }
228 if (props.additionalEcpuCountPerNode !== undefined) {
229 properties.additionalEcpuCountPerNode = props.additionalEcpuCountPerNode;
230 }
231 if (props.dataCollectionOptions !== undefined) {
232 properties.dataCollectionOptions = props.dataCollectionOptions;
233 }
234 if (props.shapeAttribute !== undefined) {
235 properties.shapeAttribute = props.shapeAttribute;
236 }
237 if (props.nodeCount !== undefined) properties.nodeCount = props.nodeCount;
238 if (props.enabledEcpuCountPerNode !== undefined) {
239 properties.enabledEcpuCountPerNode = props.enabledEcpuCountPerNode;
240 }
241 if (props.scanListenerPortTcp !== undefined) {
242 properties.scanListenerPortTcp = props.scanListenerPortTcp;
243 }
244 if (props.sshPublicKeys !== undefined) {
245 properties.sshPublicKeys = props.sshPublicKeys;
246 }
247 if (props.timeZone !== undefined) properties.timeZone = props.timeZone;
248 if (props.exascaleDbStorageVault !== undefined) {
249 properties.exascaleDbStorageVault = props.exascaleDbStorageVault;
250 }
251 if (props.hostnamePrefix !== undefined) {
252 properties.hostnamePrefix = props.hostnamePrefix;
253 }
254 const body: oracle.ExadbVmCluster = {
255 labels: desiredLabels,
256 properties,
257 };
258 if (news.displayName !== undefined) body.displayName = news.displayName;
259 if (news.odbSubnet !== undefined) body.odbSubnet = news.odbSubnet;
260 if (news.backupOdbSubnet !== undefined) {
261 body.backupOdbSubnet = news.backupOdbSubnet;
262 }
263 if (news.odbNetwork !== undefined) body.odbNetwork = news.odbNetwork;
264 return body;
265 };
266
267 const toAttrs = (cluster: oracle.ExadbVmCluster, project: string) => {
268 const name = cluster.name ?? "";
269 const parsed = parseName(name, COLLECTION);
270 return {
271 name,
272 exadbVmClusterId: parsed.id,
273 project: parsed.project || project,
274 location: parsed.location,
275 displayName: cluster.displayName,
276 odbSubnet: cluster.odbSubnet,
277 backupOdbSubnet: cluster.backupOdbSubnet,
278 odbNetwork: cluster.odbNetwork,
279 labels: userLabels(cluster.labels),
280 gcpOracleZone: cluster.gcpOracleZone,
281 entitlementId: cluster.entitlementId,
282 lifecycleState: cluster.properties?.lifecycleState,
283 nodeCount: cluster.properties?.nodeCount,
284 hostname: cluster.properties?.hostname,
285 giVersion: cluster.properties?.giVersion,
286 createTime: cluster.createTime,
287 };
288 };
289
290 const getByName = (name: string) =>
291 retryQuota(oracle.getProjectsLocationsExadbVmClusters({ name })).pipe(
292 Effect.catchTag("NotFound", () => Effect.undefined),
293 );
294
295 const listClusters = (project: string, region: string) => {
296 const collect = (parent: string) =>
297 collectPages(
298 oracle.listProjectsLocationsExadbVmClusters.pages({
299 parent,
300 pageSize: 1000,
301 }),
302 (page) => page.exadbVmClusters,
303 ).pipe(Effect.map((items) => items.filter((item) => hasAlchemyLabelMap(item.labels))));
304 return listAtLocation(project, region, collect).pipe(
305 Effect.catchTag("NotFound", () => Effect.succeed([])),
306 );
307 };
308
309 export const ExadbVmClusterProvider = () =>
310 Provider.succeed(ExadbVmCluster, {
311 stables: ["name", "exadbVmClusterId", "project", "location", "createTime"],
312
313 diff: Effect.fn(function* ({ news, olds, output }) {
314 if (!isResolved(news)) return undefined;
315 const env = yield* GcpEnvironment.current;
316 const previousOdb = olds?.odbSubnet ?? output?.odbSubnet ?? "";
317 const nextOdb = news.odbSubnet ?? previousOdb;
318 const previousBackup = olds?.backupOdbSubnet ?? output?.backupOdbSubnet ?? "";
319 const nextBackup = news.backupOdbSubnet ?? previousBackup;
320 const previousVault =
321 olds?.exascaleDbStorageVault ?? olds?.properties?.exascaleDbStorageVault ?? "";
322 const nextVault =
323 news.exascaleDbStorageVault ?? news.properties?.exascaleDbStorageVault ?? previousVault;
324 return replaceOnIdentity({
325 previousId: olds?.exadbVmClusterId ?? output?.exadbVmClusterId,
326 nextId: news.exadbVmClusterId ?? olds?.exadbVmClusterId ?? output?.exadbVmClusterId,
327 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
328 nextLocation: normalizeLocation(
329 news.location ?? olds?.location ?? output?.location ?? env.region,
330 ),
331 extra:
332 nextOdb !== previousOdb || nextBackup !== previousBackup || nextVault !== previousVault,
333 });
334 }),
335
336 read: Effect.fn(function* ({ id, olds, output }) {
337 const env = yield* GcpEnvironment.current;
338 const exadbVmClusterId = yield* toPhysicalId(
339 id,
340 olds?.exadbVmClusterId,
341 output?.exadbVmClusterId,
342 FALLBACK_ID,
343 );
344 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
345 const name =
346 output?.name ?? resourceNameOf(env.project, location, COLLECTION, exadbVmClusterId);
347 const existing = yield* getByName(name);
348 if (existing === undefined) return undefined;
349 const attrs = toAttrs(existing, env.project);
350 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
351 }),
352
353 list: () =>
354 Effect.gen(function* () {
355 const env = yield* GcpEnvironment.current;
356 const items = yield* listClusters(env.project, env.region);
357 return items.map((item) => toAttrs(item, env.project));
358 }),
359
360 reconcile: Effect.fn(function* ({ id, news, output }) {
361 const env = yield* GcpEnvironment.current;
362 const exadbVmClusterId = yield* toPhysicalId(
363 id,
364 news.exadbVmClusterId,
365 output?.exadbVmClusterId,
366 FALLBACK_ID,
367 );
368 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
369 const name = resourceNameOf(env.project, location, COLLECTION, exadbVmClusterId);
370 const desiredLabels = {
371 ...toLabels(news.labels),
372 ...(yield* createInternalLabels(id)),
373 };
374
375 let current = yield* getByName(output?.name ?? name);
376
377 if (current === undefined) {
378 const created = yield* oracle
379 .createProjectsLocationsExadbVmClusters({
380 parent: parentOf(env.project, location),
381 exadbVmClusterId,
382 body: toCreateBody(news, desiredLabels),
383 })
384 .pipe(
385 retryQuota,
386 Effect.catchTag("Conflict", () => Effect.undefined),
387 );
388 if (created !== undefined) {
389 yield* waitForOperation(created);
390 }
391 current = yield* waitUntilExists(getByName(name), name);
392 }
393
394 if (current === undefined) {
395 return yield* new OracleDatabaseNotResolved({ resourceName: name });
396 }
397
398 const ready = yield* waitUntilReady(
399 getByName(current.name ?? name),
400 current.name ?? name,
401 (value) => value.properties?.lifecycleState,
402 );
403
404 const props = mergedProperties(news);
405 const observedLabels = tagRecord(ready.labels);
406 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
407 const labelsChanged = upsert.length > 0 || removed.length > 0;
408 const nodeCountChanged =
409 props.nodeCount !== undefined &&
410 !specifiedEquals(props.nodeCount, ready.properties?.nodeCount);
411
412 if (labelsChanged || nodeCountChanged) {
413 const mask = [
414 labelsChanged ? "labels" : undefined,
415 nodeCountChanged ? "properties.node_count" : undefined,
416 ].filter((field): field is string => field !== undefined);
417 const operation = yield* retryQuota(
418 oracle.patchProjectsLocationsExadbVmClusters({
419 name: ready.name ?? name,
420 updateMask: mask.join(","),
421 body: {
422 name: ready.name ?? name,
423 labels: desiredLabels,
424 properties: {
425 nodeCount: props.nodeCount,
426 },
427 },
428 }),
429 );
430 yield* waitForOperation(operation);
431 return toAttrs(
432 yield* waitUntilExists(getByName(ready.name ?? name), ready.name ?? name),
433 env.project,
434 );
435 }
436
437 return toAttrs(ready, env.project);
438 }),
439
440 delete: Effect.fn(function* ({ output }) {
441 const operation = yield* oracle
442 .deleteProjectsLocationsExadbVmClusters({
443 name: output.name,
444 })
445 .pipe(
446 retryConflict,
447 Effect.catchTag("NotFound", () => Effect.undefined),
448 );
449 if (operation !== undefined) {
450 yield* waitForOperation(operation, { notFoundOk: true });
451 }
452 yield* waitUntilGone(getByName(output.name), output.name);
453 }),
454 });