@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, 06:00 UTC

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