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

main
ts 280 lines 9.16 KB
Raw
1 import * as mc from "@distilled.cloud/gcp/migrationcenter_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, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 fieldMask,
15 hasAlchemyLabelMap,
16 locationParent,
17 normalizeLocation,
18 parseName,
19 replaceOnIdentity,
20 ResourceNotResolved,
21 toPhysicalId,
22 userLabels,
23 waitForOperation,
24 waitUntilExists,
25 waitUntilGone,
26 } from "./internal.ts";
27
28 export type GroupProps = {
29 /**
30 * Group id (the `{group}` segment of
31 * `projects/{project}/locations/{location}/groups/{group}`). If omitted,
32 * a unique RFC1035 name is generated. Immutable — changing it replaces
33 * the group.
34 */
35 groupId?: string;
36 /**
37 * Region (`us-central1`, …). Immutable — changing it replaces the
38 * group. `US-CENTRAL1` is accepted and normalized to `us-central1`.
39 * @default the stack's GCP region (`GCP.Region`, else the profile
40 * region, else `us-central1`)
41 */
42 location?: string;
43 /**
44 * User-friendly display name.
45 */
46 displayName?: string;
47 /**
48 * Free-text description.
49 */
50 description?: string;
51 /**
52 * User labels. Alchemy ownership labels are merged in automatically.
53 */
54 labels?: Record<string, string>;
55 };
56
57 export type Group = Resource<
58 "GCP.MigrationCenter.Group",
59 GroupProps,
60 {
61 /** Full resource name. */
62 name: string;
63 /** Group id (last path segment). */
64 groupId: string;
65 /** Project id. */
66 project: string;
67 /** Location id. */
68 location: string;
69 /** User-friendly display name. */
70 displayName: string | undefined;
71 /** Free-text description. */
72 description: string | undefined;
73 /** User labels (Alchemy ownership labels stripped). */
74 labels: Record<string, string>;
75 /** RFC3339 creation timestamp. */
76 createTime: string | undefined;
77 /** RFC3339 last-update timestamp. */
78 updateTime: string | undefined;
79 },
80 never,
81 Providers
82 >;
83
84 /**
85 * A Migration Center asset group used to bundle related assets and
86 * generate reports.
87 *
88 * Changing `groupId` or `location` replaces the group. Display name,
89 * description, and labels update in place.
90 *
91 * ### Creating a Group
92 * **Example:** Generated name
93 * ```typescript
94 * const group = yield* GCP.MigrationCenter.Group("Workloads", {
95 * displayName: "workloads",
96 * labels: { env: "test" },
97 * });
98 * ```
99 *
100 * **Example:** Explicit id
101 * ```typescript
102 * const group = yield* GCP.MigrationCenter.Group("Workloads", {
103 * groupId: "app-workloads",
104 * description: "production vms",
105 * });
106 * ```
107 *
108 * @resource
109 * @category MigrationCenter
110 */
111 export const Group = Resource<Group>("GCP.MigrationCenter.Group");
112
113 const resourceName = (project: string, location: string, groupId: string) =>
114 `${locationParent(project, location)}/groups/${groupId}`;
115
116 const toAttrs = (group: mc.Group, project: string, region: string) => {
117 const name = group.name ?? "";
118 const parsed = parseName(name, "groups", region);
119 return {
120 name,
121 groupId: parsed.id,
122 project: parsed.project || project,
123 location: parsed.location,
124 displayName: group.displayName,
125 description: group.description,
126 labels: userLabels(group.labels),
127 createTime: group.createTime,
128 updateTime: group.updateTime,
129 };
130 };
131
132 const getByName = (name: string) =>
133 name.length === 0
134 ? Effect.undefined
135 : mc
136 .getProjectsLocationsGroups({ name })
137 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
138
139 const listOwned = (project: string, region: string) =>
140 mc.listProjectsLocationsGroups
141 .pages({
142 parent: `projects/${project}/locations/-`,
143 pageSize: 1000,
144 })
145 .pipe(
146 Stream.flatMap((page) => Stream.fromIterable(page.groups ?? [])),
147 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
148 Stream.runCollect,
149 Effect.map((chunk) => Array.from(chunk)),
150 Effect.catchTag("NotFound", () =>
151 mc.listProjectsLocationsGroups
152 .pages({
153 parent: locationParent(project, region),
154 pageSize: 1000,
155 })
156 .pipe(
157 Stream.flatMap((page) => Stream.fromIterable(page.groups ?? [])),
158 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
159 Stream.runCollect,
160 Effect.map((chunk) => Array.from(chunk)),
161 Effect.catchTag("NotFound", () => Effect.succeed([] as mc.Group[])),
162 ),
163 ),
164 );
165
166 export const GroupProvider = () =>
167 Provider.succeed(Group, {
168 stables: ["name", "groupId", "project", "location", "createTime"],
169
170 diff: Effect.fn(function* ({ news, olds, output }) {
171 if (!isResolved(news)) return undefined;
172 const env = yield* GcpEnvironment.current;
173 return replaceOnIdentity({
174 previousId: olds?.groupId ?? output?.groupId,
175 nextId: news.groupId ?? olds?.groupId ?? output?.groupId,
176 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
177 nextLocation: normalizeLocation(
178 news.location ?? olds?.location ?? output?.location,
179 env.region,
180 ),
181 });
182 }),
183
184 read: Effect.fn(function* ({ id, olds, output }) {
185 const env = yield* GcpEnvironment.current;
186 const groupId = yield* toPhysicalId(id, olds?.groupId, output?.groupId, "group");
187 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
188 const name = output?.name ?? resourceName(env.project, location, groupId);
189 const existing = yield* getByName(name);
190 if (existing === undefined) return undefined;
191 const attrs = toAttrs(existing, env.project, env.region);
192 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
193 }),
194
195 list: () =>
196 Effect.gen(function* () {
197 const env = yield* GcpEnvironment.current;
198 const items = yield* listOwned(env.project, env.region);
199 return items.map((item) => toAttrs(item, env.project, env.region));
200 }),
201
202 reconcile: Effect.fn(function* ({ id, news, output }) {
203 const env = yield* GcpEnvironment.current;
204 const groupId = yield* toPhysicalId(id, news.groupId, output?.groupId, "group");
205 const location = normalizeLocation(news.location ?? output?.location, env.region);
206 const name = resourceName(env.project, location, groupId);
207 const desiredLabels = {
208 ...toLabels(news.labels),
209 ...(yield* createInternalLabels(id)),
210 };
211 const displayName = news.displayName ?? groupId;
212
213 let current = yield* getByName(output?.name ?? name);
214
215 if (current === undefined) {
216 const created = yield* mc
217 .createProjectsLocationsGroups({
218 parent: locationParent(env.project, location),
219 groupId,
220 body: {
221 displayName,
222 description: news.description,
223 labels: desiredLabels,
224 },
225 })
226 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
227 if (created !== undefined) {
228 yield* waitForOperation(created);
229 }
230 current = yield* waitUntilExists(getByName(name), name);
231 }
232
233 if (current === undefined) {
234 return yield* new ResourceNotResolved({ resourceName: name });
235 }
236
237 const observedLabels = tagRecord(current.labels);
238 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
239 const labelsChanged = upsert.length > 0 || removed.length > 0;
240 const displayNameChanged = (current.displayName ?? "") !== displayName;
241 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
242 const mask = fieldMask([
243 labelsChanged && "labels",
244 displayNameChanged && "displayName",
245 descriptionChanged && "description",
246 ]);
247
248 if (mask.length > 0) {
249 const operation = yield* mc.patchProjectsLocationsGroups({
250 name: current.name ?? name,
251 updateMask: mask,
252 body: {
253 name: current.name ?? name,
254 displayName,
255 description: news.description,
256 labels: desiredLabels,
257 },
258 });
259 yield* waitForOperation(operation);
260 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
261 }
262
263 return toAttrs(current, env.project, env.region);
264 }),
265
266 delete: Effect.fn(function* ({ output }) {
267 const operation = yield* mc.deleteProjectsLocationsGroups({ name: output.name }).pipe(
268 Effect.retry({
269 while: (error) => error._tag === "Conflict",
270 times: 8,
271 schedule: Schedule.spaced("2 seconds"),
272 }),
273 Effect.catchTag("NotFound", () => Effect.undefined),
274 );
275 if (operation !== undefined) {
276 yield* waitForOperation(operation, { notFoundOk: true });
277 }
278 yield* waitUntilGone(getByName(output.name), output.name);
279 }),
280 });