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

main
ts 347 lines 11.3 KB
Raw
1 import * as gkehub from "@distilled.cloud/gcp/gkehub_v2";
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 * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels, diffLabels, hasAlchemyLabels, toLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 fieldMask,
15 fingerprint,
16 listLabeledPages,
17 membershipName,
18 normalizeLocation,
19 parseName,
20 replaceOnIdentity,
21 ResourceNotResolved,
22 toPhysicalId,
23 userLabels,
24 waitForOperation,
25 waitUntilExists,
26 waitUntilGone,
27 } from "./internal.ts";
28
29 export type FeatureSpec = gkehub.FeatureSpec;
30 export type FeatureState = gkehub.FeatureState;
31
32 export type MembershipsFeatureProps = {
33 /**
34 * Parent Fleet membership. Full name
35 * `projects/{project}/locations/{location}/memberships/{membership}`
36 * or the membership id (combined with `location`). Immutable —
37 * changing it replaces the feature.
38 */
39 membership: string;
40 /**
41 * Location of the parent membership (`global`, `us-central1`, …).
42 * Used when `membership` is a bare id. Immutable — changing it
43 * replaces the feature. Fleet memberships are typically `global`.
44 * @default "global"
45 */
46 location?: string;
47 /**
48 * Feature id (the `{feature}` segment of
49 * `.../memberships/{membership}/features/{feature}`). Well-known Fleet
50 * Feature names such as `configmanagement`, `servicemesh`, or
51 * `policycontroller`. If omitted, a unique RFC1035 name is generated.
52 * Immutable — changing it replaces the feature.
53 */
54 featureId?: string;
55 /**
56 * Per-feature spec for this membership (Config Management, Service
57 * Mesh, Policy Controller, …).
58 */
59 spec?: FeatureSpec;
60 /**
61 * User labels. Alchemy ownership labels are merged in automatically.
62 */
63 labels?: Record<string, string>;
64 };
65
66 export type MembershipsFeature = Resource<
67 "GCP.GKEHub.MembershipsFeature",
68 MembershipsFeatureProps,
69 {
70 /** Full resource name. */
71 name: string;
72 /** Feature id (last path segment). */
73 featureId: string;
74 /** Parent membership resource name. */
75 membership: string;
76 /** Membership id (last path segment of the parent). */
77 membershipId: string;
78 /** Project id. */
79 project: string;
80 /** Location id. */
81 location: string;
82 /** Per-feature spec. */
83 spec: FeatureSpec | undefined;
84 /** User labels (Alchemy ownership labels stripped). */
85 labels: Record<string, string>;
86 /** Lifecycle of the MembershipFeature resource. */
87 lifecycleState: string | undefined;
88 /** High-level Feature state. */
89 state: FeatureState | undefined;
90 /** RFC3339 creation timestamp. */
91 createTime: string | undefined;
92 /** RFC3339 last-update timestamp. */
93 updateTime: string | undefined;
94 /** RFC3339 deletion timestamp. */
95 deleteTime: string | undefined;
96 },
97 never,
98 Providers
99 >;
100
101 /**
102 * A GKE Hub MembershipFeature — the per-membership settings for a Fleet
103 * Feature such as Config Management or Service Mesh.
104 *
105 * Changing `featureId`, `membership`, or `location` replaces the
106 * feature. Spec and labels update in place.
107 *
108 * ### Creating a Membership Feature
109 * **Example:** Config Management on a membership
110 * ```typescript
111 * const feature = yield* GCP.GKEHub.MembershipsFeature("ConfigSync", {
112 * membership: "projects/my-project/locations/global/memberships/app",
113 * featureId: "configmanagement",
114 * spec: {
115 * configmanagement: {
116 * configSync: { enabled: true, sourceFormat: "unstructured" },
117 * },
118 * },
119 * labels: { env: "prod" },
120 * });
121 * ```
122 *
123 * **Example:** Service Mesh
124 * ```typescript
125 * const feature = yield* GCP.GKEHub.MembershipsFeature("Mesh", {
126 * membership: membership.name,
127 * featureId: "servicemesh",
128 * spec: {
129 * servicemesh: { management: "MANAGEMENT_AUTOMATIC" },
130 * },
131 * });
132 * ```
133 *
134 * ### Updating a Membership Feature
135 * **Example:** Spec and labels
136 * ```typescript
137 * // Same logical id, changed props: updated in place.
138 * const feature = yield* GCP.GKEHub.MembershipsFeature("ConfigSync", {
139 * membership: membership.name,
140 * featureId: "configmanagement",
141 * spec: {
142 * configmanagement: {
143 * configSync: { enabled: true, preventDrift: true },
144 * },
145 * },
146 * labels: { env: "prod", team: "platform" },
147 * });
148 * ```
149 *
150 * @resource
151 * @category GKEHub
152 */
153 export const MembershipsFeature = Resource<MembershipsFeature>("GCP.GKEHub.MembershipsFeature");
154
155 const resourceName = (membership: string, featureId: string) =>
156 `${membership}/features/${featureId}`;
157
158 const toAttrs = (item: gkehub.MembershipFeature, project: string) => {
159 const name = item.name ?? "";
160 const parsed = parseName(name, "features");
161 return {
162 name,
163 featureId: parsed.id,
164 membership: parsed.parent,
165 membershipId: parsed.membershipId,
166 project: parsed.project || project,
167 location: parsed.location,
168 spec: item.spec,
169 labels: userLabels(item.labels),
170 lifecycleState: item.lifecycleState?.state,
171 state: item.state,
172 createTime: item.createTime,
173 updateTime: item.updateTime,
174 deleteTime: item.deleteTime,
175 };
176 };
177
178 const getByName = (name: string) =>
179 gkehub
180 .getProjectsLocationsMembershipsFeatures({ name })
181 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
182
183 const listChildren = (parent: string) =>
184 listLabeledPages(
185 gkehub.listProjectsLocationsMembershipsFeatures.pages({
186 parent,
187 pageSize: 1000,
188 }),
189 (page) => page.membershipFeatures,
190 (item) => item.labels,
191 );
192
193 const listOwned = (project: string) =>
194 gkehub.listProjectsLocations.pages({ name: `projects/${project}`, pageSize: 100 }).pipe(
195 Stream.flatMap((page) => Stream.fromIterable(page.locations ?? [])),
196 Stream.map((location) => location.locationId),
197 Stream.filter(
198 (locationId): locationId is string => locationId !== undefined && locationId.length > 0,
199 ),
200 Stream.runCollect,
201 Effect.flatMap((locations) =>
202 Effect.forEach(
203 Array.from(locations),
204 (location) => listChildren(`projects/${project}/locations/${location}/memberships/-`),
205 { concurrency: 4 },
206 ),
207 ),
208 Effect.map((pages) => pages.flat()),
209 );
210
211 export const MembershipsFeatureProvider = () =>
212 Provider.succeed(MembershipsFeature, {
213 stables: [
214 "name",
215 "featureId",
216 "membership",
217 "membershipId",
218 "project",
219 "location",
220 "createTime",
221 ],
222
223 diff: Effect.fn(function* ({ news, olds, output }) {
224 if (!isResolved(news)) return undefined;
225 const env = yield* GcpEnvironment.current;
226 const location = normalizeLocation(news.location ?? olds?.location ?? output?.location);
227 return replaceOnIdentity({
228 previousId: olds?.featureId ?? output?.featureId,
229 nextId: news.featureId ?? olds?.featureId ?? output?.featureId,
230 previousLocation: normalizeLocation(olds?.location ?? output?.location),
231 nextLocation: location,
232 previousParent: olds?.membership ?? output?.membership,
233 nextParent: membershipName(news.membership, env.project, location),
234 });
235 }),
236
237 read: Effect.fn(function* ({ id, olds, output }) {
238 const env = yield* GcpEnvironment.current;
239 const featureId = yield* toPhysicalId(id, olds?.featureId, output?.featureId, "feature");
240 const location = normalizeLocation(olds?.location ?? output?.location);
241 const membership = membershipName(
242 olds?.membership ?? output?.membership ?? "",
243 env.project,
244 location,
245 );
246 const name = output?.name ?? resourceName(membership, featureId);
247 const existing = yield* getByName(name);
248 if (existing === undefined) return undefined;
249 const attrs = toAttrs(existing, env.project);
250 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
251 }),
252
253 list: () =>
254 Effect.gen(function* () {
255 const env = yield* GcpEnvironment.current;
256 const items = yield* listOwned(env.project);
257 return items.map((item) => toAttrs(item, env.project));
258 }),
259
260 reconcile: Effect.fn(function* ({ id, news, output }) {
261 const env = yield* GcpEnvironment.current;
262 const featureId = yield* toPhysicalId(id, news.featureId, output?.featureId, "feature");
263 const location = normalizeLocation(news.location ?? output?.location);
264 const membership = membershipName(news.membership, env.project, location);
265 const name = resourceName(membership, featureId);
266 const desiredLabels = {
267 ...toLabels(news.labels),
268 ...(yield* createInternalLabels(id)),
269 };
270
271 let current = yield* getByName(output?.name ?? name);
272
273 if (current === undefined) {
274 const created = yield* gkehub
275 .createProjectsLocationsMembershipsFeatures({
276 parent: membership,
277 featureId,
278 body: {
279 labels: desiredLabels,
280 spec: news.spec,
281 },
282 })
283 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
284 if (created !== undefined) {
285 // ALREADY_EXISTS (6): a concurrent create won the race.
286 yield* waitForOperation(created).pipe(
287 Effect.catchTag("GCP.OperationFailed", (error) =>
288 error.code === 6 ? Effect.void : Effect.fail(error),
289 ),
290 );
291 }
292 current = yield* waitUntilExists(getByName(name), name);
293 }
294
295 if (current === undefined) {
296 return yield* new ResourceNotResolved({ resourceName: name });
297 }
298
299 const observedLabels = tagRecord(current.labels);
300 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
301 const specChanged =
302 news.spec !== undefined && fingerprint(current.spec) !== fingerprint(news.spec);
303 const mask = fieldMask([
304 (upsert.length > 0 || removed.length > 0) && "labels",
305 specChanged && "spec",
306 ]);
307
308 if (mask.length > 0) {
309 const operation = yield* gkehub.patchProjectsLocationsMembershipsFeatures({
310 name: current.name ?? name,
311 updateMask: mask,
312 body: {
313 labels: desiredLabels,
314 spec: news.spec,
315 },
316 });
317 yield* waitForOperation(operation);
318 current = yield* waitUntilExists(getByName(current.name ?? name), current.name ?? name);
319 }
320
321 return toAttrs(current, env.project);
322 }),
323
324 delete: Effect.fn(function* ({ output }) {
325 const operation = yield* gkehub
326 .deleteProjectsLocationsMembershipsFeatures({
327 name: output.name,
328 })
329 .pipe(
330 Effect.retry({
331 while: (error) => error._tag === "Conflict",
332 times: 8,
333 schedule: Schedule.spaced("2 seconds"),
334 }),
335 Effect.catchTag("NotFound", () => Effect.undefined),
336 );
337 if (operation !== undefined) {
338 // NOT_FOUND (5): the feature was already gone.
339 yield* waitForOperation(operation).pipe(
340 Effect.catchTag("GCP.OperationFailed", (error) =>
341 error.code === 5 ? Effect.void : Effect.fail(error),
342 ),
343 );
344 }
345 yield* waitUntilGone(getByName(output.name), output.name);
346 }),
347 });