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

main
ts 305 lines 10.7 KB
Raw
1 import * as autoscaling from "@distilled.cloud/aws/auto-scaling";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import type { AutoScalingGroup as AutoScalingGroupResource } from "./AutoScalingGroup.ts";
13
14 export class ScheduledActionUnexpectedResponse extends Data.TaggedError(
15 "ScheduledActionUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export type ScheduledActionName = string;
22
23 export interface ScheduledActionProps {
24 /**
25 * Scheduled action name. If omitted, a deterministic name is generated.
26 */
27 scheduledActionName?: string;
28 /**
29 * Auto Scaling Group whose capacity the action changes.
30 */
31 autoScalingGroup: Input<string> | AutoScalingGroupResource;
32 /**
33 * Cron expression describing a recurring schedule (e.g. `"0 9 * * MON-FRI"`).
34 * Omit for a one-time action scheduled via `startTime`.
35 */
36 recurrence?: string;
37 /**
38 * ISO-8601 timestamp the action first runs (recurring) or the single time it
39 * runs (one-time). Must be in the future.
40 */
41 startTime?: string;
42 /**
43 * ISO-8601 timestamp after which the recurring action stops running.
44 */
45 endTime?: string;
46 /**
47 * IANA time zone the `recurrence` is evaluated in (e.g. `"America/New_York"`).
48 */
49 timeZone?: string;
50 /**
51 * Minimum group size to set when the action runs.
52 */
53 minSize?: number;
54 /**
55 * Maximum group size to set when the action runs.
56 */
57 maxSize?: number;
58 /**
59 * Desired capacity to set when the action runs.
60 */
61 desiredCapacity?: number;
62 }
63
64 export interface ScheduledAction extends Resource<
65 "AWS.AutoScaling.ScheduledAction",
66 ScheduledActionProps,
67 {
68 /**
69 * Name of the scheduled action.
70 */
71 scheduledActionName: ScheduledActionName;
72 /**
73 * ARN of the scheduled action.
74 */
75 scheduledActionARN: string;
76 /**
77 * Name of the Auto Scaling Group the action applies to.
78 */
79 autoScalingGroupName: string;
80 /**
81 * Cron expression for recurring actions.
82 */
83 recurrence?: string;
84 /**
85 * ISO-8601 time the action first fires.
86 */
87 startTime?: string;
88 /**
89 * ISO-8601 time after which the recurrence stops.
90 */
91 endTime?: string;
92 /**
93 * IANA timezone the recurrence is evaluated in.
94 */
95 timeZone?: string;
96 /**
97 * Minimum group size applied when the action fires.
98 */
99 minSize?: number;
100 /**
101 * Maximum group size applied when the action fires.
102 */
103 maxSize?: number;
104 /**
105 * Desired capacity applied when the action fires.
106 */
107 desiredCapacity?: number;
108 },
109 never,
110 Providers
111 > {}
112
113 /**
114 * A scheduled scaling action that changes an Auto Scaling Group's capacity on a
115 * recurring cron schedule or at a single future time.
116 *
117 * ### Creating a Scheduled Action
118 * **Example:** Scale up every weekday morning
119 * ```typescript
120 * const action = yield* ScheduledAction("MorningScaleUp", {
121 * autoScalingGroup: group,
122 * recurrence: "0 9 * * MON-FRI",
123 * timeZone: "America/New_York",
124 * minSize: 2,
125 * maxSize: 10,
126 * desiredCapacity: 4,
127 * });
128 * ```
129 *
130 * **Example:** One-time capacity change
131 * ```typescript
132 * const action = yield* ScheduledAction("BlackFriday", {
133 * autoScalingGroup: group,
134 * startTime: "2026-11-27T00:00:00Z",
135 * desiredCapacity: 20,
136 * });
137 * ```
138 *
139 * @resource
140 */
141 export const ScheduledAction = Resource<ScheduledAction>("AWS.AutoScaling.ScheduledAction");
142
143 // A whole AutoScalingGroup resource resolves to its bare Attributes before
144 // reaching the provider — narrow on the attributes shape, never on `Type`.
145 const toAutoScalingGroupName = (
146 input: ScheduledActionProps["autoScalingGroup"] | undefined,
147 ): string | undefined =>
148 typeof input === "string"
149 ? input
150 : typeof (input as { autoScalingGroupName?: unknown } | undefined)?.autoScalingGroupName ===
151 "string"
152 ? (input as unknown as { autoScalingGroupName: string }).autoScalingGroupName
153 : undefined;
154
155 export const ScheduledActionProvider = () =>
156 Provider.effect(
157 ScheduledAction,
158 Effect.gen(function* () {
159 const toName = (id: string, props: { scheduledActionName?: string } = {}) =>
160 props.scheduledActionName
161 ? Effect.succeed(props.scheduledActionName)
162 : createPhysicalName({ id, maxLength: 255, lowercase: true });
163
164 const describeAction = ({
165 autoScalingGroupName,
166 scheduledActionName,
167 }: {
168 autoScalingGroupName: string | undefined;
169 scheduledActionName: string;
170 }) =>
171 autoscaling
172 .describeScheduledActions({
173 AutoScalingGroupName: autoScalingGroupName,
174 ScheduledActionNames: [scheduledActionName],
175 } as any)
176 .pipe(
177 Effect.map((result) => result.ScheduledUpdateGroupActions?.[0]),
178 // A deleted/absent Auto Scaling Group surfaces as
179 // `ValidationError: AutoScalingGroup ... not found` (typed
180 // `AutoScalingGroupNotFound` via the auto-scaling patch); treat it
181 // as "action gone" so refresh/read converge instead of failing.
182 Effect.catchTag("AutoScalingGroupNotFound", () => Effect.undefined),
183 );
184
185 const toAttributes = (
186 action: autoscaling.ScheduledUpdateGroupAction,
187 ): ScheduledAction["Attributes"] => ({
188 scheduledActionName: action.ScheduledActionName!,
189 scheduledActionARN: action.ScheduledActionARN!,
190 autoScalingGroupName: action.AutoScalingGroupName!,
191 recurrence: action.Recurrence,
192 startTime: action.StartTime ? new Date(action.StartTime).toISOString() : undefined,
193 endTime: action.EndTime ? new Date(action.EndTime).toISOString() : undefined,
194 timeZone: action.TimeZone,
195 minSize: action.MinSize,
196 maxSize: action.MaxSize,
197 desiredCapacity: action.DesiredCapacity,
198 });
199
200 return {
201 stables: ["scheduledActionName", "scheduledActionARN", "autoScalingGroupName"],
202 // `describeScheduledActions` enumerates scheduled actions across every
203 // Auto Scaling Group in the account/region when no AutoScalingGroupName
204 // filter is supplied, so no parent enumeration is needed.
205 list: () =>
206 autoscaling.describeScheduledActions.pages({} as any).pipe(
207 Stream.runCollect,
208 Effect.map((chunk) =>
209 Array.from(chunk).flatMap((page) =>
210 (page.ScheduledUpdateGroupActions ?? []).map(toAttributes),
211 ),
212 ),
213 ),
214 diff: Effect.fn(function* ({ id, olds, news: _news }) {
215 if (!isResolved(_news)) return undefined;
216 const news = _news as typeof olds;
217 const oldName = yield* toName(id, olds ?? {});
218 const newName = yield* toName(id, news ?? {});
219 const oldGroup = toAutoScalingGroupName(olds.autoScalingGroup);
220 const newGroup = toAutoScalingGroupName(news.autoScalingGroup);
221 if (
222 oldName !== newName ||
223 (oldGroup !== undefined && newGroup !== undefined && oldGroup !== newGroup)
224 ) {
225 return { action: "replace" } as const;
226 }
227
228 if (!deepEqual(olds, news)) {
229 return {
230 action: "update",
231 stables: ["scheduledActionName", "scheduledActionARN", "autoScalingGroupName"],
232 } as const;
233 }
234 }),
235 read: Effect.fn(function* ({ id, olds, output }) {
236 const autoScalingGroupName =
237 output?.autoScalingGroupName ?? toAutoScalingGroupName(olds?.autoScalingGroup);
238 const scheduledActionName =
239 output?.scheduledActionName ?? (yield* toName(id, olds ?? {}));
240 const action = yield* describeAction({
241 autoScalingGroupName,
242 scheduledActionName,
243 });
244 return action ? toAttributes(action) : undefined;
245 }),
246 reconcile: Effect.fn(function* ({ id, news, output, session }) {
247 const autoScalingGroupName =
248 output?.autoScalingGroupName ?? toAutoScalingGroupName(news.autoScalingGroup);
249 if (!autoScalingGroupName) {
250 return yield* Effect.die(
251 new Error("ScheduledAction requires a resolvable autoScalingGroup name"),
252 );
253 }
254 const scheduledActionName = output?.scheduledActionName ?? (yield* toName(id, news));
255
256 // Ensure + Sync — `putScheduledUpdateGroupAction` is the single
257 // create-or-update API. It overwrites the whole action, so we issue
258 // it unconditionally (idempotent on matching params).
259 yield* autoscaling.putScheduledUpdateGroupAction({
260 AutoScalingGroupName: autoScalingGroupName,
261 ScheduledActionName: scheduledActionName,
262 Recurrence: news.recurrence,
263 StartTime: news.startTime ? new Date(news.startTime) : undefined,
264 EndTime: news.endTime ? new Date(news.endTime) : undefined,
265 TimeZone: news.timeZone,
266 MinSize: news.minSize,
267 MaxSize: news.maxSize,
268 DesiredCapacity: news.desiredCapacity,
269 } as any);
270
271 const action = yield* describeAction({
272 autoScalingGroupName,
273 scheduledActionName,
274 }).pipe(
275 Effect.flatMap((action) =>
276 action
277 ? Effect.succeed(action)
278 : Effect.fail(
279 new ScheduledActionUnexpectedResponse({
280 message: `Scheduled action '${scheduledActionName}' was not readable after reconcile`,
281 }),
282 ),
283 ),
284 );
285 yield* session.note(scheduledActionName);
286 return toAttributes(action);
287 }),
288 delete: Effect.fn(function* ({ output }) {
289 // `deleteScheduledAction` is idempotent — a missing action returns
290 // success. Retry only the transient contention fault.
291 yield* autoscaling
292 .deleteScheduledAction({
293 AutoScalingGroupName: output.autoScalingGroupName,
294 ScheduledActionName: output.scheduledActionName,
295 } as any)
296 .pipe(
297 Effect.retry({
298 while: (error) => error._tag === "ResourceContentionFault",
299 schedule: Schedule.max([Schedule.recurs(5), Schedule.exponential("250 millis")]),
300 }),
301 );
302 }),
303 };
304 }),
305 );