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

main
ts 310 lines 10.8 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 * 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 fingerprint,
16 hasOwnershipMarker,
17 locationParent,
18 normalizeLocation,
19 ownedByAlchemy,
20 parseName,
21 parseOwnership,
22 replaceOnIdentity,
23 ResourceNotResolved,
24 toPhysicalId,
25 waitForOperation,
26 waitUntilExists,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type VirtualMachinePreferences = mc.VirtualMachinePreferences;
31
32 export type PreferenceSetProps = {
33 /**
34 * Preference set id (the `{preferenceSet}` segment of
35 * `projects/{project}/locations/{location}/preferenceSets/{preferenceSet}`).
36 * If omitted, a unique RFC1035 name is generated. Immutable — changing
37 * it replaces the preference set.
38 */
39 preferenceSetId?: string;
40 /**
41 * Region (`us-central1`, …). Immutable — changing it replaces the
42 * preference set. `US-CENTRAL1` is accepted and normalized to
43 * `us-central1`.
44 * @default the stack's GCP region (`GCP.Region`, else the profile
45 * region, else `us-central1`)
46 */
47 location?: string;
48 /**
49 * User-friendly display name. Maximum length is 63 characters.
50 */
51 displayName?: string;
52 /**
53 * Free-text description. Preference sets have no labels field, so
54 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
55 * from attributes.
56 */
57 description?: string;
58 /**
59 * Preferences that apply to virtual machines in this set.
60 */
61 virtualMachinePreferences?: VirtualMachinePreferences;
62 };
63
64 export type PreferenceSet = Resource<
65 "GCP.MigrationCenter.PreferenceSet",
66 PreferenceSetProps,
67 {
68 /** Full resource name. */
69 name: string;
70 /** Preference set id (last path segment). */
71 preferenceSetId: string;
72 /** Project id. */
73 project: string;
74 /** Location id. */
75 location: string;
76 /** User-friendly display name. */
77 displayName: string | undefined;
78 /** User description with the Alchemy ownership prefix stripped. */
79 description: string | undefined;
80 /** Virtual machine preferences. */
81 virtualMachinePreferences: VirtualMachinePreferences | undefined;
82 /** RFC3339 creation timestamp. */
83 createTime: string | undefined;
84 /** RFC3339 last-update timestamp. */
85 updateTime: string | undefined;
86 },
87 never,
88 Providers
89 >;
90
91 // Report input rather than the preference set's own location; kept fixed so a
92 // stack-region change doesn't rewrite existing preference sets.
93 const DEFAULT_VM: VirtualMachinePreferences = {
94 targetProduct: "COMPUTE_MIGRATION_TARGET_PRODUCT_COMPUTE_ENGINE",
95 regionPreferences: { preferredRegions: ["us-central1"] },
96 sizingOptimizationStrategy: "SIZING_OPTIMIZATION_STRATEGY_MODERATE",
97 commitmentPlan: "COMMITMENT_PLAN_THREE_YEARS",
98 };
99
100 /**
101 * A Migration Center preference set capturing target-product, region, and
102 * sizing assumptions used when generating reports.
103 *
104 * Preference sets have no labels field — Alchemy stamps ownership into
105 * the description so `list` / nuke can find them. Id and location are
106 * immutable. Display name, description, and VM preferences update in
107 * place.
108 *
109 * ### Creating a Preference Set
110 * **Example:** Compute Engine defaults
111 * ```typescript
112 * const prefs = yield* GCP.MigrationCenter.PreferenceSet("Prod", {
113 * displayName: "prod-gce",
114 * });
115 * ```
116 *
117 * **Example:** Explicit VM preferences
118 * ```typescript
119 * const prefs = yield* GCP.MigrationCenter.PreferenceSet("Prod", {
120 * virtualMachinePreferences: {
121 * targetProduct: "COMPUTE_MIGRATION_TARGET_PRODUCT_COMPUTE_ENGINE",
122 * regionPreferences: { preferredRegions: ["us-central1"] },
123 * sizingOptimizationStrategy: "SIZING_OPTIMIZATION_STRATEGY_MODERATE",
124 * commitmentPlan: "COMMITMENT_PLAN_THREE_YEARS",
125 * },
126 * });
127 * ```
128 *
129 * @resource
130 * @category MigrationCenter
131 */
132 export const PreferenceSet = Resource<PreferenceSet>("GCP.MigrationCenter.PreferenceSet");
133
134 const resourceName = (project: string, location: string, preferenceSetId: string) =>
135 `${locationParent(project, location)}/preferenceSets/${preferenceSetId}`;
136
137 const toAttrs = (item: mc.PreferenceSet, project: string, region: string) => {
138 const name = item.name ?? "";
139 const parsed = parseName(name, "preferenceSets", region);
140 const ownership = parseOwnership(item.description);
141 return {
142 name,
143 preferenceSetId: parsed.id,
144 project: parsed.project || project,
145 location: parsed.location,
146 displayName: item.displayName,
147 description: ownership.text,
148 virtualMachinePreferences: item.virtualMachinePreferences,
149 createTime: item.createTime,
150 updateTime: item.updateTime,
151 };
152 };
153
154 const getByName = (name: string) =>
155 name.length === 0
156 ? Effect.undefined
157 : mc
158 .getProjectsLocationsPreferenceSets({ name })
159 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
160
161 const listOwned = (project: string, region: string) =>
162 mc.listProjectsLocationsPreferenceSets
163 .pages({
164 parent: `projects/${project}/locations/-`,
165 pageSize: 1000,
166 })
167 .pipe(
168 Stream.flatMap((page) => Stream.fromIterable(page.preferenceSets ?? [])),
169 Stream.filter((item) => hasOwnershipMarker(item.description)),
170 Stream.runCollect,
171 Effect.map((chunk) => Array.from(chunk)),
172 Effect.catchTag("NotFound", () =>
173 mc.listProjectsLocationsPreferenceSets
174 .pages({
175 parent: locationParent(project, region),
176 pageSize: 1000,
177 })
178 .pipe(
179 Stream.flatMap((page) => Stream.fromIterable(page.preferenceSets ?? [])),
180 Stream.filter((item) => hasOwnershipMarker(item.description)),
181 Stream.runCollect,
182 Effect.map((chunk) => Array.from(chunk)),
183 Effect.catchTag("NotFound", () => Effect.succeed([] as mc.PreferenceSet[])),
184 ),
185 ),
186 );
187
188 export const PreferenceSetProvider = () =>
189 Provider.succeed(PreferenceSet, {
190 stables: ["name", "preferenceSetId", "project", "location", "createTime"],
191
192 diff: Effect.fn(function* ({ news, olds, output }) {
193 if (!isResolved(news)) return undefined;
194 const env = yield* GcpEnvironment.current;
195 return replaceOnIdentity({
196 previousId: olds?.preferenceSetId ?? output?.preferenceSetId,
197 nextId: news.preferenceSetId ?? olds?.preferenceSetId ?? output?.preferenceSetId,
198 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
199 nextLocation: normalizeLocation(
200 news.location ?? olds?.location ?? output?.location,
201 env.region,
202 ),
203 });
204 }),
205
206 read: Effect.fn(function* ({ id, olds, output }) {
207 const env = yield* GcpEnvironment.current;
208 const preferenceSetId = yield* toPhysicalId(
209 id,
210 olds?.preferenceSetId,
211 output?.preferenceSetId,
212 "prefset",
213 );
214 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
215 const name = output?.name ?? resourceName(env.project, location, preferenceSetId);
216 const existing = yield* getByName(name);
217 if (existing === undefined) return undefined;
218 const attrs = toAttrs(existing, env.project, env.region);
219 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
220 }),
221
222 list: () =>
223 Effect.gen(function* () {
224 const env = yield* GcpEnvironment.current;
225 const items = yield* listOwned(env.project, env.region);
226 return items.map((item) => toAttrs(item, env.project, env.region));
227 }),
228
229 reconcile: Effect.fn(function* ({ id, news, output }) {
230 const env = yield* GcpEnvironment.current;
231 const preferenceSetId = yield* toPhysicalId(
232 id,
233 news.preferenceSetId,
234 output?.preferenceSetId,
235 "prefset",
236 );
237 const location = normalizeLocation(news.location ?? output?.location, env.region);
238 const name = resourceName(env.project, location, preferenceSetId);
239 const ownership = yield* createInternalLabels(id);
240 const description = encodeOwnership(ownership, news.description);
241 const displayName = news.displayName ?? preferenceSetId;
242 const virtualMachinePreferences = news.virtualMachinePreferences ?? DEFAULT_VM;
243
244 let current = yield* getByName(output?.name ?? name);
245
246 if (current === undefined) {
247 const created = yield* mc
248 .createProjectsLocationsPreferenceSets({
249 parent: locationParent(env.project, location),
250 preferenceSetId,
251 body: {
252 displayName,
253 description,
254 virtualMachinePreferences,
255 },
256 })
257 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
258 if (created !== undefined) {
259 yield* waitForOperation(created);
260 }
261 current = yield* waitUntilExists(getByName(name), name);
262 }
263
264 if (current === undefined) {
265 return yield* new ResourceNotResolved({ resourceName: name });
266 }
267
268 const descriptionChanged = (current.description ?? "") !== description;
269 const displayNameChanged = (current.displayName ?? "") !== displayName;
270 const prefsChanged =
271 fingerprint(current.virtualMachinePreferences) !== fingerprint(virtualMachinePreferences);
272 const mask = fieldMask([
273 descriptionChanged && "description",
274 displayNameChanged && "displayName",
275 prefsChanged && "virtualMachinePreferences",
276 ]);
277
278 if (mask.length > 0) {
279 const operation = yield* mc.patchProjectsLocationsPreferenceSets({
280 name: current.name ?? name,
281 updateMask: mask,
282 body: {
283 name: current.name ?? name,
284 displayName,
285 description,
286 virtualMachinePreferences,
287 },
288 });
289 yield* waitForOperation(operation);
290 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
291 }
292
293 return toAttrs(current, env.project, env.region);
294 }),
295
296 delete: Effect.fn(function* ({ output }) {
297 const operation = yield* mc.deleteProjectsLocationsPreferenceSets({ name: output.name }).pipe(
298 Effect.retry({
299 while: (error) => error._tag === "Conflict",
300 times: 8,
301 schedule: Schedule.spaced("2 seconds"),
302 }),
303 Effect.catchTag("NotFound", () => Effect.undefined),
304 );
305 if (operation !== undefined) {
306 yield* waitForOperation(operation, { notFoundOk: true });
307 }
308 yield* waitUntilGone(getByName(output.name), output.name);
309 }),
310 });