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

main
ts 343 lines 12.1 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 listAtLocation,
17 locationParent,
18 networkOf,
19 normalizeLocation,
20 parseName,
21 replaceOnIdentity,
22 ResourceNotResolved,
23 settleOperation,
24 toPhysicalId,
25 userLabels,
26 waitUntilExists,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type PrivateConnectionState = ds.PrivateConnectionStateEnum | (string & {});
31 export type VpcPeeringConfig = ds.VpcPeeringConfig;
32 export type PscInterfaceConfig = ds.PscInterfaceConfig;
33 type DatastreamError = ds.Datastream_Error;
34
35 export type PrivateConnectionProps = {
36 /**
37 * Private connection id (the `{privateConnection}` segment of
38 * `projects/{project}/locations/{location}/privateConnections/{privateConnection}`).
39 * If omitted, a unique RFC1035 name is generated. Immutable — changing
40 * it replaces the connection.
41 */
42 privateConnectionId?: string;
43 /**
44 * Region (`us-central1`, …). Immutable — changing it replaces the
45 * connection. `US-CENTRAL1` is accepted and normalized to `us-central1`.
46 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
47 */
48 location?: string;
49 /**
50 * User-friendly display name. The API has no patch method — changing
51 * display name replaces the connection.
52 */
53 displayName?: string;
54 /**
55 * User labels. Alchemy ownership labels are merged in automatically.
56 * The API has no patch method — changing labels replaces the
57 * connection.
58 */
59 labels?: Record<string, string>;
60 /**
61 * VPC peering configuration. Mutually exclusive with
62 * `pscInterfaceConfig`. Immutable — changing it replaces the
63 * connection. `vpc` may be a full resource name or a bare network id.
64 */
65 vpcPeeringConfig?: {
66 vpc: 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 force?: 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.Datastream.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: DatastreamError | undefined;
108 /** Whether the connection satisfies physical zone isolation. */
109 satisfiesPzi: boolean | undefined;
110 /** Whether the connection satisfies physical zone separation. */
111 satisfiesPzs: boolean | undefined;
112 /** RFC3339 creation timestamp. */
113 createTime: string | undefined;
114 /** RFC3339 last-update timestamp. */
115 updateTime: string | undefined;
116 },
117 never,
118 Providers
119 >;
120
121 /**
122 * A Datastream private connection: VPC peering or a PSC interface
123 * between Datastream and a consumer network.
124 *
125 * The API has no patch method. `privateConnectionId`, `location`,
126 * `vpcPeeringConfig`, `pscInterfaceConfig`, display name, and labels are
127 * replacement triggers. Delete always force-deletes child routes.
128 *
129 * ### Creating a Private Connection
130 * **Example:** VPC peering
131 * ```typescript
132 * const network = yield* GCP.Compute.Network("DsVpc", {
133 * autoCreateSubnetworks: false,
134 * });
135 * const peering = yield* GCP.Datastream.PrivateConnection("DsPeer", {
136 * displayName: "ds-peer",
137 * vpcPeeringConfig: {
138 * vpc: network.networkName,
139 * subnet: "10.9.0.0/29",
140 * },
141 * labels: { env: "test" },
142 * });
143 * ```
144 *
145 * @resource
146 * @category Datastream
147 */
148 export const PrivateConnection = Resource<PrivateConnection>("GCP.Datastream.PrivateConnection");
149
150 const resourceName = (project: string, location: string, privateConnectionId: string) =>
151 `${locationParent(project, location)}/privateConnections/${privateConnectionId}`;
152
153 const peeringOf = (
154 value: PrivateConnectionProps["vpcPeeringConfig"] | VpcPeeringConfig | undefined,
155 project: string,
156 ) =>
157 value?.vpc === undefined && value?.subnet === undefined
158 ? undefined
159 : {
160 vpc: value?.vpc ? networkOf(value.vpc, project) : undefined,
161 subnet: value?.subnet,
162 };
163
164 const kindOf = (value: { vpcPeeringConfig?: unknown; pscInterfaceConfig?: unknown }) =>
165 value.vpcPeeringConfig ? "vpc" : value.pscInterfaceConfig ? "psc" : "";
166
167 export const toPrivateConnectionAttrs = (
168 item: ds.PrivateConnection,
169 project: string,
170 region: string,
171 ) => {
172 const name = item.name ?? "";
173 const parsed = parseName(name, "privateConnections", region);
174 return {
175 name,
176 privateConnectionId: parsed.id,
177 project: parsed.project || project,
178 location: parsed.location,
179 displayName: item.displayName,
180 labels: userLabels(item.labels),
181 vpcPeeringConfig: item.vpcPeeringConfig,
182 pscInterfaceConfig: item.pscInterfaceConfig,
183 state: item.state,
184 error: item.error,
185 satisfiesPzi: item.satisfiesPzi,
186 satisfiesPzs: item.satisfiesPzs,
187 createTime: item.createTime,
188 updateTime: item.updateTime,
189 };
190 };
191
192 export const getPrivateConnectionByName = (name: string) =>
193 name.length === 0
194 ? Effect.undefined
195 : ds
196 .getProjectsLocationsPrivateConnections({ name })
197 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
198
199 export const listPrivateConnections = (project: string, region: string) =>
200 listAtLocation(project, region, (parent) =>
201 collectPages(
202 ds.listProjectsLocationsPrivateConnections.pages({
203 parent,
204 pageSize: 1000,
205 }),
206 (page) => page.privateConnections,
207 ),
208 );
209
210 const listOwned = (project: string, region: string) =>
211 listPrivateConnections(project, region).pipe(
212 Effect.map((items) => items.filter((item) => hasAlchemyLabelMap(item.labels))),
213 );
214
215 export const PrivateConnectionProvider = () =>
216 Provider.succeed(PrivateConnection, {
217 stables: ["name", "privateConnectionId", "project", "location", "createTime"],
218
219 diff: Effect.fn(function* ({ news, olds, output }) {
220 if (!isResolved(news)) return undefined;
221 const env = yield* GcpEnvironment.current;
222 const previousKind = kindOf({
223 vpcPeeringConfig: olds?.vpcPeeringConfig ?? output?.vpcPeeringConfig,
224 pscInterfaceConfig: olds?.pscInterfaceConfig ?? output?.pscInterfaceConfig,
225 });
226 const nextKind = kindOf(news) || previousKind;
227 const previousPeering = fingerprint(olds?.vpcPeeringConfig ?? output?.vpcPeeringConfig);
228 const nextPeering = fingerprint(news.vpcPeeringConfig);
229 const previousPsc = fingerprint(olds?.pscInterfaceConfig ?? output?.pscInterfaceConfig);
230 const nextPsc = fingerprint(news.pscInterfaceConfig);
231 const previousDisplay = olds?.displayName ?? output?.displayName;
232 const nextDisplay = news.displayName ?? previousDisplay;
233 const previousLabels = fingerprint(olds?.labels ?? output?.labels);
234 const nextLabels = fingerprint(news.labels ?? olds?.labels ?? output?.labels);
235 return replaceOnIdentity({
236 previousId: olds?.privateConnectionId ?? output?.privateConnectionId,
237 nextId:
238 news.privateConnectionId ?? olds?.privateConnectionId ?? output?.privateConnectionId,
239 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
240 nextLocation: normalizeLocation(
241 news.location ?? olds?.location ?? output?.location,
242 env.region,
243 ),
244 extra:
245 (olds !== undefined || output !== undefined) &&
246 (previousKind !== nextKind ||
247 (news.vpcPeeringConfig !== undefined && previousPeering !== nextPeering) ||
248 (news.pscInterfaceConfig !== undefined && previousPsc !== nextPsc) ||
249 previousDisplay !== nextDisplay ||
250 previousLabels !== nextLabels),
251 });
252 }),
253
254 read: Effect.fn(function* ({ id, olds, output }) {
255 const env = yield* GcpEnvironment.current;
256 const privateConnectionId = yield* toPhysicalId(
257 id,
258 olds?.privateConnectionId,
259 output?.privateConnectionId,
260 "pconn",
261 );
262 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
263 const name = output?.name ?? resourceName(env.project, location, privateConnectionId);
264 const existing = yield* getPrivateConnectionByName(name);
265 if (existing === undefined) return undefined;
266 const attrs = toPrivateConnectionAttrs(existing, env.project, env.region);
267 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
268 }),
269
270 list: () =>
271 Effect.gen(function* () {
272 const env = yield* GcpEnvironment.current;
273 const items = yield* listOwned(env.project, env.region);
274 return items.map((item) => toPrivateConnectionAttrs(item, env.project, env.region));
275 }),
276
277 reconcile: Effect.fn(function* ({ id, news, output }) {
278 const env = yield* GcpEnvironment.current;
279 const privateConnectionId = yield* toPhysicalId(
280 id,
281 news.privateConnectionId,
282 output?.privateConnectionId,
283 "pconn",
284 );
285 const location = normalizeLocation(news.location ?? output?.location, env.region);
286 const name = resourceName(env.project, location, privateConnectionId);
287 const desiredLabels = {
288 ...toLabels(news.labels),
289 ...(yield* createInternalLabels(id)),
290 };
291 const displayName = news.displayName ?? privateConnectionId;
292 const vpcPeeringConfig = peeringOf(news.vpcPeeringConfig, env.project);
293
294 let current = yield* getPrivateConnectionByName(output?.name ?? name);
295
296 if (current === undefined) {
297 const created = yield* ds
298 .createProjectsLocationsPrivateConnections({
299 parent: locationParent(env.project, location),
300 privateConnectionId,
301 force: news.force,
302 validateOnly: news.validateOnly,
303 body: {
304 displayName,
305 labels: desiredLabels,
306 vpcPeeringConfig,
307 pscInterfaceConfig: news.pscInterfaceConfig,
308 },
309 })
310 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
311 // VPC peering takes 5-10 minutes.
312 yield* settleOperation(created);
313 current = yield* waitUntilExists(getPrivateConnectionByName(name), name);
314 }
315
316 if (current === undefined) {
317 return yield* new ResourceNotResolved({ resourceName: name });
318 }
319
320 return toPrivateConnectionAttrs(current, env.project, env.region);
321 }),
322
323 delete: Effect.fn(function* ({ output }) {
324 const operation = yield* ds
325 .deleteProjectsLocationsPrivateConnections({
326 name: output.name,
327 force: true,
328 })
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 yield* settleOperation(operation, { notFoundOk: true });
338 yield* waitUntilGone(getPrivateConnectionByName(output.name), output.name, {
339 times: 8,
340 interval: "4 seconds",
341 });
342 }),
343 });