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

main
ts 261 lines 8.49 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 GLOBAL_LOCATION,
16 globalParent,
17 hasOwnershipMarker,
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 TargetProps = {
30 /**
31 * Target project id (the `{targetProject}` segment of
32 * `projects/{project}/locations/global/targetProjects/{targetProject}`).
33 * If omitted, a unique RFC1035 name is generated. Immutable — changing
34 * it replaces the target.
35 */
36 targetProjectId?: string;
37 /**
38 * Compute Engine project id (or number) this target points at.
39 * Defaults to the current Alchemy GCP project.
40 */
41 project?: string;
42 /**
43 * Free-text description. Target projects have no labels field, so
44 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
45 * from attributes.
46 */
47 description?: string;
48 };
49
50 export type Target = Resource<
51 "GCP.VMMigration.Target",
52 TargetProps,
53 {
54 /** Full resource name. */
55 name: string;
56 /** Target project id (last path segment). */
57 targetProjectId: string;
58 /** Host project id of the VM Migration resource. */
59 hostProject: string;
60 /** Compute Engine project this target points at. */
61 project: string;
62 /** Location id — always `global`. */
63 location: string;
64 /** User description with the Alchemy ownership prefix stripped. */
65 description: string | undefined;
66 /** RFC3339 creation timestamp. */
67 createTime: string | undefined;
68 /** RFC3339 last-update timestamp. */
69 updateTime: string | undefined;
70 },
71 never,
72 Providers
73 >;
74
75 /**
76 * A VM Migration target project: the Compute Engine project clones and
77 * cutovers land in.
78 *
79 * Target projects are global. They have no labels field — Alchemy stamps
80 * ownership into the description so `list` / nuke can find them. The
81 * resource id is immutable; `project` and `description` update in place.
82 *
83 * ### Creating a Target
84 * **Example:** Point at the current project
85 * ```typescript
86 * const target = yield* GCP.VMMigration.Target("Default", {
87 * description: "this project",
88 * });
89 * ```
90 *
91 * **Example:** Explicit Compute Engine project
92 * ```typescript
93 * const target = yield* GCP.VMMigration.Target("Prod", {
94 * project: "prod-compute",
95 * description: "production landing zone",
96 * });
97 * ```
98 *
99 * @resource
100 * @category VMMigration
101 */
102 export const Target = Resource<Target>("GCP.VMMigration.Target");
103
104 const resourceName = (hostProject: string, targetProjectId: string) =>
105 `${globalParent(hostProject)}/targetProjects/${targetProjectId}`;
106
107 const toAttrs = (target: vm.TargetProject, hostProject: string) => {
108 const name = target.name ?? "";
109 const parsed = parseName(name, "targetProjects", "global");
110 const ownership = parseOwnership(target.description);
111 return {
112 name,
113 targetProjectId: parsed.id,
114 hostProject: parsed.project || hostProject,
115 project: target.project ?? parsed.project ?? hostProject,
116 location: GLOBAL_LOCATION,
117 description: ownership.text,
118 createTime: target.createTime,
119 updateTime: target.updateTime,
120 };
121 };
122
123 const getByName = (name: string) =>
124 name.length === 0
125 ? Effect.undefined
126 : vm
127 .getProjectsLocationsTargetProjects({ name })
128 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
129
130 const listOwned = (project: string) =>
131 vm.listProjectsLocationsTargetProjects
132 .pages({
133 parent: globalParent(project),
134 pageSize: 1000,
135 })
136 .pipe(
137 Stream.flatMap((page) => Stream.fromIterable(page.targetProjects ?? [])),
138 Stream.filter((item) => hasOwnershipMarker(item.description)),
139 Stream.runCollect,
140 Effect.map((chunk) => Array.from(chunk)),
141 Effect.catchTag("NotFound", () => Effect.succeed([] as vm.TargetProject[])),
142 );
143
144 export const TargetProvider = () =>
145 Provider.succeed(Target, {
146 stables: ["name", "targetProjectId", "hostProject", "location", "createTime"],
147
148 diff: Effect.fn(function* ({ news, olds, output }) {
149 if (!isResolved(news)) return undefined;
150 return replaceOnIdentity({
151 previousId: olds?.targetProjectId ?? output?.targetProjectId,
152 nextId: news?.targetProjectId ?? olds?.targetProjectId ?? output?.targetProjectId,
153 previousLocation: GLOBAL_LOCATION,
154 nextLocation: GLOBAL_LOCATION,
155 });
156 }),
157
158 read: Effect.fn(function* ({ id, olds, output }) {
159 const env = yield* GcpEnvironment.current;
160 const targetProjectId = yield* toPhysicalId(
161 id,
162 olds?.targetProjectId,
163 output?.targetProjectId,
164 "target",
165 );
166 const name = output?.name ?? resourceName(env.project, targetProjectId);
167 const existing = yield* getByName(name);
168 if (existing === undefined) return undefined;
169 const attrs = toAttrs(existing, env.project);
170 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
171 }),
172
173 list: () =>
174 Effect.gen(function* () {
175 const env = yield* GcpEnvironment.current;
176 const items = yield* listOwned(env.project);
177 return items.map((item) => toAttrs(item, env.project));
178 }),
179
180 reconcile: Effect.fn(function* ({ id, news, output }) {
181 const env = yield* GcpEnvironment.current;
182 const targetProjectId = yield* toPhysicalId(
183 id,
184 news?.targetProjectId,
185 output?.targetProjectId,
186 "target",
187 );
188 const name = resourceName(env.project, targetProjectId);
189 const ownership = yield* createInternalLabels(id);
190 const description = encodeOwnership(ownership, news?.description);
191 const project = news?.project ?? env.project;
192
193 let current = yield* getByName(output?.name ?? name);
194
195 if (current === undefined) {
196 const created = yield* vm
197 .createProjectsLocationsTargetProjects({
198 parent: globalParent(env.project),
199 targetProjectId,
200 body: {
201 project,
202 description,
203 },
204 })
205 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
206 if (created !== undefined) {
207 // ALREADY_EXISTS (6): a concurrent create won the race.
208 yield* waitForOperation(created).pipe(
209 Effect.catchTag("GCP.OperationFailed", (error) =>
210 error.code === 6 ? Effect.void : Effect.fail(error),
211 ),
212 );
213 }
214 current = yield* waitUntilExists(getByName(name), name);
215 }
216
217 if (current === undefined) {
218 return yield* new ResourceNotResolved({ resourceName: name });
219 }
220
221 const descriptionChanged = (current.description ?? "") !== description;
222 const projectChanged = (current.project ?? "") !== project;
223 const mask = fieldMask([descriptionChanged && "description", projectChanged && "project"]);
224
225 if (mask.length > 0) {
226 const operation = yield* vm.patchProjectsLocationsTargetProjects({
227 name: current.name ?? name,
228 updateMask: mask,
229 body: {
230 name: current.name ?? name,
231 project,
232 description,
233 },
234 });
235 yield* waitForOperation(operation);
236 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
237 }
238
239 return toAttrs(current, env.project);
240 }),
241
242 delete: Effect.fn(function* ({ output }) {
243 const operation = yield* vm.deleteProjectsLocationsTargetProjects({ name: output.name }).pipe(
244 Effect.retry({
245 while: (error) => error._tag === "Conflict",
246 times: 8,
247 schedule: Schedule.spaced("2 seconds"),
248 }),
249 Effect.catchTag("NotFound", () => Effect.undefined),
250 );
251 if (operation !== undefined) {
252 // NOT_FOUND (5): already gone.
253 yield* waitForOperation(operation).pipe(
254 Effect.catchTag("GCP.OperationFailed", (error) =>
255 error.code === 5 ? Effect.void : Effect.fail(error),
256 ),
257 );
258 }
259 yield* waitUntilGone(getByName(output.name), output.name);
260 }),
261 });