@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 292 lines 10.4 KB
Raw
1 import * as devopsguru from "@distilled.cloud/aws/devops-guru";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9
10 export interface TagAppBoundary {
11 /**
12 * Tag key that defines an application boundary. DevOps Guru requires the
13 * key to begin with `devops-guru-` (any casing, e.g.
14 * `DevOps-Guru-deployment-application`).
15 */
16 appBoundaryKey: string;
17 /**
18 * Tag values that select the resources to analyze. Use `["*"]` to match
19 * every resource carrying the key.
20 */
21 tagValues: string[];
22 }
23
24 export interface ResourceCollectionProps {
25 /**
26 * Analyze resources belonging to the named CloudFormation stacks. Use
27 * `{ stackNames: ["*"] }` to analyze every stack in the account. Mutually
28 * exclusive with `tags` — an account's collection uses one filter type at
29 * a time.
30 */
31 cloudFormation?: {
32 /** CloudFormation stack names to analyze (`["*"]` for all stacks). */
33 stackNames: string[];
34 };
35 /**
36 * Analyze resources carrying the given app-boundary tags. Tag keys must
37 * begin with `devops-guru-` (any casing). Mutually exclusive with
38 * `cloudFormation`.
39 */
40 tags?: TagAppBoundary[];
41 }
42
43 export interface ResourceCollection extends Resource<
44 "AWS.DevOpsGuru.ResourceCollection",
45 ResourceCollectionProps,
46 {
47 /** CloudFormation stack names DevOps Guru analyzes. */
48 cloudFormationStackNames: string[];
49 /** App-boundary tag filters DevOps Guru analyzes. */
50 tags: TagAppBoundary[];
51 },
52 never,
53 Providers
54 > {}
55
56 /**
57 * The DevOps Guru resource collection — the account/region singleton that
58 * defines which AWS resources DevOps Guru analyzes for operational insights,
59 * either by CloudFormation stack or by app-boundary tag. Configuring a
60 * collection is what "enables" DevOps Guru analysis in an account.
61 *
62 * An account has exactly one collection, so this resource is a
63 * capture-and-restore singleton: adopting a collection that Alchemy did not
64 * configure requires `--adopt`.
65 *
66 * ### Defining Coverage
67 * **Example:** Analyze specific CloudFormation stacks
68 * ```typescript
69 * const collection = yield* DevOpsGuru.ResourceCollection("Coverage", {
70 * cloudFormation: { stackNames: ["my-app-prod"] },
71 * });
72 * ```
73 *
74 * **Example:** Analyze every stack in the account
75 * ```typescript
76 * const collection = yield* DevOpsGuru.ResourceCollection("Coverage", {
77 * cloudFormation: { stackNames: ["*"] },
78 * });
79 * ```
80 *
81 * **Example:** Analyze resources by app-boundary tag
82 * ```typescript
83 * const collection = yield* DevOpsGuru.ResourceCollection("Coverage", {
84 * tags: [
85 * { appBoundaryKey: "devops-guru-app", tagValues: ["checkout", "billing"] },
86 * ],
87 * });
88 * ```
89 *
90 * @resource
91 */
92 export const ResourceCollection = Resource<ResourceCollection>("AWS.DevOpsGuru.ResourceCollection");
93
94 /**
95 * Concurrent `UpdateResourceCollection` calls conflict server-side — retry
96 * the typed conflict tag on a short bounded schedule.
97 *
98 * Explicitly typed: inlining `Effect.retry` with options in provider
99 * lifecycle code can widen the provider layer to `unknown` in declaration
100 * emit.
101 *
102 * @internal
103 */
104 const retryUpdateConflict = <A, E extends { readonly _tag: string }, R>(
105 self: Effect.Effect<A, E, R>,
106 ): Effect.Effect<A, E, R> =>
107 Effect.retry(self, {
108 while: (e) => e._tag === "ConflictException",
109 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(8)]),
110 });
111
112 const sameKey = (left: string, right: string) => left.toLowerCase() === right.toLowerCase();
113
114 export const ResourceCollectionProvider = () =>
115 Provider.effect(
116 ResourceCollection,
117 Effect.gen(function* () {
118 // GetResourceCollection fails with a typed ResourceNotFoundException
119 // ("No CustomerResourceFilter present") when nothing has ever been
120 // configured — treat that as an empty collection.
121 const observeType = Effect.fn(function* (type: devopsguru.ResourceCollectionType) {
122 return yield* devopsguru.getResourceCollection.pages({ ResourceCollectionType: type }).pipe(
123 Stream.runCollect,
124 Effect.map((chunk) => Array.from(chunk)),
125 Effect.catchTag("ResourceNotFoundException", () =>
126 Effect.succeed([] as devopsguru.GetResourceCollectionResponse[]),
127 ),
128 );
129 });
130
131 // Observe the full account collection (both filter types).
132 const observe = Effect.gen(function* () {
133 const cfnPages = yield* observeType("AWS_CLOUD_FORMATION");
134 const tagPages = yield* observeType("AWS_TAGS");
135 const stackNames = [
136 ...new Set(
137 cfnPages.flatMap((page) => page.ResourceCollection?.CloudFormation?.StackNames ?? []),
138 ),
139 ].sort();
140 const tagMap = new Map<string, Set<string>>();
141 for (const page of tagPages) {
142 for (const tag of page.ResourceCollection?.Tags ?? []) {
143 const values = tagMap.get(tag.AppBoundaryKey) ?? new Set<string>();
144 for (const value of tag.TagValues) values.add(value);
145 tagMap.set(tag.AppBoundaryKey, values);
146 }
147 }
148 // AWS keeps an app-boundary key with an empty TagValues list after
149 // its last value is removed — a key selecting no values analyzes
150 // nothing, so it is treated as absent.
151 const tags = [...tagMap.entries()]
152 .filter(([, values]) => values.size > 0)
153 .map(([appBoundaryKey, values]) => ({
154 appBoundaryKey,
155 tagValues: [...values].sort(),
156 }))
157 .sort((l, r) => l.appBoundaryKey.localeCompare(r.appBoundaryKey));
158 return { stackNames, tags };
159 });
160
161 const update = Effect.fn(function* (
162 action: devopsguru.UpdateResourceCollectionAction,
163 filter: devopsguru.UpdateResourceCollectionFilter,
164 ) {
165 yield* retryUpdateConflict(
166 devopsguru.updateResourceCollection({
167 Action: action,
168 ResourceCollection: filter,
169 }),
170 );
171 });
172
173 const toAttrs = (observed: { stackNames: string[]; tags: TagAppBoundary[] }) => ({
174 cloudFormationStackNames: observed.stackNames,
175 tags: observed.tags,
176 });
177
178 return {
179 // Account/region singleton — the one collection, when configured.
180 list: () =>
181 observe.pipe(
182 Effect.map((observed) =>
183 observed.stackNames.length > 0 || observed.tags.length > 0 ? [toAttrs(observed)] : [],
184 ),
185 ),
186
187 read: Effect.fn(function* ({ output }) {
188 const observed = yield* observe;
189 if (observed.stackNames.length === 0 && observed.tags.length === 0) {
190 return undefined;
191 }
192 const attrs = toAttrs(observed);
193 // The collection can't carry ownership tags — a configured
194 // collection we have no record of belongs to someone else until
195 // explicitly adopted.
196 return output !== undefined ? attrs : Unowned(attrs);
197 }),
198
199 reconcile: Effect.fn(function* ({ news, session }) {
200 const desiredStacks = news.cloudFormation?.stackNames ?? [];
201 const desiredTags = news.tags ?? [];
202
203 // 1. OBSERVE — the live account collection is authoritative.
204 const observed = yield* observe;
205
206 // 2. SYNC (removals first) — the two filter types are mutually
207 // exclusive, so pruning before adding also handles switching
208 // between CloudFormation- and tag-based coverage.
209 const stacksToRemove = observed.stackNames.filter(
210 (name) => !desiredStacks.includes(name),
211 );
212 if (stacksToRemove.length > 0) {
213 yield* update("REMOVE", {
214 CloudFormation: { StackNames: stacksToRemove },
215 });
216 }
217 for (const tag of observed.tags) {
218 const desired = desiredTags.find((t) => sameKey(t.appBoundaryKey, tag.appBoundaryKey));
219 const valuesToRemove = tag.tagValues.filter(
220 (value) => !(desired?.tagValues ?? []).includes(value),
221 );
222 if (valuesToRemove.length > 0) {
223 yield* update("REMOVE", {
224 Tags: [
225 {
226 AppBoundaryKey: tag.appBoundaryKey,
227 TagValues: valuesToRemove,
228 },
229 ],
230 });
231 }
232 }
233
234 // 3. SYNC (additions) — apply only the delta.
235 const stacksToAdd = desiredStacks.filter((name) => !observed.stackNames.includes(name));
236 if (stacksToAdd.length > 0) {
237 yield* update("ADD", {
238 CloudFormation: { StackNames: stacksToAdd },
239 });
240 }
241 for (const desired of desiredTags) {
242 const current = observed.tags.find((t) =>
243 sameKey(t.appBoundaryKey, desired.appBoundaryKey),
244 );
245 const valuesToAdd = desired.tagValues.filter(
246 (value) => !(current?.tagValues ?? []).includes(value),
247 );
248 if (valuesToAdd.length > 0) {
249 yield* update("ADD", {
250 Tags: [
251 {
252 AppBoundaryKey: desired.appBoundaryKey,
253 TagValues: valuesToAdd,
254 },
255 ],
256 });
257 }
258 }
259
260 // 4. RETURN fresh attributes.
261 const final = yield* observe;
262 yield* session.note(
263 final.stackNames.length > 0
264 ? `stacks: ${final.stackNames.join(", ")}`
265 : `tags: ${final.tags.map((t) => t.appBoundaryKey).join(", ")}`,
266 );
267 return toAttrs(final);
268 }),
269
270 // Deleting the collection removes every observed filter, returning
271 // the account to "DevOps Guru analyzes nothing".
272 delete: Effect.fn(function* () {
273 const observed = yield* observe;
274 if (observed.stackNames.length > 0) {
275 yield* update("REMOVE", {
276 CloudFormation: { StackNames: observed.stackNames },
277 });
278 }
279 for (const tag of observed.tags) {
280 yield* update("REMOVE", {
281 Tags: [
282 {
283 AppBoundaryKey: tag.appBoundaryKey,
284 TagValues: tag.tagValues,
285 },
286 ],
287 });
288 }
289 }),
290 };
291 }),
292 );