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

main
ts 373 lines 13 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 = "releases";
33
34 export type ReleaseBlueprint = {
35 /**
36 * URI of the OCI blueprint package. Hostname may be omitted to use
37 * the regional Artifact Registry path. Immutable.
38 */
39 package?: string;
40 /** Actuation engine (`terraform`, `helm`, …). Output-only. */
41 engine?: string;
42 /** Version metadata from the image manifest. Output-only. */
43 version?: string;
44 };
45
46 export type ReleaseVariable = {
47 type?: saasservicemgmt.UnitVariableTypeEnum | (string & {});
48 value?: string;
49 variable?: string;
50 };
51
52 export type ReleaseProps = {
53 /**
54 * Release id (the `{release}` segment of
55 * `projects/{project}/locations/{location}/releases/{release}`). If
56 * omitted, a unique RFC1035 name is generated. Immutable — changing
57 * it replaces the release.
58 */
59 releaseId?: string;
60 /**
61 * Region of the release (`us-central1`, …). Immutable — changing it
62 * replaces the release. `US-CENTRAL1` is accepted and normalized to
63 * `us-central1`.
64 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
65 */
66 location?: string;
67 /**
68 * UnitKind this release belongs to. Accepts a unit kind id or a full
69 * resource name. Immutable — changing it replaces the release.
70 */
71 unitKind: string;
72 /**
73 * Blueprint package that actuates units of this release. `package` is
74 * immutable — changing it replaces the release.
75 */
76 blueprint?: ReleaseBlueprint;
77 /**
78 * Default values for input variables declared on the blueprint.
79 * Maximum 100.
80 */
81 inputVariableDefaults?: ReleaseVariable[];
82 /**
83 * Releases a unit may upgrade from to reach this one. Empty means no
84 * constraint.
85 */
86 upgradeableFromReleases?: string[];
87 /**
88 * User labels. Alchemy ownership labels are merged in automatically.
89 */
90 labels?: Record<string, string>;
91 /**
92 * Unstructured annotations preserved across updates.
93 */
94 annotations?: Record<string, string>;
95 };
96
97 export type Release = Resource<
98 "GCP.SaasServiceManagement.Release",
99 ReleaseProps,
100 {
101 /** Full resource name `projects/{project}/locations/{location}/releases/{release}`. */
102 name: string;
103 /** Release id (last path segment). */
104 releaseId: string;
105 /** Project id. */
106 project: string;
107 /** Location id. */
108 location: string;
109 /** UnitKind resource name. */
110 unitKind: string | undefined;
111 /** UnitKind id (last path segment). */
112 unitKindId: string | undefined;
113 /** Blueprint package. */
114 blueprint: ReleaseBlueprint | undefined;
115 /** Input variable defaults. */
116 inputVariableDefaults: ReleaseVariable[];
117 /** Input variables declared on the blueprint. */
118 inputVariables: ReleaseVariable[];
119 /** Output variables declared on the blueprint. */
120 outputVariables: ReleaseVariable[];
121 /** Releases this one may be upgraded from. */
122 upgradeableFromReleases: ReadonlyArray<string>;
123 /** User labels (Alchemy ownership labels stripped). */
124 labels: Record<string, string>;
125 /** User annotations. */
126 annotations: Record<string, string>;
127 /** Server UUID. */
128 uid: string | undefined;
129 /** Server etag. */
130 etag: string | undefined;
131 /** RFC3339 creation timestamp. */
132 createTime: string | undefined;
133 /** RFC3339 last-update timestamp. */
134 updateTime: string | undefined;
135 },
136 never,
137 Providers
138 >;
139
140 /**
141 * An App Lifecycle Manager release — a version of a UnitKind packaged
142 * as an OCI blueprint.
143 *
144 * `releaseId`, `location`, `unitKind`, and `blueprint.package` replace
145 * the release. Input variable defaults, upgrade constraints, labels,
146 * and annotations update in place.
147 *
148 * ### Creating a Release
149 * **Example:** Blueprint release
150 * ```typescript
151 * const release = yield* GCP.SaasServiceManagement.Release("V1", {
152 * unitKind: kind.name,
153 * blueprint: { package: "us-central1-docker.pkg.dev/proj/blueprints/store:v1" },
154 * labels: { env: "prod" },
155 * });
156 * ```
157 *
158 * ### Updating a Release
159 * **Example:** Default input variables
160 * ```typescript
161 * const release = yield* GCP.SaasServiceManagement.Release("V1", {
162 * releaseId: release.releaseId,
163 * unitKind: kind.name,
164 * blueprint: { package: "us-central1-docker.pkg.dev/proj/blueprints/store:v1" },
165 * inputVariableDefaults: [{ variable: "region", type: "STRING", value: "us-central1" }],
166 * });
167 * ```
168 *
169 * @resource
170 * @category SaasServiceManagement
171 */
172 export const Release = Resource<Release>("GCP.SaasServiceManagement.Release");
173
174 const expandUpgradeable = (values: string[] | undefined, project: string, location: string) =>
175 values?.map((value) => expandName(value, project, location, COLLECTION));
176
177 const toAttrs = (item: saasservicemgmt.Release, project: string) => {
178 const name = item.name ?? "";
179 const parsed = parseName(name, COLLECTION);
180 return {
181 name,
182 releaseId: parsed.id,
183 project: parsed.project || project,
184 location: parsed.location,
185 unitKind: item.unitKind,
186 unitKindId: item.unitKind ? lastSegment(item.unitKind) : undefined,
187 blueprint: item.blueprint
188 ? {
189 package: item.blueprint.package,
190 engine: item.blueprint.engine,
191 version: item.blueprint.version,
192 }
193 : undefined,
194 inputVariableDefaults: item.inputVariableDefaults ?? [],
195 inputVariables: item.inputVariables ?? [],
196 outputVariables: item.outputVariables ?? [],
197 upgradeableFromReleases: item.releaseRequirements?.upgradeableFromReleases ?? [],
198 labels: userLabels(item.labels),
199 annotations: userAnnotations(item.annotations),
200 uid: item.uid,
201 etag: item.etag,
202 createTime: item.createTime,
203 updateTime: item.updateTime,
204 };
205 };
206
207 const getByName = (name: string) =>
208 name.length === 0
209 ? Effect.undefined
210 : saasservicemgmt
211 .getProjectsLocationsReleases({ name })
212 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
213
214 const listOwned = (project: string, location: string) =>
215 collectPages(
216 saasservicemgmt.listProjectsLocationsReleases.pages({
217 parent: parentOf(project, "-"),
218 pageSize: 1000,
219 }),
220 (page) => page.releases,
221 ).pipe(
222 Effect.map((items) => items.filter((item) => hasAlchemyLabelKeys(item.labels))),
223 Effect.flatMap((items) =>
224 items.length > 0
225 ? Effect.succeed(items)
226 : collectPages(
227 saasservicemgmt.listProjectsLocationsReleases.pages({
228 parent: parentOf(project, location),
229 pageSize: 1000,
230 }),
231 (page) => page.releases,
232 ).pipe(
233 Effect.map((fallback) => fallback.filter((item) => hasAlchemyLabelKeys(item.labels))),
234 ),
235 ),
236 );
237
238 export const ReleaseProvider = () =>
239 Provider.succeed(Release, {
240 stables: ["name", "releaseId", "project", "location", "unitKindId", "uid", "createTime"],
241
242 diff: Effect.fn(function* ({ news, olds, output }) {
243 if (!isResolved(news)) return undefined;
244 const env = yield* GcpEnvironment.current;
245 const previousPackage = olds?.blueprint?.package ?? output?.blueprint?.package;
246 const nextPackage = news.blueprint?.package ?? previousPackage;
247 return replaceOnIdentity({
248 previousId: olds?.releaseId ?? output?.releaseId,
249 nextId: news.releaseId ?? olds?.releaseId ?? output?.releaseId,
250 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
251 nextLocation: normalizeLocation(
252 news.location ?? olds?.location ?? output?.location ?? env.region,
253 ),
254 extra:
255 !sameRef(olds?.unitKind ?? output?.unitKind, news.unitKind) ||
256 (previousPackage !== undefined &&
257 nextPackage !== undefined &&
258 previousPackage !== nextPackage),
259 });
260 }),
261
262 read: Effect.fn(function* ({ id, olds, output }) {
263 const env = yield* GcpEnvironment.current;
264 const releaseId = yield* toPhysicalId(id, olds?.releaseId, output?.releaseId, "rel");
265 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
266 const name = output?.name ?? resourceName(env.project, location, COLLECTION, releaseId);
267 const existing = yield* getByName(name);
268 if (existing === undefined) return undefined;
269 const attrs = toAttrs(existing, env.project);
270 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
271 }),
272
273 list: () =>
274 Effect.gen(function* () {
275 const env = yield* GcpEnvironment.current;
276 const items = yield* listOwned(env.project, env.region);
277 return items.map((item) => toAttrs(item, env.project));
278 }),
279
280 reconcile: Effect.fn(function* ({ id, news, output }) {
281 const env = yield* GcpEnvironment.current;
282 const releaseId = yield* toPhysicalId(id, news.releaseId, output?.releaseId, "rel");
283 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
284 const name = resourceName(env.project, location, COLLECTION, releaseId);
285 const desiredLabels = {
286 ...toLabels(news.labels),
287 ...(yield* createInternalLabels(id)),
288 };
289 const unitKind = expandName(news.unitKind, env.project, location, "unitKinds");
290 const upgradeableFromReleases = expandUpgradeable(
291 news.upgradeableFromReleases,
292 env.project,
293 location,
294 );
295 const annotations = news.annotations;
296 const blueprint = news.blueprint ? { package: news.blueprint.package } : undefined;
297
298 let current = yield* getByName(output?.name ?? name);
299
300 if (current === undefined) {
301 const created = yield* saasservicemgmt
302 .createProjectsLocationsReleases({
303 parent: parentOf(env.project, location),
304 releaseId,
305 body: {
306 unitKind,
307 blueprint,
308 inputVariableDefaults: news.inputVariableDefaults,
309 releaseRequirements:
310 upgradeableFromReleases === undefined ? undefined : { upgradeableFromReleases },
311 labels: desiredLabels,
312 annotations,
313 },
314 })
315 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
316 current = created ?? undefined;
317 }
318
319 if (current === undefined) {
320 return yield* new ResourceNotResolved({ resourceName: name });
321 }
322
323 const observedLabels = tagRecord(current.labels);
324 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
325 const labelsChanged = upsert.length > 0 || removed.length > 0;
326 const annotationsChanged =
327 annotations !== undefined &&
328 fingerprint(userAnnotations(current.annotations)) !== fingerprint(annotations);
329 const defaultsChanged =
330 news.inputVariableDefaults !== undefined &&
331 fingerprint(current.inputVariableDefaults) !== fingerprint(news.inputVariableDefaults);
332 const requirementsChanged =
333 news.upgradeableFromReleases !== undefined &&
334 fingerprint(current.releaseRequirements?.upgradeableFromReleases) !==
335 fingerprint(upgradeableFromReleases);
336 const mask = fieldMask([
337 labelsChanged && "labels",
338 annotationsChanged && "annotations",
339 defaultsChanged && "inputVariableDefaults",
340 requirementsChanged && "releaseRequirements",
341 ]);
342
343 if (mask.length > 0) {
344 current = yield* saasservicemgmt.patchProjectsLocationsReleases({
345 name: current.name ?? name,
346 updateMask: mask,
347 body: {
348 name: current.name ?? name,
349 etag: current.etag,
350 inputVariableDefaults: news.inputVariableDefaults,
351 releaseRequirements:
352 upgradeableFromReleases === undefined ? undefined : { upgradeableFromReleases },
353 labels: desiredLabels,
354 annotations,
355 },
356 });
357 }
358
359 return toAttrs(current, env.project);
360 }),
361
362 delete: Effect.fn(function* ({ output }) {
363 yield* saasservicemgmt.deleteProjectsLocationsReleases({ name: output.name }).pipe(
364 Effect.retry({
365 while: (error) => error._tag === "Conflict",
366 times: 8,
367 schedule: Schedule.spaced("2 seconds"),
368 }),
369 Effect.catchTag("NotFound", () => Effect.void),
370 );
371 yield* waitUntilGone(getByName(output.name), output.name);
372 }),
373 });