The best way to control Claude Code, Codex and more from any computer or phone

main
ts 321 lines 10.7 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 hasAlchemyLabelMap,
15 listAtLocation,
16 normalizeLocation,
17 parentOf,
18 parseName,
19 replaceOnIdentity,
20 resourceNameOf,
21 retryConflict,
22 retryQuota,
23 toPhysicalId,
24 userLabels,
25 waitUntilExists,
26 waitUntilGone,
27 waitUntilReady,
28 } from "./internal.ts";
29 import { waitForOperation } from "./operations.ts";
30
31 const COLLECTION = "goldengateConnections";
32 const FALLBACK_ID = "ggconn";
33
34 export type GoldengateConnectionProps = {
35 /**
36 * Connection id. If omitted, a unique RFC1035 name is generated.
37 * Immutable.
38 */
39 goldengateConnectionId?: string;
40 /**
41 * Region. Immutable.
42 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
43 */
44 location?: string;
45 /**
46 * GCP Oracle zone. Immutable.
47 */
48 gcpOracleZone?: string;
49 /**
50 * ODB Network. Immutable.
51 */
52 odbNetwork?: string;
53 /**
54 * ODB Subnet. Immutable.
55 */
56 odbSubnet?: string;
57 /**
58 * User labels. Alchemy ownership labels are merged in automatically.
59 */
60 labels?: Record<string, string>;
61 /**
62 * Connection properties. `connectionType` and `displayName` are
63 * required on create. Type-specific nested objects (Oracle, Kafka,
64 * PostgreSQL, …) are passed through to the API.
65 */
66 properties?: oracle.GoldengateConnectionProperties;
67 /** Connection type. Convenience alias for `properties.connectionType`. */
68 connectionType?: oracle.GoldengateConnectionPropertiesConnectionTypeEnum | (string & {});
69 /** Display name. Convenience alias for `properties.displayName`. */
70 displayName?: string;
71 /** Description. Convenience alias for `properties.description`. */
72 description?: string;
73 /** Routing method. Convenience alias for `properties.routingMethod`. */
74 routingMethod?: oracle.GoldengateConnectionPropertiesRoutingMethodEnum | (string & {});
75 };
76
77 export type GoldengateConnection = Resource<
78 "GCP.OracleDatabase.GoldengateConnection",
79 GoldengateConnectionProps,
80 {
81 /** Full resource name. */
82 name: string;
83 /** Connection id. */
84 goldengateConnectionId: string;
85 /** Project id. */
86 project: string;
87 /** Location id. */
88 location: string;
89 /** GCP Oracle zone. */
90 gcpOracleZone: string | undefined;
91 /** ODB Network. */
92 odbNetwork: string | undefined;
93 /** ODB Subnet. */
94 odbSubnet: string | undefined;
95 /** User labels (Alchemy ownership labels stripped). */
96 labels: Record<string, string>;
97 /** Entitlement id. */
98 entitlementId: string | undefined;
99 /** Connection type. */
100 connectionType: string | undefined;
101 /** Display name. */
102 displayName: string | undefined;
103 /** Lifecycle state. */
104 lifecycleState: string | undefined;
105 /** OCID. */
106 ocid: string | undefined;
107 /** Ingress IPs. */
108 ingressIpAddresses: string[];
109 /** RFC3339 creation timestamp. */
110 createTime: string | undefined;
111 },
112 never,
113 Providers
114 >;
115
116 /**
117 * An Oracle GoldenGate connection on Google Cloud.
118 *
119 * Changing `goldengateConnectionId`, `location`, `connectionType`, or
120 * ODB identity replaces the connection. There is no patch API in the
121 * distilled SDK, so labels are applied at create.
122 *
123 * ### Creating a GoldenGate connection
124 * **Example:** Generic connection
125 * ```typescript
126 * const conn = yield* GCP.OracleDatabase.GoldengateConnection("Src", {
127 * connectionType: "GENERIC",
128 * displayName: "src",
129 * properties: {
130 * genericConnectionProperties: {
131 * host: "db.example.com",
132 * technologyType: "GENERIC",
133 * },
134 * },
135 * });
136 * ```
137 *
138 * @resource
139 * @category OracleDatabase
140 */
141 export const GoldengateConnection = Resource<GoldengateConnection>(
142 "GCP.OracleDatabase.GoldengateConnection",
143 );
144
145 const mergedProperties = (
146 news: GoldengateConnectionProps,
147 ): oracle.GoldengateConnectionProperties => ({
148 ...news.properties,
149 connectionType: news.connectionType ?? news.properties?.connectionType,
150 displayName: news.displayName ?? news.properties?.displayName,
151 description: news.description ?? news.properties?.description,
152 routingMethod: news.routingMethod ?? news.properties?.routingMethod,
153 });
154
155 const toCreateBody = (
156 news: GoldengateConnectionProps,
157 desiredLabels: Record<string, string>,
158 ): oracle.GoldengateConnection => {
159 const body: oracle.GoldengateConnection = {
160 labels: desiredLabels,
161 properties: mergedProperties(news),
162 };
163 if (news.gcpOracleZone !== undefined) body.gcpOracleZone = news.gcpOracleZone;
164 if (news.odbNetwork !== undefined) body.odbNetwork = news.odbNetwork;
165 if (news.odbSubnet !== undefined) body.odbSubnet = news.odbSubnet;
166 return body;
167 };
168
169 const toAttrs = (connection: oracle.GoldengateConnection, project: string) => {
170 const name = connection.name ?? "";
171 const parsed = parseName(name, COLLECTION);
172 return {
173 name,
174 goldengateConnectionId: parsed.id,
175 project: parsed.project || project,
176 location: parsed.location,
177 gcpOracleZone: connection.gcpOracleZone,
178 odbNetwork: connection.odbNetwork,
179 odbSubnet: connection.odbSubnet,
180 labels: userLabels(connection.labels),
181 entitlementId: connection.entitlementId,
182 connectionType: connection.properties?.connectionType,
183 displayName: connection.properties?.displayName,
184 lifecycleState: connection.properties?.lifecycleState,
185 ocid: connection.properties?.ocid,
186 ingressIpAddresses: [...(connection.properties?.ingressIpAddresses ?? [])],
187 createTime: connection.createTime,
188 };
189 };
190
191 const getByName = (name: string) =>
192 retryQuota(oracle.getProjectsLocationsGoldengateConnections({ name })).pipe(
193 Effect.catchTag("NotFound", () => Effect.undefined),
194 );
195
196 const listConnections = (project: string, region: string) => {
197 const collect = (parent: string) =>
198 collectPages(
199 oracle.listProjectsLocationsGoldengateConnections.pages({
200 parent,
201 pageSize: 1000,
202 }),
203 (page) => page.goldengateConnections,
204 ).pipe(Effect.map((items) => items.filter((item) => hasAlchemyLabelMap(item.labels))));
205 return listAtLocation(project, region, collect).pipe(
206 Effect.catchTag("NotFound", () => Effect.succeed([])),
207 );
208 };
209
210 export const GoldengateConnectionProvider = () =>
211 Provider.succeed(GoldengateConnection, {
212 stables: ["name", "goldengateConnectionId", "project", "location", "createTime", "ocid"],
213
214 diff: Effect.fn(function* ({ news, olds, output }) {
215 if (!isResolved(news)) return undefined;
216 const env = yield* GcpEnvironment.current;
217 const previousType =
218 olds?.connectionType ?? olds?.properties?.connectionType ?? output?.connectionType ?? "";
219 const nextType = news.connectionType ?? news.properties?.connectionType ?? previousType;
220 const previousOdb = olds?.odbSubnet ?? output?.odbSubnet ?? "";
221 const nextOdb = news.odbSubnet ?? previousOdb;
222 return replaceOnIdentity({
223 previousId: olds?.goldengateConnectionId ?? output?.goldengateConnectionId,
224 nextId:
225 news.goldengateConnectionId ??
226 olds?.goldengateConnectionId ??
227 output?.goldengateConnectionId,
228 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
229 nextLocation: normalizeLocation(
230 news.location ?? olds?.location ?? output?.location ?? env.region,
231 ),
232 extra: nextType !== previousType || nextOdb !== previousOdb,
233 });
234 }),
235
236 read: Effect.fn(function* ({ id, olds, output }) {
237 const env = yield* GcpEnvironment.current;
238 const goldengateConnectionId = yield* toPhysicalId(
239 id,
240 olds?.goldengateConnectionId,
241 output?.goldengateConnectionId,
242 FALLBACK_ID,
243 );
244 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
245 const name =
246 output?.name ?? resourceNameOf(env.project, location, COLLECTION, goldengateConnectionId);
247 const existing = yield* getByName(name);
248 if (existing === undefined) return undefined;
249 const attrs = toAttrs(existing, env.project);
250 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
251 }),
252
253 list: () =>
254 Effect.gen(function* () {
255 const env = yield* GcpEnvironment.current;
256 const items = yield* listConnections(env.project, env.region);
257 return items.map((item) => toAttrs(item, env.project));
258 }),
259
260 reconcile: Effect.fn(function* ({ id, news, output }) {
261 const env = yield* GcpEnvironment.current;
262 const goldengateConnectionId = yield* toPhysicalId(
263 id,
264 news.goldengateConnectionId,
265 output?.goldengateConnectionId,
266 FALLBACK_ID,
267 );
268 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
269 const name = resourceNameOf(env.project, location, COLLECTION, goldengateConnectionId);
270 const desiredLabels = {
271 ...toLabels(news.labels),
272 ...(yield* createInternalLabels(id)),
273 };
274
275 let current = yield* getByName(output?.name ?? name);
276
277 if (current === undefined) {
278 const created = yield* oracle
279 .createProjectsLocationsGoldengateConnections({
280 parent: parentOf(env.project, location),
281 goldengateConnectionId,
282 body: toCreateBody(news, desiredLabels),
283 })
284 .pipe(
285 retryQuota,
286 Effect.catchTag("Conflict", () => Effect.undefined),
287 );
288 if (created !== undefined) {
289 yield* waitForOperation(created);
290 }
291 current = yield* waitUntilExists(getByName(name), name);
292 }
293
294 if (current === undefined) {
295 return yield* new OracleDatabaseNotResolved({ resourceName: name });
296 }
297
298 const ready = yield* waitUntilReady(
299 getByName(current.name ?? name),
300 current.name ?? name,
301 (value) => value.properties?.lifecycleState,
302 );
303
304 return toAttrs(ready, env.project);
305 }),
306
307 delete: Effect.fn(function* ({ output }) {
308 const operation = yield* oracle
309 .deleteProjectsLocationsGoldengateConnections({
310 name: output.name,
311 })
312 .pipe(
313 retryConflict,
314 Effect.catchTag("NotFound", () => Effect.undefined),
315 );
316 if (operation !== undefined) {
317 yield* waitForOperation(operation, { notFoundOk: true });
318 }
319 yield* waitUntilGone(getByName(output.name), output.name);
320 }),
321 });