@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 308 lines 9.42 KB
Raw
1 import type * as scheduler from "@distilled.cloud/aws/scheduler";
2 import type { Input, InputProps } from "alchemy/Input";
3 import * as Effect from "effect/Effect";
4 import type { Cluster } from "../ECS/Cluster.ts";
5 import * as IAM from "../IAM/index.ts";
6 import type { Function } from "../Lambda/Function.ts";
7 import type { Queue } from "../SQS/Queue.ts";
8 import { Schedule } from "./Schedule.ts";
9 import type { ScheduleGroup } from "./ScheduleGroup.ts";
10
11 /**
12 * Accumulated state of a fluent schedule builder (`every`/`cron`/`at` plus
13 * any `.named(...)` and target options applied so far).
14 */
15 export interface ScheduleBuilderState {
16 /** Schedule expression: `rate(...)`, `cron(...)`, or `at(...)`. */
17 expression: string;
18 /** Explicit schedule name set via `.named(...)`. */
19 name?: string;
20 /** Schedule group the schedule is created in. */
21 group?: ScheduleGroup;
22 /** Description on the backing schedule. */
23 description?: string;
24 /** Timezone for cron or at expressions. */
25 timezone?: string;
26 /** Date before which the schedule does not fire. */
27 startDate?: Date;
28 /** Date after which the schedule stops firing. */
29 endDate?: Date;
30 /** Desired schedule state (`ENABLED` / `DISABLED`). */
31 state?: string;
32 /** KMS key ARN used to encrypt the schedule's target input. */
33 kmsKeyArn?: string;
34 /**
35 * Flexible time window configuration.
36 * @default { Mode: "OFF" }
37 */
38 flexibleTimeWindow?: scheduler.FlexibleTimeWindow;
39 /** Action after a one-time schedule completes (e.g. `DELETE`). */
40 actionAfterCompletion?: string;
41 }
42
43 /**
44 * Options accepted by the `every`/`cron`/`at` schedule builders.
45 */
46 export interface ScheduleOptions {
47 /** Schedule group the schedule is created in. */
48 group?: ScheduleGroup;
49 /** Description on the backing schedule. */
50 description?: string;
51 /** Timezone for cron or at expressions. */
52 timezone?: string;
53 /** Date before which the schedule does not fire. */
54 startDate?: Date;
55 /** Date after which the schedule stops firing. */
56 endDate?: Date;
57 /** Desired schedule state (`ENABLED` / `DISABLED`). */
58 state?: string;
59 /** KMS key ARN used to encrypt the schedule's target input. */
60 kmsKeyArn?: string;
61 /**
62 * Flexible time window configuration.
63 * @default { Mode: "OFF" }
64 */
65 flexibleTimeWindow?: scheduler.FlexibleTimeWindow;
66 /** Action after a one-time schedule completes (e.g. `DELETE`). */
67 actionAfterCompletion?: string;
68 }
69
70 /**
71 * Target options for `.toLambda(fn, props)`.
72 */
73 export interface LambdaTargetProps {
74 /** JSON-serializable payload passed to the function as the event. */
75 input?: unknown;
76 /** Retry policy for failed invocations. */
77 retryPolicy?: scheduler.RetryPolicy;
78 /** Dead-letter queue for undeliverable invocations. */
79 deadLetterConfig?: scheduler.DeadLetterConfig;
80 }
81
82 /**
83 * Target options for `.toQueue(queue, payload, props)` — note the message
84 * payload is passed as `.toQueue`'s second argument, not via `input`.
85 */
86 export interface QueueTargetProps {
87 /** JSON-serializable payload used as the message body. */
88 input?: unknown;
89 /** Retry policy for failed deliveries. */
90 retryPolicy?: scheduler.RetryPolicy;
91 /** Dead-letter queue for undeliverable deliveries. */
92 deadLetterConfig?: scheduler.DeadLetterConfig;
93 /** SQS-specific parameters (e.g. `MessageGroupId` for FIFO queues). */
94 sqs?: scheduler.SqsParameters;
95 }
96
97 /**
98 * Target options for `.toEcsTask(props)`.
99 */
100 export interface EcsTaskTargetProps {
101 /** ECS cluster the task runs on. */
102 cluster: Cluster;
103 /**
104 * Task definition and the roles Scheduler passes to it.
105 *
106 * This is a builder argument (not resource Props), so the fields are
107 * `Input`-typed explicitly: an `AWS.ECS.Task` resource — whose attributes
108 * are `Output`s — is directly assignable here.
109 */
110 task: {
111 /** ARN of the task definition to run. */
112 taskDefinitionArn: Input<string>;
113 /** ARN of the task role (`iam:PassRole` is granted automatically). */
114 taskRoleArn: Input<string>;
115 /** ARN of the execution role (`iam:PassRole` is granted automatically). */
116 executionRoleArn: Input<string>;
117 };
118 /** Subnets for the task's awsvpc network configuration. */
119 subnets: Input<string[]>;
120 /** Security groups for the task's awsvpc network configuration. */
121 securityGroups?: Input<string[]>;
122 /**
123 * Whether the task gets a public IP.
124 * @default false
125 */
126 assignPublicIp?: boolean;
127 /**
128 * Number of tasks to launch per invocation.
129 * @default 1
130 */
131 taskCount?: number;
132 /** JSON-serializable payload passed to the task as the event. */
133 input?: unknown;
134 /** Retry policy for failed task launches. */
135 retryPolicy?: scheduler.RetryPolicy;
136 /** Dead-letter queue for undeliverable invocations. */
137 deadLetterConfig?: scheduler.DeadLetterConfig;
138 }
139
140 export const every = (value: string, options: ScheduleOptions = {}) =>
141 makeBuilder({
142 expression: value.startsWith("rate(") || value.startsWith("cron(") ? value : `rate(${value})`,
143 ...options,
144 });
145
146 export const cron = (expression: string, options: ScheduleOptions = {}) =>
147 makeBuilder({
148 expression,
149 ...options,
150 });
151
152 export const at = (date: Date, options: ScheduleOptions = {}) =>
153 makeBuilder({
154 expression: `at(${date.toISOString().replace(/\.\d{3}Z$/, "Z")})`,
155 ...options,
156 });
157
158 /**
159 * The fluent schedule builder returned by `every`/`cron`/`at`. Route it to a
160 * target with `.toLambda`/`.toQueue`/`.toEcsTask`, or consume it on the host
161 * Function with `consumeSchedule(builder, handler)`.
162 */
163 export type ScheduleBuilder = ReturnType<typeof makeBuilder>;
164
165 const makeBuilder = (state: ScheduleBuilderState) => ({
166 /**
167 * The accumulated builder state (expression, name, group, ...). Read by
168 * `consumeSchedule` to materialize the schedule against the host Function.
169 */
170 state,
171
172 named: (name: string) =>
173 makeBuilder({
174 ...state,
175 name,
176 }),
177
178 toLambda: (fn: Function, props: LambdaTargetProps = {}) =>
179 materializeSchedule(
180 state,
181 fn.LogicalId,
182 [
183 {
184 Effect: "Allow",
185 Action: ["lambda:InvokeFunction"],
186 Resource: [fn.functionArn],
187 },
188 ],
189 {
190 Arn: fn.functionArn as any,
191 Input: toInput(props.input),
192 RetryPolicy: props.retryPolicy,
193 DeadLetterConfig: props.deadLetterConfig,
194 },
195 ),
196
197 toQueue: (queue: Queue, payload?: unknown, props: Omit<QueueTargetProps, "input"> = {}) =>
198 materializeSchedule(
199 state,
200 queue.LogicalId,
201 [
202 {
203 Effect: "Allow",
204 Action: ["sqs:SendMessage"],
205 Resource: [queue.queueArn],
206 },
207 ],
208 {
209 Arn: queue.queueArn as any,
210 Input: toInput(payload),
211 RetryPolicy: props.retryPolicy,
212 DeadLetterConfig: props.deadLetterConfig,
213 SqsParameters: props.sqs,
214 },
215 ),
216
217 toEcsTask: (props: EcsTaskTargetProps) =>
218 materializeSchedule(
219 state,
220 props.cluster.LogicalId,
221 [
222 {
223 Effect: "Allow",
224 Action: ["ecs:RunTask"],
225 Resource: [props.task.taskDefinitionArn],
226 },
227 {
228 Effect: "Allow",
229 Action: ["iam:PassRole"],
230 Resource: [props.task.taskRoleArn, props.task.executionRoleArn],
231 },
232 ],
233 {
234 Arn: props.cluster.clusterArn as any,
235 Input: toInput(props.input),
236 RetryPolicy: props.retryPolicy,
237 DeadLetterConfig: props.deadLetterConfig,
238 EcsParameters: {
239 TaskDefinitionArn: props.task.taskDefinitionArn,
240 TaskCount: props.taskCount ?? 1,
241 LaunchType: "FARGATE",
242 NetworkConfiguration: {
243 awsvpcConfiguration: {
244 Subnets: props.subnets,
245 SecurityGroups: props.securityGroups,
246 AssignPublicIp: props.assignPublicIp ? "ENABLED" : "DISABLED",
247 },
248 },
249 },
250 },
251 ),
252 });
253
254 const materializeSchedule = (
255 state: ScheduleBuilderState,
256 targetId: string,
257 statements: any[],
258 // `InputProps` so target fields may carry unresolved `Output`s (e.g. a
259 // Task's `taskDefinitionArn`); they flow into the `Schedule` resource's
260 // Input-typed `target` prop and resolve at deploy time.
261 target: InputProps<Omit<scheduler.Target, "RoleArn">>,
262 ) =>
263 Effect.gen(function* () {
264 const scheduleId = state.name ?? `${targetId}Schedule`;
265 const role = yield* IAM.Role(`${scheduleId}Role`, {
266 assumeRolePolicyDocument: {
267 Version: "2012-10-17",
268 Statement: [
269 {
270 Effect: "Allow",
271 Principal: {
272 Service: "scheduler.amazonaws.com",
273 },
274 Action: ["sts:AssumeRole"],
275 },
276 ],
277 },
278 inlinePolicies: {
279 ScheduleTarget: {
280 Version: "2012-10-17",
281 Statement: statements,
282 },
283 },
284 });
285
286 return yield* Schedule(scheduleId, {
287 name: state.name,
288 groupName: state.group?.scheduleGroupName,
289 scheduleExpression: state.expression,
290 startDate: state.startDate,
291 endDate: state.endDate,
292 description: state.description,
293 scheduleExpressionTimezone: state.timezone,
294 state: state.state,
295 kmsKeyArn: state.kmsKeyArn,
296 flexibleTimeWindow: state.flexibleTimeWindow ?? {
297 Mode: "OFF",
298 },
299 actionAfterCompletion: state.actionAfterCompletion,
300 target: {
301 ...target,
302 RoleArn: role.roleArn,
303 } as any,
304 });
305 });
306
307 const toInput = (value: unknown) =>
308 value === undefined ? undefined : typeof value === "string" ? value : JSON.stringify(value);