@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 290 lines 8.78 KB
Raw
1 import * as monitoring from "@distilled.cloud/gcp/monitoring_v3";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
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 encodeDisplayName,
15 hasOwnershipMarker,
16 lastSegment,
17 parentOf,
18 parseMarker,
19 } from "./ownership.ts";
20
21 const MAX_DISPLAY_NAME_LENGTH = 512;
22
23 export type GroupProps = {
24 /**
25 * Human-readable display name. If omitted, a unique name is generated
26 * from the stack, stage, and logical id. Groups have no labels field,
27 * so Alchemy stamps ownership into this value for `list` / nuke.
28 */
29 displayName?: string;
30 /**
31 * Monitoring filter matching member resources (for example
32 * `resource.metadata.region="us-central1"`).
33 */
34 filter: string;
35 /**
36 * Parent group resource name
37 * (`projects/{project}/groups/{group}`). Empty means a root group.
38 */
39 parentName?: string;
40 /**
41 * When true, members are treated as a cluster for extra analysis.
42 * @default false
43 */
44 isCluster?: boolean;
45 };
46
47 export type Group = Resource<
48 "GCP.Monitoring.Group",
49 GroupProps,
50 {
51 /** Full resource name `projects/{project}/groups/{group}`. */
52 name: string;
53 /** Server-assigned group id (last path segment). */
54 groupId: string;
55 /** Project id. */
56 project: string;
57 /** Human-readable display name (ownership marker stripped). */
58 displayName: string | undefined;
59 /** Membership filter. */
60 filter: string;
61 /** Parent group resource name, or empty for a root group. */
62 parentName: string;
63 /** Whether members are treated as a cluster. */
64 isCluster: boolean;
65 },
66 never,
67 Providers
68 >;
69
70 /**
71 * A Cloud Monitoring group — a dynamic collection of monitored
72 * resources selected by a filter.
73 *
74 * Group ids are assigned by the API. Groups have no labels field, so
75 * Alchemy stamps ownership into `displayName` (`[alchemy
76 * alchemy-stack=… alchemy-stage=… alchemy-id=…]`) so `list` /
77 * `pnpm nuke:gcp` can find them. Display name, filter, parent, and
78 * cluster flag update in place.
79 *
80 * ### Creating a Group
81 * **Example:** Root group of GCE instances in a region
82 * ```typescript
83 * const group = yield* GCP.Monitoring.Group("Prod", {
84 * displayName: "production instances",
85 * filter: 'resource.metadata.region="us-central1"',
86 * });
87 * ```
88 *
89 * **Example:** Nested group
90 * ```typescript
91 * const parent = yield* GCP.Monitoring.Group("Prod", {
92 * filter: 'resource.metadata.region="us-central1"',
93 * });
94 * const child = yield* GCP.Monitoring.Group("Workers", {
95 * filter: 'resource.metadata.tag="worker"',
96 * parentName: parent.name,
97 * });
98 * ```
99 *
100 * ### Updating a Group
101 * **Example:** Retarget the filter and mark as a cluster
102 * ```typescript
103 * const group = yield* GCP.Monitoring.Group("Prod", {
104 * displayName: "production instances",
105 * filter: 'resource.metadata.region="us-east1"',
106 * isCluster: true,
107 * });
108 * ```
109 *
110 * @resource
111 * @category Monitoring
112 */
113 export const Group = Resource<Group>("GCP.Monitoring.Group");
114
115 export class GroupNotResolved extends Data.TaggedError("GCP.Monitoring.GroupNotResolved")<{
116 resourceName: string;
117 }> {}
118
119 const toDisplayName = (id: string, displayName: string | undefined, existing?: string) =>
120 Effect.gen(function* () {
121 return (
122 displayName ??
123 existing ??
124 (yield* createPhysicalName({
125 id,
126 maxLength: MAX_DISPLAY_NAME_LENGTH,
127 lowercase: true,
128 }))
129 );
130 });
131
132 const toAttrs = (group: monitoring.Group, project: string) => {
133 const name = group.name ?? "";
134 const parsed = parseMarker(group.displayName);
135 return {
136 name,
137 groupId: lastSegment(name),
138 project,
139 displayName: parsed.rest,
140 filter: group.filter ?? "",
141 parentName: group.parentName ?? "",
142 isCluster: group.isCluster === true,
143 };
144 };
145
146 const getByName = (name: string) =>
147 monitoring.getProjectsGroups({ name }).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
148
149 const listPages = (project: string) =>
150 monitoring.listProjectsGroups
151 .pages({
152 name: parentOf(project),
153 pageSize: 1000,
154 })
155 .pipe(
156 Stream.flatMap((page) => Stream.fromIterable(page.group ?? [])),
157 Stream.runCollect,
158 Effect.map((chunk) => Array.from(chunk)),
159 Effect.catchTag("NotFound", () => Effect.succeed([])),
160 );
161
162 const listOwned = (project: string) =>
163 Effect.gen(function* () {
164 const groups = yield* listPages(project);
165 return groups
166 .filter((group) => hasOwnershipMarker(group.displayName))
167 .map((group) => toAttrs(group, project));
168 });
169
170 const findOwned = (project: string, id: string) =>
171 Effect.gen(function* () {
172 const groups = yield* listPages(project);
173 for (const group of groups) {
174 if (yield* hasAlchemyLabels(id, parseMarker(group.displayName).labels)) {
175 return group;
176 }
177 }
178 return undefined;
179 });
180
181 const observe = (project: string, id: string, name: string | undefined) =>
182 Effect.gen(function* () {
183 if (name !== undefined) {
184 const existing = yield* getByName(name);
185 if (existing !== undefined) return existing;
186 }
187 return yield* findOwned(project, id);
188 });
189
190 /**
191 * Monitoring answers 409 "Too many concurrent edits to the project
192 * configuration" while another write to the project's monitoring config is
193 * in flight; it clears within seconds.
194 */
195 const retryConcurrentEdits = <A, E extends { readonly _tag: string }, R>(
196 effect: Effect.Effect<A, E, R>,
197 ) =>
198 effect.pipe(
199 Effect.retry({
200 while: (error) => error._tag === "Conflict",
201 times: 8,
202 schedule: Schedule.exponential("500 millis"),
203 }),
204 );
205
206 export const GroupProvider = () =>
207 Provider.succeed(Group, {
208 stables: ["name", "groupId", "project"],
209
210 read: Effect.fn(function* ({ id, output }) {
211 const env = yield* GcpEnvironment.current;
212 const existing = yield* observe(env.project, id, output?.name);
213 if (existing === undefined) return undefined;
214 const attrs = toAttrs(existing, env.project);
215 return (yield* hasAlchemyLabels(id, parseMarker(existing.displayName).labels))
216 ? attrs
217 : Unowned(attrs);
218 }),
219
220 list: () =>
221 Effect.gen(function* () {
222 const env = yield* GcpEnvironment.current;
223 return yield* listOwned(env.project);
224 }),
225
226 reconcile: Effect.fn(function* ({ id, news, output }) {
227 const env = yield* GcpEnvironment.current;
228 const displayName = yield* toDisplayName(id, news.displayName, output?.displayName);
229 const ownership = yield* createInternalLabels(id);
230 const encodedDisplayName = encodeDisplayName(ownership, displayName);
231 const desiredParent = news.parentName ?? "";
232 const desiredCluster = news.isCluster === true;
233
234 let current = yield* observe(env.project, id, output?.name);
235
236 if (current === undefined) {
237 const created = yield* monitoring
238 .createProjectsGroups({
239 name: parentOf(env.project),
240 body: {
241 displayName: encodedDisplayName,
242 filter: news.filter,
243 parentName: news.parentName,
244 isCluster: desiredCluster,
245 },
246 })
247 // Group ids are server-assigned, so a 409 here is the transient
248 // "too many concurrent edits", never an existing group.
249 .pipe(retryConcurrentEdits);
250 current = created;
251 }
252
253 if (current === undefined) {
254 return yield* new GroupNotResolved({
255 resourceName: output?.name ?? displayName,
256 });
257 }
258
259 const name = current.name ?? output?.name ?? "";
260 const needsUpdate =
261 (current.displayName ?? "") !== encodedDisplayName ||
262 (current.filter ?? "") !== news.filter ||
263 (current.parentName ?? "") !== desiredParent ||
264 (current.isCluster === true) !== desiredCluster;
265
266 if (needsUpdate) {
267 current = yield* monitoring
268 .updateProjectsGroups({
269 name,
270 body: {
271 name,
272 displayName: encodedDisplayName,
273 filter: news.filter,
274 parentName: desiredParent,
275 isCluster: desiredCluster,
276 },
277 })
278 .pipe(retryConcurrentEdits);
279 }
280
281 return toAttrs(current, env.project);
282 }),
283
284 delete: Effect.fn(function* ({ output }) {
285 yield* monitoring.deleteProjectsGroups({ name: output.name, recursive: true }).pipe(
286 retryConcurrentEdits,
287 Effect.catchTag("NotFound", () => Effect.void),
288 );
289 }),
290 });