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