@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, 06:00 UTC

main
ts 297 lines 10.5 KB
Raw
1 import * as ds from "@distilled.cloud/gcp/datastream_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 { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 collectPages,
14 fingerprint,
15 hasAlchemyLabelMap,
16 normalizeLocation,
17 parseName,
18 privateConnectionOf,
19 replaceOnIdentity,
20 ResourceNotResolved,
21 settleOperation,
22 toPhysicalId,
23 userLabels,
24 waitUntilExists,
25 waitUntilGone,
26 } from "./internal.ts";
27 import { listPrivateConnections } from "./PrivateConnection.ts";
28
29 export type PrivateConnectionsRouteProps = {
30 /**
31 * Parent private connection. Full name
32 * `projects/{project}/locations/{location}/privateConnections/{privateConnection}`
33 * or the connection id (combined with `location`). Immutable —
34 * changing it replaces the route.
35 */
36 privateConnection: string;
37 /**
38 * Region used when `privateConnection` is a bare id.
39 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
40 */
41 location?: string;
42 /**
43 * Route id (the `{route}` segment of
44 * `{privateConnection}/routes/{route}`). If omitted, a unique RFC1035
45 * name is generated. Immutable — changing it replaces the route.
46 */
47 routeId?: string;
48 /**
49 * User-friendly display name. The API has no patch method — changing
50 * display name replaces the route.
51 */
52 displayName?: string;
53 /**
54 * User labels. Alchemy ownership labels are merged in automatically.
55 * The API has no patch method — changing labels replaces the route.
56 */
57 labels?: Record<string, string>;
58 /**
59 * Destination address for the route (hostname or IP). Immutable —
60 * changing it replaces the route.
61 */
62 destinationAddress: string;
63 /**
64 * Destination port for the route. Immutable — changing it replaces
65 * the route.
66 */
67 destinationPort?: number;
68 };
69
70 export type PrivateConnectionsRoute = Resource<
71 "GCP.Datastream.PrivateConnectionsRoute",
72 PrivateConnectionsRouteProps,
73 {
74 /** Full resource name. */
75 name: string;
76 /** Route id (last path segment). */
77 routeId: string;
78 /** Parent private connection resource name. */
79 privateConnection: string;
80 /** Project id. */
81 project: string;
82 /** Location id. */
83 location: string;
84 /** User-friendly display name. */
85 displayName: string | undefined;
86 /** User labels (Alchemy ownership labels stripped). */
87 labels: Record<string, string>;
88 /** Destination address. */
89 destinationAddress: string | undefined;
90 /** Destination port. */
91 destinationPort: number | undefined;
92 /** RFC3339 creation timestamp. */
93 createTime: string | undefined;
94 /** RFC3339 last-update timestamp. */
95 updateTime: string | undefined;
96 },
97 never,
98 Providers
99 >;
100
101 /**
102 * A Datastream route attached to a private connection. Routes advertise
103 * a destination address (and optional port) through the private
104 * connection's VPC peering or PSC interface.
105 *
106 * The API has no patch method. `routeId`, parent private connection,
107 * destination address/port, display name, and labels are replacement
108 * triggers.
109 *
110 * ### Creating a Route
111 * **Example:** Advertise a database host
112 * ```typescript
113 * const peering = yield* GCP.Datastream.PrivateConnection("DsPeer", {
114 * vpcPeeringConfig: {
115 * vpc: network.networkName,
116 * subnet: "10.9.0.0/29",
117 * },
118 * });
119 * const route = yield* GCP.Datastream.PrivateConnectionsRoute("DbHost", {
120 * privateConnection: peering.name,
121 * destinationAddress: "10.0.0.8",
122 * destinationPort: 3306,
123 * labels: { env: "test" },
124 * });
125 * ```
126 *
127 * @resource
128 * @category Datastream
129 */
130 export const PrivateConnectionsRoute = Resource<PrivateConnectionsRoute>(
131 "GCP.Datastream.PrivateConnectionsRoute",
132 );
133
134 const resourceName = (privateConnection: string, routeId: string) =>
135 `${privateConnection}/routes/${routeId}`;
136
137 const toAttrs = (item: ds.Route, project: string, region: string) => {
138 const name = item.name ?? "";
139 const parsed = parseName(name, "routes", region);
140 return {
141 name,
142 routeId: parsed.id,
143 privateConnection: parsed.parent,
144 project: parsed.project || project,
145 location: parsed.location,
146 displayName: item.displayName,
147 labels: userLabels(item.labels),
148 destinationAddress: item.destinationAddress,
149 destinationPort: item.destinationPort,
150 createTime: item.createTime,
151 updateTime: item.updateTime,
152 };
153 };
154
155 const getByName = (name: string) =>
156 name.length === 0
157 ? Effect.undefined
158 : ds
159 .getProjectsLocationsPrivateConnectionsRoutes({ name })
160 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
161
162 const listRoutes = (parent: string) =>
163 collectPages(
164 ds.listProjectsLocationsPrivateConnectionsRoutes.pages({
165 parent,
166 pageSize: 1000,
167 }),
168 (page) => page.routes,
169 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as ds.Route[])));
170
171 const listOwned = (project: string, region: string) =>
172 Effect.gen(function* () {
173 const connections = yield* listPrivateConnections(project, region);
174 const pages = yield* Effect.forEach(
175 connections.filter((item) => (item.name ?? "").length > 0),
176 (item) => listRoutes(item.name!),
177 { concurrency: 4 },
178 );
179 return pages.flat().filter((route) => hasAlchemyLabelMap(route.labels));
180 });
181
182 export const PrivateConnectionsRouteProvider = () =>
183 Provider.succeed(PrivateConnectionsRoute, {
184 stables: ["name", "routeId", "privateConnection", "project", "location"],
185
186 diff: Effect.fn(function* ({ news, olds, output }) {
187 if (!isResolved(news)) return undefined;
188 const env = yield* GcpEnvironment.current;
189 const previousAddress = olds?.destinationAddress ?? output?.destinationAddress;
190 const nextAddress = news.destinationAddress ?? previousAddress;
191 const previousPort = olds?.destinationPort ?? output?.destinationPort;
192 const nextPort = news.destinationPort ?? previousPort;
193 const previousDisplay = olds?.displayName ?? output?.displayName;
194 const nextDisplay = news.displayName ?? previousDisplay;
195 const previousLabels = fingerprint(olds?.labels ?? output?.labels);
196 const nextLabels = fingerprint(news.labels ?? olds?.labels ?? output?.labels);
197 const previousParent = olds?.privateConnection ?? output?.privateConnection;
198 const nextParent = news.privateConnection ?? previousParent;
199 return replaceOnIdentity({
200 previousId: olds?.routeId ?? output?.routeId,
201 nextId: news.routeId ?? olds?.routeId ?? output?.routeId,
202 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
203 nextLocation: normalizeLocation(
204 news.location ?? olds?.location ?? output?.location,
205 env.region,
206 ),
207 previousParent,
208 nextParent,
209 extra:
210 (olds !== undefined || output !== undefined) &&
211 (previousAddress !== nextAddress ||
212 previousPort !== nextPort ||
213 previousDisplay !== nextDisplay ||
214 previousLabels !== nextLabels),
215 });
216 }),
217
218 read: Effect.fn(function* ({ id, olds, output }) {
219 const env = yield* GcpEnvironment.current;
220 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
221 const parentId = olds?.privateConnection ?? output?.privateConnection;
222 // Recovering an interrupted create whose parent never resolved: no
223 // route can exist without its private connection.
224 if (typeof parentId !== "string" || parentId.length === 0) {
225 return undefined;
226 }
227 const parent = privateConnectionOf(parentId, env.project, location);
228 const routeId = yield* toPhysicalId(id, olds?.routeId, output?.routeId, "route");
229 const name = output?.name ?? resourceName(parent, routeId);
230 const existing = yield* getByName(name);
231 if (existing === undefined) return undefined;
232 const attrs = toAttrs(existing, env.project, env.region);
233 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
234 }),
235
236 list: () =>
237 Effect.gen(function* () {
238 const env = yield* GcpEnvironment.current;
239 const items = yield* listOwned(env.project, env.region);
240 return items.map((item) => toAttrs(item, env.project, env.region));
241 }),
242
243 reconcile: Effect.fn(function* ({ id, news, output }) {
244 const env = yield* GcpEnvironment.current;
245 const location = normalizeLocation(news.location ?? output?.location, env.region);
246 const parent = privateConnectionOf(news.privateConnection, env.project, location);
247 const routeId = yield* toPhysicalId(id, news.routeId, output?.routeId, "route");
248 const name = resourceName(parent, routeId);
249 const desiredLabels = {
250 ...toLabels(news.labels),
251 ...(yield* createInternalLabels(id)),
252 };
253 const displayName = news.displayName ?? routeId;
254
255 let current = yield* getByName(output?.name ?? name);
256
257 if (current === undefined) {
258 const created = yield* ds
259 .createProjectsLocationsPrivateConnectionsRoutes({
260 parent,
261 routeId,
262 body: {
263 displayName,
264 labels: desiredLabels,
265 destinationAddress: news.destinationAddress,
266 destinationPort: news.destinationPort,
267 },
268 })
269 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
270 yield* settleOperation(created);
271 current = yield* waitUntilExists(getByName(name), name);
272 }
273
274 if (current === undefined) {
275 return yield* new ResourceNotResolved({ resourceName: name });
276 }
277
278 return toAttrs(current, env.project, env.region);
279 }),
280
281 delete: Effect.fn(function* ({ output }) {
282 const operation = yield* ds
283 .deleteProjectsLocationsPrivateConnectionsRoutes({
284 name: output.name,
285 })
286 .pipe(
287 Effect.retry({
288 while: (error) => error._tag === "Conflict",
289 times: 8,
290 schedule: Schedule.spaced("2 seconds"),
291 }),
292 Effect.catchTag("NotFound", () => Effect.undefined),
293 );
294 yield* settleOperation(operation, { notFoundOk: true });
295 yield* waitUntilGone(getByName(output.name), output.name);
296 }),
297 });