@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, 06:00 UTC

main
ts 298 lines 10.6 KB
Raw
1 import * as aas from "@distilled.cloud/aws/application-auto-scaling";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9 import { SERVICE_NAMESPACES, retryWhileTargetPropagates } from "./internal.ts";
10
11 export interface ScheduledActionProps {
12 /**
13 * Scheduled action name. If omitted, a deterministic name is generated.
14 *
15 * Changing this triggers a replacement.
16 */
17 scheduledActionName?: string;
18 /**
19 * The namespace of the AWS service that provides the scalable target,
20 * e.g. `ecs`, `dynamodb`.
21 *
22 * Changing this triggers a replacement.
23 */
24 serviceNamespace: aas.ServiceNamespace;
25 /**
26 * The identifier of the resource the action's scalable target scales,
27 * e.g. `service/{clusterName}/{serviceName}` or `table/{tableName}`.
28 *
29 * Changing this triggers a replacement.
30 */
31 resourceId: string;
32 /**
33 * The scalable dimension of the scalable target,
34 * e.g. `ecs:service:DesiredCount` or `dynamodb:table:ReadCapacityUnits`.
35 *
36 * Changing this triggers a replacement.
37 */
38 scalableDimension: aas.ScalableDimension;
39 /**
40 * The schedule expression: `at(yyyy-mm-ddThh:mm:ss)` for one-time actions,
41 * `rate(value unit)` or `cron(fields)` for recurring actions.
42 */
43 schedule: string;
44 /**
45 * Time zone for the schedule expression (IANA name, e.g.
46 * `America/Los_Angeles`).
47 * @default "UTC"
48 */
49 timezone?: string;
50 /**
51 * ISO-8601 date-time at which a recurring schedule begins.
52 */
53 startTime?: string;
54 /**
55 * ISO-8601 date-time at which a recurring schedule ends.
56 */
57 endTime?: string;
58 /**
59 * The new minimum and/or maximum capacity applied when the action runs.
60 */
61 scalableTargetAction: aas.ScalableTargetAction;
62 }
63
64 export interface ScheduledAction extends Resource<
65 "AWS.ApplicationAutoScaling.ScheduledAction",
66 ScheduledActionProps,
67 {
68 /**
69 * Name of the scheduled action.
70 */
71 scheduledActionName: string;
72 /**
73 * ARN of the scheduled action.
74 */
75 scheduledActionArn: string;
76 /**
77 * Namespace of the AWS service that provides the scalable target.
78 */
79 serviceNamespace: aas.ServiceNamespace;
80 /**
81 * Identifier of the scaled resource.
82 */
83 resourceId: string;
84 /**
85 * Scalable dimension the action applies to.
86 */
87 scalableDimension: aas.ScalableDimension;
88 /**
89 * Schedule expression (`at(...)`, `rate(...)`, or `cron(...)`).
90 */
91 schedule: string;
92 /**
93 * IANA timezone the schedule is evaluated in.
94 */
95 timezone: string | undefined;
96 /**
97 * Capacity bounds applied when the action fires.
98 */
99 scalableTargetAction: aas.ScalableTargetAction | undefined;
100 },
101 never,
102 Providers
103 > {}
104
105 /**
106 * An Application Auto Scaling scheduled action — adjusts a scalable target's
107 * minimum and/or maximum capacity on a one-time (`at(...)`) or recurring
108 * (`cron(...)` / `rate(...)`) schedule.
109 *
110 * The action applies to the scalable target identified by the
111 * (`serviceNamespace`, `resourceId`, `scalableDimension`) triple, which must
112 * be registered (see {@link ScalableTarget}) before the action is created —
113 * pass the target's outputs so deployment orders correctly.
114 * ### Scheduling Capacity Changes
115 * **Example:** Scale Out for Business Hours
116 * ```typescript
117 * yield* ScheduledAction("BusinessHoursScaleOut", {
118 * serviceNamespace: target.serviceNamespace,
119 * resourceId: target.resourceId,
120 * scalableDimension: target.scalableDimension,
121 * schedule: "cron(0 8 ? * MON-FRI *)",
122 * timezone: "America/Los_Angeles",
123 * scalableTargetAction: { MinCapacity: 3, MaxCapacity: 10 },
124 * });
125 * ```
126 *
127 * **Example:** One-Time Capacity Bump
128 * ```typescript
129 * yield* ScheduledAction("LaunchDayBump", {
130 * serviceNamespace: target.serviceNamespace,
131 * resourceId: target.resourceId,
132 * scalableDimension: target.scalableDimension,
133 * schedule: "at(2030-01-01T00:00:00)",
134 * scalableTargetAction: { MinCapacity: 5 },
135 * });
136 * ```
137 *
138 * @resource
139 */
140 export const ScheduledAction = Resource<ScheduledAction>(
141 "AWS.ApplicationAutoScaling.ScheduledAction",
142 );
143
144 export const ScheduledActionProvider = () =>
145 Provider.effect(
146 ScheduledAction,
147 Effect.gen(function* () {
148 const toName = (id: string, props: { scheduledActionName?: string } = {}) =>
149 props.scheduledActionName
150 ? Effect.succeed(props.scheduledActionName)
151 : createPhysicalName({ id, maxLength: 255 });
152
153 const describe = (props: {
154 serviceNamespace: aas.ServiceNamespace;
155 scheduledActionName: string;
156 resourceId?: string;
157 scalableDimension?: aas.ScalableDimension;
158 }) =>
159 aas
160 .describeScheduledActions({
161 ServiceNamespace: props.serviceNamespace,
162 ScheduledActionNames: [props.scheduledActionName],
163 ResourceId: props.resourceId,
164 ScalableDimension: props.scalableDimension,
165 })
166 .pipe(
167 Effect.map((res) =>
168 res.ScheduledActions?.find(
169 (a) => a.ScheduledActionName === props.scheduledActionName,
170 ),
171 ),
172 );
173
174 const toAttributes = (action: aas.ScheduledAction): ScheduledAction["Attributes"] => ({
175 scheduledActionName: action.ScheduledActionName,
176 scheduledActionArn: action.ScheduledActionARN,
177 serviceNamespace: action.ServiceNamespace,
178 resourceId: action.ResourceId,
179 scalableDimension: action.ScalableDimension ?? "",
180 schedule: action.Schedule,
181 timezone: action.Timezone,
182 scalableTargetAction: action.ScalableTargetAction,
183 });
184
185 return {
186 stables: [
187 "scheduledActionName",
188 "scheduledActionArn",
189 "serviceNamespace",
190 "resourceId",
191 "scalableDimension",
192 ],
193
194 // Account/region-wide enumeration; the describe API requires a
195 // `ServiceNamespace` filter, so union the per-namespace pages.
196 list: () =>
197 Effect.forEach(
198 SERVICE_NAMESPACES,
199 (namespace) =>
200 aas.describeScheduledActions.pages({ ServiceNamespace: namespace }).pipe(
201 Stream.runCollect,
202 Effect.map((chunk) =>
203 Array.from(chunk).flatMap((page) =>
204 (page.ScheduledActions ?? []).map(toAttributes),
205 ),
206 ),
207 ),
208 { concurrency: 4 },
209 ).pipe(Effect.map((groups) => groups.flat())),
210
211 diff: Effect.fn(function* ({ id, news, olds }) {
212 if (!isResolved(news)) return undefined;
213 const oldName = yield* toName(id, olds ?? {});
214 const newName = yield* toName(id, news);
215 if (oldName !== newName) {
216 return { action: "replace" } as const;
217 }
218 // The target triple pins the action to a scalable target — any
219 // change replaces the action. Only compare sides that are known:
220 // a half-created state row may have lost Output-valued props.
221 for (const key of ["serviceNamespace", "resourceId", "scalableDimension"] as const) {
222 const oldValue = olds?.[key];
223 if (oldValue !== undefined && isResolved(oldValue) && oldValue !== news[key]) {
224 return { action: "replace" } as const;
225 }
226 }
227 }),
228
229 read: Effect.fn(function* ({ id, olds, output }) {
230 const serviceNamespace = output?.serviceNamespace ?? olds?.serviceNamespace;
231 if (serviceNamespace === undefined) return undefined;
232 const scheduledActionName =
233 output?.scheduledActionName ?? (yield* toName(id, olds ?? {}));
234 const action = yield* describe({
235 serviceNamespace,
236 scheduledActionName,
237 resourceId: output?.resourceId ?? olds?.resourceId,
238 scalableDimension: output?.scalableDimension ?? olds?.scalableDimension,
239 });
240 return action ? toAttributes(action) : undefined;
241 }),
242
243 reconcile: Effect.fn(function* ({ id, news, session }) {
244 const scheduledActionName = yield* toName(id, news);
245
246 // Ensure + sync — `putScheduledAction` is the single
247 // create-or-update API, keyed by (name, target triple). Note the
248 // AWS semantics: unspecified StartTime/EndTime are *deleted* on
249 // update, which matches declarative convergence exactly. A put
250 // issued immediately after the target registers can race its
251 // propagation — retry the typed ObjectNotFoundException briefly.
252 yield* retryWhileTargetPropagates(
253 aas.putScheduledAction({
254 ScheduledActionName: scheduledActionName,
255 ServiceNamespace: news.serviceNamespace,
256 ResourceId: news.resourceId,
257 ScalableDimension: news.scalableDimension,
258 Schedule: news.schedule,
259 Timezone: news.timezone,
260 StartTime: news.startTime !== undefined ? new Date(news.startTime) : undefined,
261 EndTime: news.endTime !== undefined ? new Date(news.endTime) : undefined,
262 ScalableTargetAction: news.scalableTargetAction,
263 }),
264 );
265
266 // Observe final state so attributes carry the generated ARN.
267 const action = yield* describe({
268 serviceNamespace: news.serviceNamespace,
269 scheduledActionName,
270 resourceId: news.resourceId,
271 scalableDimension: news.scalableDimension,
272 });
273 if (action === undefined) {
274 return yield* aas.ObjectNotFoundException.make({
275 message: `Scheduled action '${scheduledActionName}' was not readable after PutScheduledAction`,
276 });
277 }
278
279 yield* session.note(action.ScheduledActionARN);
280 return toAttributes(action);
281 }),
282
283 // Deleting the parent scalable target implicitly deletes its
284 // scheduled actions, so an action that is already gone (typed
285 // `ObjectNotFoundException`) is success.
286 delete: Effect.fn(function* ({ output }) {
287 yield* aas
288 .deleteScheduledAction({
289 ScheduledActionName: output.scheduledActionName,
290 ServiceNamespace: output.serviceNamespace,
291 ResourceId: output.resourceId,
292 ScalableDimension: output.scalableDimension,
293 })
294 .pipe(Effect.catchTag("ObjectNotFoundException", () => Effect.void));
295 }),
296 };
297 }),
298 );