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