@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 327 lines 10.7 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 expandParent,
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 ReportType = mc.ReportTypeEnum | (string & {});
31 export type ReportState = mc.ReportStateEnum | (string & {});
32
33 export type ReportConfigsReportProps = {
34 /**
35 * Parent report config. Full name
36 * `projects/{project}/locations/{location}/reportConfigs/{reportConfig}`
37 * or the report config id (combined with `location`). Immutable —
38 * changing it replaces the report.
39 */
40 reportConfig: string;
41 /**
42 * Region used when `reportConfig` is a bare id.
43 * @default the stack's GCP region (`GCP.Region`, else the profile
44 * region, else `us-central1`)
45 */
46 location?: string;
47 /**
48 * Report id (the `{report}` segment). If omitted, a unique RFC1035 name
49 * is generated. Immutable — changing it replaces the report.
50 */
51 reportId?: string;
52 /**
53 * Report type. The API has no update method, so changing it replaces
54 * the report.
55 * @default "TOTAL_COST_OF_OWNERSHIP"
56 */
57 type?: ReportType;
58 /**
59 * User-friendly display name. Maximum length is 63 characters.
60 */
61 displayName?: string;
62 /**
63 * Free-text description. Reports have no labels field, so Alchemy
64 * ownership is stored in a `[alchemy …]` prefix and stripped from
65 * attributes.
66 */
67 description?: string;
68 };
69
70 export type ReportConfigsReport = Resource<
71 "GCP.MigrationCenter.ReportConfigsReport",
72 ReportConfigsReportProps,
73 {
74 /** Full resource name. */
75 name: string;
76 /** Report id (last path segment). */
77 reportId: string;
78 /** Parent report config resource name. */
79 reportConfig: string;
80 /** Project id. */
81 project: string;
82 /** Location id. */
83 location: string;
84 /** Report type. */
85 type: string | undefined;
86 /** User-friendly display name. */
87 displayName: string | undefined;
88 /** User description with the Alchemy ownership prefix stripped. */
89 description: string | undefined;
90 /** Server-reported state. */
91 state: string | undefined;
92 /** RFC3339 creation timestamp. */
93 createTime: string | undefined;
94 /** RFC3339 last-update timestamp. */
95 updateTime: string | undefined;
96 },
97 never,
98 Providers
99 >;
100
101 /**
102 * A point-in-time Migration Center report rendered from a report config
103 * (typically a total cost of ownership view).
104 *
105 * Reports have no labels field — Alchemy stamps ownership into the
106 * description so `list` / nuke can find them. The API has no patch
107 * method; changing type, display name, or description replaces the
108 * report.
109 *
110 * ### Creating a Report
111 * **Example:** TCO report
112 * ```typescript
113 * const report = yield* GCP.MigrationCenter.ReportConfigsReport("Tco", {
114 * reportConfig: config.name,
115 * type: "TOTAL_COST_OF_OWNERSHIP",
116 * displayName: "q1-tco",
117 * });
118 * ```
119 *
120 * @resource
121 * @category MigrationCenter
122 */
123 export const ReportConfigsReport = Resource<ReportConfigsReport>(
124 "GCP.MigrationCenter.ReportConfigsReport",
125 );
126
127 const DEFAULT_TYPE: ReportType = "TOTAL_COST_OF_OWNERSHIP";
128
129 const configNameOf = (value: string, project: string, location: string) =>
130 expandParent(value, project, location, "reportConfigs");
131
132 const resourceName = (reportConfig: string, reportId: string) =>
133 `${reportConfig}/reports/${reportId}`;
134
135 const toAttrs = (item: mc.Report, project: string, region: string) => {
136 const name = item.name ?? "";
137 const parsed = parseName(name, "reports", region);
138 const ownership = parseOwnership(item.description);
139 return {
140 name,
141 reportId: parsed.id,
142 reportConfig: parsed.parent,
143 project: parsed.project || project,
144 location: parsed.location,
145 type: item.type,
146 displayName: item.displayName,
147 description: ownership.text,
148 state: item.state,
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 .getProjectsLocationsReportConfigsReports({
159 name,
160 view: "REPORT_VIEW_BASIC",
161 })
162 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
163
164 const listReports = (parent: string) =>
165 mc.listProjectsLocationsReportConfigsReports
166 .pages({
167 parent,
168 pageSize: 1000,
169 view: "REPORT_VIEW_BASIC",
170 })
171 .pipe(
172 Stream.flatMap((page) => Stream.fromIterable(page.reports ?? [])),
173 Stream.runCollect,
174 Effect.map((chunk) => Array.from(chunk)),
175 Effect.catchTag("NotFound", () => Effect.succeed([] as mc.Report[])),
176 );
177
178 const listConfigs = (project: string, region: string) =>
179 mc.listProjectsLocationsReportConfigs
180 .pages({
181 parent: `projects/${project}/locations/-`,
182 pageSize: 1000,
183 })
184 .pipe(
185 Stream.flatMap((page) => Stream.fromIterable(page.reportConfigs ?? [])),
186 Stream.runCollect,
187 Effect.map((chunk) => Array.from(chunk)),
188 Effect.catchTag("NotFound", () =>
189 mc.listProjectsLocationsReportConfigs
190 .pages({
191 parent: locationParent(project, region),
192 pageSize: 1000,
193 })
194 .pipe(
195 Stream.flatMap((page) => Stream.fromIterable(page.reportConfigs ?? [])),
196 Stream.runCollect,
197 Effect.map((chunk) => Array.from(chunk)),
198 Effect.catchTag("NotFound", () => Effect.succeed([] as mc.ReportConfig[])),
199 ),
200 ),
201 );
202
203 const listOwned = (project: string, region: string) =>
204 Effect.gen(function* () {
205 const configs = yield* listConfigs(project, region);
206 const reports: mc.Report[] = [];
207 for (const config of configs) {
208 if (config.name === undefined) continue;
209 const nested = yield* listReports(config.name);
210 for (const report of nested) {
211 if (hasOwnershipMarker(report.description)) reports.push(report);
212 }
213 }
214 return reports;
215 });
216
217 export const ReportConfigsReportProvider = () =>
218 Provider.succeed(ReportConfigsReport, {
219 stables: ["name", "reportId", "reportConfig", "project", "location", "createTime"],
220
221 diff: Effect.fn(function* ({ news, olds, output }) {
222 if (!isResolved(news)) return undefined;
223 const env = yield* GcpEnvironment.current;
224 const payloadChanged =
225 fingerprint({
226 type: news.type ?? DEFAULT_TYPE,
227 displayName: news.displayName,
228 description: news.description,
229 }) !==
230 fingerprint({
231 type: olds?.type ?? output?.type ?? DEFAULT_TYPE,
232 displayName: olds?.displayName ?? output?.displayName,
233 description: olds?.description ?? output?.description,
234 });
235 return replaceOnIdentity({
236 previousId: olds?.reportId ?? output?.reportId,
237 nextId: news.reportId ?? olds?.reportId ?? output?.reportId,
238 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
239 nextLocation: normalizeLocation(
240 news.location ?? olds?.location ?? output?.location,
241 env.region,
242 ),
243 previousParent: olds?.reportConfig ?? output?.reportConfig,
244 nextParent: news.reportConfig,
245 extra: payloadChanged,
246 });
247 }),
248
249 read: Effect.fn(function* ({ id, olds, output }) {
250 const env = yield* GcpEnvironment.current;
251 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
252 const reportConfig = configNameOf(
253 olds?.reportConfig ?? output?.reportConfig ?? "",
254 env.project,
255 location,
256 );
257 const reportId = yield* toPhysicalId(id, olds?.reportId, output?.reportId, "report");
258 const name =
259 output?.name ?? (reportConfig.length > 0 ? resourceName(reportConfig, reportId) : "");
260 const existing = yield* getByName(name);
261 if (existing === undefined) return undefined;
262 const attrs = toAttrs(existing, env.project, env.region);
263 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
264 }),
265
266 list: () =>
267 Effect.gen(function* () {
268 const env = yield* GcpEnvironment.current;
269 const items = yield* listOwned(env.project, env.region);
270 return items.map((item) => toAttrs(item, env.project, env.region));
271 }),
272
273 reconcile: Effect.fn(function* ({ id, news, output }) {
274 const env = yield* GcpEnvironment.current;
275 const location = normalizeLocation(news.location ?? output?.location, env.region);
276 const reportConfig = configNameOf(news.reportConfig, env.project, location);
277 const reportId = yield* toPhysicalId(id, news.reportId, output?.reportId, "report");
278 const name = resourceName(reportConfig, reportId);
279 const ownership = yield* createInternalLabels(id);
280 const description = encodeOwnership(ownership, news.description);
281 const displayName = news.displayName ?? reportId;
282 const type = news.type ?? DEFAULT_TYPE;
283
284 let current = yield* getByName(output?.name ?? name);
285
286 if (current === undefined) {
287 const created = yield* mc
288 .createProjectsLocationsReportConfigsReports({
289 parent: reportConfig,
290 reportId,
291 body: {
292 type,
293 displayName,
294 description,
295 },
296 })
297 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
298 if (created !== undefined) {
299 yield* waitForOperation(created);
300 }
301 current = yield* waitUntilExists(getByName(name), name);
302 }
303
304 if (current === undefined) {
305 return yield* new ResourceNotResolved({ resourceName: name });
306 }
307
308 return toAttrs(current, env.project, env.region);
309 }),
310
311 delete: Effect.fn(function* ({ output }) {
312 const operation = yield* mc
313 .deleteProjectsLocationsReportConfigsReports({ name: output.name })
314 .pipe(
315 Effect.retry({
316 while: (error) => error._tag === "Conflict",
317 times: 8,
318 schedule: Schedule.spaced("2 seconds"),
319 }),
320 Effect.catchTag("NotFound", () => Effect.undefined),
321 );
322 if (operation !== undefined) {
323 yield* waitForOperation(operation, { notFoundOk: true });
324 }
325 yield* waitUntilGone(getByName(output.name), output.name);
326 }),
327 });