@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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