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

main
ts 362 lines 12.3 KB
Raw
1 import * as compute from "@distilled.cloud/gcp/compute_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 * as Data from "effect/Data";
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, hasAlchemyLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 encodeDescription,
15 hasOwnershipMarker,
16 lastSegment,
17 normalizeRegion,
18 parseDescription,
19 runRegionOp,
20 sameUrlList,
21 toPhysicalName,
22 } from "./internal.ts";
23
24 const DEFAULT_SOURCE_TYPE = "BACKEND_SERVICE";
25
26 export type RegionHealthSourceType = compute.HealthSourceSourceTypeEnum | (string & {});
27
28 export type RegionHealthSourceProps = {
29 /**
30 * Source name (RFC1035, 1-63 characters). If omitted, a unique name is
31 * generated from the stack, stage, and logical id. Changing it replaces
32 * the source.
33 */
34 sourceName?: string;
35 /**
36 * Region the source lives in. Immutable — changing it replaces the
37 * source. `US-CENTRAL1` is accepted and normalized to `us-central1`.
38 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
39 */
40 region?: string;
41 /**
42 * Optional description. Health sources have no labels field, so Alchemy
43 * ownership is stored in a `[alchemy …]` prefix for `list` / nuke.
44 */
45 description?: string;
46 /**
47 * Source type. The only allowed value is `BACKEND_SERVICE`. Immutable —
48 * changing it replaces the source.
49 * @default "BACKEND_SERVICE"
50 */
51 sourceType?: RegionHealthSourceType;
52 /**
53 * URLs to the source resources. Must be size 1. Must be a regional
54 * BackendService with load balancing scheme `INTERNAL` or
55 * `INTERNAL_MANAGED` in the same region.
56 */
57 sources: string[];
58 /**
59 * URL of the regional HealthAggregationPolicy in the same region.
60 */
61 healthAggregationPolicy: string;
62 };
63
64 export type RegionHealthSource = Resource<
65 "GCP.Compute.RegionHealthSource",
66 RegionHealthSourceProps,
67 {
68 /** Source name. */
69 sourceName: string;
70 /** Project id. */
71 project: string;
72 /** Region short name (`us-central1`). */
73 region: string;
74 /** Source type. */
75 sourceType: string;
76 /** User description with the Alchemy ownership prefix stripped. */
77 description: string | undefined;
78 /** Source resource URLs. */
79 sources: string[];
80 /** Health aggregation policy URL. */
81 healthAggregationPolicy: string | undefined;
82 /** Optimistic-locking fingerprint. */
83 fingerprint: string | undefined;
84 /** Server-defined URL. */
85 selfLink: string | undefined;
86 /** Server-defined URL including the numeric id. */
87 selfLinkWithId: string | undefined;
88 /** Server-assigned numeric id. */
89 sourceId: string | undefined;
90 /** RFC3339 creation timestamp. */
91 creationTimestamp: string | undefined;
92 /** Resource kind. */
93 kind: string | undefined;
94 },
95 never,
96 Providers
97 >;
98
99 /**
100 * A regional Compute Engine health source.
101 *
102 * A health source names the backend resources whose health is aggregated
103 * by a HealthAggregationPolicy (used by composite health checks). Type is
104 * immutable. Sources, aggregation policy, and description update in place
105 * via `regionHealthSources.patch`.
106 *
107 * ### Creating a Health Source
108 * **Example:** Backend-service source
109 * ```typescript
110 * const policy = yield* GCP.Compute.RegionHealthAggregationPolicy(
111 * "Agg",
112 * {},
113 * );
114 * const backend = yield* GCP.Compute.RegionBackendService("Web", {
115 * protocol: "TCP",
116 * loadBalancingScheme: "INTERNAL",
117 * });
118 * const source = yield* GCP.Compute.RegionHealthSource("Src", {
119 * sources: [backend.selfLink],
120 * healthAggregationPolicy: policy.selfLink,
121 * });
122 * ```
123 *
124 * **Example:** Named source
125 * ```typescript
126 * const source = yield* GCP.Compute.RegionHealthSource("Src", {
127 * sourceName: "web-health",
128 * sources: [backend.selfLink],
129 * healthAggregationPolicy: policy.selfLink,
130 * description: "internal backends",
131 * });
132 * ```
133 *
134 * @resource
135 * @category Compute
136 */
137 export const RegionHealthSource = Resource<RegionHealthSource>("GCP.Compute.RegionHealthSource");
138
139 export class RegionHealthSourceNotResolved extends Data.TaggedError(
140 "GCP.Compute.RegionHealthSourceNotResolved",
141 )<{
142 sourceName: string;
143 region: string;
144 }> {}
145
146 const typeOf = (value: string | undefined) => (value ?? DEFAULT_SOURCE_TYPE).toUpperCase();
147
148 const toBackendServiceUrl = (project: string, region: string, value: string | undefined) => {
149 if (value === undefined || value.length === 0) return undefined;
150 if (value.includes("/backendServices/")) return value;
151 return `projects/${project}/regions/${region}/backendServices/${lastSegment(value)}`;
152 };
153
154 const toHealthAggregationPolicyUrl = (
155 project: string,
156 region: string,
157 value: string | undefined,
158 ) => {
159 if (value === undefined || value.length === 0) return undefined;
160 if (value.includes("/healthAggregationPolicies/")) return value;
161 return `projects/${project}/regions/${region}/healthAggregationPolicies/${lastSegment(value)}`;
162 };
163
164 const toAttrs = (
165 source: compute.HealthSource,
166 project: string,
167 ): RegionHealthSource["Attributes"] => {
168 const parsed = parseDescription(source.description);
169 return {
170 sourceName: source.name ?? lastSegment(source.selfLink),
171 project,
172 region: lastSegment(source.region).toLowerCase(),
173 sourceType: typeOf(source.sourceType),
174 description: parsed.description,
175 sources: source.sources ?? [],
176 healthAggregationPolicy: source.healthAggregationPolicy,
177 fingerprint: source.fingerprint,
178 selfLink: source.selfLink,
179 selfLinkWithId: source.selfLinkWithId,
180 sourceId: source.id,
181 creationTimestamp: source.creationTimestamp,
182 kind: source.kind,
183 };
184 };
185
186 const getByName = (project: string, region: string, name: string) =>
187 compute
188 .getRegionHealthSources({ project, region, healthSource: name })
189 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
190
191 const awaitResource = (project: string, region: string, sourceName: string) =>
192 getByName(project, region, sourceName).pipe(
193 Effect.flatMap((source) =>
194 source !== undefined
195 ? Effect.succeed(source)
196 : Effect.fail(new RegionHealthSourceNotResolved({ sourceName, region })),
197 ),
198 Effect.retry({
199 while: (error) => error._tag === "GCP.Compute.RegionHealthSourceNotResolved",
200 times: 8,
201 schedule: Schedule.spaced("1 second"),
202 }),
203 );
204
205 export const RegionHealthSourceProvider = () =>
206 Provider.succeed(RegionHealthSource, {
207 stables: [
208 "sourceName",
209 "project",
210 "region",
211 "sourceType",
212 "sourceId",
213 "selfLink",
214 "creationTimestamp",
215 ],
216
217 diff: Effect.fn(function* ({ news, olds, output }) {
218 if (!isResolved(news)) return undefined;
219 const env = yield* GcpEnvironment.current;
220 const previousName = olds?.sourceName ?? output?.sourceName;
221 const nextName = news.sourceName ?? previousName;
222 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
223 const nextRegion = normalizeRegion(news.region ?? (previousRegion || env.region), env.region);
224 const nameChanged =
225 previousName !== undefined && nextName !== undefined && previousName !== nextName;
226 const regionChanged = previousRegion.length > 0 && previousRegion !== nextRegion;
227 const previousType = typeOf(olds?.sourceType ?? output?.sourceType);
228 const nextType = typeOf(news.sourceType ?? output?.sourceType);
229 if (nameChanged || regionChanged || previousType !== nextType) {
230 return {
231 action: "replace" as const,
232 deleteFirst: !nameChanged || nextName === undefined || nextName === previousName,
233 };
234 }
235 return undefined;
236 }),
237
238 read: Effect.fn(function* ({ id, olds, output }) {
239 const env = yield* GcpEnvironment.current;
240 const sourceName = yield* toPhysicalName(id, olds?.sourceName, output?.sourceName, "source");
241 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
242 const existing = yield* getByName(env.project, region, sourceName);
243 if (existing === undefined) return undefined;
244 const attrs = toAttrs(existing, env.project);
245 const { labels } = parseDescription(existing.description);
246 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
247 }),
248
249 list: () =>
250 Effect.gen(function* () {
251 const env = yield* GcpEnvironment.current;
252 const pages = yield* compute.aggregatedListRegionHealthSources
253 .pages({
254 project: env.project,
255 maxResults: 500,
256 returnPartialSuccess: true,
257 })
258 .pipe(
259 Stream.runCollect,
260 Effect.catchTag("NotFound", () => Effect.succeed([] as never[])),
261 );
262 return Array.from(pages as readonly compute.HealthSourceAggregatedList[]).flatMap((page) =>
263 Object.values(page.items ?? {}).flatMap((scoped) =>
264 (scoped?.healthSources ?? [])
265 .filter((item) => hasOwnershipMarker(item.description))
266 .map((item) => toAttrs(item, env.project)),
267 ),
268 );
269 }),
270
271 reconcile: Effect.fn(function* ({ id, news, output }) {
272 const env = yield* GcpEnvironment.current;
273 const sourceName = yield* toPhysicalName(id, news.sourceName, output?.sourceName, "source");
274 const region = normalizeRegion(news.region ?? output?.region, env.region);
275 const ownership = yield* createInternalLabels(id);
276 const desiredDescription = encodeDescription(ownership, news.description);
277 const sourceType = typeOf(news.sourceType);
278 const sources = news.sources.flatMap((source) => {
279 const url = toBackendServiceUrl(env.project, region, source);
280 return url === undefined ? [] : [url];
281 });
282 const healthAggregationPolicy =
283 toHealthAggregationPolicyUrl(env.project, region, news.healthAggregationPolicy) ??
284 news.healthAggregationPolicy;
285
286 let current = yield* getByName(env.project, region, sourceName);
287
288 if (current === undefined) {
289 yield* runRegionOp(
290 env.project,
291 region,
292 compute.insertRegionHealthSources({
293 project: env.project,
294 region,
295 body: {
296 name: sourceName,
297 description: desiredDescription,
298 sourceType,
299 sources,
300 healthAggregationPolicy,
301 },
302 }),
303 { ignoreAlreadyExists: true },
304 ).pipe(Effect.catchTag("Conflict", () => Effect.undefined));
305 current = yield* awaitResource(env.project, region, sourceName);
306 }
307
308 if (current === undefined) {
309 return yield* new RegionHealthSourceNotResolved({
310 sourceName,
311 region,
312 });
313 }
314
315 const patch: compute.HealthSource = {
316 fingerprint: current.fingerprint,
317 };
318 let dirty = false;
319 if ((current.description ?? "") !== desiredDescription) {
320 patch.description = desiredDescription;
321 dirty = true;
322 }
323 if (!sameUrlList(current.sources, sources)) {
324 patch.sources = sources;
325 dirty = true;
326 }
327 if (lastSegment(current.healthAggregationPolicy) !== lastSegment(healthAggregationPolicy)) {
328 patch.healthAggregationPolicy = healthAggregationPolicy;
329 dirty = true;
330 }
331 if (dirty) {
332 yield* runRegionOp(
333 env.project,
334 region,
335 compute.patchRegionHealthSources({
336 project: env.project,
337 region,
338 healthSource: sourceName,
339 body: patch,
340 }),
341 );
342 current = (yield* getByName(env.project, region, sourceName)) ?? current;
343 }
344
345 return toAttrs(current, env.project);
346 }),
347
348 delete: Effect.fn(function* ({ output }) {
349 const env = yield* GcpEnvironment.current;
350 const region = normalizeRegion(output.region, env.region);
351 yield* runRegionOp(
352 env.project,
353 region,
354 compute.deleteRegionHealthSources({
355 project: env.project,
356 region,
357 healthSource: output.sourceName,
358 }),
359 { ignoreNotFound: true },
360 ).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
361 }),
362 });