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

main
ts 339 lines 11.6 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 { tagRecord } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 fingerprint,
15 hasAlchemyLabelMap,
16 locationParent,
17 normalizeLocation,
18 parseName,
19 replaceOnIdentity,
20 ResourceNotResolved,
21 toPhysicalId,
22 userLabels,
23 waitForOperation,
24 waitUntilExists,
25 waitUntilGone,
26 } from "./internal.ts";
27
28 export type AssetsExportJobFileFormat = mc.SignedUriDestinationFileFormatEnum | (string & {});
29
30 export type AssetsExportJobProps = {
31 /**
32 * Assets export job id (the `{assetsExportJob}` segment of
33 * `projects/{project}/locations/{location}/assetsExportJobs/{assetsExportJob}`).
34 * If omitted, a unique RFC1035 name is generated. Immutable — changing
35 * it replaces the job.
36 */
37 assetsExportJobId?: string;
38 /**
39 * Region (`us-central1`, …). Immutable — changing it replaces the job.
40 * `US-CENTRAL1` is accepted and normalized to `us-central1`.
41 * @default the stack's GCP region (`GCP.Region`, else the profile
42 * region, else `us-central1`)
43 */
44 location?: string;
45 /**
46 * File format for signed-URI downloads. The API has no update method,
47 * so changing it replaces the job.
48 * @default "CSV"
49 */
50 fileFormat?: AssetsExportJobFileFormat;
51 /**
52 * Optional filter selecting which assets to export.
53 */
54 filter?: string;
55 /**
56 * When true, hidden assets are included in the export.
57 * @default false
58 */
59 showHidden?: boolean;
60 /**
61 * When true, export asset inventory details.
62 * @default true
63 */
64 inventory?: boolean;
65 /**
66 * When true, export network-dependency data.
67 * @default false
68 */
69 networkDependencies?: boolean;
70 /**
71 * Performance-data window in days (1-420). Omit to skip performance
72 * export.
73 */
74 performanceDataMaxDays?: number;
75 /**
76 * User labels. Alchemy ownership labels are merged in automatically.
77 * The API has no update method, so changing labels replaces the job.
78 */
79 labels?: Record<string, string>;
80 };
81
82 export type AssetsExportJob = Resource<
83 "GCP.MigrationCenter.AssetsExportJob",
84 AssetsExportJobProps,
85 {
86 /** Full resource name. */
87 name: string;
88 /** Assets export job id (last path segment). */
89 assetsExportJobId: string;
90 /** Project id. */
91 project: string;
92 /** Location id. */
93 location: string;
94 /** Signed-URI destination file format. */
95 fileFormat: string | undefined;
96 /** Asset filter. */
97 filter: string | undefined;
98 /** Whether hidden assets are included. */
99 showHidden: boolean | undefined;
100 /** Whether inventory details are exported. */
101 inventory: boolean;
102 /** Whether network-dependency data is exported. */
103 networkDependencies: boolean;
104 /** Performance-data window in days. */
105 performanceDataMaxDays: number | undefined;
106 /** User labels (Alchemy ownership labels stripped). */
107 labels: Record<string, string>;
108 /** RFC3339 creation timestamp. */
109 createTime: string | undefined;
110 /** RFC3339 last-update timestamp. */
111 updateTime: string | undefined;
112 },
113 never,
114 Providers
115 >;
116
117 /**
118 * A Migration Center assets export job that writes inventory (and
119 * optional performance / network-dependency) data to signed-URI files.
120 *
121 * The API has no patch method — changing format, filter, inventory flags,
122 * or labels replaces the job. Id and location are also immutable.
123 *
124 * ### Creating an Assets Export Job
125 * **Example:** CSV inventory export
126 * ```typescript
127 * const job = yield* GCP.MigrationCenter.AssetsExportJob("Inventory", {
128 * fileFormat: "CSV",
129 * labels: { env: "test" },
130 * });
131 * ```
132 *
133 * **Example:** XLSX with performance data
134 * ```typescript
135 * const job = yield* GCP.MigrationCenter.AssetsExportJob("Inventory", {
136 * fileFormat: "XLSX",
137 * performanceDataMaxDays: 40,
138 * });
139 * ```
140 *
141 * @resource
142 * @category MigrationCenter
143 */
144 export const AssetsExportJob = Resource<AssetsExportJob>("GCP.MigrationCenter.AssetsExportJob");
145
146 const DEFAULT_FORMAT: AssetsExportJobFileFormat = "CSV";
147
148 const resourceName = (project: string, location: string, assetsExportJobId: string) =>
149 `${locationParent(project, location)}/assetsExportJobs/${assetsExportJobId}`;
150
151 const toAttrs = (job: mc.AssetsExportJob, project: string, region: string) => {
152 const name = job.name ?? "";
153 const parsed = parseName(name, "assetsExportJobs", region);
154 return {
155 name,
156 assetsExportJobId: parsed.id,
157 project: parsed.project || project,
158 location: parsed.location,
159 fileFormat: job.signedUriDestination?.fileFormat,
160 filter: job.condition?.filter,
161 showHidden: job.showHidden,
162 inventory: job.inventory !== undefined,
163 networkDependencies: job.networkDependencies !== undefined,
164 performanceDataMaxDays: job.performanceData?.maxDays,
165 labels: userLabels(job.labels),
166 createTime: job.createTime,
167 updateTime: job.updateTime,
168 };
169 };
170
171 const desiredBody = (
172 news: AssetsExportJobProps,
173 labels: Record<string, string>,
174 ): mc.AssetsExportJob => ({
175 labels,
176 showHidden: news.showHidden === true,
177 condition:
178 news.filter !== undefined && news.filter.length > 0 ? { filter: news.filter } : undefined,
179 signedUriDestination: {
180 fileFormat: news.fileFormat ?? DEFAULT_FORMAT,
181 },
182 inventory: news.inventory === false ? undefined : {},
183 networkDependencies: news.networkDependencies === true ? {} : undefined,
184 performanceData:
185 news.performanceDataMaxDays !== undefined
186 ? { maxDays: news.performanceDataMaxDays }
187 : undefined,
188 });
189
190 const getByName = (name: string) =>
191 name.length === 0
192 ? Effect.undefined
193 : mc
194 .getProjectsLocationsAssetsExportJobs({ name })
195 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
196
197 const listOwned = (project: string, region: string) =>
198 mc.listProjectsLocationsAssetsExportJobs
199 .pages({
200 parent: `projects/${project}/locations/-`,
201 pageSize: 1000,
202 })
203 .pipe(
204 Stream.flatMap((page) => Stream.fromIterable(page.assetsExportJobs ?? [])),
205 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
206 Stream.runCollect,
207 Effect.map((chunk) => Array.from(chunk)),
208 Effect.catchTag("NotFound", () =>
209 mc.listProjectsLocationsAssetsExportJobs
210 .pages({
211 parent: locationParent(project, region),
212 pageSize: 1000,
213 })
214 .pipe(
215 Stream.flatMap((page) => Stream.fromIterable(page.assetsExportJobs ?? [])),
216 Stream.filter((item) => hasAlchemyLabelMap(item.labels)),
217 Stream.runCollect,
218 Effect.map((chunk) => Array.from(chunk)),
219 Effect.catchTag("NotFound", () => Effect.succeed([] as mc.AssetsExportJob[])),
220 ),
221 ),
222 );
223
224 export const AssetsExportJobProvider = () =>
225 Provider.succeed(AssetsExportJob, {
226 stables: ["name", "assetsExportJobId", "project", "location", "createTime"],
227
228 diff: Effect.fn(function* ({ news, olds, output }) {
229 if (!isResolved(news)) return undefined;
230 const env = yield* GcpEnvironment.current;
231 const payloadChanged =
232 fingerprint({
233 fileFormat: news.fileFormat ?? DEFAULT_FORMAT,
234 filter: news.filter,
235 showHidden: news.showHidden === true,
236 inventory: news.inventory !== false,
237 networkDependencies: news.networkDependencies === true,
238 performanceDataMaxDays: news.performanceDataMaxDays,
239 labels: news.labels ?? {},
240 }) !==
241 fingerprint({
242 fileFormat: olds?.fileFormat ?? output?.fileFormat ?? DEFAULT_FORMAT,
243 filter: olds?.filter ?? output?.filter,
244 showHidden: (olds?.showHidden ?? output?.showHidden) === true,
245 inventory: (olds?.inventory ?? output?.inventory) !== false,
246 networkDependencies: (olds?.networkDependencies ?? output?.networkDependencies) === true,
247 performanceDataMaxDays: olds?.performanceDataMaxDays ?? output?.performanceDataMaxDays,
248 labels: olds?.labels ?? {},
249 });
250 return replaceOnIdentity({
251 previousId: olds?.assetsExportJobId ?? output?.assetsExportJobId,
252 nextId: news.assetsExportJobId ?? olds?.assetsExportJobId ?? output?.assetsExportJobId,
253 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
254 nextLocation: normalizeLocation(
255 news.location ?? olds?.location ?? output?.location,
256 env.region,
257 ),
258 extra: payloadChanged,
259 });
260 }),
261
262 read: Effect.fn(function* ({ id, olds, output }) {
263 const env = yield* GcpEnvironment.current;
264 const assetsExportJobId = yield* toPhysicalId(
265 id,
266 olds?.assetsExportJobId,
267 output?.assetsExportJobId,
268 "exportjob",
269 );
270 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
271 const name = output?.name ?? resourceName(env.project, location, assetsExportJobId);
272 const existing = yield* getByName(name);
273 if (existing === undefined) return undefined;
274 const attrs = toAttrs(existing, env.project, env.region);
275 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
276 }),
277
278 list: () =>
279 Effect.gen(function* () {
280 const env = yield* GcpEnvironment.current;
281 const items = yield* listOwned(env.project, env.region);
282 return items.map((item) => toAttrs(item, env.project, env.region));
283 }),
284
285 reconcile: Effect.fn(function* ({ id, news, output }) {
286 const env = yield* GcpEnvironment.current;
287 const assetsExportJobId = yield* toPhysicalId(
288 id,
289 news.assetsExportJobId,
290 output?.assetsExportJobId,
291 "exportjob",
292 );
293 const location = normalizeLocation(news.location ?? output?.location, env.region);
294 const name = resourceName(env.project, location, assetsExportJobId);
295 const desiredLabels = {
296 ...toLabels(news.labels),
297 ...(yield* createInternalLabels(id)),
298 };
299
300 let current = yield* getByName(output?.name ?? name);
301
302 if (current === undefined) {
303 const created = yield* mc
304 .createProjectsLocationsAssetsExportJobs({
305 parent: locationParent(env.project, location),
306 assetsExportJobId,
307 body: desiredBody(news, desiredLabels),
308 })
309 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
310 if (created !== undefined) {
311 yield* waitForOperation(created);
312 }
313 current = yield* waitUntilExists(getByName(name), name);
314 }
315
316 if (current === undefined) {
317 return yield* new ResourceNotResolved({ resourceName: name });
318 }
319
320 return toAttrs(current, env.project, env.region);
321 }),
322
323 delete: Effect.fn(function* ({ output }) {
324 const operation = yield* mc
325 .deleteProjectsLocationsAssetsExportJobs({ name: output.name })
326 .pipe(
327 Effect.retry({
328 while: (error) => error._tag === "Conflict",
329 times: 8,
330 schedule: Schedule.spaced("2 seconds"),
331 }),
332 Effect.catchTag("NotFound", () => Effect.undefined),
333 );
334 if (operation !== undefined) {
335 yield* waitForOperation(operation, { notFoundOk: true });
336 }
337 yield* waitUntilGone(getByName(output.name), output.name);
338 }),
339 });