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

main
ts 323 lines 10.5 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 fieldMask,
16 fingerprint,
17 hasAlchemyLabelKeys,
18 normalizeLocation,
19 parentOf,
20 parseName,
21 replaceOnIdentity,
22 resourceName,
23 toPhysicalId,
24 userAnnotations,
25 userLabels,
26 waitUntilGone,
27 } from "./internal.ts";
28
29 const COLLECTION = "saas";
30
31 export type SaasLocation = {
32 /** Location id, e.g. `us-central1`. */
33 name?: string;
34 };
35
36 export type SaasCondition = {
37 reason: string | undefined;
38 status: string | undefined;
39 type: string | undefined;
40 message: string | undefined;
41 lastTransitionTime: string | undefined;
42 };
43
44 export type SaaProps = {
45 /**
46 * SaaS id (the `{saas}` segment of
47 * `projects/{project}/locations/{location}/saas/{saas}`). If omitted, a
48 * unique RFC1035 name is generated. Immutable — changing it replaces
49 * the SaaS.
50 */
51 saasId?: string;
52 /**
53 * Region of the SaaS resource (`us-central1`, …). Immutable —
54 * changing it replaces the SaaS. `US-CENTRAL1` is accepted and
55 * normalized to `us-central1`.
56 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
57 */
58 location?: string;
59 /**
60 * Locations the product is offered in. Rollouts use this list to
61 * build a plan. Defaults to the resource location.
62 */
63 locations?: SaasLocation[];
64 /**
65 * User labels. Alchemy ownership labels are merged in automatically.
66 */
67 labels?: Record<string, string>;
68 /**
69 * Unstructured annotations preserved across updates.
70 */
71 annotations?: Record<string, string>;
72 };
73
74 export type Saa = Resource<
75 "GCP.SaasServiceManagement.Saa",
76 SaaProps,
77 {
78 /** Full resource name `projects/{project}/locations/{location}/saas/{saas}`. */
79 name: string;
80 /** SaaS id (last path segment). */
81 saasId: string;
82 /** Project id. */
83 project: string;
84 /** Location id of the resource. */
85 location: string;
86 /** Locations the product is offered in. */
87 locations: SaasLocation[];
88 /** User labels (Alchemy ownership labels stripped). */
89 labels: Record<string, string>;
90 /** User annotations. */
91 annotations: Record<string, string>;
92 /** Server-reported state (`STATE_ACTIVE`, …). */
93 state: string | undefined;
94 /** Server UUID. */
95 uid: string | undefined;
96 /** Server etag. */
97 etag: string | undefined;
98 /** Status conditions. */
99 conditions: SaasCondition[];
100 /** RFC3339 creation timestamp. */
101 createTime: string | undefined;
102 /** RFC3339 last-update timestamp. */
103 updateTime: string | undefined;
104 },
105 never,
106 Providers
107 >;
108
109 /**
110 * An App Lifecycle Manager SaaS product definition.
111 *
112 * A SaaS is the producer-side product that Tenants, UnitKinds, and
113 * Units hang off. `saasId` and `location` replace the resource.
114 * `locations`, labels, and annotations update in place.
115 *
116 * ### Creating a SaaS
117 * **Example:** Generated name
118 * ```typescript
119 * const product = yield* GCP.SaasServiceManagement.Saa("Inventory", {
120 * locations: [{ name: "us-central1" }],
121 * });
122 * ```
123 *
124 * **Example:** Named SaaS with labels
125 * ```typescript
126 * const product = yield* GCP.SaasServiceManagement.Saa("Inventory", {
127 * saasId: "inventory",
128 * locations: [{ name: "us-central1" }, { name: "europe-west1" }],
129 * labels: { env: "prod" },
130 * });
131 * ```
132 *
133 * ### Updating a SaaS
134 * **Example:** Offer an extra region
135 * ```typescript
136 * const product = yield* GCP.SaasServiceManagement.Saa("Inventory", {
137 * saasId: "inventory",
138 * locations: [{ name: "us-central1" }, { name: "us-east1" }],
139 * labels: { env: "prod", role: "saas" },
140 * });
141 * ```
142 *
143 * @resource
144 * @category SaasServiceManagement
145 */
146 export const Saa = Resource<Saa>("GCP.SaasServiceManagement.Saa");
147
148 const desiredLocations = (news: SaaProps, location: string): saasservicemgmt.Location[] => {
149 const listed = news.locations ?? [{ name: location }];
150 return listed.map((item) => ({
151 name: item.name ? normalizeLocation(item.name) : location,
152 }));
153 };
154
155 const toAttrs = (item: saasservicemgmt.Saas, project: string) => {
156 const name = item.name ?? "";
157 const parsed = parseName(name, COLLECTION);
158 return {
159 name,
160 saasId: parsed.id,
161 project: parsed.project || project,
162 location: parsed.location,
163 locations: (item.locations ?? []).map((entry) => ({ name: entry.name })),
164 labels: userLabels(item.labels),
165 annotations: userAnnotations(item.annotations),
166 state: item.state,
167 uid: item.uid,
168 etag: item.etag,
169 conditions: (item.conditions ?? []).map((condition) => ({
170 reason: condition.reason,
171 status: condition.status,
172 type: condition.type,
173 message: condition.message,
174 lastTransitionTime: condition.lastTransitionTime,
175 })),
176 createTime: item.createTime,
177 updateTime: item.updateTime,
178 };
179 };
180
181 const getByName = (name: string) =>
182 name.length === 0
183 ? Effect.undefined
184 : saasservicemgmt
185 .getProjectsLocationsSaas({ name })
186 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
187
188 const listOwned = (project: string, location: string) =>
189 collectPages(
190 saasservicemgmt.listProjectsLocationsSaas.pages({
191 parent: parentOf(project, "-"),
192 pageSize: 1000,
193 }),
194 (page) => page.saas,
195 ).pipe(
196 Effect.map((items) => items.filter((item) => hasAlchemyLabelKeys(item.labels))),
197 Effect.flatMap((items) =>
198 items.length > 0
199 ? Effect.succeed(items)
200 : collectPages(
201 saasservicemgmt.listProjectsLocationsSaas.pages({
202 parent: parentOf(project, location),
203 pageSize: 1000,
204 }),
205 (page) => page.saas,
206 ).pipe(
207 Effect.map((fallback) => fallback.filter((item) => hasAlchemyLabelKeys(item.labels))),
208 ),
209 ),
210 );
211
212 export const SaaProvider = () =>
213 Provider.succeed(Saa, {
214 stables: ["name", "saasId", "project", "location", "uid", "createTime"],
215
216 diff: Effect.fn(function* ({ news, olds, output }) {
217 if (!isResolved(news)) return undefined;
218 const env = yield* GcpEnvironment.current;
219 return replaceOnIdentity({
220 previousId: olds?.saasId ?? output?.saasId,
221 nextId: news.saasId ?? olds?.saasId ?? output?.saasId,
222 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
223 nextLocation: normalizeLocation(
224 news.location ?? olds?.location ?? output?.location ?? env.region,
225 ),
226 });
227 }),
228
229 read: Effect.fn(function* ({ id, olds, output }) {
230 const env = yield* GcpEnvironment.current;
231 const saasId = yield* toPhysicalId(id, olds?.saasId, output?.saasId, "saa");
232 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
233 const name = output?.name ?? resourceName(env.project, location, COLLECTION, saasId);
234 const existing = yield* getByName(name);
235 if (existing === undefined) return undefined;
236 const attrs = toAttrs(existing, env.project);
237 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
238 }),
239
240 list: () =>
241 Effect.gen(function* () {
242 const env = yield* GcpEnvironment.current;
243 const items = yield* listOwned(env.project, env.region);
244 return items.map((item) => toAttrs(item, env.project));
245 }),
246
247 reconcile: Effect.fn(function* ({ id, news, output }) {
248 const env = yield* GcpEnvironment.current;
249 const saasId = yield* toPhysicalId(id, news.saasId, output?.saasId, "saa");
250 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
251 const name = resourceName(env.project, location, COLLECTION, saasId);
252 const desiredLabels = {
253 ...toLabels(news.labels),
254 ...(yield* createInternalLabels(id)),
255 };
256 const locations = desiredLocations(news, location);
257 const annotations = news.annotations;
258
259 let current = yield* getByName(output?.name ?? name);
260
261 if (current === undefined) {
262 const created = yield* saasservicemgmt
263 .createProjectsLocationsSaas({
264 parent: parentOf(env.project, location),
265 saasId,
266 body: {
267 locations,
268 labels: desiredLabels,
269 annotations,
270 },
271 })
272 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
273 // The create response omits server fields such as createTime.
274 current = created === undefined ? undefined : yield* getByName(name);
275 }
276
277 if (current === undefined) {
278 return yield* new ResourceNotResolved({ resourceName: name });
279 }
280
281 const observedLabels = tagRecord(current.labels);
282 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
283 const labelsChanged = upsert.length > 0 || removed.length > 0;
284 const locationsChanged =
285 news.locations !== undefined && fingerprint(current.locations) !== fingerprint(locations);
286 const annotationsChanged =
287 annotations !== undefined &&
288 fingerprint(userAnnotations(current.annotations)) !== fingerprint(annotations);
289 const mask = fieldMask([
290 labelsChanged && "labels",
291 locationsChanged && "locations",
292 annotationsChanged && "annotations",
293 ]);
294
295 if (mask.length > 0) {
296 current = yield* saasservicemgmt.patchProjectsLocationsSaas({
297 name: current.name ?? name,
298 updateMask: mask,
299 body: {
300 name: current.name ?? name,
301 etag: current.etag,
302 locations,
303 labels: desiredLabels,
304 annotations,
305 },
306 });
307 }
308
309 return toAttrs(current, env.project);
310 }),
311
312 delete: Effect.fn(function* ({ output }) {
313 yield* saasservicemgmt.deleteProjectsLocationsSaas({ name: output.name }).pipe(
314 Effect.retry({
315 while: (error) => error._tag === "Conflict",
316 times: 8,
317 schedule: Schedule.spaced("2 seconds"),
318 }),
319 Effect.catchTag("NotFound", () => Effect.void),
320 );
321 yield* waitUntilGone(getByName(output.name), output.name);
322 }),
323 });