@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 521 lines 17.6 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 * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 alphanumericId,
15 expandParent,
16 hasAlchemyLabelMap,
17 lastSegment,
18 listAtLocation,
19 normalizeLocation,
20 parentOf,
21 parseName,
22 replaceOnIdentity,
23 ResourceNotResolved,
24 toPhysicalId,
25 userLabels,
26 waitForOperation,
27 waitUntilExists,
28 waitUntilGone,
29 waitUntilReady,
30 } from "./internal.ts";
31
32 const DEFAULT_DEPLOYMENT_TYPE = "DATABASE_ORACLE";
33 const DEFAULT_ADMIN_USERNAME = "oggadmin";
34
35 export type GoldengateOggData = {
36 /**
37 * GoldenGate console username. Required on create.
38 */
39 adminUsername: string;
40 /**
41 * Name of the GoldenGate service deployment (1–32 alphanumeric
42 * characters, starting with a letter). Distinct from the GCP resource
43 * id.
44 */
45 deployment: string;
46 /**
47 * Console password in plain text. Create-only; omitted from attributes.
48 */
49 adminPassword?: string;
50 /**
51 * Secret Manager version holding the console password
52 * (`projects/{project}/secrets/{secret}/versions/{version}`).
53 */
54 adminPasswordSecretVersion?: string;
55 /**
56 * Oracle GoldenGate version. If omitted, the service picks a default.
57 */
58 oggVersion?: string;
59 };
60
61 export type GoldengateMaintenanceWindow = {
62 /** UTC start hour for the maintenance window. */
63 startHour?: number;
64 /** Day of week (`MONDAY` … `SUNDAY`). */
65 day?: oracle.GoldengateMaintenanceWindowDayEnum | (string & {});
66 };
67
68 export type GoldengateMaintenanceConfig = {
69 /** Auto-upgrade period for bundle releases, in days. */
70 bundleReleaseUpgradePeriodDays?: number;
71 /** Auto-upgrade period for major releases, in days. */
72 majorReleaseUpgradePeriodDays?: number;
73 /** Auto-upgrade period for security patches, in days. */
74 securityPatchUpgradePeriodDays?: number;
75 /** Enable auto-upgrade for interim releases. */
76 isInterimReleaseAutoUpgradeEnabled?: boolean;
77 /** Auto-upgrade period for interim releases, in days. */
78 interimReleaseUpgradePeriodDays?: number;
79 };
80
81 export type GoldengateDeploymentProps = {
82 /**
83 * Deployment id (the `{goldengate_deployment}` segment of
84 * `projects/{project}/locations/{location}/goldengateDeployments/{goldengate_deployment}`).
85 * If omitted, a unique RFC1035 name is generated. Immutable —
86 * changing it replaces the deployment.
87 */
88 goldengateDeploymentId?: string;
89 /**
90 * Region (`us-central1`, `us-east4`, …). Immutable — changing it
91 * replaces the deployment.
92 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
93 */
94 location?: string;
95 /**
96 * User-facing display name. Defaults to the generated resource id.
97 */
98 displayName?: string;
99 /**
100 * Parent ODB Network. Full name or id. Immutable — changing it
101 * replaces the deployment.
102 */
103 odbNetwork?: string;
104 /**
105 * ODB Subnet used for IP allocation. Full name
106 * `projects/{project}/locations/{location}/odbNetworks/{odb_network}/odbSubnets/{odb_subnet}`
107 * or a bare subnet id (requires `odbNetwork`). Immutable — changing
108 * it replaces the deployment.
109 */
110 odbSubnet: string;
111 /**
112 * GCP Oracle zone (e.g. `us-east4-b-r2`). Immutable — changing it
113 * replaces the deployment.
114 */
115 gcpOracleZone?: string;
116 /**
117 * Oracle GoldenGate deployment type (`DATABASE_ORACLE`, `BIGDATA`,
118 * `DATABASE_POSTGRESQL`, …). Immutable — changing it replaces the
119 * deployment.
120 * @default "DATABASE_ORACLE"
121 */
122 deploymentType?: string;
123 /**
124 * GoldenGate console and service identity. `deployment` is immutable.
125 */
126 oggData: GoldengateOggData;
127 /**
128 * Human-readable description stored on the Oracle properties.
129 */
130 description?: string;
131 /**
132 * Minimum OCPU count.
133 */
134 cpuCoreCount?: number;
135 /**
136 * Oracle license model (`LICENSE_INCLUDED`, `BRING_YOUR_OWN_LICENSE`).
137 */
138 licenseModel?: oracle.GoldengateDeploymentPropertiesLicenseModelEnum | (string & {});
139 /**
140 * GoldenGate environment type (from `ListGoldengateDeploymentEnvironments`).
141 */
142 environmentType?: string;
143 /**
144 * Enable CPU auto-scaling.
145 */
146 isAutoScalingEnabled?: boolean;
147 /**
148 * Preferred weekly maintenance window.
149 */
150 maintenanceWindow?: GoldengateMaintenanceWindow;
151 /**
152 * Auto-upgrade periods for GoldenGate releases.
153 */
154 maintenanceConfig?: GoldengateMaintenanceConfig;
155 /**
156 * User labels. Alchemy ownership labels are merged in automatically.
157 */
158 labels?: Record<string, string>;
159 };
160
161 export type GoldengateDeployment = Resource<
162 "GCP.OracleDatabase.GoldengateDeployment",
163 GoldengateDeploymentProps,
164 {
165 /** Full resource name. */
166 name: string;
167 /** Deployment id (last path segment). */
168 goldengateDeploymentId: string;
169 /** Project id. */
170 project: string;
171 /** Location id. */
172 location: string;
173 /** Display name. */
174 displayName: string | undefined;
175 /** Parent ODB Network resource name. */
176 odbNetwork: string | undefined;
177 /** ODB Subnet resource name. */
178 odbSubnet: string | undefined;
179 /** GCP Oracle zone. */
180 gcpOracleZone: string | undefined;
181 /** GoldenGate deployment type. */
182 deploymentType: string | undefined;
183 /** GoldenGate service deployment name. */
184 oggDeployment: string | undefined;
185 /** GoldenGate console username. */
186 adminUsername: string | undefined;
187 /** GoldenGate version. */
188 oggVersion: string | undefined;
189 /** Description. */
190 description: string | undefined;
191 /** Minimum OCPU count. */
192 cpuCoreCount: number | undefined;
193 /** License model. */
194 licenseModel: string | undefined;
195 /** Environment type. */
196 environmentType: string | undefined;
197 /** Whether CPU auto-scaling is enabled. */
198 isAutoScalingEnabled: boolean | undefined;
199 /** User labels (Alchemy ownership labels stripped). */
200 labels: Record<string, string>;
201 /** Lifecycle state. */
202 lifecycleState: string | undefined;
203 /** Lifecycle details. */
204 lifecycleDetails: string | undefined;
205 /** GoldenGate FQDN. */
206 fqdn: string | undefined;
207 /** Deployment URL. */
208 deploymentUrl: string | undefined;
209 /** Private IP address. */
210 privateIpAddress: string | undefined;
211 /** Public IP address. */
212 publicIpAddress: string | undefined;
213 /** OCI console URL. */
214 ociUrl: string | undefined;
215 /** Marketplace entitlement id. */
216 entitlementId: string | undefined;
217 /** Oracle Cloud identifier. */
218 ocid: string | undefined;
219 /** RFC3339 creation timestamp. */
220 createTime: string | undefined;
221 },
222 never,
223 Providers
224 >;
225
226 /**
227 * An Oracle Database@Google Cloud GoldenGate deployment.
228 *
229 * Changing `goldengateDeploymentId`, `location`, `odbNetwork`,
230 * `odbSubnet`, `gcpOracleZone`, `deploymentType`, or
231 * `oggData.deployment` replaces the deployment. Labels and most
232 * properties are set at create; the API has no update. Requires an
233 * Oracle Database@Google Cloud entitlement and a client ODB Subnet.
234 *
235 * ### Creating a GoldenGate Deployment
236 * **Example:** Oracle GoldenGate on an ODB Subnet
237 * ```typescript
238 * const gg = yield* GCP.OracleDatabase.GoldengateDeployment("Replicat", {
239 * odbSubnet: subnet.name,
240 * odbNetwork: net.name,
241 * displayName: "app-gg",
242 * deploymentType: "DATABASE_ORACLE",
243 * oggData: {
244 * adminUsername: "oggadmin",
245 * deployment: "oggdeploy",
246 * adminPassword: "change-me",
247 * },
248 * });
249 * ```
250 *
251 * **Example:** Explicit id and labels
252 * ```typescript
253 * const gg = yield* GCP.OracleDatabase.GoldengateDeployment("Replicat", {
254 * goldengateDeploymentId: "app-gg",
255 * odbSubnet: subnet.name,
256 * deploymentType: "DATABASE_ORACLE",
257 * oggData: {
258 * adminUsername: "oggadmin",
259 * deployment: "oggdeploy",
260 * adminPasswordSecretVersion: secret.latestVersionName,
261 * },
262 * labels: { env: "prod" },
263 * });
264 * ```
265 *
266 * @resource
267 * @category OracleDatabase
268 */
269 export const GoldengateDeployment = Resource<GoldengateDeployment>(
270 "GCP.OracleDatabase.GoldengateDeployment",
271 );
272
273 const resourceName = (project: string, location: string, goldengateDeploymentId: string) =>
274 `projects/${project}/locations/${location}/goldengateDeployments/${goldengateDeploymentId}`;
275
276 const subnetOf = (
277 odbSubnet: string,
278 odbNetwork: string | undefined,
279 project: string,
280 location: string,
281 ) => {
282 if (odbSubnet.includes("/")) return odbSubnet.replace(/\/+$/, "");
283 const network = odbNetwork
284 ? expandParent(odbNetwork, project, location, "odbNetworks")
285 : `projects/${project}/locations/${location}/odbNetworks`;
286 return `${network}/odbSubnets/${odbSubnet}`;
287 };
288
289 const networkOf = (odbNetwork: string | undefined, project: string, location: string) =>
290 odbNetwork === undefined || odbNetwork.length === 0
291 ? undefined
292 : expandParent(odbNetwork, project, location, "odbNetworks");
293
294 const desiredType = (type: string | undefined) => type ?? DEFAULT_DEPLOYMENT_TYPE;
295
296 const toAttrs = (deployment: oracle.GoldengateDeployment, project: string) => {
297 const name = deployment.name ?? "";
298 const parsed = parseName(name, "goldengateDeployments");
299 const properties = deployment.properties;
300 return {
301 name,
302 goldengateDeploymentId: parsed.id,
303 project: parsed.project || project,
304 location: parsed.location,
305 displayName: deployment.displayName,
306 odbNetwork: deployment.odbNetwork,
307 odbSubnet: deployment.odbSubnet,
308 gcpOracleZone: deployment.gcpOracleZone,
309 deploymentType: properties?.deploymentType,
310 oggDeployment: properties?.oggData?.deployment,
311 adminUsername: properties?.oggData?.adminUsername,
312 oggVersion: properties?.oggData?.oggVersion,
313 description: properties?.description,
314 cpuCoreCount: properties?.cpuCoreCount,
315 licenseModel: properties?.licenseModel,
316 environmentType: properties?.environmentType,
317 isAutoScalingEnabled: properties?.isAutoScalingEnabled,
318 labels: userLabels(deployment.labels),
319 lifecycleState: properties?.lifecycleState,
320 lifecycleDetails: properties?.lifecycleDetails,
321 fqdn: properties?.fqdn,
322 deploymentUrl: properties?.deploymentUrl,
323 privateIpAddress: properties?.privateIpAddress,
324 publicIpAddress: properties?.publicIpAddress,
325 ociUrl: deployment.ociUrl,
326 entitlementId: deployment.entitlementId,
327 ocid: properties?.ocid,
328 createTime: deployment.createTime,
329 };
330 };
331
332 const getByName = (name: string) =>
333 name.length === 0
334 ? Effect.undefined
335 : oracle
336 .getProjectsLocationsGoldengateDeployments({ name })
337 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
338
339 const listOwned = (project: string, region: string) =>
340 listAtLocation(project, region, (parent) =>
341 oracle.listProjectsLocationsGoldengateDeployments.pages({ parent, pageSize: 1000 }).pipe(
342 Stream.flatMap((page) => Stream.fromIterable(page.goldengateDeployments ?? [])),
343 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
344 Stream.runCollect,
345 Effect.map((chunk) => Array.from(chunk)),
346 Effect.catchTag("NotFound", () => Effect.succeed([])),
347 ),
348 );
349
350 const toCreateBody = (
351 news: GoldengateDeploymentProps,
352 desiredLabels: Record<string, string>,
353 displayName: string,
354 odbNetwork: string | undefined,
355 odbSubnet: string,
356 ): oracle.GoldengateDeployment => ({
357 displayName,
358 odbNetwork,
359 odbSubnet,
360 gcpOracleZone: news.gcpOracleZone,
361 labels: desiredLabels,
362 properties: {
363 deploymentType: desiredType(news.deploymentType),
364 description: news.description,
365 cpuCoreCount: news.cpuCoreCount,
366 licenseModel: news.licenseModel,
367 environmentType: news.environmentType,
368 isAutoScalingEnabled: news.isAutoScalingEnabled,
369 maintenanceWindow: news.maintenanceWindow,
370 maintenanceConfig: news.maintenanceConfig,
371 oggData: {
372 adminUsername: news.oggData.adminUsername || DEFAULT_ADMIN_USERNAME,
373 deployment: alphanumericId(news.oggData.deployment),
374 adminPassword: news.oggData.adminPassword,
375 adminPasswordSecretVersion: news.oggData.adminPasswordSecretVersion,
376 oggVersion: news.oggData.oggVersion,
377 },
378 },
379 });
380
381 export const GoldengateDeploymentProvider = () =>
382 Provider.succeed(GoldengateDeployment, {
383 stables: [
384 "name",
385 "goldengateDeploymentId",
386 "project",
387 "location",
388 "odbNetwork",
389 "odbSubnet",
390 "gcpOracleZone",
391 "deploymentType",
392 "oggDeployment",
393 "entitlementId",
394 "ocid",
395 "createTime",
396 ],
397
398 diff: Effect.fn(function* ({ news, olds, output }) {
399 if (!isResolved(news)) return undefined;
400 const env = yield* GcpEnvironment.current;
401 const previousType = desiredType(olds?.deploymentType ?? output?.deploymentType);
402 const nextType = desiredType(news.deploymentType ?? previousType);
403 const previousOgg = olds?.oggData?.deployment ?? output?.oggDeployment ?? "";
404 const nextOgg = news.oggData?.deployment ?? previousOgg;
405 const previousZone = olds?.gcpOracleZone ?? output?.gcpOracleZone ?? "";
406 const nextZone = news.gcpOracleZone ?? previousZone;
407 const previousSubnet = lastSegment(olds?.odbSubnet ?? output?.odbSubnet ?? "");
408 const nextSubnet = lastSegment(news.odbSubnet ?? previousSubnet);
409 return replaceOnIdentity({
410 previousId: olds?.goldengateDeploymentId ?? output?.goldengateDeploymentId,
411 nextId:
412 news.goldengateDeploymentId ??
413 olds?.goldengateDeploymentId ??
414 output?.goldengateDeploymentId,
415 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
416 nextLocation: normalizeLocation(
417 news.location ?? olds?.location ?? output?.location ?? env.region,
418 ),
419 previousParent: olds?.odbNetwork ?? output?.odbNetwork,
420 nextParent: news.odbNetwork ?? olds?.odbNetwork ?? output?.odbNetwork,
421 extra:
422 previousType !== nextType ||
423 previousOgg !== nextOgg ||
424 previousZone !== nextZone ||
425 previousSubnet !== nextSubnet,
426 });
427 }),
428
429 read: Effect.fn(function* ({ id, olds, output }) {
430 const env = yield* GcpEnvironment.current;
431 const goldengateDeploymentId = yield* toPhysicalId(
432 id,
433 olds?.goldengateDeploymentId,
434 output?.goldengateDeploymentId,
435 "goldengate",
436 );
437 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
438 const name = output?.name ?? resourceName(env.project, location, goldengateDeploymentId);
439 const existing = yield* getByName(name);
440 if (existing === undefined) return undefined;
441 const attrs = toAttrs(existing, env.project);
442 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
443 }),
444
445 list: () =>
446 Effect.gen(function* () {
447 const env = yield* GcpEnvironment.current;
448 const items = yield* listOwned(env.project, env.region);
449 return items.map((item) => toAttrs(item, env.project));
450 }),
451
452 reconcile: Effect.fn(function* ({ id, news, output }) {
453 const env = yield* GcpEnvironment.current;
454 const goldengateDeploymentId = yield* toPhysicalId(
455 id,
456 news.goldengateDeploymentId,
457 output?.goldengateDeploymentId,
458 "goldengate",
459 );
460 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
461 const name = resourceName(env.project, location, goldengateDeploymentId);
462 const odbNetwork = networkOf(news.odbNetwork, env.project, location);
463 const odbSubnet = subnetOf(
464 news.odbSubnet,
465 news.odbNetwork ?? odbNetwork,
466 env.project,
467 location,
468 );
469 const displayName = news.displayName ?? goldengateDeploymentId;
470 const desiredLabels = {
471 ...toLabels(news.labels),
472 ...(yield* createInternalLabels(id)),
473 };
474
475 let current = yield* getByName(output?.name ?? name);
476
477 if (current === undefined) {
478 const created = yield* oracle
479 .createProjectsLocationsGoldengateDeployments({
480 parent: parentOf(env.project, location),
481 goldengateDeploymentId,
482 body: toCreateBody(news, desiredLabels, displayName, odbNetwork, odbSubnet),
483 })
484 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
485 if (created !== undefined) {
486 yield* waitForOperation(created);
487 }
488 current = yield* waitUntilExists(getByName(name), name);
489 }
490
491 if (current === undefined) {
492 return yield* new ResourceNotResolved({ resourceName: name });
493 }
494
495 const ready = yield* waitUntilReady(
496 getByName(current.name ?? name),
497 current.name ?? name,
498 (item) => item.properties?.lifecycleState,
499 (item) => item.properties?.lifecycleDetails,
500 );
501
502 return toAttrs(ready, env.project);
503 }),
504
505 delete: Effect.fn(function* ({ output }) {
506 const operation = yield* oracle
507 .deleteProjectsLocationsGoldengateDeployments({ name: output.name })
508 .pipe(
509 Effect.retry({
510 while: (error) => error._tag === "Conflict",
511 times: 8,
512 schedule: Schedule.spaced("5 seconds"),
513 }),
514 Effect.catchTag("NotFound", () => Effect.undefined),
515 );
516 if (operation !== undefined) {
517 yield* waitForOperation(operation, { notFoundOk: true });
518 }
519 yield* waitUntilGone(getByName(output.name), output.name);
520 }),
521 });