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

main
ts 356 lines 12 KB
Raw
1 import * as scheduler from "@distilled.cloud/aws/scheduler";
2 import { 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
13 export class SchedulerScheduleUnexpectedResponse extends Data.TaggedError(
14 "SchedulerScheduleUnexpectedResponse",
15 )<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 /**
21 * EventBridge Scheduler validates that the target's execution role is
22 * assumable by `scheduler.amazonaws.com`. A freshly-created IAM role can take
23 * well over a minute to propagate, surfacing as the typed
24 * `ExecutionRoleNotAssumable` error ("The execution role you provide must
25 * allow AWS EventBridge Scheduler to assume the role"). Retry (bounded) until
26 * propagation completes.
27 */
28 const retryUntilRoleAssumable = <A, E extends { _tag: string }, R>(
29 effect: Effect.Effect<A, E, R>,
30 ): Effect.Effect<A, E, R> =>
31 Effect.retry(effect, {
32 while: (e) => e._tag === "ExecutionRoleNotAssumable",
33 schedule: Schedule_.spaced("5 seconds"),
34 times: 24,
35 });
36
37 export interface ScheduleProps {
38 /**
39 * Schedule name. If omitted, Alchemy generates a deterministic name.
40 */
41 name?: string;
42 /**
43 * Optional schedule group. Defaults to the AWS default group.
44 */
45 groupName?: Input<string>;
46 /**
47 * Required schedule expression, such as `rate(5 minutes)` or `cron(...)`.
48 */
49 scheduleExpression: string;
50 /**
51 * Optional start date.
52 */
53 startDate?: Date;
54 /**
55 * Optional end date.
56 */
57 endDate?: Date;
58 /**
59 * Optional description.
60 */
61 description?: string;
62 /**
63 * Optional timezone for cron or at expressions.
64 */
65 scheduleExpressionTimezone?: string;
66 /**
67 * Desired schedule state.
68 */
69 state?: string;
70 /**
71 * Optional KMS key ARN.
72 */
73 kmsKeyArn?: Input<string>;
74 /**
75 * Scheduler target configuration.
76 */
77 target: Input<scheduler.Target>;
78 /**
79 * Flexible time window configuration.
80 */
81 flexibleTimeWindow?: Input<scheduler.FlexibleTimeWindow>;
82 /**
83 * Action after a one-time schedule completes.
84 */
85 actionAfterCompletion?: string;
86 }
87
88 /**
89 * An EventBridge Scheduler schedule.
90 *
91 * `Schedule` is the canonical time-based delivery primitive. High-level helpers
92 * like `every`, `cron`, and `at` can synthesize the target role and scheduler
93 * target configuration on top of this resource.
94 * ### Creating Schedules
95 * **Example:** Hourly Schedule
96 * ```typescript
97 * const schedule = yield* Schedule("HourlyJob", {
98 * scheduleExpression: "rate(1 hour)",
99 * target: {
100 * Arn: fn.functionArn,
101 * RoleArn: role.roleArn,
102 * },
103 * flexibleTimeWindow: {
104 * Mode: "OFF",
105 * },
106 * });
107 * ```
108 *
109 * @resource
110 */
111 export interface Schedule extends Resource<
112 "AWS.Scheduler.Schedule",
113 ScheduleProps,
114 {
115 /**
116 * ARN of the schedule.
117 */
118 scheduleArn: string;
119 /**
120 * Name of the schedule.
121 */
122 scheduleName: string;
123 /**
124 * Name of the schedule group containing the schedule.
125 */
126 groupName: string;
127 /**
128 * Current state of the schedule (`ENABLED` or `DISABLED`).
129 */
130 state: string | undefined;
131 /**
132 * The schedule definition (expression, timezone, dates, target,
133 * flexible window, KMS key, completion action), as observed. Lets
134 * `alchemy drift` detect out-of-band changes.
135 */
136 configuration?: ScheduleConfiguration;
137 },
138 never,
139 Providers
140 > {}
141
142 export const Schedule = Resource<Schedule>("AWS.Scheduler.Schedule");
143
144 /** The managed configuration of a schedule, as observed. */
145 export interface ScheduleConfiguration {
146 scheduleExpression?: string;
147 scheduleExpressionTimezone?: string;
148 startDate?: string;
149 endDate?: string;
150 description?: string;
151 kmsKeyArn?: string;
152 target?: scheduler.Target;
153 flexibleTimeWindow?: scheduler.FlexibleTimeWindow;
154 actionAfterCompletion?: string;
155 }
156
157 /**
158 * The configuration `read` and `reconcile` both report, so a converged
159 * schedule reads unchanged.
160 */
161 const observeScheduleConfiguration = (
162 described: scheduler.GetScheduleOutput,
163 ): ScheduleConfiguration => ({
164 scheduleExpression: described.ScheduleExpression,
165 scheduleExpressionTimezone: described.ScheduleExpressionTimezone,
166 startDate: described.StartDate?.toISOString(),
167 endDate: described.EndDate?.toISOString(),
168 description: described.Description || undefined,
169 kmsKeyArn: described.KmsKeyArn,
170 target: described.Target,
171 flexibleTimeWindow: described.FlexibleTimeWindow,
172 actionAfterCompletion: described.ActionAfterCompletion,
173 });
174
175 export const ScheduleProvider = () =>
176 Provider.effect(
177 Schedule,
178 Effect.gen(function* () {
179 const toName = (id: string, props: ScheduleProps) =>
180 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 64 });
181
182 return {
183 stables: ["scheduleArn", "scheduleName", "groupName"],
184 diff: Effect.fn(function* ({ id, olds, news }) {
185 if (!isResolved(news)) return undefined;
186 if ((yield* toName(id, olds)) !== (yield* toName(id, news))) {
187 return { action: "replace" } as const;
188 }
189
190 if ((olds.groupName ?? "default") !== (news.groupName ?? "default")) {
191 return { action: "replace" } as const;
192 }
193 }),
194 read: Effect.fn(function* ({ id, olds, output }) {
195 const scheduleName = output?.scheduleName ?? (yield* toName(id, olds));
196 const groupName =
197 output?.groupName ?? (olds.groupName as string | undefined) ?? "default";
198 const described = yield* scheduler
199 .getSchedule({
200 Name: scheduleName,
201 GroupName: groupName !== "default" ? groupName : undefined,
202 })
203 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
204
205 if (!described?.Arn || !described.Name) {
206 return undefined;
207 }
208
209 return {
210 scheduleArn: described.Arn,
211 scheduleName: described.Name,
212 groupName: described.GroupName ?? groupName,
213 state: described.State,
214 configuration: observeScheduleConfiguration(described),
215 };
216 }),
217 reconcile: Effect.fn(function* ({ id, news, output, session }) {
218 const scheduleName = output?.scheduleName ?? (yield* toName(id, news));
219 const groupName =
220 output?.groupName ?? (news.groupName as string | undefined) ?? "default";
221 const groupNameParam = groupName !== "default" ? groupName : undefined;
222
223 const desiredConfig = {
224 ScheduleExpression: news.scheduleExpression,
225 StartDate: news.startDate,
226 EndDate: news.endDate,
227 Description: news.description,
228 ScheduleExpressionTimezone: news.scheduleExpressionTimezone,
229 State: news.state,
230 KmsKeyArn: news.kmsKeyArn as string | undefined,
231 Target: news.target as scheduler.Target,
232 FlexibleTimeWindow: (news.flexibleTimeWindow as
233 | scheduler.FlexibleTimeWindow
234 | undefined) ?? {
235 Mode: "OFF" as const,
236 },
237 ActionAfterCompletion: news.actionAfterCompletion,
238 };
239
240 // Observe — fetch live schedule.
241 let observed = yield* scheduler
242 .getSchedule({ Name: scheduleName, GroupName: groupNameParam })
243 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
244
245 // Ensure — create if missing. EventBridge Scheduler does not support
246 // tagging individual schedules (only schedule groups), so ownership
247 // can't be branded/verified via tags. A `ConflictException` means a
248 // schedule with this deterministic name already exists; fall through
249 // to the sync (`updateSchedule`) path to converge it.
250 if (!observed?.Arn) {
251 yield* scheduler
252 .createSchedule({
253 Name: scheduleName,
254 GroupName: groupNameParam,
255 ...desiredConfig,
256 })
257 .pipe(
258 retryUntilRoleAssumable,
259 Effect.catchTag("ConflictException", () => Effect.void),
260 );
261 observed = yield* scheduler
262 .getSchedule({ Name: scheduleName, GroupName: groupNameParam })
263 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
264 }
265
266 if (!observed?.Arn) {
267 return yield* new SchedulerScheduleUnexpectedResponse({
268 message: `Failed to read created Schedule '${scheduleName}'`,
269 });
270 }
271
272 const scheduleArn = observed.Arn;
273
274 // Sync schedule configuration. Scheduler doesn't support a partial
275 // update — `updateSchedule` is a full PUT — so we always send the
276 // full desired config. Fields like `state` are reflected in
277 // `observed.State`; sending a no-op update is cheap.
278 yield* scheduler
279 .updateSchedule({
280 Name: scheduleName,
281 GroupName: groupNameParam,
282 ...desiredConfig,
283 })
284 .pipe(retryUntilRoleAssumable);
285
286 yield* session.note(scheduleArn);
287
288 const final = yield* scheduler.getSchedule({
289 Name: scheduleName,
290 GroupName: groupNameParam,
291 });
292 return {
293 scheduleArn,
294 scheduleName,
295 groupName,
296 state: final.State,
297 configuration: observeScheduleConfiguration(final),
298 };
299 }),
300 list: () =>
301 Effect.gen(function* () {
302 // Enumerate every schedule in the account/region. Omitting
303 // GroupName makes ListSchedules return summaries across all
304 // schedule groups, paginated.
305 const summaries = yield* scheduler.listSchedules.pages({}).pipe(
306 Stream.runCollect,
307 Effect.map((chunk) =>
308 Array.from(chunk).flatMap((page) =>
309 (page.Schedules ?? []).filter(
310 (s): s is scheduler.ScheduleSummary & { Name: string } => s.Name != null,
311 ),
312 ),
313 ),
314 );
315
316 // Hydrate each summary via GetSchedule into the exact `read`
317 // shape. Skip schedules deleted between list and get.
318 const rows = yield* Effect.forEach(
319 summaries,
320 (summary) => {
321 const groupName = summary.GroupName ?? "default";
322 return scheduler
323 .getSchedule({
324 Name: summary.Name,
325 GroupName: groupName !== "default" ? groupName : undefined,
326 })
327 .pipe(
328 Effect.map((described) =>
329 described.Arn && described.Name
330 ? {
331 scheduleArn: described.Arn,
332 scheduleName: described.Name,
333 groupName: described.GroupName ?? groupName,
334 state: described.State,
335 }
336 : undefined,
337 ),
338 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
339 );
340 },
341 { concurrency: 10 },
342 );
343
344 return rows.filter((row): row is Schedule["Attributes"] => row !== undefined);
345 }),
346 delete: Effect.fn(function* ({ output }) {
347 yield* scheduler
348 .deleteSchedule({
349 Name: output.scheduleName,
350 GroupName: output.groupName !== "default" ? output.groupName : undefined,
351 })
352 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
353 }),
354 };
355 }),
356 );