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

main
ts 297 lines 10.9 KB
Raw
1 import * as ce from "@distilled.cloud/aws/cost-explorer";
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 { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { fetchCeTags, pinCe, syncCeTags, toResourceTags } from "./common.ts";
11
12 /**
13 * A subscriber notified when a monitored anomaly crosses the subscription's
14 * threshold.
15 */
16 export interface AnomalySubscriber {
17 /**
18 * The destination — an email address (for `EMAIL`) or an SNS topic ARN
19 * (for `SNS`).
20 */
21 address: string;
22 /**
23 * How the subscriber is notified. `IMMEDIATE` frequency requires `SNS`
24 * subscribers; `DAILY`/`WEEKLY` require `EMAIL`.
25 */
26 type: "EMAIL" | "SNS" | (string & {});
27 }
28
29 export interface AnomalySubscriptionProps {
30 /**
31 * Name of the subscription. If omitted, a unique name is generated from
32 * the app, stage, and logical ID. Renaming updates the subscription in
33 * place.
34 */
35 subscriptionName?: string;
36 /**
37 * ARNs of the anomaly monitors this subscription listens to. Pass
38 * `monitor.monitorArn` outputs from {@link AnomalyMonitor} resources.
39 */
40 monitorArnList: string[];
41 /**
42 * Who gets notified when an anomaly crosses the threshold.
43 */
44 subscribers: AnomalySubscriber[];
45 /**
46 * How often notifications are sent. `IMMEDIATE` requires SNS subscribers;
47 * `DAILY` and `WEEKLY` send email digests.
48 */
49 frequency: "DAILY" | "IMMEDIATE" | "WEEKLY" | (string & {});
50 /**
51 * An expression gating notifications on anomaly impact — e.g. only alert
52 * when the total absolute impact exceeds $100:
53 * `{ Dimensions: { Key: "ANOMALY_TOTAL_IMPACT_ABSOLUTE", MatchOptions: ["GREATER_THAN_OR_EQUAL"], Values: ["100"] } }`
54 * (raw Cost Explorer `Expression` shape).
55 */
56 thresholdExpression?: ce.Expression;
57 /**
58 * User-defined tags to apply to the subscription.
59 */
60 tags?: Record<string, string>;
61 }
62
63 export interface AnomalySubscription extends Resource<
64 "AWS.CostExplorer.AnomalySubscription",
65 AnomalySubscriptionProps,
66 {
67 /** ARN of the anomaly subscription. */
68 subscriptionArn: string;
69 /** Name of the anomaly subscription. */
70 subscriptionName: string;
71 /** Account ID the subscription belongs to. */
72 accountId: string | undefined;
73 /** Current tags on the subscription. */
74 tags: Record<string, string>;
75 },
76 never,
77 Providers
78 > {}
79
80 /**
81 * A Cost Explorer anomaly alert subscription. Attaches email or SNS
82 * subscribers to one or more {@link AnomalyMonitor}s with a notification
83 * frequency and an impact threshold.
84 *
85 * Cost Explorer is a global service — all calls are pinned to `us-east-1`
86 * regardless of the stack region. Every property is mutable in place.
87 *
88 * ### Creating Anomaly Subscriptions
89 * **Example:** Daily email digest for anomalies over $100
90 * ```typescript
91 * import * as CostExplorer from "@alchemy.run/aws/CostExplorer";
92 *
93 * const monitor = yield* CostExplorer.AnomalyMonitor("ServiceSpend", {
94 * monitorType: "DIMENSIONAL",
95 * monitorDimension: "SERVICE",
96 * });
97 *
98 * const subscription = yield* CostExplorer.AnomalySubscription("Alerts", {
99 * monitorArnList: [monitor.monitorArn],
100 * frequency: "DAILY",
101 * subscribers: [{ type: "EMAIL", address: "team@example.com" }],
102 * thresholdExpression: {
103 * Dimensions: {
104 * Key: "ANOMALY_TOTAL_IMPACT_ABSOLUTE",
105 * MatchOptions: ["GREATER_THAN_OR_EQUAL"],
106 * Values: ["100"],
107 * },
108 * },
109 * });
110 * ```
111 *
112 * **Example:** Immediate SNS notifications
113 * ```typescript
114 * const subscription = yield* CostExplorer.AnomalySubscription("PagerFeed", {
115 * monitorArnList: [monitor.monitorArn],
116 * frequency: "IMMEDIATE",
117 * subscribers: [{ type: "SNS", address: topic.topicArn }],
118 * });
119 * ```
120 *
121 * @resource
122 */
123 export const AnomalySubscription = Resource<AnomalySubscription>(
124 "AWS.CostExplorer.AnomalySubscription",
125 );
126
127 const sameStringSets = (l: readonly string[], r: readonly string[]) =>
128 l.length === r.length && [...l].sort().join("\n") === [...r].sort().join("\n");
129
130 export const AnomalySubscriptionProvider = () =>
131 Provider.effect(
132 AnomalySubscription,
133 Effect.gen(function* () {
134 const createName = Effect.fn(function* (
135 id: string,
136 props: { subscriptionName?: string | undefined },
137 ) {
138 return props.subscriptionName ?? (yield* createPhysicalName({ id, maxLength: 100 }));
139 });
140
141 const getByArn = (subscriptionArn: string) =>
142 pinCe(
143 ce.getAnomalySubscriptions({
144 SubscriptionArnList: [subscriptionArn],
145 }),
146 ).pipe(
147 Effect.map((r) => r.AnomalySubscriptions[0]),
148 Effect.catchTag("UnknownSubscriptionException", () => Effect.undefined),
149 );
150
151 const findByName = (subscriptionName: string) =>
152 pinCe(
153 ce.getAnomalySubscriptions.items({}).pipe(
154 Stream.filter((s) => s.SubscriptionName === subscriptionName),
155 Stream.take(1),
156 Stream.runCollect,
157 ),
158 ).pipe(Effect.map((chunk) => Array.from(chunk)[0]));
159
160 const toAttrs = Effect.fn(function* (live: ce.AnomalySubscription) {
161 const subscriptionArn = live.SubscriptionArn!;
162 return {
163 subscriptionArn,
164 subscriptionName: live.SubscriptionName,
165 accountId: live.AccountId,
166 tags: yield* fetchCeTags(subscriptionArn),
167 };
168 });
169
170 const toSubscribers = (subscribers: AnomalySubscriber[]): ce.Subscriber[] =>
171 subscribers.map((s) => ({ Address: s.address, Type: s.type }));
172
173 return AnomalySubscription.Provider.of({
174 stables: ["subscriptionArn", "accountId"],
175 list: () =>
176 Effect.gen(function* () {
177 const subscriptions = yield* pinCe(
178 ce.getAnomalySubscriptions.items({}).pipe(Stream.runCollect),
179 ).pipe(Effect.map((chunk) => Array.from(chunk)));
180 return yield* Effect.forEach(
181 subscriptions.filter((s) => s.SubscriptionArn !== undefined),
182 toAttrs,
183 { concurrency: 10 },
184 );
185 }),
186 read: Effect.fn(function* ({ id, olds, output }) {
187 const live = output?.subscriptionArn
188 ? yield* getByArn(output.subscriptionArn)
189 : yield* findByName(yield* createName(id, olds ?? {}));
190 if (live?.SubscriptionArn === undefined) return undefined;
191 const attrs = yield* toAttrs(live);
192 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
193 }),
194 reconcile: Effect.fn(function* ({ id, news, output, session }) {
195 const name = yield* createName(id, news);
196 const internalTags = yield* createInternalTags(id);
197 const desiredTags: Record<string, string> = {
198 ...news.tags,
199 ...internalTags,
200 };
201 const desiredSubscribers = toSubscribers(news.subscribers);
202
203 // OBSERVE — cloud state is authoritative.
204 const live = output?.subscriptionArn
205 ? yield* getByArn(output.subscriptionArn)
206 : yield* findByName(name);
207
208 let subscriptionArn: string;
209 if (live?.SubscriptionArn === undefined) {
210 // ENSURE — create if missing. Subscription names are unique per
211 // account; tolerate the AlreadyExists race by adopting the
212 // same-name subscription and converging it (every property is
213 // mutable via UpdateAnomalySubscription).
214 const created = yield* pinCe(
215 ce.createAnomalySubscription({
216 AnomalySubscription: {
217 SubscriptionName: name,
218 MonitorArnList: news.monitorArnList,
219 Subscribers: desiredSubscribers,
220 Frequency: news.frequency,
221 ThresholdExpression: news.thresholdExpression,
222 },
223 ResourceTags: toResourceTags(desiredTags),
224 }),
225 ).pipe(
226 Effect.catchTag("AnomalySubscriptionAlreadyExists", (error) =>
227 Effect.gen(function* () {
228 const existing = yield* findByName(name);
229 const existingArn = existing?.SubscriptionArn;
230 if (existingArn === undefined) {
231 return yield* error;
232 }
233 return yield* pinCe(
234 ce.updateAnomalySubscription({
235 SubscriptionArn: existingArn,
236 SubscriptionName: name,
237 MonitorArnList: news.monitorArnList,
238 Subscribers: desiredSubscribers,
239 Frequency: news.frequency,
240 ThresholdExpression: news.thresholdExpression,
241 }),
242 );
243 }),
244 ),
245 );
246 subscriptionArn = created.SubscriptionArn;
247 } else {
248 // SYNC — diff observed against desired; every field is mutable.
249 subscriptionArn = live.SubscriptionArn;
250 const observed = live;
251 const needsUpdate =
252 observed.SubscriptionName !== name ||
253 observed.Frequency !== news.frequency ||
254 !sameStringSets(observed.MonitorArnList, news.monitorArnList) ||
255 !sameStringSets(
256 observed.Subscribers.map((s) => `${s.Type}:${s.Address}`),
257 desiredSubscribers.map((s) => `${s.Type}:${s.Address}`),
258 ) ||
259 (news.thresholdExpression !== undefined &&
260 JSON.stringify(observed.ThresholdExpression) !==
261 JSON.stringify(news.thresholdExpression));
262 if (needsUpdate) {
263 yield* pinCe(
264 ce.updateAnomalySubscription({
265 SubscriptionArn: subscriptionArn,
266 SubscriptionName: name,
267 MonitorArnList: news.monitorArnList,
268 Subscribers: desiredSubscribers,
269 Frequency: news.frequency,
270 ThresholdExpression: news.thresholdExpression,
271 }),
272 );
273 }
274 }
275
276 // SYNC TAGS — diff against observed cloud tags.
277 yield* syncCeTags(subscriptionArn, desiredTags);
278
279 yield* session.note(subscriptionArn);
280 const final = yield* getByArn(subscriptionArn);
281 return {
282 subscriptionArn,
283 subscriptionName: name,
284 accountId: final?.AccountId,
285 tags: desiredTags,
286 };
287 }),
288 delete: Effect.fn(function* ({ output }) {
289 yield* pinCe(
290 ce.deleteAnomalySubscription({
291 SubscriptionArn: output.subscriptionArn,
292 }),
293 ).pipe(Effect.catchTag("UnknownSubscriptionException", () => Effect.void));
294 }),
295 });
296 }),
297 );