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

main
ts 440 lines 15.3 KB
Raw
1 import * as networkconnectivity from "@distilled.cloud/gcp/networkconnectivity_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, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 NetworkConnectivityNotResolved,
14 changedFields,
15 collectPages,
16 hasAlchemyLabelKeys,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 rfc1035,
21 sameJson,
22 toNetworkResource,
23 toPhysicalId,
24 userLabels,
25 waitForOperation,
26 waitUntilGone,
27 waitUntilPresent,
28 } from "./internal.ts";
29
30 const COLLECTION = "serviceConnectionMaps";
31
32 export type AutomatedDnsCreationSpec = {
33 /** DNS suffix with trailing dot, e.g. `"internal."`. */
34 dnsSuffix?: string;
35 /** Hostname (first label of the FQDN). */
36 hostname?: string;
37 /** TTL as a duration string, e.g. `"30s"`. */
38 ttl?: string;
39 };
40
41 export type ProducerPscConfig = {
42 /** Service attachment URI. */
43 serviceAttachmentUri?: string;
44 /** Optional spec for automatically creating a DNS record. */
45 automatedDnsCreationSpec?: AutomatedDnsCreationSpec;
46 };
47
48 export type ConsumerPscConfig = {
49 /** Consumer project id or number. */
50 project?: string;
51 /** Consumer instance project path (`projects/{project}`). */
52 consumerInstanceProject?: string;
53 /** Consumer VPC (`projects/{project}/global/networks/{network}`). */
54 network?: string;
55 /** Disable global access on the PSC endpoint. */
56 disableGlobalAccess?: boolean;
57 /** Requested IP version (`IPV4` or `IPV6`). */
58 ipVersion?: string;
59 /** Static IP map from VIP to service attachment. */
60 serviceAttachmentIpAddressMap?: Record<string, string>;
61 /** Producer instance metadata. Immutable on the producer. */
62 producerInstanceMetadata?: Record<string, string>;
63 /** Deprecated producer instance id. */
64 producerInstanceId?: string;
65 /** Output-only overall state. */
66 state?: string;
67 };
68
69 export type ServiceConnectionMapProps = {
70 /**
71 * Map id (the `{service_connection_map}` segment). If omitted, a unique
72 * name is generated. Immutable — changing it replaces the map.
73 */
74 serviceConnectionMapId?: string;
75 /**
76 * Location (`us-central1`, …). Immutable — changing it replaces the
77 * map. `US-CENTRAL1` is accepted and normalized to `us-central1`.
78 * @default the stack's GCP region (`GCP.Region`, else the profile
79 * region, else `us-central1`)
80 */
81 location?: string;
82 /**
83 * Service class identifier this map is for. Callers need
84 * `networkconnectivity.serviceClasses.use`.
85 */
86 serviceClass?: string;
87 /**
88 * Consumer-provided token that authenticates PSC connection creation.
89 */
90 token?: string;
91 /**
92 * Producer-side PSC configurations (service attachments).
93 */
94 producerPscConfigs?: ProducerPscConfig[];
95 /**
96 * Consumer-side PSC configurations (allowed networks/projects).
97 */
98 consumerPscConfigs?: ConsumerPscConfig[];
99 /**
100 * Human-readable description.
101 */
102 description?: string;
103 /**
104 * User labels. Alchemy ownership labels are merged in automatically.
105 */
106 labels?: Record<string, string>;
107 };
108
109 export type ServiceConnectionMap = Resource<
110 "GCP.NetworkConnectivity.ServiceConnectionMap",
111 ServiceConnectionMapProps,
112 {
113 /** Full resource name `projects/{project}/locations/{location}/serviceConnectionMaps/{id}`. */
114 name: string;
115 /** Map id (last path segment). */
116 serviceConnectionMapId: string;
117 /** Project id. */
118 project: string;
119 /** Location id. */
120 location: string;
121 /** Service class identifier. */
122 serviceClass: string | undefined;
123 /** Service class URI (output-only). */
124 serviceClassUri: string | undefined;
125 /** Consumer-provided token. */
126 token: string | undefined;
127 /** Producer PSC configs. */
128 producerPscConfigs: ProducerPscConfig[];
129 /** Consumer PSC configs. */
130 consumerPscConfigs: ConsumerPscConfig[];
131 /** Infrastructure used for connections (`PSC`, …). */
132 infrastructure: string | undefined;
133 /** User-provided description. */
134 description: string | undefined;
135 /** User labels (Alchemy ownership labels stripped). */
136 labels: Record<string, string>;
137 /** Server etag. */
138 etag: string | undefined;
139 /** RFC3339 creation timestamp. */
140 createTime: string | undefined;
141 /** RFC3339 last-update timestamp. */
142 updateTime: string | undefined;
143 },
144 never,
145 Providers
146 >;
147
148 /**
149 * A PSC Service Connection Map that pairs producer service attachments
150 * with consumer networks for Cross-Cloud / producer-consumer
151 * connectivity.
152 *
153 * Changing `serviceConnectionMapId` or `location` replaces the map.
154 * Description, labels, token, and PSC configs update in place.
155 *
156 * ### Creating a ServiceConnectionMap
157 * **Example:** Producer map for a service class
158 * ```typescript
159 * const map = yield* GCP.NetworkConnectivity.ServiceConnectionMap("Sql", {
160 * serviceClass: "gcp-cloud-sql",
161 * description: "sql psc map",
162 * labels: { env: "prod" },
163 * });
164 * ```
165 *
166 * ### Updating a ServiceConnectionMap
167 * **Example:** Description and labels
168 * ```typescript
169 * const map = yield* GCP.NetworkConnectivity.ServiceConnectionMap("Sql", {
170 * serviceClass: "gcp-cloud-sql",
171 * description: "sql psc map v2",
172 * labels: { env: "prod", role: "psc" },
173 * });
174 * ```
175 *
176 * @resource
177 * @category NetworkConnectivity
178 */
179 export const ServiceConnectionMap = Resource<ServiceConnectionMap>(
180 "GCP.NetworkConnectivity.ServiceConnectionMap",
181 );
182
183 const resourceName = (project: string, location: string, serviceConnectionMapId: string) =>
184 `projects/${project}/locations/${location}/serviceConnectionMaps/${serviceConnectionMapId}`;
185
186 const toStringMap = (
187 value: Record<string, string | undefined> | null | undefined,
188 ): Record<string, string> | undefined => {
189 if (value === undefined || value === null) return undefined;
190 const entries = Object.entries(value).filter(
191 (entry): entry is [string, string] => entry[1] !== undefined,
192 );
193 return entries.length > 0 ? Object.fromEntries(entries) : undefined;
194 };
195
196 const toProducer = (
197 config: ProducerPscConfig | networkconnectivity.ProducerPscConfig,
198 ): ProducerPscConfig => ({
199 serviceAttachmentUri: config.serviceAttachmentUri,
200 automatedDnsCreationSpec: config.automatedDnsCreationSpec
201 ? {
202 dnsSuffix: config.automatedDnsCreationSpec.dnsSuffix,
203 hostname: config.automatedDnsCreationSpec.hostname,
204 ttl: config.automatedDnsCreationSpec.ttl,
205 }
206 : undefined,
207 });
208
209 const toConsumer = (
210 config: ConsumerPscConfig | networkconnectivity.ConsumerPscConfig,
211 project: string,
212 ): ConsumerPscConfig => ({
213 project: config.project,
214 consumerInstanceProject: config.consumerInstanceProject,
215 network: config.network !== undefined ? toNetworkResource(project, config.network) : undefined,
216 disableGlobalAccess: config.disableGlobalAccess,
217 ipVersion: config.ipVersion,
218 serviceAttachmentIpAddressMap: toStringMap(config.serviceAttachmentIpAddressMap),
219 producerInstanceMetadata: toStringMap(config.producerInstanceMetadata),
220 producerInstanceId: config.producerInstanceId,
221 state: config.state,
222 });
223
224 const desiredConsumer = (config: ConsumerPscConfig, project: string) => ({
225 project: config.project,
226 consumerInstanceProject: config.consumerInstanceProject,
227 network: config.network !== undefined ? toNetworkResource(project, config.network) : undefined,
228 disableGlobalAccess: config.disableGlobalAccess,
229 ipVersion: config.ipVersion,
230 serviceAttachmentIpAddressMap: toStringMap(config.serviceAttachmentIpAddressMap),
231 producerInstanceMetadata: toStringMap(config.producerInstanceMetadata),
232 producerInstanceId: config.producerInstanceId,
233 });
234
235 const toAttrs = (
236 map: networkconnectivity.ServiceConnectionMap,
237 project: string,
238 region: string,
239 ) => {
240 const name = map.name ?? "";
241 const parsed = parseName(name, COLLECTION, region);
242 return {
243 name,
244 serviceConnectionMapId: parsed.id,
245 project: parsed.project || project,
246 location: parsed.location || region,
247 serviceClass: map.serviceClass,
248 serviceClassUri: map.serviceClassUri,
249 token: map.token,
250 producerPscConfigs: (map.producerPscConfigs ?? []).map(toProducer),
251 consumerPscConfigs: (map.consumerPscConfigs ?? []).map((config) =>
252 toConsumer(config, parsed.project || project),
253 ),
254 infrastructure: map.infrastructure,
255 description: map.description,
256 labels: userLabels(map.labels),
257 etag: map.etag,
258 createTime: map.createTime,
259 updateTime: map.updateTime,
260 };
261 };
262
263 const getByName = (name: string) =>
264 networkconnectivity
265 .getProjectsLocationsServiceConnectionMaps({ name })
266 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
267
268 export const ServiceConnectionMapProvider = () =>
269 Provider.succeed(ServiceConnectionMap, {
270 stables: ["name", "serviceConnectionMapId", "project", "location", "createTime"],
271
272 diff: Effect.fn(function* ({ news, olds, output }) {
273 if (!isResolved(news)) return undefined;
274 const env = yield* GcpEnvironment.current;
275 const previousId = olds?.serviceConnectionMapId ?? output?.serviceConnectionMapId;
276 const nextId = news.serviceConnectionMapId
277 ? rfc1035(news.serviceConnectionMapId, "service-connection-map")
278 : previousId;
279 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
280 const nextLocation = normalizeLocation(
281 news.location ?? olds?.location ?? output?.location,
282 env.region,
283 );
284 if (
285 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
286 previousLocation !== nextLocation
287 ) {
288 return { action: "replace" as const };
289 }
290 return undefined;
291 }),
292
293 read: Effect.fn(function* ({ id, olds, output }) {
294 const env = yield* GcpEnvironment.current;
295 const serviceConnectionMapId = yield* toPhysicalId(
296 id,
297 olds?.serviceConnectionMapId,
298 output?.serviceConnectionMapId,
299 "service-connection-map",
300 );
301 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
302 const name = output?.name ?? resourceName(env.project, location, serviceConnectionMapId);
303 const existing = yield* getByName(name);
304 if (existing === undefined) return undefined;
305 const attrs = toAttrs(existing, env.project, env.region);
306 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
307 }),
308
309 list: () =>
310 Effect.gen(function* () {
311 const env = yield* GcpEnvironment.current;
312 const items = yield* collectPages(
313 networkconnectivity.listProjectsLocationsServiceConnectionMaps.pages({
314 parent: parentOf(env.project, "-"),
315 pageSize: 1000,
316 }),
317 (page) => page.serviceConnectionMaps,
318 );
319 return items
320 .filter((item) => hasAlchemyLabelKeys(item.labels))
321 .map((item) => toAttrs(item, env.project, env.region));
322 }),
323
324 reconcile: Effect.fn(function* ({ id, news, output }) {
325 const env = yield* GcpEnvironment.current;
326 const serviceConnectionMapId = yield* toPhysicalId(
327 id,
328 news.serviceConnectionMapId,
329 output?.serviceConnectionMapId,
330 "service-connection-map",
331 );
332 const location = normalizeLocation(news.location ?? output?.location, env.region);
333 const name = resourceName(env.project, location, serviceConnectionMapId);
334 const desiredLabels = {
335 ...toLabels(news.labels),
336 ...(yield* createInternalLabels(id)),
337 };
338 const producerPscConfigs = (news.producerPscConfigs ?? []).map(toProducer);
339 const consumerPscConfigs = (news.consumerPscConfigs ?? []).map((config) =>
340 desiredConsumer(config, env.project),
341 );
342
343 let current = yield* getByName(name);
344
345 if (current === undefined) {
346 const created = yield* networkconnectivity
347 .createProjectsLocationsServiceConnectionMaps({
348 parent: parentOf(env.project, location),
349 serviceConnectionMapId,
350 body: {
351 serviceClass: news.serviceClass,
352 token: news.token,
353 producerPscConfigs,
354 consumerPscConfigs,
355 description: news.description,
356 labels: desiredLabels,
357 },
358 })
359 .pipe(
360 Effect.retry({
361 while: (error) => error._tag === "Conflict",
362 times: 5,
363 schedule: Schedule.spaced("2 seconds"),
364 }),
365 Effect.catchTag("Conflict", () => Effect.undefined),
366 );
367 if (created !== undefined) {
368 yield* waitForOperation(created);
369 }
370 current = yield* waitUntilPresent(getByName(name), name);
371 }
372
373 if (current === undefined) {
374 return yield* new NetworkConnectivityNotResolved({ resourceName: name });
375 }
376
377 const observedLabels = tagRecord(current.labels);
378 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
379 const labelsChanged = upsert.length > 0 || removed.length > 0;
380 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
381 const tokenChanged = (current.token ?? "") !== (news.token ?? "");
382 const producerChanged = !sameJson(
383 (current.producerPscConfigs ?? []).map(toProducer),
384 producerPscConfigs,
385 );
386 const consumerChanged = !sameJson(
387 (current.consumerPscConfigs ?? []).map((config) =>
388 desiredConsumer(toConsumer(config, env.project), env.project),
389 ),
390 consumerPscConfigs,
391 );
392 const updateMask = changedFields([
393 ["labels", labelsChanged],
394 ["description", descriptionChanged],
395 ["token", tokenChanged],
396 ["producerPscConfigs", producerChanged],
397 ["consumerPscConfigs", consumerChanged],
398 ]);
399
400 if (updateMask.length > 0) {
401 const operation = yield* networkconnectivity.patchProjectsLocationsServiceConnectionMaps({
402 name: current.name ?? name,
403 updateMask: updateMask.join(","),
404 body: {
405 name: current.name ?? name,
406 labels: desiredLabels,
407 description: news.description,
408 token: news.token,
409 producerPscConfigs,
410 consumerPscConfigs,
411 etag: current.etag,
412 },
413 });
414 yield* waitForOperation(operation);
415 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
416 }
417
418 return toAttrs(current, env.project, env.region);
419 }),
420
421 delete: Effect.fn(function* ({ output }) {
422 const operation = yield* networkconnectivity
423 .deleteProjectsLocationsServiceConnectionMaps({
424 name: output.name,
425 etag: output.etag,
426 })
427 .pipe(
428 Effect.retry({
429 while: (error) => error._tag === "Conflict",
430 times: 8,
431 schedule: Schedule.spaced("2 seconds"),
432 }),
433 Effect.catchTag("NotFound", () => Effect.undefined),
434 );
435 if (operation !== undefined) {
436 yield* waitForOperation(operation, { notFoundOk: true });
437 }
438 yield* waitUntilGone(getByName(output.name), output.name);
439 }),
440 });