@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 253 lines 9.72 KB
Raw
1 import * as ce from "@distilled.cloud/aws/cost-explorer";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { fetchCeTags, pinCe, syncCeTags, toResourceTags } from "./common.ts";
12
13 export interface AnomalyMonitorProps {
14 /**
15 * Name of the anomaly monitor. If omitted, a unique name is generated from
16 * the app, stage, and logical ID. Renaming updates the monitor in place.
17 */
18 monitorName?: string;
19 /**
20 * The type of monitor.
21 *
22 * - `DIMENSIONAL` — monitors spend grouped by a built-in dimension
23 * (`monitorDimension`). AWS allows only one `SERVICE`-dimension monitor
24 * per account.
25 * - `CUSTOM` — monitors spend matching a custom `monitorSpecification`
26 * expression (linked accounts, cost allocation tags, or cost categories).
27 *
28 * Changing the type replaces the monitor.
29 */
30 monitorType: "DIMENSIONAL" | "CUSTOM" | (string & {});
31 /**
32 * The dimension to group spend by for `DIMENSIONAL` monitors. Required when
33 * `monitorType` is `DIMENSIONAL`. Changing it replaces the monitor.
34 */
35 monitorDimension?: "SERVICE" | (string & {});
36 /**
37 * The expression selecting the spend a `CUSTOM` monitor evaluates —
38 * linked accounts, cost allocation tags, or cost categories (raw
39 * Cost Explorer `Expression` shape). Required when `monitorType` is
40 * `CUSTOM`. Changing it replaces the monitor.
41 */
42 monitorSpecification?: ce.Expression;
43 /**
44 * User-defined tags to apply to the monitor.
45 */
46 tags?: Record<string, string>;
47 }
48
49 export interface AnomalyMonitor extends Resource<
50 "AWS.CostExplorer.AnomalyMonitor",
51 AnomalyMonitorProps,
52 {
53 /** ARN of the anomaly monitor. */
54 monitorArn: string;
55 /** Name of the anomaly monitor. */
56 monitorName: string;
57 /** Type of the monitor (`DIMENSIONAL` or `CUSTOM`). */
58 monitorType: string;
59 /** Current tags on the monitor. */
60 tags: Record<string, string>;
61 },
62 never,
63 Providers
64 > {}
65
66 /**
67 * A Cost Explorer anomaly detection monitor. Monitors evaluate your spend for
68 * unusual patterns; pair with an
69 * {@link ../AnomalySubscription | AnomalySubscription} to receive alerts.
70 *
71 * Cost Explorer is a global service — all calls are pinned to `us-east-1`
72 * regardless of the stack region. Monitors are free and take effect
73 * immediately.
74 *
75 * ### Creating Anomaly Monitors
76 * **Example:** Custom monitor scoped by a cost allocation tag
77 * ```typescript
78 * import * as CostExplorer from "@alchemy.run/aws/CostExplorer";
79 *
80 * const monitor = yield* CostExplorer.AnomalyMonitor("TeamSpend", {
81 * monitorType: "CUSTOM",
82 * monitorSpecification: {
83 * Tags: { Key: "CostCenter", Values: ["10000"] },
84 * },
85 * });
86 * ```
87 *
88 * **Example:** Dimensional monitor across all AWS services
89 * ```typescript
90 * const monitor = yield* CostExplorer.AnomalyMonitor("ServiceSpend", {
91 * monitorType: "DIMENSIONAL",
92 * monitorDimension: "SERVICE",
93 * });
94 * ```
95 *
96 * @resource
97 */
98 export const AnomalyMonitor = Resource<AnomalyMonitor>("AWS.CostExplorer.AnomalyMonitor");
99
100 export const AnomalyMonitorProvider = () =>
101 Provider.effect(
102 AnomalyMonitor,
103 Effect.gen(function* () {
104 const createName = Effect.fn(function* (
105 id: string,
106 props: { monitorName?: string | undefined },
107 ) {
108 return props.monitorName ?? (yield* createPhysicalName({ id, maxLength: 100 }));
109 });
110
111 // Observe by ARN — the typed miss tag is UnknownMonitorException.
112 const getByArn = (monitorArn: string) =>
113 pinCe(ce.getAnomalyMonitors({ MonitorArnList: [monitorArn] })).pipe(
114 Effect.map((r) => r.AnomalyMonitors[0]),
115 Effect.catchTag("UnknownMonitorException", () => Effect.undefined),
116 );
117
118 // Fallback observation when no ARN is cached: scan all monitors for the
119 // deterministic physical name.
120 const findByName = (monitorName: string) =>
121 pinCe(
122 ce.getAnomalyMonitors.items({}).pipe(
123 Stream.filter((m) => m.MonitorName === monitorName),
124 Stream.take(1),
125 Stream.runCollect,
126 ),
127 ).pipe(Effect.map((chunk) => Array.from(chunk)[0]));
128
129 const toAttrs = Effect.fn(function* (live: ce.AnomalyMonitor) {
130 const monitorArn = live.MonitorArn!;
131 return {
132 monitorArn,
133 monitorName: live.MonitorName,
134 monitorType: live.MonitorType,
135 tags: yield* fetchCeTags(monitorArn),
136 };
137 });
138
139 return AnomalyMonitor.Provider.of({
140 stables: ["monitorArn"],
141 list: () =>
142 Effect.gen(function* () {
143 const monitors = yield* pinCe(
144 ce.getAnomalyMonitors.items({}).pipe(Stream.runCollect),
145 ).pipe(Effect.map((chunk) => Array.from(chunk)));
146 return yield* Effect.forEach(
147 monitors.filter((m) => m.MonitorArn !== undefined),
148 toAttrs,
149 { concurrency: 10 },
150 );
151 }),
152 read: Effect.fn(function* ({ id, olds, output }) {
153 const live = output?.monitorArn
154 ? yield* getByArn(output.monitorArn)
155 : yield* findByName(yield* createName(id, olds ?? {}));
156 if (live?.MonitorArn === undefined) return undefined;
157 const attrs = yield* toAttrs(live);
158 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
159 }),
160 diff: Effect.fn(function* ({ olds, news }) {
161 if (!isResolved(news)) return;
162 const prior: Partial<AnomalyMonitorProps> = olds ?? {};
163 if (prior.monitorType === undefined) return;
164 // Only the name is mutable via UpdateAnomalyMonitor — the type,
165 // dimension, and specification are create-only.
166 if (
167 prior.monitorType !== news.monitorType ||
168 prior.monitorDimension !== news.monitorDimension ||
169 JSON.stringify(prior.monitorSpecification) !== JSON.stringify(news.monitorSpecification)
170 ) {
171 return { action: "replace" } as const;
172 }
173 }),
174 reconcile: Effect.fn(function* ({ id, news, output, session }) {
175 const name = yield* createName(id, news);
176 const internalTags = yield* createInternalTags(id);
177 const desiredTags = { ...news.tags, ...internalTags };
178
179 // OBSERVE — cloud state is authoritative; output is only an ARN
180 // cache. Monitor names are not unique identity (the ARN is), so the
181 // find-by-name fallback only adopts a monitor whose create-only
182 // props already match the desired state. This keeps replacement
183 // correct: while the engine replaces a monitor (spec change), the
184 // old same-name monitor is still live and must NOT be adopted.
185 const matchesDesired = (m: ce.AnomalyMonitor) =>
186 m.MonitorType === news.monitorType &&
187 m.MonitorDimension === news.monitorDimension &&
188 JSON.stringify(m.MonitorSpecification ?? null) ===
189 JSON.stringify(news.monitorSpecification ?? null);
190 const live = output?.monitorArn
191 ? yield* getByArn(output.monitorArn)
192 : yield* findByName(name).pipe(
193 Effect.map((m) => (m !== undefined && matchesDesired(m) ? m : undefined)),
194 );
195
196 let monitorArn = live?.MonitorArn;
197 if (monitorArn === undefined) {
198 // ENSURE — create if missing. Monitor names are unique per
199 // account; tolerate the AlreadyExists race by adopting the
200 // same-name monitor only when its create-only props match the
201 // desired state (a mismatch means a genuine conflict — e.g. a
202 // replacement targeting an explicit name — and must surface).
203 const created = yield* pinCe(
204 ce.createAnomalyMonitor({
205 AnomalyMonitor: {
206 MonitorName: name,
207 MonitorType: news.monitorType,
208 MonitorDimension: news.monitorDimension,
209 MonitorSpecification: news.monitorSpecification,
210 },
211 ResourceTags: toResourceTags(desiredTags),
212 }),
213 ).pipe(
214 Effect.catchTag("AnomalyMonitorAlreadyExists", (error) =>
215 findByName(name).pipe(
216 Effect.flatMap((m) =>
217 m?.MonitorArn !== undefined && matchesDesired(m)
218 ? Effect.succeed({ MonitorArn: m.MonitorArn })
219 : Effect.fail(error),
220 ),
221 ),
222 ),
223 );
224 monitorArn = created.MonitorArn;
225 } else if (live!.MonitorName !== name) {
226 // SYNC — the name is the only mutable aspect of a monitor.
227 yield* pinCe(
228 ce.updateAnomalyMonitor({
229 MonitorArn: monitorArn,
230 MonitorName: name,
231 }),
232 );
233 }
234
235 // SYNC TAGS — diff against observed cloud tags.
236 yield* syncCeTags(monitorArn, desiredTags);
237
238 yield* session.note(monitorArn);
239 return {
240 monitorArn,
241 monitorName: name,
242 monitorType: news.monitorType,
243 tags: desiredTags,
244 };
245 }),
246 delete: Effect.fn(function* ({ output }) {
247 yield* pinCe(ce.deleteAnomalyMonitor({ MonitorArn: output.monitorArn })).pipe(
248 Effect.catchTag("UnknownMonitorException", () => Effect.void),
249 );
250 }),
251 });
252 }),
253 );