@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, 04:45 UTC

main
ts 300 lines 10.1 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 { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 collectPages,
13 encodeOwnershipLine,
14 fingerprint,
15 forEachSource,
16 hasOwnershipMarker,
17 normalizeLocation,
18 ownedByAlchemy,
19 parseName,
20 parseOwnership,
21 replaceOnIdentity,
22 ResourceNotResolved,
23 sourceOf,
24 toPhysicalId,
25 waitForOperation,
26 waitUntilExists,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type UtilizationReportTimeFrame = vm.UtilizationReportTimeFrameEnum | (string & {});
31 export type UtilizationReportState = vm.UtilizationReportStateEnum | (string & {});
32 export type VmUtilizationInfo = vm.VmUtilizationInfo;
33
34 export type SourcesUtilizationReportProps = {
35 /**
36 * Parent source. Full name
37 * `projects/{project}/locations/{location}/sources/{source}` or the
38 * source id (combined with `location`). Immutable — changing it
39 * replaces the report.
40 */
41 source: string;
42 /**
43 * Region used when `source` is a bare id.
44 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
45 */
46 location?: string;
47 /**
48 * Utilization report id. If omitted, a unique RFC1035 name is
49 * generated. Immutable — changing it replaces the report.
50 */
51 utilizationReportId?: string;
52 /**
53 * User-friendly display name. Reports have no labels field, so
54 * Alchemy ownership is stored in a `[alchemy …]` prefix and stripped
55 * from attributes.
56 */
57 displayName?: string;
58 /**
59 * Time frame of the report.
60 * @default "WEEK"
61 */
62 timeFrame?: UtilizationReportTimeFrame;
63 /**
64 * VMs to include. Only `vmId` is honored on create; other fields are
65 * filled by the service.
66 */
67 vms?: VmUtilizationInfo[];
68 };
69
70 export type SourcesUtilizationReport = Resource<
71 "GCP.VMMigration.SourcesUtilizationReport",
72 SourcesUtilizationReportProps,
73 {
74 /** Full resource name. */
75 name: string;
76 /** Utilization report id (last path segment). */
77 utilizationReportId: string;
78 /** Parent source resource name. */
79 source: string;
80 /** Project id. */
81 project: string;
82 /** Location id. */
83 location: string;
84 /** Display name with the Alchemy ownership prefix stripped. */
85 displayName: string | undefined;
86 /** Time frame of the report. */
87 timeFrame: string | undefined;
88 /** VMs included in the report. */
89 vms: VmUtilizationInfo[] | undefined;
90 /** Number of VMs included. */
91 vmCount: number | undefined;
92 /** Report state. */
93 state: string | undefined;
94 /** End of the sampled time frame. */
95 frameEndTime: string | undefined;
96 /** RFC3339 creation timestamp. */
97 createTime: string | undefined;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * A VM Migration utilization report for selected VMs in a source
105 * environment (CPU, memory, disk, network).
106 *
107 * Reports have no labels field — Alchemy stamps ownership into the
108 * display name so `list` / nuke can find them. The API has no patch
109 * method; changing time frame, VMs, or display name replaces the
110 * report.
111 *
112 * ### Creating a Utilization Report
113 * **Example:** Weekly report for selected VMs
114 * ```typescript
115 * const report = yield* GCP.VMMigration.SourcesUtilizationReport("Week", {
116 * source: source.name,
117 * timeFrame: "WEEK",
118 * vms: [{ vmId: "vm-123" }, { vmId: "vm-456" }],
119 * });
120 * ```
121 *
122 * @resource
123 * @category VMMigration
124 */
125 export const SourcesUtilizationReport = Resource<SourcesUtilizationReport>(
126 "GCP.VMMigration.SourcesUtilizationReport",
127 );
128
129 const DEFAULT_TIME_FRAME: UtilizationReportTimeFrame = "WEEK";
130
131 const resourceName = (source: string, utilizationReportId: string) =>
132 `${source}/utilizationReports/${utilizationReportId}`;
133
134 const toAttrs = (report: vm.UtilizationReport, project: string, region: string) => {
135 const name = report.name ?? "";
136 const parsed = parseName(name, "utilizationReports", region);
137 const ownership = parseOwnership(report.displayName);
138 return {
139 name,
140 utilizationReportId: parsed.id,
141 source: parsed.parent,
142 project: parsed.project || project,
143 location: parsed.location,
144 displayName: ownership.text,
145 timeFrame: report.timeFrame,
146 vms: report.vms,
147 vmCount: report.vmCount,
148 state: report.state,
149 frameEndTime: report.frameEndTime,
150 createTime: report.createTime,
151 };
152 };
153
154 const getByName = (name: string) =>
155 name.length === 0
156 ? Effect.undefined
157 : vm
158 .getProjectsLocationsSourcesUtilizationReports({ name })
159 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
160
161 const listChildren = (parent: string) =>
162 collectPages(
163 vm.listProjectsLocationsSourcesUtilizationReports.pages({
164 parent,
165 pageSize: 1000,
166 view: "BASIC",
167 }),
168 (page) => page.utilizationReports,
169 ).pipe(Effect.catchTag("NotFound", () => Effect.succeed([] as vm.UtilizationReport[])));
170
171 export const SourcesUtilizationReportProvider = () =>
172 Provider.succeed(SourcesUtilizationReport, {
173 stables: ["name", "utilizationReportId", "source", "project", "location", "createTime"],
174
175 diff: Effect.fn(function* ({ news, olds, output }) {
176 if (!isResolved(news)) return undefined;
177 const env = yield* GcpEnvironment.current;
178 const previousSource = olds?.source ?? output?.source;
179 const previousFrame = olds?.timeFrame ?? output?.timeFrame ?? DEFAULT_TIME_FRAME;
180 const nextFrame = news.timeFrame ?? previousFrame;
181 const extra =
182 previousFrame !== nextFrame ||
183 fingerprint(news.vms?.map((vmInfo) => vmInfo.vmId)) !==
184 fingerprint((olds?.vms ?? output?.vms)?.map((vmInfo) => vmInfo.vmId));
185 return replaceOnIdentity({
186 previousId: olds?.utilizationReportId ?? output?.utilizationReportId,
187 nextId:
188 news.utilizationReportId ?? olds?.utilizationReportId ?? output?.utilizationReportId,
189 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
190 nextLocation: normalizeLocation(
191 news.location ?? olds?.location ?? output?.location,
192 env.region,
193 ),
194 previousParent: previousSource,
195 nextParent: news.source ?? previousSource,
196 extra,
197 });
198 }),
199
200 read: Effect.fn(function* ({ id, olds, output }) {
201 const env = yield* GcpEnvironment.current;
202 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
203 const utilizationReportId = yield* toPhysicalId(
204 id,
205 olds?.utilizationReportId,
206 output?.utilizationReportId,
207 "utilreport",
208 );
209 const source =
210 olds?.source !== undefined
211 ? sourceOf(olds.source, env.project, location)
212 : (output?.source ?? "");
213 const name =
214 output?.name ?? (source.length > 0 ? resourceName(source, utilizationReportId) : "");
215 const existing = yield* getByName(name);
216 if (existing === undefined) return undefined;
217 const attrs = toAttrs(existing, env.project, env.region);
218 return (yield* ownedByAlchemy(id, existing.displayName)) ? attrs : Unowned(attrs);
219 }),
220
221 list: () =>
222 Effect.gen(function* () {
223 const env = yield* GcpEnvironment.current;
224 const items = yield* forEachSource(env.project, listChildren, env.region);
225 return items
226 .filter((item) => hasOwnershipMarker(item.displayName))
227 .map((item) => toAttrs(item, env.project, env.region));
228 }),
229
230 reconcile: Effect.fn(function* ({ id, news, output }) {
231 const env = yield* GcpEnvironment.current;
232 const location = normalizeLocation(news.location ?? output?.location, env.region);
233 const source = sourceOf(news.source, env.project, location);
234 const utilizationReportId = yield* toPhysicalId(
235 id,
236 news.utilizationReportId,
237 output?.utilizationReportId,
238 "utilreport",
239 );
240 const name = resourceName(source, utilizationReportId);
241 const ownership = yield* createInternalLabels(id);
242 const displayName = encodeOwnershipLine(ownership, news.displayName ?? utilizationReportId);
243 const timeFrame = news.timeFrame ?? DEFAULT_TIME_FRAME;
244
245 let current = yield* getByName(output?.name ?? name);
246
247 if (current === undefined) {
248 const created = yield* vm
249 .createProjectsLocationsSourcesUtilizationReports({
250 parent: source,
251 utilizationReportId,
252 body: {
253 displayName,
254 timeFrame,
255 vms: news.vms,
256 },
257 })
258 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
259 if (created !== undefined) {
260 // ALREADY_EXISTS (6): a concurrent create won the race.
261 yield* waitForOperation(created).pipe(
262 Effect.catchTag("GCP.OperationFailed", (error) =>
263 error.code === 6 ? Effect.void : Effect.fail(error),
264 ),
265 );
266 }
267 current = yield* waitUntilExists(getByName(name), name);
268 }
269
270 if (current === undefined) {
271 return yield* new ResourceNotResolved({ resourceName: name });
272 }
273
274 return toAttrs(current, env.project, env.region);
275 }),
276
277 delete: Effect.fn(function* ({ output }) {
278 const operation = yield* vm
279 .deleteProjectsLocationsSourcesUtilizationReports({
280 name: output.name,
281 })
282 .pipe(
283 Effect.retry({
284 while: (error) => error._tag === "Conflict",
285 times: 8,
286 schedule: Schedule.spaced("2 seconds"),
287 }),
288 Effect.catchTag("NotFound", () => Effect.undefined),
289 );
290 if (operation !== undefined) {
291 // NOT_FOUND (5): already gone.
292 yield* waitForOperation(operation).pipe(
293 Effect.catchTag("GCP.OperationFailed", (error) =>
294 error.code === 5 ? Effect.void : Effect.fail(error),
295 ),
296 );
297 }
298 yield* waitUntilGone(getByName(output.name), output.name);
299 }),
300 });