@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 319 lines 10.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 * 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 fieldMask,
16 fingerprint,
17 hasOwnershipMarker,
18 lastSegment,
19 locationParent,
20 normalizeLocation,
21 ownedByAlchemy,
22 parseName,
23 parseOwnership,
24 replaceOnIdentity,
25 ResourceNotResolved,
26 toPhysicalId,
27 waitForOperation,
28 waitUntilExists,
29 waitUntilGone,
30 } from "./internal.ts";
31
32 export type SourceType = mc.SourceTypeEnum | (string & {});
33 export type SourceState = mc.SourceStateEnum | (string & {});
34
35 export type SourceProps = {
36 /**
37 * Source id (the `{source}` segment of
38 * `projects/{project}/locations/{location}/sources/{source}`). If
39 * omitted, a unique RFC1035 name is generated. Immutable — changing it
40 * replaces the source.
41 */
42 sourceId?: string;
43 /**
44 * Region (`us-central1`, …). Immutable — changing it replaces the
45 * source. `US-CENTRAL1` is accepted and normalized to `us-central1`.
46 * @default the stack's GCP region (`GCP.Region`, else the profile
47 * region, else `us-central1`)
48 */
49 location?: string;
50 /**
51 * Data source type. Immutable — changing it replaces the source.
52 * @default "SOURCE_TYPE_UPLOAD"
53 */
54 type?: SourceType;
55 /**
56 * User-friendly display name.
57 */
58 displayName?: string;
59 /**
60 * Free-text description. Sources have no labels field, so Alchemy
61 * ownership is stored in a `[alchemy …]` prefix and stripped from
62 * attributes.
63 */
64 description?: string;
65 /**
66 * Information confidence of the source. Higher is more confident.
67 */
68 priority?: number;
69 };
70
71 export type Source = Resource<
72 "GCP.MigrationCenter.Source",
73 SourceProps,
74 {
75 /** Full resource name. */
76 name: string;
77 /** Source id (last path segment). */
78 sourceId: string;
79 /** Project id. */
80 project: string;
81 /** Location id. */
82 location: string;
83 /** Data source type. */
84 type: string | undefined;
85 /** User-friendly display name. */
86 displayName: string | undefined;
87 /** User description with the Alchemy ownership prefix stripped. */
88 description: string | undefined;
89 /** Information confidence. */
90 priority: number | undefined;
91 /** Whether another service manages this source. */
92 managed: boolean | undefined;
93 /** Server-reported state. */
94 state: string | undefined;
95 /** Frames still being processed. */
96 pendingFrameCount: number | undefined;
97 /** Frames that contained errors. */
98 errorFrameCount: number | undefined;
99 /** RFC3339 creation timestamp. */
100 createTime: string | undefined;
101 /** RFC3339 last-update timestamp. */
102 updateTime: string | undefined;
103 },
104 never,
105 Providers
106 >;
107
108 /**
109 * A Migration Center source that streams asset frames into a project.
110 *
111 * Sources have no labels field — Alchemy stamps ownership into the
112 * description so `list` / nuke can find them. `sourceId`, `location`, and
113 * `type` are immutable. Display name, description, and priority update
114 * in place.
115 *
116 * ### Creating a Source
117 * **Example:** Upload source
118 * ```typescript
119 * const source = yield* GCP.MigrationCenter.Source("Inventory", {
120 * type: "SOURCE_TYPE_UPLOAD",
121 * displayName: "rvtools",
122 * });
123 * ```
124 *
125 * **Example:** Discovery-client source
126 * ```typescript
127 * const source = yield* GCP.MigrationCenter.Source("Scanner", {
128 * type: "SOURCE_TYPE_DISCOVERY_CLIENT",
129 * description: "on-prem scanner",
130 * });
131 * ```
132 *
133 * @resource
134 * @category MigrationCenter
135 */
136 export const Source = Resource<Source>("GCP.MigrationCenter.Source");
137
138 const DEFAULT_TYPE: SourceType = "SOURCE_TYPE_UPLOAD";
139
140 const resourceName = (project: string, location: string, sourceId: string) =>
141 `${locationParent(project, location)}/sources/${sourceId}`;
142
143 const toAttrs = (source: mc.Source, project: string, region: string) => {
144 const name = source.name ?? "";
145 const parsed = parseName(name, "sources", region);
146 const ownership = parseOwnership(source.description);
147 return {
148 name,
149 sourceId: parsed.id,
150 project: parsed.project || project,
151 location: parsed.location,
152 type: source.type,
153 displayName: source.displayName,
154 description: ownership.text,
155 priority: source.priority,
156 managed: source.managed,
157 state: source.state,
158 pendingFrameCount: source.pendingFrameCount,
159 errorFrameCount: source.errorFrameCount,
160 createTime: source.createTime,
161 updateTime: source.updateTime,
162 };
163 };
164
165 const getByName = (name: string) =>
166 name.length === 0
167 ? Effect.undefined
168 : mc
169 .getProjectsLocationsSources({ name })
170 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
171
172 const listOwned = (project: string, region: string) =>
173 mc.listProjectsLocationsSources
174 .pages({
175 parent: `projects/${project}/locations/-`,
176 pageSize: 1000,
177 })
178 .pipe(
179 Stream.flatMap((page) => Stream.fromIterable(page.sources ?? [])),
180 Stream.filter((item) => hasOwnershipMarker(item.description)),
181 Stream.runCollect,
182 Effect.map((chunk) => Array.from(chunk)),
183 Effect.catchTag("NotFound", () =>
184 mc.listProjectsLocationsSources
185 .pages({
186 parent: locationParent(project, region),
187 pageSize: 1000,
188 })
189 .pipe(
190 Stream.flatMap((page) => Stream.fromIterable(page.sources ?? [])),
191 Stream.filter((item) => hasOwnershipMarker(item.description)),
192 Stream.runCollect,
193 Effect.map((chunk) => Array.from(chunk)),
194 Effect.catchTag("NotFound", () => Effect.succeed([] as mc.Source[])),
195 ),
196 ),
197 );
198
199 export const SourceProvider = () =>
200 Provider.succeed(Source, {
201 stables: ["name", "sourceId", "project", "location", "createTime"],
202
203 diff: Effect.fn(function* ({ news, olds, output }) {
204 if (!isResolved(news)) return undefined;
205 const env = yield* GcpEnvironment.current;
206 const previousType = olds?.type ?? output?.type ?? DEFAULT_TYPE;
207 const nextType = news.type ?? previousType;
208 return replaceOnIdentity({
209 previousId: olds?.sourceId ?? output?.sourceId,
210 nextId: news.sourceId ?? olds?.sourceId ?? output?.sourceId,
211 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
212 nextLocation: normalizeLocation(
213 news.location ?? olds?.location ?? output?.location,
214 env.region,
215 ),
216 extra: previousType !== nextType,
217 });
218 }),
219
220 read: Effect.fn(function* ({ id, olds, output }) {
221 const env = yield* GcpEnvironment.current;
222 const sourceId = yield* toPhysicalId(id, olds?.sourceId, output?.sourceId, "source");
223 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
224 const name = output?.name ?? resourceName(env.project, location, sourceId);
225 const existing = yield* getByName(name);
226 if (existing === undefined) return undefined;
227 const attrs = toAttrs(existing, env.project, env.region);
228 return (yield* ownedByAlchemy(id, existing.description)) ? attrs : Unowned(attrs);
229 }),
230
231 list: () =>
232 Effect.gen(function* () {
233 const env = yield* GcpEnvironment.current;
234 const items = yield* listOwned(env.project, env.region);
235 return items.map((item) => toAttrs(item, env.project, env.region));
236 }),
237
238 reconcile: Effect.fn(function* ({ id, news, output }) {
239 const env = yield* GcpEnvironment.current;
240 const sourceId = yield* toPhysicalId(id, news.sourceId, output?.sourceId, "source");
241 const location = normalizeLocation(news.location ?? output?.location, env.region);
242 const name = resourceName(env.project, location, sourceId);
243 const ownership = yield* createInternalLabels(id);
244 const description = encodeOwnership(ownership, news.description);
245 const type = news.type ?? DEFAULT_TYPE;
246 const displayName = news.displayName ?? sourceId;
247
248 let current = yield* getByName(output?.name ?? name);
249
250 if (current === undefined) {
251 const created = yield* mc
252 .createProjectsLocationsSources({
253 parent: locationParent(env.project, location),
254 sourceId,
255 body: {
256 type,
257 displayName,
258 description,
259 priority: news.priority,
260 },
261 })
262 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
263 if (created !== undefined) {
264 yield* waitForOperation(created);
265 }
266 current = yield* waitUntilExists(getByName(name), name);
267 }
268
269 if (current === undefined) {
270 return yield* new ResourceNotResolved({ resourceName: name });
271 }
272
273 const descriptionChanged = (current.description ?? "") !== description;
274 const displayNameChanged = (current.displayName ?? "") !== displayName;
275 const priorityChanged = fingerprint(current.priority) !== fingerprint(news.priority);
276 const mask = fieldMask([
277 descriptionChanged && "description",
278 displayNameChanged && "displayName",
279 priorityChanged && "priority",
280 ]);
281
282 if (mask.length > 0) {
283 const operation = yield* mc.patchProjectsLocationsSources({
284 name: current.name ?? name,
285 updateMask: mask,
286 body: {
287 name: current.name ?? name,
288 displayName,
289 description,
290 priority: news.priority,
291 },
292 });
293 yield* waitForOperation(operation);
294 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
295 }
296
297 return toAttrs(current, env.project, env.region);
298 }),
299
300 delete: Effect.fn(function* ({ output }) {
301 const operation = yield* mc.deleteProjectsLocationsSources({ name: output.name }).pipe(
302 Effect.retry({
303 while: (error) => error._tag === "Conflict",
304 times: 10,
305 schedule: Schedule.spaced("3 seconds"),
306 }),
307 Effect.catchTag("NotFound", () => Effect.undefined),
308 );
309 if (operation !== undefined) {
310 yield* waitForOperation(operation, { notFoundOk: true });
311 }
312 yield* waitUntilGone(getByName(output.name), output.name);
313 }),
314 });
315
316 export const sourceNameOf = (value: string, project: string, location: string) =>
317 expandParent(value, project, location, "sources");
318
319 export const sourceIdOf = (name: string) => lastSegment(name);