@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 351 lines 12.5 KB
Raw
1 import * as dm from "@distilled.cloud/gcp/datamigration_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 fingerprint,
15 hasAlchemyLabelMap,
16 locationParent,
17 networkOf,
18 normalizeLocation,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 toPhysicalId,
23 userLabels,
24 waitForOperation,
25 waitUntilExists,
26 waitUntilGone,
27 } from "./internal.ts";
28
29 export type PrivateConnectionState = dm.PrivateConnectionStateEnum | (string & {});
30 export type VpcPeeringConfig = dm.VpcPeeringConfig;
31 export type PscInterfaceConfig = dm.PscInterfaceConfig;
32 type Status = dm.Status;
33
34 export type PrivateConnectionProps = {
35 /**
36 * Private connection id (the `{privateConnection}` segment of
37 * `projects/{project}/locations/{location}/privateConnections/{privateConnection}`).
38 * If omitted, a unique RFC1035 name is generated. Immutable — changing
39 * it replaces the connection.
40 */
41 privateConnectionId?: string;
42 /**
43 * Region (`us-central1`, …). Immutable — changing it replaces the
44 * connection. `US-CENTRAL1` is accepted and normalized to `us-central1`.
45 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
46 */
47 location?: string;
48 /**
49 * User-friendly display name. The API has no patch method — changing
50 * display name replaces the connection.
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
56 * connection.
57 */
58 labels?: Record<string, string>;
59 /**
60 * VPC peering configuration. Mutually exclusive with
61 * `pscInterfaceConfig`. Immutable — changing it replaces the
62 * connection. `vpcName` may be a full resource name or a bare network
63 * id.
64 */
65 vpcPeeringConfig?: {
66 vpcName: string;
67 subnet: string;
68 };
69 /**
70 * PSC interface configuration. Mutually exclusive with
71 * `vpcPeeringConfig`. Immutable — changing it replaces the connection.
72 */
73 pscInterfaceConfig?: PscInterfaceConfig;
74 /**
75 * Skip validations on create.
76 */
77 skipValidation?: boolean;
78 /**
79 * PSC interface only: resolve the tenant project without creating.
80 */
81 validateOnly?: boolean;
82 };
83
84 export type PrivateConnection = Resource<
85 "GCP.DataMigration.PrivateConnection",
86 PrivateConnectionProps,
87 {
88 /** Full resource name. */
89 name: string;
90 /** Private connection id (last path segment). */
91 privateConnectionId: string;
92 /** Project id. */
93 project: string;
94 /** Location id. */
95 location: string;
96 /** User-friendly display name. */
97 displayName: string | undefined;
98 /** User labels (Alchemy ownership labels stripped). */
99 labels: Record<string, string>;
100 /** VPC peering configuration. */
101 vpcPeeringConfig: VpcPeeringConfig | undefined;
102 /** PSC interface configuration. */
103 pscInterfaceConfig: PscInterfaceConfig | undefined;
104 /** Server-reported state. */
105 state: string | undefined;
106 /** Failure details when `state` is `FAILED`. */
107 error: Status | undefined;
108 /** RFC3339 creation timestamp. */
109 createTime: string | undefined;
110 /** RFC3339 last-update timestamp. */
111 updateTime: string | undefined;
112 },
113 never,
114 Providers
115 >;
116
117 /**
118 * A Database Migration Service private connection: VPC peering or a PSC
119 * interface between DMS and a consumer network.
120 *
121 * The API has no patch method. `privateConnectionId`, `location`,
122 * `vpcPeeringConfig`, `pscInterfaceConfig`, display name, and labels are
123 * replacement triggers.
124 *
125 * ### Creating a Private Connection
126 * **Example:** VPC peering
127 * ```typescript
128 * const network = yield* GCP.Compute.Network("DmsVpc", {
129 * autoCreateSubnetworks: false,
130 * });
131 * const peering = yield* GCP.DataMigration.PrivateConnection("DmsPeer", {
132 * displayName: "dms-peer",
133 * vpcPeeringConfig: {
134 * vpcName: network.selfLink ?? network.networkName,
135 * subnet: "10.8.0.0/29",
136 * },
137 * labels: { env: "test" },
138 * });
139 * ```
140 *
141 * @resource
142 * @category DataMigration
143 */
144 export const PrivateConnection = Resource<PrivateConnection>("GCP.DataMigration.PrivateConnection");
145
146 const resourceName = (project: string, location: string, privateConnectionId: string) =>
147 `${locationParent(project, location)}/privateConnections/${privateConnectionId}`;
148
149 const peeringOf = (
150 value: PrivateConnectionProps["vpcPeeringConfig"] | VpcPeeringConfig | undefined,
151 project: string,
152 ) =>
153 value?.vpcName === undefined && value?.subnet === undefined
154 ? undefined
155 : {
156 vpcName: value?.vpcName ? networkOf(value.vpcName, project) : undefined,
157 subnet: value?.subnet,
158 };
159
160 const kindOf = (value: { vpcPeeringConfig?: unknown; pscInterfaceConfig?: unknown }) =>
161 value.vpcPeeringConfig ? "vpc" : value.pscInterfaceConfig ? "psc" : "";
162
163 const toAttrs = (item: dm.PrivateConnection, project: string) => {
164 const name = item.name ?? "";
165 const parsed = parseName(name, "privateConnections");
166 return {
167 name,
168 privateConnectionId: parsed.id,
169 project: parsed.project || project,
170 location: parsed.location,
171 displayName: item.displayName,
172 labels: userLabels(item.labels),
173 vpcPeeringConfig: item.vpcPeeringConfig,
174 pscInterfaceConfig: item.pscInterfaceConfig,
175 state: item.state,
176 error: item.error,
177 createTime: item.createTime,
178 updateTime: item.updateTime,
179 };
180 };
181
182 const getByName = (name: string) =>
183 name.length === 0
184 ? Effect.undefined
185 : dm
186 .getProjectsLocationsPrivateConnections({ name })
187 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
188
189 const listOwned = (project: string, region: string) =>
190 dm.listProjectsLocationsPrivateConnections
191 .pages({
192 parent: `projects/${project}/locations/-`,
193 pageSize: 1000,
194 })
195 .pipe(
196 Stream.flatMap((page) => Stream.fromIterable(page.privateConnections ?? [])),
197 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
198 Stream.runCollect,
199 Effect.map((chunk) => Array.from(chunk)),
200 Effect.catchTag("NotFound", () =>
201 dm.listProjectsLocationsPrivateConnections
202 .pages({
203 parent: locationParent(project, region),
204 pageSize: 1000,
205 })
206 .pipe(
207 Stream.flatMap((page) => Stream.fromIterable(page.privateConnections ?? [])),
208 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
209 Stream.runCollect,
210 Effect.map((chunk) => Array.from(chunk)),
211 Effect.catchTag("NotFound", () => Effect.succeed([] as dm.PrivateConnection[])),
212 ),
213 ),
214 );
215
216 export const PrivateConnectionProvider = () =>
217 Provider.succeed(PrivateConnection, {
218 stables: ["name", "privateConnectionId", "project", "location", "createTime"],
219
220 diff: Effect.fn(function* ({ news, olds, output }) {
221 if (!isResolved(news)) return undefined;
222 const env = yield* GcpEnvironment.current;
223 const previousKind = kindOf({
224 vpcPeeringConfig: olds?.vpcPeeringConfig ?? output?.vpcPeeringConfig,
225 pscInterfaceConfig: olds?.pscInterfaceConfig ?? output?.pscInterfaceConfig,
226 });
227 const nextKind = kindOf(news) || previousKind;
228 const previousPeering = fingerprint(olds?.vpcPeeringConfig ?? output?.vpcPeeringConfig);
229 const nextPeering = fingerprint(news.vpcPeeringConfig);
230 const previousPsc = fingerprint(olds?.pscInterfaceConfig ?? output?.pscInterfaceConfig);
231 const nextPsc = fingerprint(news.pscInterfaceConfig);
232 const previousDisplay = olds?.displayName ?? output?.displayName;
233 const nextDisplay = news.displayName ?? previousDisplay;
234 const previousLabels = fingerprint(olds?.labels ?? output?.labels);
235 const nextLabels = fingerprint(news.labels ?? olds?.labels ?? output?.labels);
236 return replaceOnIdentity({
237 previousId: olds?.privateConnectionId ?? output?.privateConnectionId,
238 nextId:
239 news.privateConnectionId ?? olds?.privateConnectionId ?? output?.privateConnectionId,
240 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
241 nextLocation: normalizeLocation(
242 news.location ?? olds?.location ?? output?.location,
243 env.region,
244 ),
245 extra:
246 (olds !== undefined || output !== undefined) &&
247 (previousKind !== nextKind ||
248 (news.vpcPeeringConfig !== undefined && previousPeering !== nextPeering) ||
249 (news.pscInterfaceConfig !== undefined && previousPsc !== nextPsc) ||
250 previousDisplay !== nextDisplay ||
251 previousLabels !== nextLabels),
252 });
253 }),
254
255 read: Effect.fn(function* ({ id, olds, output }) {
256 const env = yield* GcpEnvironment.current;
257 const privateConnectionId = yield* toPhysicalId(
258 id,
259 olds?.privateConnectionId,
260 output?.privateConnectionId,
261 "pconn",
262 );
263 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
264 const name = output?.name ?? resourceName(env.project, location, privateConnectionId);
265 const existing = yield* getByName(name);
266 if (existing === undefined) return undefined;
267 const attrs = toAttrs(existing, env.project);
268 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
269 }),
270
271 list: () =>
272 Effect.gen(function* () {
273 const env = yield* GcpEnvironment.current;
274 const items = yield* listOwned(env.project, env.region);
275 return items.map((item) => toAttrs(item, env.project));
276 }),
277
278 reconcile: Effect.fn(function* ({ id, news, output }) {
279 const env = yield* GcpEnvironment.current;
280 const privateConnectionId = yield* toPhysicalId(
281 id,
282 news.privateConnectionId,
283 output?.privateConnectionId,
284 "pconn",
285 );
286 const location = normalizeLocation(news.location ?? output?.location, env.region);
287 const name = resourceName(env.project, location, privateConnectionId);
288 const desiredLabels = {
289 ...toLabels(news.labels),
290 ...(yield* createInternalLabels(id)),
291 };
292 const displayName = news.displayName ?? privateConnectionId;
293 const vpcPeeringConfig = peeringOf(news.vpcPeeringConfig, env.project);
294
295 let current = yield* getByName(output?.name ?? name);
296
297 if (current === undefined) {
298 const created = yield* dm
299 .createProjectsLocationsPrivateConnections({
300 parent: locationParent(env.project, location),
301 privateConnectionId,
302 skipValidation: news.skipValidation,
303 validateOnly: news.validateOnly,
304 body: {
305 displayName,
306 labels: desiredLabels,
307 vpcPeeringConfig,
308 pscInterfaceConfig: news.pscInterfaceConfig,
309 },
310 })
311 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
312 if (created !== undefined) {
313 yield* waitForOperation(created);
314 }
315 current = yield* waitUntilExists(getByName(name), name);
316 }
317
318 if (current === undefined) {
319 return yield* new ResourceNotResolved({ resourceName: name });
320 }
321
322 return toAttrs(current, env.project);
323 }),
324
325 delete: Effect.fn(function* ({ output }) {
326 yield* Effect.gen(function* () {
327 const operation = yield* dm
328 .deleteProjectsLocationsPrivateConnections({ name: output.name })
329 .pipe(
330 Effect.retry({
331 while: (error) => error._tag === "Conflict",
332 times: 8,
333 schedule: Schedule.spaced("2 seconds"),
334 }),
335 Effect.catchTag("NotFound", () => Effect.undefined),
336 );
337 if (operation !== undefined) {
338 yield* waitForOperation(operation, { notFoundOk: true });
339 }
340 }).pipe(
341 // Tearing down the VPC peering occasionally ends with a server-side
342 // DEADLINE_EXCEEDED ("Operation timed out."); a fresh delete succeeds.
343 Effect.retry({
344 while: (error) => error._tag === "GCP.OperationFailed" && error.code === 4,
345 times: 5,
346 schedule: Schedule.spaced("10 seconds"),
347 }),
348 );
349 yield* waitUntilGone(getByName(output.name), output.name);
350 }),
351 });