@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 414 lines 14.1 KB
Raw
1 import * as saasservicemgmt from "@distilled.cloud/gcp/saasservicemgmt_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 { GcpEnvironment } from "../Environment.ts";
10 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
11 import type { Providers } from "../Providers.ts";
12 import {
13 ResourceNotResolved,
14 collectPages,
15 expandName,
16 fieldMask,
17 fingerprint,
18 hasAlchemyLabelKeys,
19 lastSegment,
20 normalizeLocation,
21 parentOf,
22 parseName,
23 replaceOnIdentity,
24 resourceName,
25 sameRef,
26 toPhysicalId,
27 userAnnotations,
28 userLabels,
29 waitUntilGone,
30 } from "./internal.ts";
31
32 const COLLECTION = "unitKinds";
33
34 export type UnitKindBoundaryType = saasservicemgmt.UnitKindBoundaryTypeEnum | (string & {});
35
36 export type UnitKindDependency = {
37 /** UnitKind resource name this kind depends on. Immutable. */
38 unitKind?: string;
39 /** Alias used in variable mappings. */
40 alias?: string;
41 };
42
43 export type UnitKindFromMapping = {
44 outputVariable?: string;
45 dependency?: string;
46 };
47
48 export type UnitKindToMapping = {
49 inputVariable?: string;
50 ignoreForLookup?: boolean;
51 dependency?: string;
52 };
53
54 export type UnitKindVariableMapping = {
55 variable?: string;
56 from?: UnitKindFromMapping;
57 to?: UnitKindToMapping;
58 };
59
60 export type UnitKindProps = {
61 /**
62 * UnitKind id (the `{unitKind}` segment of
63 * `projects/{project}/locations/{location}/unitKinds/{unitKind}`). If
64 * omitted, a unique RFC1035 name is generated. Immutable — changing
65 * it replaces the unit kind.
66 */
67 unitKindId?: string;
68 /**
69 * Region of the unit kind (`us-central1`, …). Immutable — changing it
70 * replaces the unit kind. `US-CENTRAL1` is accepted and normalized to
71 * `us-central1`.
72 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
73 */
74 location?: string;
75 /**
76 * SaaS this unit kind belongs to. Accepts a SaaS id or a full
77 * resource name. Immutable — changing it replaces the unit kind.
78 */
79 saas: string;
80 /**
81 * Default Release used when creating new units of this kind. Accepts
82 * a release id or a full resource name.
83 */
84 defaultRelease?: string;
85 /**
86 * Default flag revisions applied to newly created units.
87 */
88 defaultFlagRevisions?: string[];
89 /**
90 * Other unit kinds this kind depends on. Immutable — changing them
91 * replaces the unit kind.
92 */
93 dependencies?: UnitKindDependency[];
94 /**
95 * Input variable mappings to or from dependencies. Maximum 100.
96 */
97 inputVariableMappings?: UnitKindVariableMapping[];
98 /**
99 * Output variable mappings from this unit kind. Maximum 100.
100 */
101 outputVariableMappings?: UnitKindVariableMapping[];
102 /**
103 * User labels. Alchemy ownership labels are merged in automatically.
104 */
105 labels?: Record<string, string>;
106 /**
107 * Unstructured annotations preserved across updates.
108 */
109 annotations?: Record<string, string>;
110 };
111
112 export type UnitKind = Resource<
113 "GCP.SaasServiceManagement.UnitKind",
114 UnitKindProps,
115 {
116 /** Full resource name `projects/{project}/locations/{location}/unitKinds/{unitKind}`. */
117 name: string;
118 /** UnitKind id (last path segment). */
119 unitKindId: string;
120 /** Project id. */
121 project: string;
122 /** Location id. */
123 location: string;
124 /** SaaS resource name. */
125 saas: string | undefined;
126 /** SaaS id (last path segment). */
127 saasId: string | undefined;
128 /** Default release resource name. */
129 defaultRelease: string | undefined;
130 /** Default flag revisions. */
131 defaultFlagRevisions: ReadonlyArray<string>;
132 /** Declared dependencies. */
133 dependencies: UnitKindDependency[];
134 /** Input variable mappings. */
135 inputVariableMappings: UnitKindVariableMapping[];
136 /** Output variable mappings. */
137 outputVariableMappings: UnitKindVariableMapping[];
138 /** Boundary type reported by the API. */
139 boundaryType: string | undefined;
140 /** User labels (Alchemy ownership labels stripped). */
141 labels: Record<string, string>;
142 /** User annotations. */
143 annotations: Record<string, string>;
144 /** Server UUID. */
145 uid: string | undefined;
146 /** Server etag. */
147 etag: string | undefined;
148 /** RFC3339 creation timestamp. */
149 createTime: string | undefined;
150 /** RFC3339 last-update timestamp. */
151 updateTime: string | undefined;
152 },
153 never,
154 Providers
155 >;
156
157 /**
158 * An App Lifecycle Manager unit kind — the blueprint family that Units
159 * of a SaaS share.
160 *
161 * Units of the same kind follow the same release model and are typically
162 * rolled out together. `unitKindId`, `location`, `saas`, and
163 * `dependencies` replace the unit kind. Default release, mappings,
164 * labels, and annotations update in place.
165 *
166 * ### Creating a UnitKind
167 * **Example:** Kind of a SaaS
168 * ```typescript
169 * const product = yield* GCP.SaasServiceManagement.Saa("Inventory", {
170 * locations: [{ name: "us-central1" }],
171 * });
172 * const kind = yield* GCP.SaasServiceManagement.UnitKind("Store", {
173 * saas: product.name,
174 * labels: { env: "prod" },
175 * });
176 * ```
177 *
178 * ### Updating a UnitKind
179 * **Example:** Point at a default release
180 * ```typescript
181 * const kind = yield* GCP.SaasServiceManagement.UnitKind("Store", {
182 * unitKindId: kind.unitKindId,
183 * saas: product.name,
184 * defaultRelease: release.name,
185 * labels: { env: "prod" },
186 * });
187 * ```
188 *
189 * @resource
190 * @category SaasServiceManagement
191 */
192 export const UnitKind = Resource<UnitKind>("GCP.SaasServiceManagement.UnitKind");
193
194 const expandDependencies = (
195 dependencies: UnitKindDependency[] | undefined,
196 project: string,
197 location: string,
198 ): saasservicemgmt.Dependency[] | undefined =>
199 dependencies?.map((dependency) => ({
200 alias: dependency.alias,
201 unitKind: dependency.unitKind
202 ? expandName(dependency.unitKind, project, location, COLLECTION)
203 : undefined,
204 }));
205
206 const toAttrs = (item: saasservicemgmt.UnitKind, project: string) => {
207 const name = item.name ?? "";
208 const parsed = parseName(name, COLLECTION);
209 return {
210 name,
211 unitKindId: parsed.id,
212 project: parsed.project || project,
213 location: parsed.location,
214 saas: item.saas,
215 saasId: item.saas ? lastSegment(item.saas) : undefined,
216 defaultRelease: item.defaultRelease,
217 defaultFlagRevisions: item.defaultFlagRevisions ?? [],
218 dependencies: (item.dependencies ?? []).map((dependency) => ({
219 unitKind: dependency.unitKind,
220 alias: dependency.alias,
221 })),
222 inputVariableMappings: item.inputVariableMappings ?? [],
223 outputVariableMappings: item.outputVariableMappings ?? [],
224 boundaryType: item.boundaryType,
225 labels: userLabels(item.labels),
226 annotations: userAnnotations(item.annotations),
227 uid: item.uid,
228 etag: item.etag,
229 createTime: item.createTime,
230 updateTime: item.updateTime,
231 };
232 };
233
234 const getByName = (name: string) =>
235 name.length === 0
236 ? Effect.undefined
237 : saasservicemgmt
238 .getProjectsLocationsUnitKinds({ name })
239 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
240
241 const listOwned = (project: string, location: string) =>
242 collectPages(
243 saasservicemgmt.listProjectsLocationsUnitKinds.pages({
244 parent: parentOf(project, "-"),
245 pageSize: 1000,
246 }),
247 (page) => page.unitKinds,
248 ).pipe(
249 Effect.map((items) => items.filter((item) => hasAlchemyLabelKeys(item.labels))),
250 Effect.flatMap((items) =>
251 items.length > 0
252 ? Effect.succeed(items)
253 : collectPages(
254 saasservicemgmt.listProjectsLocationsUnitKinds.pages({
255 parent: parentOf(project, location),
256 pageSize: 1000,
257 }),
258 (page) => page.unitKinds,
259 ).pipe(
260 Effect.map((fallback) => fallback.filter((item) => hasAlchemyLabelKeys(item.labels))),
261 ),
262 ),
263 );
264
265 export const UnitKindProvider = () =>
266 Provider.succeed(UnitKind, {
267 stables: ["name", "unitKindId", "project", "location", "saasId", "uid", "createTime"],
268
269 diff: Effect.fn(function* ({ news, olds, output }) {
270 if (!isResolved(news)) return undefined;
271 const env = yield* GcpEnvironment.current;
272 return replaceOnIdentity({
273 previousId: olds?.unitKindId ?? output?.unitKindId,
274 nextId: news.unitKindId ?? olds?.unitKindId ?? output?.unitKindId,
275 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
276 nextLocation: normalizeLocation(
277 news.location ?? olds?.location ?? output?.location ?? env.region,
278 ),
279 extra:
280 !sameRef(olds?.saas ?? output?.saas, news.saas) ||
281 (news.dependencies !== undefined &&
282 fingerprint(news.dependencies) !==
283 fingerprint(olds?.dependencies ?? output?.dependencies)),
284 });
285 }),
286
287 read: Effect.fn(function* ({ id, olds, output }) {
288 const env = yield* GcpEnvironment.current;
289 const unitKindId = yield* toPhysicalId(id, olds?.unitKindId, output?.unitKindId, "ukind");
290 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
291 const name = output?.name ?? resourceName(env.project, location, COLLECTION, unitKindId);
292 const existing = yield* getByName(name);
293 if (existing === undefined) return undefined;
294 const attrs = toAttrs(existing, env.project);
295 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
296 }),
297
298 list: () =>
299 Effect.gen(function* () {
300 const env = yield* GcpEnvironment.current;
301 const items = yield* listOwned(env.project, env.region);
302 return items.map((item) => toAttrs(item, env.project));
303 }),
304
305 reconcile: Effect.fn(function* ({ id, news, output }) {
306 const env = yield* GcpEnvironment.current;
307 const unitKindId = yield* toPhysicalId(id, news.unitKindId, output?.unitKindId, "ukind");
308 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
309 const name = resourceName(env.project, location, COLLECTION, unitKindId);
310 const desiredLabels = {
311 ...toLabels(news.labels),
312 ...(yield* createInternalLabels(id)),
313 };
314 const saas = expandName(news.saas, env.project, location, "saas");
315 const defaultRelease =
316 news.defaultRelease === undefined
317 ? undefined
318 : expandName(news.defaultRelease, env.project, location, "releases");
319 const dependencies = expandDependencies(news.dependencies, env.project, location);
320 const annotations = news.annotations;
321
322 let current = yield* getByName(output?.name ?? name);
323
324 if (current === undefined) {
325 const created = yield* saasservicemgmt
326 .createProjectsLocationsUnitKinds({
327 parent: parentOf(env.project, location),
328 unitKindId,
329 body: {
330 saas,
331 defaultRelease,
332 defaultFlagRevisions: news.defaultFlagRevisions,
333 dependencies,
334 inputVariableMappings: news.inputVariableMappings,
335 outputVariableMappings: news.outputVariableMappings,
336 labels: desiredLabels,
337 annotations,
338 },
339 })
340 .pipe(
341 // A Saas created seconds earlier is unreadable here until it
342 // propagates.
343 Effect.retry({
344 while: (error) => error._tag === "SaasNotFound",
345 schedule: Schedule.spaced("2 seconds"),
346 times: 15,
347 }),
348 Effect.catchTag("Conflict", () => getByName(name)),
349 );
350 current = created ?? undefined;
351 }
352
353 if (current === undefined) {
354 return yield* new ResourceNotResolved({ resourceName: name });
355 }
356
357 const observedLabels = tagRecord(current.labels);
358 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
359 const labelsChanged = upsert.length > 0 || removed.length > 0;
360 const annotationsChanged =
361 annotations !== undefined &&
362 fingerprint(userAnnotations(current.annotations)) !== fingerprint(annotations);
363 const defaultReleaseChanged =
364 news.defaultRelease !== undefined && !sameRef(current.defaultRelease, defaultRelease);
365 const flagRevisionsChanged =
366 news.defaultFlagRevisions !== undefined &&
367 fingerprint(current.defaultFlagRevisions) !== fingerprint(news.defaultFlagRevisions);
368 const inputChanged =
369 news.inputVariableMappings !== undefined &&
370 fingerprint(current.inputVariableMappings) !== fingerprint(news.inputVariableMappings);
371 const outputChanged =
372 news.outputVariableMappings !== undefined &&
373 fingerprint(current.outputVariableMappings) !== fingerprint(news.outputVariableMappings);
374 const mask = fieldMask([
375 labelsChanged && "labels",
376 annotationsChanged && "annotations",
377 defaultReleaseChanged && "defaultRelease",
378 flagRevisionsChanged && "defaultFlagRevisions",
379 inputChanged && "inputVariableMappings",
380 outputChanged && "outputVariableMappings",
381 ]);
382
383 if (mask.length > 0) {
384 current = yield* saasservicemgmt.patchProjectsLocationsUnitKinds({
385 name: current.name ?? name,
386 updateMask: mask,
387 body: {
388 name: current.name ?? name,
389 etag: current.etag,
390 defaultRelease,
391 defaultFlagRevisions: news.defaultFlagRevisions,
392 inputVariableMappings: news.inputVariableMappings,
393 outputVariableMappings: news.outputVariableMappings,
394 labels: desiredLabels,
395 annotations,
396 },
397 });
398 }
399
400 return toAttrs(current, env.project);
401 }),
402
403 delete: Effect.fn(function* ({ output }) {
404 yield* saasservicemgmt.deleteProjectsLocationsUnitKinds({ name: output.name }).pipe(
405 Effect.retry({
406 while: (error) => error._tag === "Conflict",
407 times: 8,
408 schedule: Schedule.spaced("2 seconds"),
409 }),
410 Effect.catchTag("NotFound", () => Effect.void),
411 );
412 yield* waitUntilGone(getByName(output.name), output.name);
413 }),
414 });