@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 368 lines 12.4 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, hasAlchemyLabels, toLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 OracleDatabaseNotResolved,
13 collectPages,
14 type CustomerContact,
15 hasAlchemyLabelMap,
16 listAtLocation,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 replaceOnIdentity,
21 resourceNameOf,
22 retryConflict,
23 retryQuota,
24 toPhysicalId,
25 userLabels,
26 waitUntilExists,
27 waitUntilGone,
28 waitUntilReady,
29 } from "./internal.ts";
30 import { waitForOperation } from "./operations.ts";
31
32 const COLLECTION = "cloudExadataInfrastructures";
33 const FALLBACK_ID = "exadata";
34
35 export type MaintenanceWindow = {
36 /** Scheduling preference (`CUSTOM_PREFERENCE`, `NO_PREFERENCE`). */
37 preference?: oracle.MaintenanceWindowPreferenceEnum | (string & {});
38 /** 4-hour UTC slots (`0`, `4`, `8`, `12`, `16`, `20`). */
39 hoursOfDay?: number[];
40 /** Custom action timeout in minutes (15-120). */
41 customActionTimeoutMins?: number;
42 /** Months when maintenance should run. */
43 months?: Array<oracle.MaintenanceWindowMonthsItemEnum | (string & {})>;
44 /** Patching mode (`ROLLING`, `NONROLLING`). */
45 patchingMode?: oracle.MaintenanceWindowPatchingModeEnum | (string & {});
46 /** Lead time in weeks (1-4). */
47 leadTimeWeek?: number;
48 /** Days of week. */
49 daysOfWeek?: Array<oracle.MaintenanceWindowDaysOfWeekItemEnum | (string & {})>;
50 /** Enable custom action timeout. */
51 isCustomActionTimeoutEnabled?: boolean;
52 /** Weeks of month (1, 2, 3, 4). */
53 weeksOfMonth?: number[];
54 };
55
56 export type CloudExadataInfrastructurePropertiesInput = {
57 /** Shape (e.g. `Exadata.X9M`). Immutable. */
58 shape?: string;
59 /** Number of compute servers. */
60 computeCount?: number;
61 /** Number of storage servers. */
62 storageCount?: number;
63 /** Total storage size in GB. */
64 totalStorageSizeGb?: number;
65 /** Maintenance window. */
66 maintenanceWindow?: MaintenanceWindow;
67 /** Customer contacts. */
68 customerContacts?: CustomerContact[];
69 };
70
71 export type CloudExadataInfrastructureProps = {
72 /**
73 * Exadata Infrastructure id (the `{cloud_exadata_infrastructure}`
74 * segment). If omitted, a unique RFC1035 name is generated. Immutable.
75 */
76 cloudExadataInfrastructureId?: string;
77 /**
78 * Region. Immutable.
79 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
80 */
81 location?: string;
82 /**
83 * User-friendly display name.
84 */
85 displayName?: string;
86 /**
87 * GCP Oracle zone (e.g. `us-east4-b-r2`). Immutable. If omitted the
88 * service picks a zone.
89 */
90 gcpOracleZone?: string;
91 /**
92 * User labels. Alchemy ownership labels are merged in automatically.
93 */
94 labels?: Record<string, string>;
95 /**
96 * Infrastructure properties. `shape` is required on create.
97 */
98 properties?: CloudExadataInfrastructurePropertiesInput;
99 /** Shape. Convenience alias for `properties.shape`. */
100 shape?: string;
101 /** Compute server count. Convenience alias for `properties.computeCount`. */
102 computeCount?: number;
103 /** Storage server count. Convenience alias for `properties.storageCount`. */
104 storageCount?: number;
105 };
106
107 export type CloudExadataInfrastructure = Resource<
108 "GCP.OracleDatabase.CloudExadataInfrastructure",
109 CloudExadataInfrastructureProps,
110 {
111 /** Full resource name. */
112 name: string;
113 /** Infrastructure id. */
114 cloudExadataInfrastructureId: string;
115 /** Project id. */
116 project: string;
117 /** Location id. */
118 location: string;
119 /** Display name. */
120 displayName: string | undefined;
121 /** GCP Oracle zone. */
122 gcpOracleZone: string | undefined;
123 /** User labels (Alchemy ownership labels stripped). */
124 labels: Record<string, string>;
125 /** Entitlement id. */
126 entitlementId: string | undefined;
127 /** Lifecycle state. */
128 state: string | undefined;
129 /** Shape. */
130 shape: string | undefined;
131 /** Compute server count. */
132 computeCount: number | undefined;
133 /** Storage server count. */
134 storageCount: number | undefined;
135 /** OCID. */
136 ocid: string | undefined;
137 /** RFC3339 creation timestamp. */
138 createTime: string | undefined;
139 },
140 never,
141 Providers
142 >;
143
144 /**
145 * An Oracle Exadata Infrastructure on Google Cloud.
146 *
147 * Changing `cloudExadataInfrastructureId`, `location`, `gcpOracleZone`,
148 * or `shape` replaces the infrastructure. There is no patch API in the
149 * distilled SDK, so labels and counts are applied at create.
150 *
151 * Provisioning typically takes tens of minutes and requires an Oracle
152 * Database@Google Cloud entitlement. Delete sends `force=true` so child
153 * VM clusters do not block teardown.
154 *
155 * ### Creating Exadata Infrastructure
156 * **Example:** Generated name
157 * ```typescript
158 * const infra = yield* GCP.OracleDatabase.CloudExadataInfrastructure("Exa", {
159 * displayName: "exa",
160 * shape: "Exadata.X9M",
161 * computeCount: 2,
162 * storageCount: 3,
163 * });
164 * ```
165 *
166 * @resource
167 * @category OracleDatabase
168 */
169 export const CloudExadataInfrastructure = Resource<CloudExadataInfrastructure>(
170 "GCP.OracleDatabase.CloudExadataInfrastructure",
171 );
172
173 const mergedProperties = (
174 news: CloudExadataInfrastructureProps,
175 ): CloudExadataInfrastructurePropertiesInput => ({
176 ...news.properties,
177 shape: news.shape ?? news.properties?.shape,
178 computeCount: news.computeCount ?? news.properties?.computeCount,
179 storageCount: news.storageCount ?? news.properties?.storageCount,
180 });
181
182 const toCreateBody = (
183 news: CloudExadataInfrastructureProps,
184 desiredLabels: Record<string, string>,
185 ): oracle.CloudExadataInfrastructure => {
186 const props = mergedProperties(news);
187 const properties: oracle.CloudExadataInfrastructureProperties = {};
188 if (props.shape !== undefined) properties.shape = props.shape;
189 if (props.computeCount !== undefined) {
190 properties.computeCount = props.computeCount;
191 }
192 if (props.storageCount !== undefined) {
193 properties.storageCount = props.storageCount;
194 }
195 if (props.totalStorageSizeGb !== undefined) {
196 properties.totalStorageSizeGb = props.totalStorageSizeGb;
197 }
198 if (props.maintenanceWindow !== undefined) {
199 properties.maintenanceWindow = props.maintenanceWindow;
200 }
201 if (props.customerContacts !== undefined) {
202 properties.customerContacts = props.customerContacts;
203 }
204 const body: oracle.CloudExadataInfrastructure = {
205 labels: desiredLabels,
206 properties,
207 };
208 if (news.displayName !== undefined) body.displayName = news.displayName;
209 if (news.gcpOracleZone !== undefined) {
210 body.gcpOracleZone = news.gcpOracleZone;
211 }
212 return body;
213 };
214
215 const toAttrs = (infra: oracle.CloudExadataInfrastructure, project: string) => {
216 const name = infra.name ?? "";
217 const parsed = parseName(name, COLLECTION);
218 return {
219 name,
220 cloudExadataInfrastructureId: parsed.id,
221 project: parsed.project || project,
222 location: parsed.location,
223 displayName: infra.displayName,
224 gcpOracleZone: infra.gcpOracleZone,
225 labels: userLabels(infra.labels),
226 entitlementId: infra.entitlementId,
227 state: infra.properties?.state,
228 shape: infra.properties?.shape,
229 computeCount: infra.properties?.computeCount,
230 storageCount: infra.properties?.storageCount,
231 ocid: infra.properties?.ocid,
232 createTime: infra.createTime,
233 };
234 };
235
236 const getByName = (name: string) =>
237 retryQuota(oracle.getProjectsLocationsCloudExadataInfrastructures({ name })).pipe(
238 Effect.catchTag("NotFound", () => Effect.undefined),
239 );
240
241 const listInfras = (project: string, region: string) => {
242 const collect = (parent: string) =>
243 collectPages(
244 oracle.listProjectsLocationsCloudExadataInfrastructures.pages({
245 parent,
246 pageSize: 1000,
247 }),
248 (page) => page.cloudExadataInfrastructures,
249 ).pipe(Effect.map((items) => items.filter((item) => hasAlchemyLabelMap(item.labels))));
250 return listAtLocation(project, region, collect).pipe(
251 Effect.catchTag("NotFound", () => Effect.succeed([])),
252 );
253 };
254
255 export const CloudExadataInfrastructureProvider = () =>
256 Provider.succeed(CloudExadataInfrastructure, {
257 stables: ["name", "cloudExadataInfrastructureId", "project", "location", "createTime", "ocid"],
258
259 diff: Effect.fn(function* ({ news, olds, output }) {
260 if (!isResolved(news)) return undefined;
261 const env = yield* GcpEnvironment.current;
262 const props = mergedProperties(news);
263 const previousShape = olds?.shape ?? olds?.properties?.shape ?? output?.shape ?? "";
264 const nextShape = props.shape ?? previousShape;
265 const previousZone = olds?.gcpOracleZone ?? output?.gcpOracleZone ?? "";
266 const nextZone = news.gcpOracleZone ?? previousZone;
267 return replaceOnIdentity({
268 previousId: olds?.cloudExadataInfrastructureId ?? output?.cloudExadataInfrastructureId,
269 nextId:
270 news.cloudExadataInfrastructureId ??
271 olds?.cloudExadataInfrastructureId ??
272 output?.cloudExadataInfrastructureId,
273 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
274 nextLocation: normalizeLocation(
275 news.location ?? olds?.location ?? output?.location ?? env.region,
276 ),
277 extra: nextShape !== previousShape || nextZone !== previousZone,
278 });
279 }),
280
281 read: Effect.fn(function* ({ id, olds, output }) {
282 const env = yield* GcpEnvironment.current;
283 const cloudExadataInfrastructureId = yield* toPhysicalId(
284 id,
285 olds?.cloudExadataInfrastructureId,
286 output?.cloudExadataInfrastructureId,
287 FALLBACK_ID,
288 );
289 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
290 const name =
291 output?.name ??
292 resourceNameOf(env.project, location, COLLECTION, cloudExadataInfrastructureId);
293 const existing = yield* getByName(name);
294 if (existing === undefined) return undefined;
295 const attrs = toAttrs(existing, env.project);
296 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
297 }),
298
299 list: () =>
300 Effect.gen(function* () {
301 const env = yield* GcpEnvironment.current;
302 const items = yield* listInfras(env.project, env.region);
303 return items.map((item) => toAttrs(item, env.project));
304 }),
305
306 reconcile: Effect.fn(function* ({ id, news, output }) {
307 const env = yield* GcpEnvironment.current;
308 const cloudExadataInfrastructureId = yield* toPhysicalId(
309 id,
310 news.cloudExadataInfrastructureId,
311 output?.cloudExadataInfrastructureId,
312 FALLBACK_ID,
313 );
314 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
315 const name = resourceNameOf(env.project, location, COLLECTION, cloudExadataInfrastructureId);
316 const desiredLabels = {
317 ...toLabels(news.labels),
318 ...(yield* createInternalLabels(id)),
319 };
320
321 let current = yield* getByName(output?.name ?? name);
322
323 if (current === undefined) {
324 const created = yield* oracle
325 .createProjectsLocationsCloudExadataInfrastructures({
326 parent: parentOf(env.project, location),
327 cloudExadataInfrastructureId,
328 body: toCreateBody(news, desiredLabels),
329 })
330 .pipe(
331 retryQuota,
332 Effect.catchTag("Conflict", () => Effect.undefined),
333 );
334 if (created !== undefined) {
335 yield* waitForOperation(created);
336 }
337 current = yield* waitUntilExists(getByName(name), name);
338 }
339
340 if (current === undefined) {
341 return yield* new OracleDatabaseNotResolved({ resourceName: name });
342 }
343
344 const ready = yield* waitUntilReady(
345 getByName(current.name ?? name),
346 current.name ?? name,
347 (value) => value.properties?.state,
348 );
349
350 return toAttrs(ready, env.project);
351 }),
352
353 delete: Effect.fn(function* ({ output }) {
354 const operation = yield* oracle
355 .deleteProjectsLocationsCloudExadataInfrastructures({
356 name: output.name,
357 force: true,
358 })
359 .pipe(
360 retryConflict,
361 Effect.catchTag("NotFound", () => Effect.undefined),
362 );
363 if (operation !== undefined) {
364 yield* waitForOperation(operation, { notFoundOk: true });
365 }
366 yield* waitUntilGone(getByName(output.name), output.name);
367 }),
368 });