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

main
ts 325 lines 11.1 KB
Raw
1 import * as cloudwatch from "@distilled.cloud/aws/cloudwatch";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import type { Input } from "alchemy/Input";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Option from "effect/Option";
11 import * as Stream from "effect/Stream";
12 import { AWSEnvironment, type AccountID } from "../Environment.ts";
13 import type { Providers } from "../Providers.ts";
14 import type { RegionID } from "../Region.ts";
15 import { createName, readResourceTags, retryConcurrent, updateResourceTags } from "./common.ts";
16
17 export class InsightRuleUnexpectedResponse extends Data.TaggedError(
18 "InsightRuleUnexpectedResponse",
19 )<{
20 readonly message: string;
21 readonly cause?: unknown;
22 }> {}
23
24 export class InsightRuleOperationFailed extends Data.TaggedError("InsightRuleOperationFailed")<{
25 readonly message: string;
26 readonly cause?: unknown;
27 }> {}
28
29 export type InsightRuleName = string;
30 export type InsightRuleArn = `arn:aws:cloudwatch:${RegionID}:${AccountID}:insight-rule/${string}`;
31
32 export interface CloudWatchLogRuleFilter {
33 Match: string;
34 In: string[];
35 }
36
37 export interface CloudWatchLogRuleDefinition {
38 Schema: {
39 Name: "CloudWatchLogRule";
40 Version: 1;
41 };
42 LogGroupNames?: string[];
43 LogGroupARNs?: string[];
44 LogFormat: "JSON" | "CLF" | (string & {});
45 Contribution: {
46 Keys: string[];
47 ValueOf?: string;
48 Filters?: CloudWatchLogRuleFilter[];
49 };
50 AggregateOn: "Count" | "Sum" | (string & {});
51 }
52
53 export interface InsightRuleProps extends Omit<
54 cloudwatch.PutInsightRuleInput,
55 "RuleDefinition" | "RuleName" | "Tags"
56 > {
57 /**
58 * Name of the insight rule. If omitted, a unique name is generated.
59 */
60 name?: InsightRuleName;
61 /**
62 * Optional tags to apply to the insight rule.
63 */
64 tags?: Record<string, string>;
65 /**
66 * Typed Contributor Insights rule definition. The provider serializes this
67 * object to the JSON string expected by the CloudWatch API.
68 */
69 RuleDefinition?: CloudWatchLogRuleDefinition;
70 }
71
72 export interface InsightRule extends Resource<
73 "AWS.CloudWatch.InsightRule",
74 InsightRuleProps,
75 {
76 /** Physical name of the insight rule. */
77 ruleName: InsightRuleName;
78 /** ARN of the insight rule. */
79 ruleArn: InsightRuleArn;
80 /** Current state of the rule (`ENABLED` or `DISABLED`). */
81 state: string | undefined;
82 /** The full InsightRule description as last read from CloudWatch. */
83 insightRule: cloudwatch.InsightRule;
84 /** Tags on the insight rule, including the internal Alchemy ownership tags. */
85 tags: Record<string, string>;
86 },
87 never,
88 Providers
89 > {}
90
91 /**
92 * A CloudWatch Contributor Insights rule — analyzes log group entries to
93 * surface the top-N contributors (IPs, user IDs, …) to a metric derived
94 * from structured logs.
95 * ### Creating Insight Rules
96 * **Example:** Rule Definition
97 * ```typescript
98 * const rule = yield* InsightRule("TopContributors", {
99 * RuleState: "ENABLED",
100 * RuleDefinition: {
101 * Schema: {
102 * Name: "CloudWatchLogRule",
103 * Version: 1,
104 * },
105 * LogGroupNames: ["/my-app/access-logs"],
106 * LogFormat: "JSON",
107 * Contribution: {
108 * Keys: ["$.ip"],
109 * },
110 * AggregateOn: "Count",
111 * },
112 * });
113 * ```
114 *
115 * ### Reading Reports at Runtime
116 * **Example:** Fetch the Rule's Top Contributors from a Function
117 * ```typescript
118 * // init — bind the rule to the function (see GetInsightRuleReport)
119 * const getInsightRuleReport = yield* AWS.CloudWatch.GetInsightRuleReport(rule);
120 *
121 * // runtime
122 * const now = yield* Effect.sync(() => Date.now());
123 * const report = yield* getInsightRuleReport({
124 * StartTime: new Date(now - 3_600_000),
125 * EndTime: new Date(now),
126 * Period: 300,
127 * });
128 * ```
129 *
130 * @resource
131 */
132 export const InsightRule = Resource<InsightRule>("AWS.CloudWatch.InsightRule");
133
134 const failureMessage = (failures: cloudwatch.PartialFailure[] | undefined) =>
135 (failures ?? [])
136 .map(
137 (failure) =>
138 `${failure.FailureResource ?? "unknown"}: ${failure.FailureCode ?? failure.ExceptionType ?? "failed"}`,
139 )
140 .join(", ");
141
142 const toPutInsightRuleInput = ({
143 RuleDefinition,
144 ...input
145 }: InsightRuleProps): cloudwatch.PutInsightRuleInput => ({
146 ...input,
147 RuleDefinition: RuleDefinition ? JSON.stringify(RuleDefinition) : undefined,
148 });
149
150 export const InsightRuleProvider = () =>
151 Provider.effect(
152 InsightRule,
153 Effect.gen(function* () {
154 const createRuleName = (id: string, props: { name?: string } = {}) =>
155 createName(id, props.name, 255);
156
157 const ruleArn = (name: string) =>
158 AWSEnvironment.current.pipe(
159 Effect.map(
160 (env) =>
161 `arn:aws:cloudwatch:${env.region}:${env.accountId}:insight-rule/${name}` as InsightRuleArn,
162 ),
163 );
164
165 const readInsightRule = Effect.fn(function* (name: string) {
166 const insightRule = yield* cloudwatch.describeInsightRules.pages({}).pipe(
167 Stream.mapEffect(
168 Effect.fn(function* (page) {
169 return page.InsightRules?.find((candidate) => candidate.Name === name);
170 }),
171 ),
172 Stream.filter((candidate) => candidate !== undefined),
173 Stream.runHead,
174 Effect.map(Option.getOrUndefined),
175 );
176
177 if (!insightRule?.Name) {
178 return undefined;
179 }
180
181 const arn = yield* ruleArn(insightRule.Name);
182 const tags = yield* readResourceTags(arn).pipe(
183 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({})),
184 );
185
186 return {
187 ruleName: insightRule.Name,
188 ruleArn: arn,
189 state: insightRule.State,
190 insightRule,
191 tags,
192 };
193 });
194
195 return {
196 stables: ["ruleName", "ruleArn"],
197 diff: Effect.fn(function* ({ id, olds = {}, news = {} as Input<InsightRuleProps> }) {
198 if (!isResolved(news)) return undefined;
199 const oldName = yield* createRuleName(id, olds);
200 const newName = yield* createRuleName(id, news);
201
202 if (oldName !== newName) {
203 return { action: "replace" } as const;
204 }
205 }),
206 read: Effect.fn(function* ({ id, olds, output }) {
207 const name = output?.ruleName ?? (yield* createRuleName(id, olds ?? {}));
208 const state = yield* readInsightRule(name);
209 if (!state) return undefined;
210 return (yield* hasAlchemyTags(id, state.tags)) ? state : Unowned(state);
211 }),
212 reconcile: Effect.fn(function* ({ id, news, olds, output, session }) {
213 // Observe — pin the physical name from `output` if present;
214 // otherwise derive from desired props. Read whatever exists in
215 // CloudWatch so we have a baseline for tag-diffing on adoption.
216 const name = output?.ruleName ?? (yield* createRuleName(id, news));
217 const existing = yield* readInsightRule(name);
218
219 // Ensure — `putInsightRule` is an upsert; sending the full
220 // desired config every reconcile converges the cloud.
221 yield* retryConcurrent(
222 cloudwatch.putInsightRule({
223 ...toPutInsightRuleInput(news),
224 RuleName: name,
225 }),
226 );
227
228 // Sync tags — diff against `olds.tags` when we have prior state,
229 // otherwise fall back to what we observed. Adoption flows take
230 // the latter path.
231 const tags = yield* updateResourceTags({
232 id,
233 resourceArn: yield* ruleArn(name),
234 olds: olds?.tags ?? existing?.tags,
235 news: news.tags,
236 });
237
238 yield* session.note(yield* ruleArn(name));
239
240 const state = yield* readInsightRule(name);
241 if (!state) {
242 return yield* new InsightRuleUnexpectedResponse({
243 message: `failed to read reconciled insight rule '${name}'`,
244 });
245 }
246
247 return {
248 ...state,
249 tags,
250 };
251 }),
252 list: () =>
253 Effect.gen(function* () {
254 // Enumerate every Contributor Insights rule in the account/region
255 // by exhaustively paginating `describeInsightRules` (items live
256 // under the `InsightRules` field). ARNs are reconstructed from the
257 // ambient region/account since the API returns names only.
258 const { accountId, region } = yield* AWSEnvironment.current;
259 const rules = yield* cloudwatch.describeInsightRules.pages({}).pipe(
260 Stream.runCollect,
261 Effect.map((chunk) =>
262 Array.from(chunk).flatMap((page) =>
263 (page.InsightRules ?? []).filter(
264 (
265 candidate,
266 ): candidate is typeof candidate & {
267 Name: string;
268 } =>
269 candidate.Name != null &&
270 // Rules owned by another service reject
271 // DeleteInsightRules with AccessDenied. DynamoDB
272 // Contributor Insights rules are the pathological case:
273 // they report `ManagedRule: false` yet still can only
274 // be removed through DynamoDB (verified live), so match
275 // both the flag and the documented name prefix. Keep
276 // them out of enumeration for account-wide teardown
277 // (nuke).
278 candidate.ManagedRule !== true &&
279 !candidate.Name.startsWith("DynamoDBContributorInsights-"),
280 ),
281 ),
282 ),
283 );
284
285 const attrs: InsightRule["Attributes"][] = yield* Effect.forEach(
286 rules,
287 (insightRule) => {
288 const arn =
289 `arn:aws:cloudwatch:${region}:${accountId}:insight-rule/${insightRule.Name}` as InsightRuleArn;
290 return readResourceTags(arn).pipe(
291 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({})),
292 Effect.map((tags) => ({
293 ruleName: insightRule.Name,
294 ruleArn: arn,
295 state: insightRule.State,
296 insightRule,
297 tags,
298 })),
299 );
300 },
301 { concurrency: 10 },
302 );
303 return attrs;
304 }),
305 delete: Effect.fn(function* ({ output }) {
306 const existing = yield* readInsightRule(output.ruleName);
307 if (!existing) {
308 return;
309 }
310
311 const response = yield* retryConcurrent(
312 cloudwatch.deleteInsightRules({
313 RuleNames: [output.ruleName],
314 }),
315 );
316
317 if ((response.Failures?.length ?? 0) > 0) {
318 return yield* new InsightRuleOperationFailed({
319 message: `failed to delete insight rule '${output.ruleName}': ${failureMessage(response.Failures)}`,
320 });
321 }
322 }),
323 };
324 }),
325 );