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

main
ts 473 lines 16.4 KB
Raw
1 import * as budgets from "@distilled.cloud/aws/budgets";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags, diffTags } from "alchemy/Tags";
6 import * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import type { BudgetSubscriber } from "./Budget.ts";
13
14 /**
15 * The threshold that triggers a budget action.
16 */
17 export interface BudgetActionThreshold {
18 /**
19 * The threshold value. Interpreted as a percentage of the budget limit by
20 * default, or an absolute amount when `actionThresholdType` is
21 * `ABSOLUTE_VALUE`.
22 */
23 actionThresholdValue: number;
24 /**
25 * Whether the threshold is a percentage of the budget or an absolute value.
26 */
27 actionThresholdType: "PERCENTAGE" | "ABSOLUTE_VALUE" | (string & {});
28 }
29
30 /**
31 * What the action does when it fires — exactly one of the three definitions
32 * must be set, matching the action's `actionType`.
33 */
34 export interface BudgetActionDefinition {
35 /**
36 * For `APPLY_IAM_POLICY` actions — attach the managed policy to the given
37 * IAM roles, groups, and/or users.
38 */
39 iamActionDefinition?: {
40 /** ARN of the managed policy to attach. */
41 policyArn: string;
42 /** IAM role names to attach the policy to. */
43 roles?: string[];
44 /** IAM group names to attach the policy to. */
45 groups?: string[];
46 /** IAM user names to attach the policy to. */
47 users?: string[];
48 };
49 /**
50 * For `APPLY_SCP_POLICY` actions — attach the service control policy to
51 * the given Organizations targets.
52 */
53 scpActionDefinition?: {
54 /** The SCP policy ID. */
55 policyId: string;
56 /** Organizations target IDs (accounts or OUs). */
57 targetIds: string[];
58 };
59 /**
60 * For `RUN_SSM_DOCUMENTS` actions — stop the given EC2 or RDS instances.
61 */
62 ssmActionDefinition?: {
63 /** Which instances to stop. */
64 actionSubType: "STOP_EC2_INSTANCES" | "STOP_RDS_INSTANCES" | (string & {});
65 /** Region of the instances. */
66 region: string;
67 /** Instance IDs to stop. */
68 instanceIds: string[];
69 };
70 }
71
72 export interface BudgetActionProps {
73 /**
74 * Name of the budget the action belongs to.
75 *
76 * Changing the budget replaces the action.
77 */
78 budgetName: string;
79 /**
80 * Whether the action triggers on actual or forecasted spend.
81 */
82 notificationType: "ACTUAL" | "FORECASTED" | (string & {});
83 /**
84 * The kind of action to run when the threshold is crossed.
85 *
86 * Changing the action type replaces the action.
87 */
88 actionType: "APPLY_IAM_POLICY" | "APPLY_SCP_POLICY" | "RUN_SSM_DOCUMENTS" | (string & {});
89 /**
90 * The threshold that triggers the action.
91 */
92 actionThreshold: BudgetActionThreshold;
93 /**
94 * What the action does — must match `actionType`.
95 */
96 definition: BudgetActionDefinition;
97 /**
98 * ARN of the IAM role AWS Budgets assumes to run the action. The role must
99 * trust `budgets.amazonaws.com`.
100 */
101 executionRoleArn: string;
102 /**
103 * Whether the action runs automatically when the threshold is crossed or
104 * requires manual approval.
105 * @default "MANUAL"
106 */
107 approvalModel?: "AUTOMATIC" | "MANUAL" | (string & {});
108 /**
109 * Subscribers notified when the action is triggered or requires approval.
110 */
111 subscribers: BudgetSubscriber[];
112 /**
113 * Tags applied to the budget action.
114 */
115 tags?: Record<string, string>;
116 }
117
118 export interface BudgetAction extends Resource<
119 "AWS.Budgets.BudgetAction",
120 BudgetActionProps,
121 {
122 /**
123 * The system-generated ID of the action.
124 */
125 actionId: string;
126 /**
127 * Name of the budget the action belongs to.
128 */
129 budgetName: string;
130 /**
131 * The AWS account ID that owns the action.
132 */
133 accountId: string;
134 /**
135 * ARN of the action, e.g.
136 * `arn:aws:budgets::123456789012:budget/my-budget/action/abc123`.
137 */
138 actionArn: string;
139 },
140 never,
141 Providers
142 > {}
143
144 /**
145 * An AWS Budgets action — runs an IAM policy attachment, SCP attachment, or
146 * SSM stop-instances document when a budget threshold is crossed, either
147 * automatically or after manual approval.
148 *
149 * The execution role must trust `budgets.amazonaws.com` and carry the
150 * permissions the action needs (the AWS managed policy
151 * `AWSBudgetsActionsWithAWSResourceControlAccess` covers all three kinds).
152 *
153 * ### Creating a Budget Action
154 * **Example:** Apply a Deny-All Policy at 100% of the Budget
155 * ```typescript
156 * import * as AWS from "@alchemy.run/aws";
157 *
158 * const budget = yield* AWS.Budgets.Budget("MonthlyCost", {
159 * budgetLimit: { amount: "100", unit: "USD" },
160 * });
161 *
162 * const action = yield* AWS.Budgets.BudgetAction("FreezeSpend", {
163 * budgetName: budget.budgetName,
164 * notificationType: "ACTUAL",
165 * actionType: "APPLY_IAM_POLICY",
166 * actionThreshold: {
167 * actionThresholdValue: 100,
168 * actionThresholdType: "PERCENTAGE",
169 * },
170 * definition: {
171 * iamActionDefinition: {
172 * policyArn: "arn:aws:iam::aws:policy/AWSDenyAll",
173 * roles: [devRole.roleName],
174 * },
175 * },
176 * executionRoleArn: executionRole.roleArn,
177 * approvalModel: "MANUAL",
178 * subscribers: [{ subscriptionType: "EMAIL", address: "team@example.com" }],
179 * });
180 * ```
181 *
182 * **Example:** Stop EC2 Instances Automatically
183 * ```typescript
184 * const action = yield* AWS.Budgets.BudgetAction("StopDevInstances", {
185 * budgetName: budget.budgetName,
186 * notificationType: "ACTUAL",
187 * actionType: "RUN_SSM_DOCUMENTS",
188 * actionThreshold: {
189 * actionThresholdValue: 100,
190 * actionThresholdType: "PERCENTAGE",
191 * },
192 * definition: {
193 * ssmActionDefinition: {
194 * actionSubType: "STOP_EC2_INSTANCES",
195 * region: "us-east-1",
196 * instanceIds: [instance.instanceId],
197 * },
198 * },
199 * executionRoleArn: executionRole.roleArn,
200 * approvalModel: "AUTOMATIC",
201 * subscribers: [{ subscriptionType: "EMAIL", address: "team@example.com" }],
202 * });
203 * ```
204 *
205 * @resource
206 */
207 export const BudgetAction = Resource<BudgetAction>("AWS.Budgets.BudgetAction");
208
209 /**
210 * Compute the ARN of a budget action. Budgets is a global service, so the ARN
211 * has no region component.
212 */
213 export const budgetActionArn = (accountId: string, budgetName: string, actionId: string): string =>
214 `arn:aws:budgets::${accountId}:budget/${budgetName}/action/${actionId}`;
215
216 const toDefinition = (d: BudgetActionDefinition): budgets.Definition => ({
217 IamActionDefinition: d.iamActionDefinition
218 ? {
219 PolicyArn: d.iamActionDefinition.policyArn,
220 Roles: d.iamActionDefinition.roles,
221 Groups: d.iamActionDefinition.groups,
222 Users: d.iamActionDefinition.users,
223 }
224 : undefined,
225 ScpActionDefinition: d.scpActionDefinition
226 ? {
227 PolicyId: d.scpActionDefinition.policyId,
228 TargetIds: d.scpActionDefinition.targetIds,
229 }
230 : undefined,
231 SsmActionDefinition: d.ssmActionDefinition
232 ? {
233 ActionSubType: d.ssmActionDefinition.actionSubType,
234 Region: d.ssmActionDefinition.region,
235 InstanceIds: d.ssmActionDefinition.instanceIds,
236 }
237 : undefined,
238 });
239
240 const toSubscribers = (subscribers: BudgetSubscriber[]): budgets.Subscriber[] =>
241 subscribers.map((s) => ({
242 SubscriptionType: s.subscriptionType,
243 Address: s.address,
244 }));
245
246 /** The updatable slice of an action, in a canonical shape for comparison. */
247 const updatableSlice = (a: {
248 NotificationType: string;
249 ActionThreshold: budgets.ActionThreshold;
250 Definition: budgets.Definition;
251 ExecutionRoleArn: string;
252 ApprovalModel: string;
253 Subscribers: readonly budgets.Subscriber[];
254 }): string =>
255 JSON.stringify({
256 NotificationType: a.NotificationType,
257 ActionThreshold: {
258 ActionThresholdValue: a.ActionThreshold.ActionThresholdValue,
259 ActionThresholdType: a.ActionThreshold.ActionThresholdType,
260 },
261 Definition: {
262 IamActionDefinition: a.Definition.IamActionDefinition
263 ? {
264 PolicyArn: a.Definition.IamActionDefinition.PolicyArn,
265 Roles: a.Definition.IamActionDefinition.Roles ?? [],
266 Groups: a.Definition.IamActionDefinition.Groups ?? [],
267 Users: a.Definition.IamActionDefinition.Users ?? [],
268 }
269 : undefined,
270 ScpActionDefinition: a.Definition.ScpActionDefinition,
271 SsmActionDefinition: a.Definition.SsmActionDefinition,
272 },
273 ExecutionRoleArn: a.ExecutionRoleArn,
274 ApprovalModel: a.ApprovalModel,
275 // Distilled marks `Subscriber.Address` sensitive — observed subscribers
276 // come back Redacted; unwrap so the observed-vs-desired comparison does
277 // not see `<redacted>` and issue a dirty update on every reconcile.
278 Subscribers: [...a.Subscribers]
279 .map(
280 (s) =>
281 `${s.SubscriptionType}:${
282 Redacted.isRedacted(s.Address) ? Redacted.value(s.Address) : s.Address
283 }`,
284 )
285 .sort(),
286 });
287
288 export const BudgetActionProvider = () =>
289 Provider.effect(
290 BudgetAction,
291 Effect.gen(function* () {
292 const syncTags = Effect.fn(function* (arn: string, desired: Record<string, string>) {
293 const observed = yield* budgets.listTagsForResource({ ResourceARN: arn }).pipe(
294 Effect.map((r) =>
295 Object.fromEntries((r.ResourceTags ?? []).map((t) => [t.Key, t.Value])),
296 ),
297 Effect.catchTag("NotFoundException", () => Effect.succeed({} as Record<string, string>)),
298 );
299 const { removed, upsert } = diffTags(observed, desired);
300 if (upsert.length > 0) {
301 yield* budgets.tagResource({
302 ResourceARN: arn,
303 ResourceTags: upsert,
304 });
305 }
306 if (removed.length > 0) {
307 yield* budgets.untagResource({
308 ResourceARN: arn,
309 ResourceTagKeys: removed,
310 });
311 }
312 });
313
314 const attrs = (accountId: string, budgetName: string, actionId: string) =>
315 ({
316 actionId,
317 budgetName,
318 accountId,
319 actionArn: budgetActionArn(accountId, budgetName, actionId),
320 }) as const;
321
322 return BudgetAction.Provider.of({
323 stables: ["actionId", "budgetName", "accountId", "actionArn"],
324 list: () =>
325 Effect.gen(function* () {
326 const { accountId } = yield* AWSEnvironment.current;
327 return yield* budgets.describeBudgetActionsForAccount
328 .pages({ AccountId: accountId })
329 .pipe(
330 Stream.runCollect,
331 Effect.map((chunk) =>
332 Array.from(chunk)
333 .flatMap((page) => page.Actions ?? [])
334 .map((a) => attrs(accountId, a.BudgetName, a.ActionId)),
335 ),
336 );
337 }),
338 read: Effect.fn(function* ({ output }) {
339 // The action ID is server-generated — without persisted output there
340 // is no deterministic way to find the action.
341 if (!output) return undefined;
342 const { accountId } = yield* AWSEnvironment.current;
343 const found = yield* budgets
344 .describeBudgetAction({
345 AccountId: accountId,
346 BudgetName: output.budgetName,
347 ActionId: output.actionId,
348 })
349 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
350 if (!found?.Action) return undefined;
351 return attrs(accountId, output.budgetName, output.actionId);
352 }),
353 diff: Effect.fn(function* ({ news, olds }) {
354 if (!isResolved(news)) return undefined;
355 if (olds.budgetName !== news.budgetName || olds.actionType !== news.actionType) {
356 return { action: "replace" } as const;
357 }
358 }),
359 reconcile: Effect.fn(function* ({ id, news, output, session }) {
360 const { accountId } = yield* AWSEnvironment.current;
361 const internalTags = yield* createInternalTags(id);
362 const desiredSubscribers = toSubscribers(news.subscribers);
363 const desired = {
364 NotificationType: news.notificationType,
365 ActionThreshold: {
366 ActionThresholdValue: news.actionThreshold.actionThresholdValue,
367 ActionThresholdType: news.actionThreshold.actionThresholdType,
368 },
369 Definition: toDefinition(news.definition),
370 ExecutionRoleArn: news.executionRoleArn,
371 ApprovalModel: news.approvalModel ?? "MANUAL",
372 Subscribers: desiredSubscribers,
373 };
374
375 // OBSERVE — the action ID is server-generated, so `output` is the
376 // only handle; cloud state stays authoritative via describe.
377 const observed = output
378 ? yield* budgets
379 .describeBudgetAction({
380 AccountId: accountId,
381 BudgetName: output.budgetName,
382 ActionId: output.actionId,
383 })
384 .pipe(
385 Effect.map((r) => r.Action),
386 Effect.catchTag("NotFoundException", () => Effect.undefined),
387 )
388 : undefined;
389
390 let actionId: string;
391 if (!observed) {
392 // ENSURE — create. A freshly created execution role can take a
393 // few seconds to become assumable by budgets.amazonaws.com, which
394 // surfaces as InvalidParameterException/AccessDeniedException.
395 const created = yield* budgets
396 .createBudgetAction({
397 AccountId: accountId,
398 BudgetName: news.budgetName,
399 NotificationType: desired.NotificationType,
400 ActionType: news.actionType,
401 ActionThreshold: desired.ActionThreshold,
402 Definition: desired.Definition,
403 ExecutionRoleArn: desired.ExecutionRoleArn,
404 ApprovalModel: desired.ApprovalModel,
405 Subscribers: desired.Subscribers,
406 ResourceTags: Object.entries({
407 ...news.tags,
408 ...internalTags,
409 }).map(([Key, Value]) => ({ Key, Value })),
410 })
411 .pipe(
412 Effect.retry({
413 while: (e): boolean =>
414 e._tag === "InvalidParameterException" || e._tag === "AccessDeniedException",
415 schedule: Schedule.exponential("2 seconds"),
416 times: 6,
417 }),
418 );
419 actionId = created.ActionId;
420 } else {
421 actionId = observed.ActionId;
422 // SYNC — apply the update only when the observed action differs
423 // from the desired definition.
424 if (updatableSlice(observed) !== updatableSlice(desired)) {
425 yield* budgets
426 .updateBudgetAction({
427 AccountId: accountId,
428 BudgetName: news.budgetName,
429 ActionId: actionId,
430 NotificationType: desired.NotificationType,
431 ActionThreshold: desired.ActionThreshold,
432 Definition: desired.Definition,
433 ExecutionRoleArn: desired.ExecutionRoleArn,
434 ApprovalModel: desired.ApprovalModel,
435 Subscribers: desired.Subscribers,
436 })
437 .pipe(
438 Effect.retry({
439 while: (e): boolean => e._tag === "ResourceLockedException",
440 schedule: Schedule.exponential("2 seconds"),
441 times: 6,
442 }),
443 );
444 }
445 }
446
447 // SYNC tags against observed cloud tags.
448 const arn = budgetActionArn(accountId, news.budgetName, actionId);
449 yield* syncTags(arn, { ...news.tags, ...internalTags });
450
451 yield* session.note(actionId);
452 return attrs(accountId, news.budgetName, actionId);
453 }),
454 delete: Effect.fn(function* ({ output }) {
455 yield* budgets
456 .deleteBudgetAction({
457 AccountId: output.accountId,
458 BudgetName: output.budgetName,
459 ActionId: output.actionId,
460 })
461 .pipe(
462 // An action mid-execution is briefly locked; wait it out.
463 Effect.retry({
464 while: (e): boolean => e._tag === "ResourceLockedException",
465 schedule: Schedule.exponential("2 seconds"),
466 times: 6,
467 }),
468 Effect.catchTag("NotFoundException", () => Effect.void),
469 );
470 }),
471 });
472 }),
473 );