@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 327 lines 11 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 expandParent,
15 hasAlchemyLabelMap,
16 listAtLocation,
17 normalizeLocation,
18 parseName,
19 replaceOnIdentity,
20 ResourceNotResolved,
21 toPhysicalId,
22 userLabels,
23 waitForOperation,
24 waitUntilExists,
25 waitUntilGone,
26 waitUntilReady,
27 } from "./internal.ts";
28
29 const DEFAULT_PURPOSE = "CLIENT_SUBNET" satisfies oracle.OdbSubnetPurposeEnum;
30
31 export type OdbNetworksOdbSubnetProps = {
32 /**
33 * Parent ODB Network. Full name
34 * `projects/{project}/locations/{location}/odbNetworks/{odb_network}`
35 * or the network id (combined with `location`). Immutable — changing
36 * it replaces the subnet.
37 */
38 odbNetwork: string;
39 /**
40 * Region used when `odbNetwork` is a bare id.
41 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
42 */
43 location?: string;
44 /**
45 * ODB Subnet id (the `{odb_subnet}` segment of
46 * `.../odbNetworks/{odb_network}/odbSubnets/{odb_subnet}`). If omitted,
47 * a unique RFC1035 name is generated. Immutable — changing it
48 * replaces the subnet.
49 */
50 odbSubnetId?: string;
51 /**
52 * CIDR range of the subnet. Must be RFC1918 and between `/27` and
53 * `/22`. Immutable — changing it replaces the subnet.
54 */
55 cidrRange: string;
56 /**
57 * Subnet purpose. `CLIENT_SUBNET` is used by databases and GoldenGate;
58 * `BACKUP_SUBNET` is used by Exadata VM Clusters. Immutable —
59 * changing it replaces the subnet.
60 * @default "CLIENT_SUBNET"
61 */
62 purpose?: oracle.OdbSubnetPurposeEnum | (string & {});
63 /**
64 * User labels. Alchemy ownership labels are merged in automatically.
65 */
66 labels?: Record<string, string>;
67 };
68
69 export type OdbNetworksOdbSubnet = Resource<
70 "GCP.OracleDatabase.OdbNetworksOdbSubnet",
71 OdbNetworksOdbSubnetProps,
72 {
73 /** Full resource name. */
74 name: string;
75 /** ODB Subnet id (last path segment). */
76 odbSubnetId: string;
77 /** Parent ODB Network resource name. */
78 odbNetwork: string;
79 /** Project id. */
80 project: string;
81 /** Location id. */
82 location: string;
83 /** CIDR range. */
84 cidrRange: string | undefined;
85 /** Subnet purpose. */
86 purpose: string | undefined;
87 /** User labels (Alchemy ownership labels stripped). */
88 labels: Record<string, string>;
89 /** Server-reported state. */
90 state: string | undefined;
91 /** RFC3339 creation timestamp. */
92 createTime: string | undefined;
93 },
94 never,
95 Providers
96 >;
97
98 /**
99 * An Oracle Database@Google Cloud ODB Subnet inside an ODB Network.
100 *
101 * Changing `odbNetwork`, `odbSubnetId`, `location`, `cidrRange`, or
102 * `purpose` replaces the subnet. Labels are set at create; the API has
103 * no update. Requires an Oracle Database@Google Cloud entitlement and
104 * a parent ODB Network.
105 *
106 * ### Creating an ODB Subnet
107 * **Example:** Client subnet under an ODB Network
108 * ```typescript
109 * const subnet = yield* GCP.OracleDatabase.OdbNetworksOdbSubnet("Client", {
110 * odbNetwork: net.name,
111 * cidrRange: "10.250.0.0/27",
112 * purpose: "CLIENT_SUBNET",
113 * });
114 * ```
115 *
116 * **Example:** Backup subnet with labels
117 * ```typescript
118 * const subnet = yield* GCP.OracleDatabase.OdbNetworksOdbSubnet("Backup", {
119 * odbNetwork: net.name,
120 * cidrRange: "10.250.0.32/27",
121 * purpose: "BACKUP_SUBNET",
122 * labels: { env: "prod" },
123 * });
124 * ```
125 *
126 * @resource
127 * @category OracleDatabase
128 */
129 export const OdbNetworksOdbSubnet = Resource<OdbNetworksOdbSubnet>(
130 "GCP.OracleDatabase.OdbNetworksOdbSubnet",
131 );
132
133 const desiredPurpose = (purpose: string | undefined) => (purpose ?? DEFAULT_PURPOSE).toUpperCase();
134
135 const networkOf = (odbNetwork: string, project: string, location: string) =>
136 expandParent(odbNetwork, project, location, "odbNetworks");
137
138 const resourceName = (odbNetwork: string, odbSubnetId: string) =>
139 `${odbNetwork}/odbSubnets/${odbSubnetId}`;
140
141 const toAttrs = (subnet: oracle.OdbSubnet, project: string) => {
142 const name = subnet.name ?? "";
143 const parsed = parseName(name, "odbSubnets");
144 return {
145 name,
146 odbSubnetId: parsed.id,
147 odbNetwork: parsed.parent,
148 project: parsed.project || project,
149 location: parsed.location,
150 cidrRange: subnet.cidrRange,
151 purpose: subnet.purpose,
152 labels: userLabels(subnet.labels),
153 state: subnet.state,
154 createTime: subnet.createTime,
155 };
156 };
157
158 const getByName = (name: string) =>
159 name.length === 0 || name.includes("//")
160 ? Effect.undefined
161 : oracle
162 .getProjectsLocationsOdbNetworksOdbSubnets({ name })
163 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
164
165 const listSubnets = (parent: string) =>
166 oracle.listProjectsLocationsOdbNetworksOdbSubnets.pages({ parent, pageSize: 1000 }).pipe(
167 Stream.flatMap((page) => Stream.fromIterable(page.odbSubnets ?? [])),
168 Stream.runCollect,
169 Effect.map((chunk) => Array.from(chunk)),
170 Effect.catchTag("NotFound", () => Effect.succeed([] as oracle.OdbSubnet[])),
171 );
172
173 const listOwned = (project: string, region: string) =>
174 Effect.gen(function* () {
175 const wildcard = yield* listSubnets(`projects/${project}/locations/-/odbNetworks/-`);
176 const labeledWildcard = wildcard.filter((item) => hasAlchemyLabelMap(item.labels));
177 if (labeledWildcard.length > 0) return labeledWildcard;
178
179 const networks = yield* listAtLocation(project, region, (parent) =>
180 oracle.listProjectsLocationsOdbNetworks.pages({ parent, pageSize: 1000 }).pipe(
181 Stream.flatMap((page) => Stream.fromIterable(page.odbNetworks ?? [])),
182 Stream.runCollect,
183 Effect.map((chunk) => Array.from(chunk)),
184 Effect.catchTag("NotFound", () => Effect.succeed([])),
185 ),
186 );
187 const nested = yield* Effect.forEach(
188 networks,
189 (network) =>
190 network.name ? listSubnets(network.name) : Effect.succeed([] as oracle.OdbSubnet[]),
191 { concurrency: 4 },
192 );
193 return nested.flat().filter((item) => hasAlchemyLabelMap(item.labels));
194 });
195
196 export const OdbNetworksOdbSubnetProvider = () =>
197 Provider.succeed(OdbNetworksOdbSubnet, {
198 stables: [
199 "name",
200 "odbSubnetId",
201 "odbNetwork",
202 "project",
203 "location",
204 "cidrRange",
205 "purpose",
206 "createTime",
207 ],
208
209 diff: Effect.fn(function* ({ news, olds, output }) {
210 if (!isResolved(news)) return undefined;
211 const env = yield* GcpEnvironment.current;
212 const previousPurpose = desiredPurpose(olds?.purpose ?? output?.purpose);
213 const nextPurpose = desiredPurpose(news.purpose ?? previousPurpose);
214 const previousCidr = olds?.cidrRange ?? output?.cidrRange ?? "";
215 const nextCidr = news.cidrRange ?? previousCidr;
216 return replaceOnIdentity({
217 previousId: olds?.odbSubnetId ?? output?.odbSubnetId,
218 nextId: news.odbSubnetId ?? olds?.odbSubnetId ?? output?.odbSubnetId,
219 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
220 nextLocation: normalizeLocation(
221 news.location ?? olds?.location ?? output?.location ?? env.region,
222 ),
223 previousParent: olds?.odbNetwork ?? output?.odbNetwork,
224 nextParent: news.odbNetwork ?? olds?.odbNetwork ?? output?.odbNetwork,
225 extra: previousPurpose !== nextPurpose || previousCidr !== nextCidr,
226 });
227 }),
228
229 read: Effect.fn(function* ({ id, olds, output }) {
230 const env = yield* GcpEnvironment.current;
231 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
232 const odbNetwork = networkOf(
233 olds?.odbNetwork ?? output?.odbNetwork ?? "",
234 env.project,
235 location,
236 );
237 const odbSubnetId = yield* toPhysicalId(
238 id,
239 olds?.odbSubnetId,
240 output?.odbSubnetId,
241 "odbsubnet",
242 );
243 const name = output?.name ?? resourceName(odbNetwork, odbSubnetId);
244 const existing = yield* getByName(name);
245 if (existing === undefined) return undefined;
246 const attrs = toAttrs(existing, env.project);
247 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
248 }),
249
250 list: () =>
251 Effect.gen(function* () {
252 const env = yield* GcpEnvironment.current;
253 const items = yield* listOwned(env.project, env.region);
254 return items.map((item) => toAttrs(item, env.project));
255 }),
256
257 reconcile: Effect.fn(function* ({ id, news, output }) {
258 const env = yield* GcpEnvironment.current;
259 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
260 const odbNetwork = networkOf(news.odbNetwork, env.project, location);
261 const odbSubnetId = yield* toPhysicalId(
262 id,
263 news.odbSubnetId,
264 output?.odbSubnetId,
265 "odbsubnet",
266 );
267 const name = resourceName(odbNetwork, odbSubnetId);
268 const purpose = desiredPurpose(news.purpose);
269 const desiredLabels = {
270 ...toLabels(news.labels),
271 ...(yield* createInternalLabels(id)),
272 };
273
274 let current = yield* getByName(output?.name ?? name);
275
276 if (current === undefined) {
277 const created = yield* oracle
278 .createProjectsLocationsOdbNetworksOdbSubnets({
279 parent: odbNetwork,
280 odbSubnetId,
281 body: {
282 cidrRange: news.cidrRange,
283 purpose,
284 labels: desiredLabels,
285 },
286 })
287 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
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 ResourceNotResolved({ resourceName: name });
296 }
297
298 const ready = yield* waitUntilReady(
299 getByName(current.name ?? name),
300 current.name ?? name,
301 (item) => item.state,
302 );
303
304 return toAttrs(ready, env.project);
305 }),
306
307 delete: Effect.fn(function* ({ output }) {
308 if (!output.name || output.name.includes("//")) return;
309 const operation = yield* oracle
310 .deleteProjectsLocationsOdbNetworksOdbSubnets({ name: output.name })
311 .pipe(
312 Effect.retry({
313 while: (error) => error._tag === "Conflict",
314 times: 8,
315 schedule: Schedule.spaced("5 seconds"),
316 }),
317 Effect.catchTags({
318 NotFound: () => Effect.undefined,
319 BadRequest: () => Effect.undefined,
320 }),
321 );
322 if (operation !== undefined) {
323 yield* waitForOperation(operation, { notFoundOk: true });
324 }
325 yield* waitUntilGone(getByName(output.name), output.name);
326 }),
327 });