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

main
ts 283 lines 9.31 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 DEFAULT_NETWORK,
15 hasAlchemyLabelMap,
16 lastSegment,
17 listAtLocation,
18 networkName,
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 export type OdbNetworkProps = {
33 /**
34 * ODB Network id (the `{odb_network}` segment of
35 * `projects/{project}/locations/{location}/odbNetworks/{odb_network}`).
36 * If omitted, a unique RFC1035 name is generated from the stack, stage,
37 * and logical id. Immutable — changing it replaces the network.
38 */
39 odbNetworkId?: string;
40 /**
41 * Region (`us-central1`, `us-east4`, …). Immutable — changing it
42 * replaces the network. `US-CENTRAL1` is accepted and normalized to
43 * `us-central1`.
44 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
45 */
46 location?: string;
47 /**
48 * VPC network used for Oracle Database@Google Cloud connectivity.
49 * Accepts a name (`default`) or
50 * `projects/{project}/global/networks/{network}`. Immutable —
51 * changing it replaces the network.
52 * @default "default"
53 */
54 network?: string;
55 /**
56 * GCP Oracle zone (e.g. `us-east4-b-r2`). If omitted, the service
57 * picks a zone. Immutable — changing it replaces the network.
58 */
59 gcpOracleZone?: string;
60 /**
61 * User labels. Alchemy ownership labels are merged in automatically.
62 */
63 labels?: Record<string, string>;
64 };
65
66 export type OdbNetwork = Resource<
67 "GCP.OracleDatabase.OdbNetwork",
68 OdbNetworkProps,
69 {
70 /** Full resource name. */
71 name: string;
72 /** ODB Network id (last path segment). */
73 odbNetworkId: string;
74 /** Project id. */
75 project: string;
76 /** Location id. */
77 location: string;
78 /** VPC network resource name. */
79 network: string | undefined;
80 /** GCP Oracle zone. */
81 gcpOracleZone: string | undefined;
82 /** User labels (Alchemy ownership labels stripped). */
83 labels: Record<string, string>;
84 /** Server-reported state. */
85 state: string | undefined;
86 /** Marketplace entitlement id. */
87 entitlementId: string | undefined;
88 /** RFC3339 creation timestamp. */
89 createTime: string | undefined;
90 },
91 never,
92 Providers
93 >;
94
95 /**
96 * An Oracle Database@Google Cloud ODB Network — the private network that
97 * connects a VPC to Oracle Database resources in a region.
98 *
99 * Changing `odbNetworkId`, `location`, `network`, or `gcpOracleZone`
100 * replaces the network. Labels are set at create; the API has no update.
101 * Requires an Oracle Database@Google Cloud marketplace entitlement.
102 *
103 * ### Creating an ODB Network
104 * **Example:** Generated name on the default VPC
105 * ```typescript
106 * const net = yield* GCP.OracleDatabase.OdbNetwork("OracleNet", {});
107 * ```
108 *
109 * **Example:** Explicit id, labels, and network
110 * ```typescript
111 * const net = yield* GCP.OracleDatabase.OdbNetwork("OracleNet", {
112 * odbNetworkId: "app-odb",
113 * location: "us-central1",
114 * network: "default",
115 * labels: { env: "prod" },
116 * });
117 * ```
118 *
119 * @resource
120 * @category OracleDatabase
121 */
122 export const OdbNetwork = Resource<OdbNetwork>("GCP.OracleDatabase.OdbNetwork");
123
124 const resourceName = (project: string, location: string, odbNetworkId: string) =>
125 `projects/${project}/locations/${location}/odbNetworks/${odbNetworkId}`;
126
127 const toAttrs = (network: oracle.OdbNetwork, project: string) => {
128 const name = network.name ?? "";
129 const parsed = parseName(name, "odbNetworks");
130 return {
131 name,
132 odbNetworkId: parsed.id,
133 project: parsed.project || project,
134 location: parsed.location,
135 network: network.network,
136 gcpOracleZone: network.gcpOracleZone,
137 labels: userLabels(network.labels),
138 state: network.state,
139 entitlementId: network.entitlementId,
140 createTime: network.createTime,
141 };
142 };
143
144 const getByName = (name: string) =>
145 name.length === 0
146 ? Effect.undefined
147 : oracle
148 .getProjectsLocationsOdbNetworks({ name })
149 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
150
151 const listOwned = (project: string, region: string) =>
152 listAtLocation(project, region, (parent) =>
153 oracle.listProjectsLocationsOdbNetworks.pages({ parent, pageSize: 1000 }).pipe(
154 Stream.flatMap((page) => Stream.fromIterable(page.odbNetworks ?? [])),
155 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
156 Stream.runCollect,
157 Effect.map((chunk) => Array.from(chunk)),
158 Effect.catchTag("NotFound", () => Effect.succeed([])),
159 ),
160 );
161
162 export const OdbNetworkProvider = () =>
163 Provider.succeed(OdbNetwork, {
164 stables: [
165 "name",
166 "odbNetworkId",
167 "project",
168 "location",
169 "network",
170 "gcpOracleZone",
171 "entitlementId",
172 "createTime",
173 ],
174
175 diff: Effect.fn(function* ({ news, olds, output }) {
176 if (!isResolved(news)) return undefined;
177 const env = yield* GcpEnvironment.current;
178 const previousNetwork = lastSegment(olds?.network ?? output?.network ?? DEFAULT_NETWORK);
179 const nextNetwork = lastSegment(
180 news.network ?? olds?.network ?? output?.network ?? DEFAULT_NETWORK,
181 );
182 const previousZone = olds?.gcpOracleZone ?? output?.gcpOracleZone ?? "";
183 const nextZone = news.gcpOracleZone ?? previousZone;
184 return replaceOnIdentity({
185 previousId: olds?.odbNetworkId ?? output?.odbNetworkId,
186 nextId: news.odbNetworkId ?? olds?.odbNetworkId ?? output?.odbNetworkId,
187 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
188 nextLocation: normalizeLocation(
189 news.location ?? olds?.location ?? output?.location ?? env.region,
190 ),
191 extra: previousNetwork !== nextNetwork || previousZone !== nextZone,
192 });
193 }),
194
195 read: Effect.fn(function* ({ id, olds, output }) {
196 const env = yield* GcpEnvironment.current;
197 const odbNetworkId = yield* toPhysicalId(
198 id,
199 olds?.odbNetworkId,
200 output?.odbNetworkId,
201 "odbnetwork",
202 );
203 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
204 const name = output?.name ?? resourceName(env.project, location, odbNetworkId);
205 const existing = yield* getByName(name);
206 if (existing === undefined) return undefined;
207 const attrs = toAttrs(existing, env.project);
208 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
209 }),
210
211 list: () =>
212 Effect.gen(function* () {
213 const env = yield* GcpEnvironment.current;
214 const items = yield* listOwned(env.project, env.region);
215 return items.map((item) => toAttrs(item, env.project));
216 }),
217
218 reconcile: Effect.fn(function* ({ id, news, output }) {
219 const env = yield* GcpEnvironment.current;
220 const odbNetworkId = yield* toPhysicalId(
221 id,
222 news.odbNetworkId,
223 output?.odbNetworkId,
224 "odbnetwork",
225 );
226 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
227 const name = resourceName(env.project, location, odbNetworkId);
228 const network = networkName(env.project, news.network);
229 const desiredLabels = {
230 ...toLabels(news.labels),
231 ...(yield* createInternalLabels(id)),
232 };
233
234 let current = yield* getByName(output?.name ?? name);
235
236 if (current === undefined) {
237 const created = yield* oracle
238 .createProjectsLocationsOdbNetworks({
239 parent: parentOf(env.project, location),
240 odbNetworkId,
241 body: {
242 network,
243 gcpOracleZone: news.gcpOracleZone,
244 labels: desiredLabels,
245 },
246 })
247 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
248 if (created !== undefined) {
249 yield* waitForOperation(created);
250 }
251 current = yield* waitUntilExists(getByName(name), name);
252 }
253
254 if (current === undefined) {
255 return yield* new ResourceNotResolved({ resourceName: name });
256 }
257
258 const ready = yield* waitUntilReady(
259 getByName(current.name ?? name),
260 current.name ?? name,
261 (item) => item.state,
262 );
263
264 return toAttrs(ready, env.project);
265 }),
266
267 delete: Effect.fn(function* ({ output }) {
268 const operation = yield* oracle
269 .deleteProjectsLocationsOdbNetworks({ name: output.name })
270 .pipe(
271 Effect.retry({
272 while: (error) => error._tag === "Conflict",
273 times: 8,
274 schedule: Schedule.spaced("5 seconds"),
275 }),
276 Effect.catchTag("NotFound", () => Effect.undefined),
277 );
278 if (operation !== undefined) {
279 yield* waitForOperation(operation, { notFoundOk: true });
280 }
281 yield* waitUntilGone(getByName(output.name), output.name);
282 }),
283 });