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

main
ts 369 lines 12.5 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 toPhysicalId,
23 userLabels,
24 waitForOperation,
25 waitUntilGone,
26 waitUntilPresent,
27 } from "./internal.ts";
28
29 const COLLECTION = "multicloudDataTransferConfigs";
30
31 export type StateMetadata = {
32 /** Transient or rest state (`ADDING`, `ACTIVE`, `DELETING`, …). */
33 state?: string;
34 /** RFC3339 time when a transient state becomes effective. */
35 effectiveTime?: string;
36 };
37
38 export type StateTimeline = {
39 /** Ordered state/activation entries. */
40 states?: StateMetadata[];
41 };
42
43 export type MulticloudDataTransferConfigProps = {
44 /**
45 * Config id (the `{multicloud_data_transfer_config}` segment of
46 * `projects/{project}/locations/{location}/multicloudDataTransferConfigs/{multicloud_data_transfer_config}`).
47 * If omitted, a unique name is generated from the stack, stage, and
48 * logical id. Immutable — changing it replaces the config.
49 */
50 multicloudDataTransferConfigId?: string;
51 /**
52 * Location (`us-central1`, …). Immutable — changing it replaces the
53 * config. `US-CENTRAL1` is accepted and normalized to `us-central1`.
54 * @default the stack's GCP region (`GCP.Region`, else the profile
55 * region, else `us-central1`)
56 */
57 location?: string;
58 /**
59 * Human-readable description.
60 */
61 description?: string;
62 /**
63 * Map of Data Transfer Essentials service names to their desired
64 * timeline. Keys are service ids such as `"google-cloud-storage"`.
65 */
66 services?: Record<string, StateTimeline>;
67 /**
68 * User labels. Alchemy ownership labels are merged in automatically.
69 */
70 labels?: Record<string, string>;
71 };
72
73 export type MulticloudDataTransferConfig = Resource<
74 "GCP.NetworkConnectivity.MulticloudDataTransferConfig",
75 MulticloudDataTransferConfigProps,
76 {
77 /** Full resource name `projects/{project}/locations/{location}/multicloudDataTransferConfigs/{id}`. */
78 name: string;
79 /** Config id (last path segment). */
80 multicloudDataTransferConfigId: string;
81 /** Project id. */
82 project: string;
83 /** Location id. */
84 location: string;
85 /** User-provided description. */
86 description: string | undefined;
87 /** Service timelines currently configured. */
88 services: Record<string, StateTimeline>;
89 /** Number of Destination resources configured. */
90 destinationsCount: number | undefined;
91 /** Number of Destination resources in use. */
92 destinationsActiveCount: number | undefined;
93 /** User labels (Alchemy ownership labels stripped). */
94 labels: Record<string, string>;
95 /** Google-generated unique id. */
96 uid: string | undefined;
97 /** Server etag. */
98 etag: string | undefined;
99 /** RFC3339 creation timestamp. */
100 createTime: string | undefined;
101 /** RFC3339 last-update timestamp. */
102 updateTime: string | undefined;
103 },
104 never,
105 Providers
106 >;
107
108 /**
109 * A Data Transfer Essentials `MulticloudDataTransferConfig` — the
110 * billing/metering configuration for services whose traffic is billed
111 * through DTE.
112 *
113 * Changing `multicloudDataTransferConfigId` or `location` replaces the
114 * config. Description, labels, and `services` update in place.
115 *
116 * ### Creating a Config
117 * **Example:** Generated name
118 * ```typescript
119 * const config = yield* GCP.NetworkConnectivity.MulticloudDataTransferConfig(
120 * "Dte",
121 * { description: "dte metering", labels: { env: "prod" } },
122 * );
123 * ```
124 *
125 * **Example:** Named config with a service
126 * ```typescript
127 * const config = yield* GCP.NetworkConnectivity.MulticloudDataTransferConfig(
128 * "Dte",
129 * {
130 * multicloudDataTransferConfigId: "app-dte",
131 * location: "us-central1",
132 * services: { "google-cloud-storage": {} },
133 * },
134 * );
135 * ```
136 *
137 * ### Updating a Config
138 * **Example:** Description and labels
139 * ```typescript
140 * const config = yield* GCP.NetworkConnectivity.MulticloudDataTransferConfig(
141 * "Dte",
142 * {
143 * multicloudDataTransferConfigId: "app-dte",
144 * location: "us-central1",
145 * description: "dte metering v2",
146 * labels: { env: "prod", role: "dte" },
147 * },
148 * );
149 * ```
150 *
151 * @resource
152 * @category NetworkConnectivity
153 */
154 export const MulticloudDataTransferConfig = Resource<MulticloudDataTransferConfig>(
155 "GCP.NetworkConnectivity.MulticloudDataTransferConfig",
156 );
157
158 const resourceName = (project: string, location: string, configId: string) =>
159 `projects/${project}/locations/${location}/multicloudDataTransferConfigs/${configId}`;
160
161 const toTimeline = (
162 timeline: StateTimeline | networkconnectivity.StateTimeline | undefined,
163 ): StateTimeline => ({
164 states: (timeline?.states ?? []).map((entry) => ({
165 state: entry.state,
166 effectiveTime: entry.effectiveTime,
167 })),
168 });
169
170 const toServices = (
171 services:
172 | Record<string, StateTimeline | undefined>
173 | networkconnectivity.StateTimelineMap
174 | undefined,
175 ): Record<string, StateTimeline> => {
176 const result: Record<string, StateTimeline> = {};
177 for (const [key, value] of Object.entries(services ?? {})) {
178 if (value !== undefined) {
179 result[key] = toTimeline(value);
180 }
181 }
182 return result;
183 };
184
185 const toAttrs = (
186 config: networkconnectivity.MulticloudDataTransferConfig,
187 project: string,
188 region: string,
189 ) => {
190 const name = config.name ?? "";
191 const parsed = parseName(name, COLLECTION, region);
192 return {
193 name,
194 multicloudDataTransferConfigId: parsed.id,
195 project: parsed.project || project,
196 location: parsed.location || region,
197 description: config.description,
198 services: toServices(config.services),
199 destinationsCount: config.destinationsCount,
200 destinationsActiveCount: config.destinationsActiveCount,
201 labels: userLabels(config.labels),
202 uid: config.uid,
203 etag: config.etag,
204 createTime: config.createTime,
205 updateTime: config.updateTime,
206 };
207 };
208
209 const getByName = (name: string) =>
210 networkconnectivity
211 .getProjectsLocationsMulticloudDataTransferConfigs({ name })
212 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
213
214 export const MulticloudDataTransferConfigProvider = () =>
215 Provider.succeed(MulticloudDataTransferConfig, {
216 stables: ["name", "multicloudDataTransferConfigId", "project", "location", "uid", "createTime"],
217
218 diff: Effect.fn(function* ({ news, olds, output }) {
219 if (!isResolved(news)) return undefined;
220 const env = yield* GcpEnvironment.current;
221 const previousId =
222 olds?.multicloudDataTransferConfigId ?? output?.multicloudDataTransferConfigId;
223 const nextId = news.multicloudDataTransferConfigId
224 ? rfc1035(news.multicloudDataTransferConfigId, "multicloud-data-transfer-config")
225 : previousId;
226 const previousLocation = normalizeLocation(olds?.location ?? output?.location, env.region);
227 const nextLocation = normalizeLocation(
228 news.location ?? olds?.location ?? output?.location,
229 env.region,
230 );
231 if (
232 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
233 previousLocation !== nextLocation
234 ) {
235 return { action: "replace" as const };
236 }
237 return undefined;
238 }),
239
240 read: Effect.fn(function* ({ id, olds, output }) {
241 const env = yield* GcpEnvironment.current;
242 const configId = yield* toPhysicalId(
243 id,
244 olds?.multicloudDataTransferConfigId,
245 output?.multicloudDataTransferConfigId,
246 "multicloud-data-transfer-config",
247 );
248 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
249 const name = output?.name ?? resourceName(env.project, location, configId);
250 const existing = yield* getByName(name);
251 if (existing === undefined) return undefined;
252 const attrs = toAttrs(existing, env.project, env.region);
253 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
254 }),
255
256 list: () =>
257 Effect.gen(function* () {
258 const env = yield* GcpEnvironment.current;
259 const items = yield* collectPages(
260 networkconnectivity.listProjectsLocationsMulticloudDataTransferConfigs.pages({
261 parent: parentOf(env.project, "-"),
262 pageSize: 1000,
263 returnPartialSuccess: true,
264 }),
265 (page) => page.multicloudDataTransferConfigs,
266 );
267 return items
268 .filter((item) => hasAlchemyLabelKeys(item.labels))
269 .map((item) => toAttrs(item, env.project, env.region));
270 }),
271
272 reconcile: Effect.fn(function* ({ id, news, output }) {
273 const env = yield* GcpEnvironment.current;
274 const configId = yield* toPhysicalId(
275 id,
276 news.multicloudDataTransferConfigId,
277 output?.multicloudDataTransferConfigId,
278 "multicloud-data-transfer-config",
279 );
280 const location = normalizeLocation(news.location ?? output?.location, env.region);
281 const name = resourceName(env.project, location, configId);
282 const desiredLabels = {
283 ...toLabels(news.labels),
284 ...(yield* createInternalLabels(id)),
285 };
286 const desiredServices = toServices(news.services);
287
288 let current = yield* getByName(name);
289
290 if (current === undefined) {
291 const created = yield* networkconnectivity
292 .createProjectsLocationsMulticloudDataTransferConfigs({
293 parent: parentOf(env.project, location),
294 multicloudDataTransferConfigId: configId,
295 body: {
296 description: news.description,
297 labels: desiredLabels,
298 services: desiredServices,
299 },
300 })
301 .pipe(
302 Effect.retry({
303 while: (error) => error._tag === "Conflict",
304 times: 5,
305 schedule: Schedule.spaced("2 seconds"),
306 }),
307 Effect.catchTag("Conflict", () => Effect.undefined),
308 );
309 if (created !== undefined) {
310 yield* waitForOperation(created);
311 }
312 current = yield* waitUntilPresent(getByName(name), name);
313 }
314
315 if (current === undefined) {
316 return yield* new NetworkConnectivityNotResolved({ resourceName: name });
317 }
318
319 const observedLabels = tagRecord(current.labels);
320 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
321 const labelsChanged = upsert.length > 0 || removed.length > 0;
322 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
323 const servicesChanged = !sameJson(toServices(current.services), desiredServices);
324 const updateMask = changedFields([
325 ["labels", labelsChanged],
326 ["description", descriptionChanged],
327 ["services", servicesChanged],
328 ]);
329
330 if (updateMask.length > 0) {
331 const operation =
332 yield* networkconnectivity.patchProjectsLocationsMulticloudDataTransferConfigs({
333 name: current.name ?? name,
334 updateMask: updateMask.join(","),
335 body: {
336 name: current.name ?? name,
337 labels: desiredLabels,
338 description: news.description,
339 services: desiredServices,
340 etag: current.etag,
341 },
342 });
343 yield* waitForOperation(operation);
344 current = yield* waitUntilPresent(getByName(current.name ?? name), current.name ?? name);
345 }
346
347 return toAttrs(current, env.project, env.region);
348 }),
349
350 delete: Effect.fn(function* ({ output }) {
351 const operation = yield* networkconnectivity
352 .deleteProjectsLocationsMulticloudDataTransferConfigs({
353 name: output.name,
354 etag: output.etag,
355 })
356 .pipe(
357 Effect.retry({
358 while: (error) => error._tag === "Conflict",
359 times: 8,
360 schedule: Schedule.spaced("2 seconds"),
361 }),
362 Effect.catchTag("NotFound", () => Effect.undefined),
363 );
364 if (operation !== undefined) {
365 yield* waitForOperation(operation, { notFoundOk: true });
366 }
367 yield* waitUntilGone(getByName(output.name), output.name);
368 }),
369 });