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

main
ts 411 lines 13.3 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 = "units";
33
34 export type UnitManagementMode = saasservicemgmt.UnitManagementModeEnum | (string & {});
35
36 export type UnitMaintenanceSettings = {
37 /** Pin the unit to its current release until this RFC3339 timestamp. */
38 pinnedUntilTime?: string;
39 };
40
41 export type UnitVariable = {
42 type?: saasservicemgmt.UnitVariableTypeEnum | (string & {});
43 value?: string;
44 variable?: string;
45 };
46
47 export type UnitDependency = {
48 unit?: string;
49 alias?: string;
50 };
51
52 export type UnitCondition = {
53 lastTransitionTime: string | undefined;
54 status: string | undefined;
55 type: string | undefined;
56 message: string | undefined;
57 reason: string | undefined;
58 };
59
60 export type UnitProps = {
61 /**
62 * Unit id (the `{unit}` segment of
63 * `projects/{project}/locations/{location}/units/{unit}`). If omitted,
64 * a unique RFC1035 name is generated. Immutable — changing it
65 * replaces the unit.
66 */
67 unitId?: string;
68 /**
69 * Region of the unit (`us-central1`, …). Immutable — changing it
70 * replaces the unit. `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 * UnitKind this unit belongs to. Accepts a unit kind id or a full
77 * resource name. Immutable — changing it replaces the unit.
78 */
79 unitKind?: string;
80 /**
81 * Tenant this unit belongs to. Accepts a tenant id or a full resource
82 * name. Immutable — changing it replaces the unit.
83 */
84 tenant?: string;
85 /**
86 * Whether the unit lifecycle is user- or system-managed. Immutable —
87 * changing it replaces the unit.
88 */
89 managementMode?: UnitManagementMode;
90 /**
91 * Maintenance pin. Updates in place.
92 */
93 maintenance?: UnitMaintenanceSettings;
94 /**
95 * User labels. Alchemy ownership labels are merged in automatically.
96 */
97 labels?: Record<string, string>;
98 /**
99 * Unstructured annotations preserved across updates.
100 */
101 annotations?: Record<string, string>;
102 };
103
104 export type Unit = Resource<
105 "GCP.SaasServiceManagement.Unit",
106 UnitProps,
107 {
108 /** Full resource name `projects/{project}/locations/{location}/units/{unit}`. */
109 name: string;
110 /** Unit id (last path segment). */
111 unitId: string;
112 /** Project id. */
113 project: string;
114 /** Location id. */
115 location: string;
116 /** UnitKind resource name. */
117 unitKind: string | undefined;
118 /** UnitKind id (last path segment). */
119 unitKindId: string | undefined;
120 /** Tenant resource name. */
121 tenant: string | undefined;
122 /** Tenant id (last path segment). */
123 tenantId: string | undefined;
124 /** Management mode. */
125 managementMode: string | undefined;
126 /** System-managed state. */
127 systemManagedState: string | undefined;
128 /** Current release resource name. */
129 release: string | undefined;
130 /** Lifecycle state. */
131 state: string | undefined;
132 /** Maintenance pin. */
133 maintenance: UnitMaintenanceSettings | undefined;
134 /** Input variables currently deployed. */
135 inputVariables: UnitVariable[];
136 /** Output variables from actuation. */
137 outputVariables: UnitVariable[];
138 /** Dependencies of this unit. */
139 dependencies: UnitDependency[];
140 /** Units that depend on this unit. */
141 dependents: UnitDependency[];
142 /** Conditions. */
143 conditions: UnitCondition[];
144 /** Ongoing unit operations. */
145 ongoingOperations: ReadonlyArray<string>;
146 /** Pending unit operations. */
147 pendingOperations: ReadonlyArray<string>;
148 /** Flag revisions in use. */
149 flagRevisions: ReadonlyArray<string>;
150 /** User labels (Alchemy ownership labels stripped). */
151 labels: Record<string, string>;
152 /** User annotations. */
153 annotations: Record<string, string>;
154 /** Server UUID. */
155 uid: string | undefined;
156 /** Server etag. */
157 etag: string | undefined;
158 /** RFC3339 creation timestamp. */
159 createTime: string | undefined;
160 /** RFC3339 last-update timestamp. */
161 updateTime: string | undefined;
162 },
163 never,
164 Providers
165 >;
166
167 /**
168 * An App Lifecycle Manager unit — one deployable instance of a UnitKind.
169 *
170 * A unit is actuated by a blueprint engine (Terraform, Helm, …) under
171 * the hood. `unitId`, `location`, `unitKind`, `tenant`, and
172 * `managementMode` replace the unit. Maintenance pins, labels, and
173 * annotations update in place.
174 *
175 * ### Creating a Unit
176 * **Example:** User-managed unit
177 * ```typescript
178 * const unit = yield* GCP.SaasServiceManagement.Unit("Store1", {
179 * unitKind: kind.name,
180 * tenant: tenant.name,
181 * managementMode: "MANAGEMENT_MODE_USER",
182 * labels: { env: "prod" },
183 * });
184 * ```
185 *
186 * ### Updating a Unit
187 * **Example:** Pin maintenance
188 * ```typescript
189 * const unit = yield* GCP.SaasServiceManagement.Unit("Store1", {
190 * unitId: unit.unitId,
191 * unitKind: kind.name,
192 * maintenance: { pinnedUntilTime: "2030-01-01T00:00:00Z" },
193 * });
194 * ```
195 *
196 * @resource
197 * @category SaasServiceManagement
198 */
199 export const Unit = Resource<Unit>("GCP.SaasServiceManagement.Unit");
200
201 const toAttrs = (item: saasservicemgmt.Unit, project: string) => {
202 const name = item.name ?? "";
203 const parsed = parseName(name, COLLECTION);
204 return {
205 name,
206 unitId: parsed.id,
207 project: parsed.project || project,
208 location: parsed.location,
209 unitKind: item.unitKind,
210 unitKindId: item.unitKind ? lastSegment(item.unitKind) : undefined,
211 tenant: item.tenant,
212 tenantId: item.tenant ? lastSegment(item.tenant) : undefined,
213 managementMode: item.managementMode,
214 systemManagedState: item.systemManagedState,
215 release: item.release,
216 state: item.state,
217 maintenance: item.maintenance
218 ? { pinnedUntilTime: item.maintenance.pinnedUntilTime }
219 : undefined,
220 inputVariables: item.inputVariables ?? [],
221 outputVariables: item.outputVariables ?? [],
222 dependencies: item.dependencies ?? [],
223 dependents: item.dependents ?? [],
224 conditions: (item.conditions ?? []).map((condition) => ({
225 lastTransitionTime: condition.lastTransitionTime,
226 status: condition.status,
227 type: condition.type,
228 message: condition.message,
229 reason: condition.reason,
230 })),
231 ongoingOperations: item.ongoingOperations ?? [],
232 pendingOperations: item.pendingOperations ?? [],
233 flagRevisions: item.flagRevisions ?? [],
234 labels: userLabels(item.labels),
235 annotations: userAnnotations(item.annotations),
236 uid: item.uid,
237 etag: item.etag,
238 createTime: item.createTime,
239 updateTime: item.updateTime,
240 };
241 };
242
243 const getByName = (name: string) =>
244 name.length === 0
245 ? Effect.undefined
246 : saasservicemgmt
247 .getProjectsLocationsUnits({ name })
248 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
249
250 const listOwned = (project: string, location: string) =>
251 collectPages(
252 saasservicemgmt.listProjectsLocationsUnits.pages({
253 parent: parentOf(project, "-"),
254 pageSize: 1000,
255 }),
256 (page) => page.units,
257 ).pipe(
258 Effect.map((items) => items.filter((item) => hasAlchemyLabelKeys(item.labels))),
259 Effect.flatMap((items) =>
260 items.length > 0
261 ? Effect.succeed(items)
262 : collectPages(
263 saasservicemgmt.listProjectsLocationsUnits.pages({
264 parent: parentOf(project, location),
265 pageSize: 1000,
266 }),
267 (page) => page.units,
268 ).pipe(
269 Effect.map((fallback) => fallback.filter((item) => hasAlchemyLabelKeys(item.labels))),
270 ),
271 ),
272 );
273
274 export const UnitProvider = () =>
275 Provider.succeed(Unit, {
276 stables: [
277 "name",
278 "unitId",
279 "project",
280 "location",
281 "unitKindId",
282 "tenantId",
283 "uid",
284 "createTime",
285 ],
286
287 diff: Effect.fn(function* ({ news, olds, output }) {
288 if (!isResolved(news)) return undefined;
289 const env = yield* GcpEnvironment.current;
290 const previousMode = olds?.managementMode ?? output?.managementMode;
291 const nextMode = news.managementMode ?? previousMode;
292 return replaceOnIdentity({
293 previousId: olds?.unitId ?? output?.unitId,
294 nextId: news.unitId ?? olds?.unitId ?? output?.unitId,
295 previousLocation: normalizeLocation(olds?.location ?? output?.location ?? env.region),
296 nextLocation: normalizeLocation(
297 news.location ?? olds?.location ?? output?.location ?? env.region,
298 ),
299 extra:
300 (news.unitKind !== undefined &&
301 !sameRef(olds?.unitKind ?? output?.unitKind, news.unitKind)) ||
302 (news.tenant !== undefined && !sameRef(olds?.tenant ?? output?.tenant, news.tenant)) ||
303 (previousMode !== undefined && nextMode !== undefined && previousMode !== nextMode),
304 });
305 }),
306
307 read: Effect.fn(function* ({ id, olds, output }) {
308 const env = yield* GcpEnvironment.current;
309 const unitId = yield* toPhysicalId(id, olds?.unitId, output?.unitId, "unit");
310 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
311 const name = output?.name ?? resourceName(env.project, location, COLLECTION, unitId);
312 const existing = yield* getByName(name);
313 if (existing === undefined) return undefined;
314 const attrs = toAttrs(existing, env.project);
315 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
316 }),
317
318 list: () =>
319 Effect.gen(function* () {
320 const env = yield* GcpEnvironment.current;
321 const items = yield* listOwned(env.project, env.region);
322 return items.map((item) => toAttrs(item, env.project));
323 }),
324
325 reconcile: Effect.fn(function* ({ id, news, output }) {
326 const env = yield* GcpEnvironment.current;
327 const unitId = yield* toPhysicalId(id, news.unitId, output?.unitId, "unit");
328 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
329 const name = resourceName(env.project, location, COLLECTION, unitId);
330 const desiredLabels = {
331 ...toLabels(news.labels),
332 ...(yield* createInternalLabels(id)),
333 };
334 const unitKind =
335 news.unitKind === undefined
336 ? undefined
337 : expandName(news.unitKind, env.project, location, "unitKinds");
338 const tenant =
339 news.tenant === undefined
340 ? undefined
341 : expandName(news.tenant, env.project, location, "tenants");
342 const annotations = news.annotations;
343
344 let current = yield* getByName(output?.name ?? name);
345
346 if (current === undefined) {
347 const created = yield* saasservicemgmt
348 .createProjectsLocationsUnits({
349 parent: parentOf(env.project, location),
350 unitId,
351 body: {
352 unitKind,
353 tenant,
354 managementMode: news.managementMode,
355 maintenance: news.maintenance,
356 labels: desiredLabels,
357 annotations,
358 },
359 })
360 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
361 current = created ?? undefined;
362 }
363
364 if (current === undefined) {
365 return yield* new ResourceNotResolved({ resourceName: name });
366 }
367
368 const observedLabels = tagRecord(current.labels);
369 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
370 const labelsChanged = upsert.length > 0 || removed.length > 0;
371 const annotationsChanged =
372 annotations !== undefined &&
373 fingerprint(userAnnotations(current.annotations)) !== fingerprint(annotations);
374 const maintenanceChanged =
375 news.maintenance !== undefined &&
376 fingerprint(current.maintenance) !== fingerprint(news.maintenance);
377 const mask = fieldMask([
378 labelsChanged && "labels",
379 annotationsChanged && "annotations",
380 maintenanceChanged && "maintenance",
381 ]);
382
383 if (mask.length > 0) {
384 current = yield* saasservicemgmt.patchProjectsLocationsUnits({
385 name: current.name ?? name,
386 updateMask: mask,
387 body: {
388 name: current.name ?? name,
389 etag: current.etag,
390 maintenance: news.maintenance,
391 labels: desiredLabels,
392 annotations,
393 },
394 });
395 }
396
397 return toAttrs(current, env.project);
398 }),
399
400 delete: Effect.fn(function* ({ output }) {
401 yield* saasservicemgmt.deleteProjectsLocationsUnits({ name: output.name }).pipe(
402 Effect.retry({
403 while: (error) => error._tag === "Conflict",
404 times: 8,
405 schedule: Schedule.spaced("2 seconds"),
406 }),
407 Effect.catchTag("NotFound", () => Effect.void),
408 );
409 yield* waitUntilGone(getByName(output.name), output.name);
410 }),
411 });