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

main
ts 367 lines 12.6 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_AGGREGATION = "NO_AGGREGATION";
25
26 export type RegionHealthCheckServiceAggregationPolicy =
27 | compute.HealthCheckServiceHealthStatusAggregationPolicyEnum
28 | (string & {});
29
30 export type RegionHealthCheckServiceProps = {
31 /**
32 * Service name (RFC1035, 1-63 characters). If omitted, a unique name is
33 * generated from the stack, stage, and logical id. Changing it replaces
34 * the service.
35 */
36 serviceName?: string;
37 /**
38 * Region the service lives in. Immutable — changing it replaces the
39 * service. `US-CENTRAL1` is accepted and normalized to `us-central1`.
40 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
41 */
42 region?: string;
43 /**
44 * Optional description. Health check services have no labels field, so
45 * Alchemy ownership is stored in a `[alchemy …]` prefix for `list` /
46 * nuke.
47 */
48 description?: string;
49 /**
50 * Regional health-check URLs. Must have at least one and at most 10.
51 * Health checks must use `USE_SERVING_PORT` or `USE_FIXED_PORT`.
52 */
53 healthChecks: string[];
54 /**
55 * Network endpoint group URLs (at most 100). Regional NEGs must be in
56 * zones of this region.
57 */
58 networkEndpointGroups?: string[];
59 /**
60 * Notification endpoint URLs (at most 10). Must be regional and in the
61 * same region.
62 */
63 notificationEndpoints?: string[];
64 /**
65 * How results from multiple health checks for the same endpoint are
66 * aggregated (`AND` or `NO_AGGREGATION`).
67 * @default "NO_AGGREGATION"
68 */
69 healthStatusAggregationPolicy?: RegionHealthCheckServiceAggregationPolicy;
70 };
71
72 export type RegionHealthCheckService = Resource<
73 "GCP.Compute.RegionHealthCheckService",
74 RegionHealthCheckServiceProps,
75 {
76 /** Service name. */
77 serviceName: string;
78 /** Project id. */
79 project: string;
80 /** Region short name (`us-central1`). */
81 region: string;
82 /** User description with the Alchemy ownership prefix stripped. */
83 description: string | undefined;
84 /** Attached health-check URLs. */
85 healthChecks: string[];
86 /** Attached NEG URLs. */
87 networkEndpointGroups: string[];
88 /** Attached notification endpoint URLs. */
89 notificationEndpoints: string[];
90 /** Aggregation policy. */
91 healthStatusAggregationPolicy: string;
92 /** Optimistic-locking fingerprint. */
93 fingerprint: string | undefined;
94 /** Server-defined URL. */
95 selfLink: string | undefined;
96 /** Server-assigned numeric id. */
97 serviceId: string | undefined;
98 /** RFC3339 creation timestamp. */
99 creationTimestamp: string | undefined;
100 /** Resource kind. */
101 kind: string | undefined;
102 },
103 never,
104 Providers
105 >;
106
107 /**
108 * A regional Compute Engine Health Check as a Service (HCSS) resource.
109 *
110 * Health check services publish endpoint health from NEGs to notification
111 * endpoints. Name and region are immutable. Health checks, NEGs,
112 * notification endpoints, aggregation policy, and description update in
113 * place via `regionHealthCheckServices.patch`.
114 *
115 * ### Creating a Health Check Service
116 * **Example:** Generated name with a regional HTTP health check
117 * ```typescript
118 * const check = yield* GCP.Compute.RegionHealthCheck("api", {
119 * httpHealthCheck: { port: 80, portSpecification: "USE_FIXED_PORT" },
120 * });
121 * const service = yield* GCP.Compute.RegionHealthCheckService("Hcss", {
122 * healthChecks: [check.selfLink],
123 * description: "endpoint health",
124 * });
125 * ```
126 *
127 * **Example:** AND aggregation
128 * ```typescript
129 * const service = yield* GCP.Compute.RegionHealthCheckService("Hcss", {
130 * healthChecks: [check.selfLink],
131 * healthStatusAggregationPolicy: "AND",
132 * });
133 * ```
134 *
135 * @resource
136 * @category Compute
137 */
138 export const RegionHealthCheckService = Resource<RegionHealthCheckService>(
139 "GCP.Compute.RegionHealthCheckService",
140 );
141
142 export class RegionHealthCheckServiceNotResolved extends Data.TaggedError(
143 "GCP.Compute.RegionHealthCheckServiceNotResolved",
144 )<{
145 serviceName: string;
146 region: string;
147 }> {}
148
149 const aggregationOf = (value: string | undefined) => (value ?? DEFAULT_AGGREGATION).toUpperCase();
150
151 const toAttrs = (
152 service: compute.HealthCheckService,
153 project: string,
154 ): RegionHealthCheckService["Attributes"] => {
155 const parsed = parseDescription(service.description);
156 return {
157 serviceName: service.name ?? lastSegment(service.selfLink),
158 project,
159 region: lastSegment(service.region).toLowerCase(),
160 description: parsed.description,
161 healthChecks: service.healthChecks ?? [],
162 networkEndpointGroups: service.networkEndpointGroups ?? [],
163 notificationEndpoints: service.notificationEndpoints ?? [],
164 healthStatusAggregationPolicy: aggregationOf(service.healthStatusAggregationPolicy),
165 fingerprint: service.fingerprint,
166 selfLink: service.selfLink,
167 serviceId: service.id,
168 creationTimestamp: service.creationTimestamp,
169 kind: service.kind,
170 };
171 };
172
173 const getByName = (project: string, region: string, name: string) =>
174 compute
175 .getRegionHealthCheckServices({
176 project,
177 region,
178 healthCheckService: name,
179 })
180 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
181
182 const awaitResource = (project: string, region: string, serviceName: string) =>
183 getByName(project, region, serviceName).pipe(
184 Effect.flatMap((service) =>
185 service !== undefined
186 ? Effect.succeed(service)
187 : Effect.fail(new RegionHealthCheckServiceNotResolved({ serviceName, region })),
188 ),
189 Effect.retry({
190 while: (error) => error._tag === "GCP.Compute.RegionHealthCheckServiceNotResolved",
191 times: 8,
192 schedule: Schedule.spaced("1 second"),
193 }),
194 );
195
196 export const RegionHealthCheckServiceProvider = () =>
197 Provider.succeed(RegionHealthCheckService, {
198 stables: ["serviceName", "project", "region", "serviceId", "selfLink", "creationTimestamp"],
199
200 diff: Effect.fn(function* ({ news, olds, output }) {
201 if (!isResolved(news)) return undefined;
202 const env = yield* GcpEnvironment.current;
203 const previousName = olds?.serviceName ?? output?.serviceName;
204 const nextName = news.serviceName ?? previousName;
205 const previousRegion = normalizeRegion(olds?.region ?? output?.region, env.region);
206 const nextRegion = normalizeRegion(news.region ?? (previousRegion || env.region), env.region);
207 const nameChanged =
208 previousName !== undefined && nextName !== undefined && previousName !== nextName;
209 const regionChanged = previousRegion.length > 0 && previousRegion !== nextRegion;
210 if (nameChanged || regionChanged) {
211 return {
212 action: "replace" as const,
213 deleteFirst: !nameChanged || nextName === undefined || nextName === previousName,
214 };
215 }
216 return undefined;
217 }),
218
219 read: Effect.fn(function* ({ id, olds, output }) {
220 const env = yield* GcpEnvironment.current;
221 const serviceName = yield* toPhysicalName(
222 id,
223 olds?.serviceName,
224 output?.serviceName,
225 "service",
226 );
227 const region = normalizeRegion(olds?.region ?? output?.region, env.region);
228 const existing = yield* getByName(env.project, region, serviceName);
229 if (existing === undefined) return undefined;
230 const attrs = toAttrs(existing, env.project);
231 const { labels } = parseDescription(existing.description);
232 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
233 }),
234
235 list: () =>
236 Effect.gen(function* () {
237 const env = yield* GcpEnvironment.current;
238 const pages = yield* compute.aggregatedListRegionHealthCheckServices
239 .pages({
240 project: env.project,
241 maxResults: 500,
242 returnPartialSuccess: true,
243 })
244 .pipe(
245 Stream.runCollect,
246 Effect.catchTag("NotFound", () => Effect.succeed([] as never[])),
247 );
248 return Array.from(pages as readonly compute.HealthCheckServiceAggregatedList[]).flatMap(
249 (page) =>
250 Object.values(page.items ?? {}).flatMap((scoped) =>
251 (scoped?.resources ?? [])
252 .filter((item) => hasOwnershipMarker(item.description))
253 .map((item) => toAttrs(item, env.project)),
254 ),
255 );
256 }),
257
258 reconcile: Effect.fn(function* ({ id, news, output }) {
259 const env = yield* GcpEnvironment.current;
260 const serviceName = yield* toPhysicalName(
261 id,
262 news.serviceName,
263 output?.serviceName,
264 "service",
265 );
266 const region = normalizeRegion(news.region ?? output?.region, env.region);
267 const ownership = yield* createInternalLabels(id);
268 const desiredDescription = encodeDescription(ownership, news.description);
269 const aggregation = aggregationOf(news.healthStatusAggregationPolicy);
270 const healthChecks = news.healthChecks;
271 const networkEndpointGroups = news.networkEndpointGroups ?? [];
272 const notificationEndpoints = news.notificationEndpoints ?? [];
273
274 let current = yield* getByName(env.project, region, serviceName);
275
276 if (current === undefined) {
277 yield* runRegionOp(
278 env.project,
279 region,
280 compute.insertRegionHealthCheckServices({
281 project: env.project,
282 region,
283 body: {
284 name: serviceName,
285 description: desiredDescription,
286 healthChecks,
287 networkEndpointGroups:
288 networkEndpointGroups.length > 0 ? networkEndpointGroups : undefined,
289 notificationEndpoints:
290 notificationEndpoints.length > 0 ? notificationEndpoints : undefined,
291 healthStatusAggregationPolicy: aggregation,
292 },
293 }),
294 { ignoreAlreadyExists: true },
295 ).pipe(Effect.catchTag("Conflict", () => Effect.undefined));
296 current = yield* awaitResource(env.project, region, serviceName);
297 }
298
299 if (current === undefined) {
300 return yield* new RegionHealthCheckServiceNotResolved({
301 serviceName,
302 region,
303 });
304 }
305
306 const patch: compute.HealthCheckService = {
307 fingerprint: current.fingerprint,
308 };
309 let dirty = false;
310 if ((current.description ?? "") !== desiredDescription) {
311 patch.description = desiredDescription;
312 dirty = true;
313 }
314 if (!sameUrlList(current.healthChecks, healthChecks)) {
315 patch.healthChecks = healthChecks;
316 dirty = true;
317 }
318 if (
319 news.networkEndpointGroups !== undefined &&
320 !sameUrlList(current.networkEndpointGroups, networkEndpointGroups)
321 ) {
322 patch.networkEndpointGroups = networkEndpointGroups;
323 dirty = true;
324 }
325 if (
326 news.notificationEndpoints !== undefined &&
327 !sameUrlList(current.notificationEndpoints, notificationEndpoints)
328 ) {
329 patch.notificationEndpoints = notificationEndpoints;
330 dirty = true;
331 }
332 if (aggregationOf(current.healthStatusAggregationPolicy) !== aggregation) {
333 patch.healthStatusAggregationPolicy = aggregation;
334 dirty = true;
335 }
336 if (dirty) {
337 yield* runRegionOp(
338 env.project,
339 region,
340 compute.patchRegionHealthCheckServices({
341 project: env.project,
342 region,
343 healthCheckService: serviceName,
344 body: patch,
345 }),
346 );
347 current = (yield* getByName(env.project, region, serviceName)) ?? current;
348 }
349
350 return toAttrs(current, env.project);
351 }),
352
353 delete: Effect.fn(function* ({ output }) {
354 const env = yield* GcpEnvironment.current;
355 const region = normalizeRegion(output.region, env.region);
356 yield* runRegionOp(
357 env.project,
358 region,
359 compute.deleteRegionHealthCheckServices({
360 project: env.project,
361 region,
362 healthCheckService: output.serviceName,
363 }),
364 { ignoreNotFound: true },
365 ).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
366 }),
367 });