@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 414 lines 13.9 KB
Raw
1 import * as developerconnect from "@distilled.cloud/gcp/developerconnect_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 { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 compact,
13 expandParent,
14 fingerprint,
15 listAtLocation,
16 listLabeledPages,
17 normalizeLocation,
18 parentOf,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 toPhysicalId,
23 userAnnotations,
24 userLabels,
25 waitForOperation,
26 waitUntilExists,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type ArtifactConfig = {
31 /**
32 * URI of the artifact that is deployed (without tag or digest), e.g.
33 * `us-docker.pkg.dev/{project}/{repo}/image`. Immutable per entry.
34 */
35 uri?: string;
36 /**
37 * Artifact Analysis project that stores provenance.
38 */
39 googleArtifactAnalysis?: {
40 projectId?: string;
41 };
42 /**
43 * Artifact Registry package that stores the artifact.
44 */
45 googleArtifactRegistry?: {
46 artifactRegistryPackage?: string;
47 projectId?: string;
48 };
49 };
50
51 export type InsightsConfigProjects = {
52 /**
53 * Project ids to track with this InsightsConfig.
54 */
55 projectIds?: string[];
56 };
57
58 export type InsightsConfigProps = {
59 /**
60 * Insights config id (the `{insightsConfig}` segment of
61 * `projects/{project}/locations/{location}/insightsConfigs/{insightsConfig}`).
62 * If omitted, a unique RFC1035 name is generated. Immutable —
63 * changing it replaces the config.
64 */
65 insightsConfigId?: string;
66 /**
67 * Region (`us-central1`, `us-east1`, …). Immutable — changing it
68 * replaces the config. `US-CENTRAL1` is accepted and normalized to
69 * `us-central1`.
70 * @default the stack's GCP region (`GCP.Region`, else the profile
71 * region, else `us-central1`)
72 */
73 location?: string;
74 /**
75 * App Hub application to associate, as
76 * `projects/{project}/locations/{location}/applications/{application}`
77 * or the application id (combined with `location`).
78 */
79 appHubApplication?: string;
80 /**
81 * Projects to track with this InsightsConfig.
82 */
83 projects?: InsightsConfigProjects;
84 /**
85 * Artifact configurations of the artifacts that are deployed.
86 */
87 artifactConfigs?: ArtifactConfig[];
88 /**
89 * User labels. Alchemy ownership labels are merged in automatically.
90 */
91 labels?: Record<string, string>;
92 /**
93 * User annotations (AIP-148).
94 */
95 annotations?: Record<string, string>;
96 };
97
98 export type InsightsConfig = Resource<
99 "GCP.DeveloperConnect.InsightsConfig",
100 InsightsConfigProps,
101 {
102 /** Full resource name. */
103 name: string;
104 /** Insights config id (last path segment). */
105 insightsConfigId: string;
106 /** Project id. */
107 project: string;
108 /** Location id. */
109 location: string;
110 /** App Hub application resource name, if any. */
111 appHubApplication: string | undefined;
112 /** Projects tracked by this config. */
113 projects: InsightsConfigProjects | undefined;
114 /** Artifact configurations. */
115 artifactConfigs: ArtifactConfig[];
116 /** User labels (Alchemy ownership labels stripped). */
117 labels: Record<string, string>;
118 /** User annotations. */
119 annotations: Record<string, string>;
120 /** Runtime configurations discovered for the application. */
121 runtimeConfigs: developerconnect.RuntimeConfig[] | undefined;
122 /** Server-reported state (`PENDING`, `COMPLETE`, `ERROR`). */
123 state: string | undefined;
124 /** True while Developer Connect is reconciling the config. */
125 reconciling: boolean;
126 /** Setup errors, if any. */
127 errors: developerconnect.Status[] | undefined;
128 /** RFC3339 creation timestamp. */
129 createTime: string | undefined;
130 /** RFC3339 last-update timestamp. */
131 updateTime: string | undefined;
132 },
133 never,
134 Providers
135 >;
136
137 /**
138 * A Developer Connect InsightsConfig — the SDLC event hub that ties an
139 * App Hub application, runtime environments, and deployed artifacts
140 * together.
141 *
142 * Changing `insightsConfigId`, `location`, `appHubApplication`, or
143 * `projects` replaces the config. Labels, annotations, and artifact configs
144 * update in place.
145 *
146 * ### Creating an Insights Config
147 * **Example:** Generated name
148 * ```typescript
149 * const insights = yield* GCP.DeveloperConnect.InsightsConfig("Sdlc", {
150 * projects: { projectIds: ["{project}"] },
151 * labels: { env: "prod" },
152 * });
153 * ```
154 *
155 * **Example:** App Hub application and artifacts
156 * ```typescript
157 * const insights = yield* GCP.DeveloperConnect.InsightsConfig("Sdlc", {
158 * insightsConfigId: "app-sdlc",
159 * appHubApplication: application.name,
160 * artifactConfigs: [
161 * {
162 * uri: "us-docker.pkg.dev/{project}/{repo}/image",
163 * googleArtifactRegistry: {
164 * projectId: "{project}",
165 * artifactRegistryPackage: "image",
166 * },
167 * },
168 * ],
169 * labels: { env: "prod" },
170 * });
171 * ```
172 *
173 * ### Updating an Insights Config
174 * **Example:** Labels on tracked projects
175 * ```typescript
176 * // Same logical id as before; only the changed props differ.
177 * const insights = yield* GCP.DeveloperConnect.InsightsConfig("Sdlc", {
178 * insightsConfigId: "app-sdlc",
179 * projects: { projectIds: ["{project}"] },
180 * labels: { env: "prod", team: "platform" },
181 * });
182 * ```
183 *
184 * @resource
185 * @category DeveloperConnect
186 */
187 export const InsightsConfig = Resource<InsightsConfig>("GCP.DeveloperConnect.InsightsConfig");
188
189 const resourceName = (project: string, location: string, insightsConfigId: string) =>
190 `projects/${project}/locations/${location}/insightsConfigs/${insightsConfigId}`;
191
192 const toArtifactConfigs = (
193 configs: ArtifactConfig[] | undefined,
194 ): developerconnect.ArtifactConfig[] | undefined => {
195 if (configs === undefined) return undefined;
196 return configs.map((config) =>
197 compact({
198 uri: config.uri,
199 googleArtifactAnalysis: config.googleArtifactAnalysis
200 ? compact({ projectId: config.googleArtifactAnalysis.projectId })
201 : undefined,
202 googleArtifactRegistry: config.googleArtifactRegistry
203 ? compact({
204 artifactRegistryPackage: config.googleArtifactRegistry.artifactRegistryPackage,
205 projectId: config.googleArtifactRegistry.projectId,
206 })
207 : undefined,
208 }),
209 );
210 };
211
212 const fromArtifactConfigs = (
213 configs: developerconnect.ArtifactConfig[] | undefined,
214 ): ArtifactConfig[] =>
215 (configs ?? []).map((config) =>
216 compact({
217 uri: config.uri,
218 googleArtifactAnalysis: config.googleArtifactAnalysis
219 ? compact({ projectId: config.googleArtifactAnalysis.projectId })
220 : undefined,
221 googleArtifactRegistry: config.googleArtifactRegistry
222 ? compact({
223 artifactRegistryPackage: config.googleArtifactRegistry.artifactRegistryPackage,
224 projectId: config.googleArtifactRegistry.projectId,
225 })
226 : undefined,
227 }),
228 );
229
230 const toAttrs = (item: developerconnect.InsightsConfig, project: string, region: string) => {
231 const name = item.name ?? "";
232 const parsed = parseName(name, "insightsConfigs", region);
233 return {
234 name,
235 insightsConfigId: parsed.id,
236 project: parsed.project || project,
237 location: parsed.location,
238 appHubApplication: item.appHubApplication,
239 projects: item.projects ? compact({ projectIds: item.projects.projectIds }) : undefined,
240 artifactConfigs: fromArtifactConfigs(item.artifactConfigs),
241 labels: userLabels(item.labels),
242 annotations: userAnnotations(item.annotations),
243 runtimeConfigs: item.runtimeConfigs,
244 state: item.state,
245 reconciling: item.reconciling === true,
246 errors: item.errors,
247 createTime: item.createTime,
248 updateTime: item.updateTime,
249 };
250 };
251
252 const getByName = (name: string) =>
253 developerconnect
254 .getProjectsLocationsInsightsConfigs({ name })
255 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
256
257 const listOwned = (project: string, region: string) =>
258 listAtLocation(project, region, (parent) =>
259 listLabeledPages(
260 developerconnect.listProjectsLocationsInsightsConfigs.pages({
261 parent,
262 pageSize: 1000,
263 }),
264 (page) => page.insightsConfigs,
265 (item) => item.labels,
266 ),
267 );
268
269 export const InsightsConfigProvider = () =>
270 Provider.succeed(InsightsConfig, {
271 stables: ["name", "insightsConfigId", "project", "location", "createTime"],
272
273 diff: Effect.fn(function* ({ news, olds, output }) {
274 if (!isResolved(news)) return undefined;
275 const env = yield* GcpEnvironment.current;
276 return replaceOnIdentity({
277 previousId: olds?.insightsConfigId ?? output?.insightsConfigId,
278 nextId: news.insightsConfigId ?? olds?.insightsConfigId ?? output?.insightsConfigId,
279 previousLocation: normalizeLocation(olds?.location ?? output?.location, env.region),
280 nextLocation: normalizeLocation(
281 news.location ?? olds?.location ?? output?.location,
282 env.region,
283 ),
284 // The API rejects patches to the tracked scope ("Projects cannot be
285 // updated"), so a new App Hub application or project set replaces.
286 extra:
287 olds !== undefined &&
288 ((olds.appHubApplication ?? "") !== (news.appHubApplication ?? "") ||
289 fingerprint(olds.projects?.projectIds ?? []) !==
290 fingerprint(news.projects?.projectIds ?? [])),
291 });
292 }),
293
294 read: Effect.fn(function* ({ id, olds, output }) {
295 const env = yield* GcpEnvironment.current;
296 const insightsConfigId = yield* toPhysicalId(
297 id,
298 olds?.insightsConfigId,
299 output?.insightsConfigId,
300 "insightsconfig",
301 );
302 const location = normalizeLocation(olds?.location ?? output?.location, env.region);
303 const name = output?.name ?? resourceName(env.project, location, insightsConfigId);
304 const existing = yield* getByName(name);
305 if (existing === undefined) return undefined;
306 const attrs = toAttrs(existing, env.project, env.region);
307 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
308 }),
309
310 list: () =>
311 Effect.gen(function* () {
312 const env = yield* GcpEnvironment.current;
313 const items = yield* listOwned(env.project, env.region);
314 return items.map((item) => toAttrs(item, env.project, env.region));
315 }),
316
317 reconcile: Effect.fn(function* ({ id, news, output }) {
318 const env = yield* GcpEnvironment.current;
319 const insightsConfigId = yield* toPhysicalId(
320 id,
321 news.insightsConfigId,
322 output?.insightsConfigId,
323 "insightsconfig",
324 );
325 const location = normalizeLocation(news.location ?? output?.location, env.region);
326 const name = resourceName(env.project, location, insightsConfigId);
327 const desiredLabels = {
328 ...toLabels(news.labels),
329 ...(yield* createInternalLabels(id)),
330 };
331 const annotations = news.annotations;
332 const appHubApplication =
333 news.appHubApplication === undefined
334 ? undefined
335 : expandParent(news.appHubApplication, env.project, location, "applications");
336 const body = compact({
337 appHubApplication,
338 projects: news.projects ? compact({ projectIds: news.projects.projectIds }) : undefined,
339 artifactConfigs: toArtifactConfigs(news.artifactConfigs),
340 labels: desiredLabels,
341 annotations,
342 });
343
344 let current = yield* getByName(output?.name ?? name);
345
346 if (current === undefined) {
347 const created = yield* developerconnect
348 .createProjectsLocationsInsightsConfigs({
349 parent: parentOf(env.project, location),
350 insightsConfigId,
351 body,
352 })
353 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
354 if (created !== undefined) {
355 yield* waitForOperation(created);
356 }
357 current = yield* waitUntilExists(getByName(name), name);
358 }
359
360 if (current === undefined) {
361 return yield* new ResourceNotResolved({ resourceName: name });
362 }
363
364 const observedLabels = tagRecord(current.labels);
365 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
366 const changed =
367 upsert.length > 0 ||
368 removed.length > 0 ||
369 fingerprint(userAnnotations(current.annotations)) !==
370 fingerprint(userAnnotations(annotations)) ||
371 fingerprint(fromArtifactConfigs(current.artifactConfigs)) !==
372 fingerprint(news.artifactConfigs ?? []);
373
374 if (changed) {
375 const operation = yield* developerconnect
376 .patchProjectsLocationsInsightsConfigs({
377 name: current.name ?? name,
378 body: compact({
379 ...body,
380 appHubApplication: undefined,
381 projects: undefined,
382 }),
383 })
384 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
385 if (operation === undefined) {
386 const created = yield* developerconnect
387 .createProjectsLocationsInsightsConfigs({
388 parent: parentOf(env.project, location),
389 insightsConfigId,
390 body,
391 })
392 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
393 if (created !== undefined) {
394 yield* waitForOperation(created);
395 }
396 } else {
397 yield* waitForOperation(operation);
398 }
399 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
400 }
401
402 return toAttrs(current, env.project, env.region);
403 }),
404
405 delete: Effect.fn(function* ({ output }) {
406 const operation = yield* developerconnect
407 .deleteProjectsLocationsInsightsConfigs({ name: output.name })
408 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
409 if (operation !== undefined) {
410 yield* waitForOperation(operation, { notFoundOk: true });
411 }
412 yield* waitUntilGone(getByName(output.name), output.name);
413 }),
414 });