@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, 04:45 UTC

main
ts 286 lines 8.8 KB
Raw
1 import { createHash } from "node:crypto";
2 import type * as scheduler from "@distilled.cloud/aws/scheduler";
3 import * as Binding from "alchemy/Binding";
4 import * as Effect from "effect/Effect";
5 import * as IAM from "../IAM/index.ts";
6 import type { Function as LambdaFunction } from "../Lambda/Function.ts";
7 import { qualifiedArnOf } from "../Lambda/QualifiedArn.ts";
8 import type { ScheduleBuilder, ScheduleBuilderState } from "./builders.ts";
9 import { Schedule } from "./Schedule.ts";
10 import type { ScheduleGroup } from "./ScheduleGroup.ts";
11
12 /**
13 * The typed event a consumed schedule delivers to its handler. EventBridge
14 * Scheduler substitutes the `<aws.scheduler.*>` context attributes into the
15 * schedule's `Input` template at invocation time; `scheduleId` is the stable
16 * route id used to match the invocation to the registered handler.
17 */
18 export interface ScheduleEvent {
19 source: "alchemy.scheduler";
20 /**
21 * Stable route id of the `consumeSchedule` registration that created the
22 * schedule.
23 */
24 scheduleId: string;
25 /**
26 * ARN of the schedule (`<aws.scheduler.schedule-arn>`).
27 */
28 scheduleArn: string;
29 /**
30 * The time the invocation was scheduled for, ISO 8601
31 * (`<aws.scheduler.scheduled-time>`).
32 */
33 scheduledTime: string;
34 /**
35 * Unique id of this delivery attempt (`<aws.scheduler.execution-id>`).
36 */
37 executionId: string;
38 /**
39 * Delivery attempt counter, 1-based (`<aws.scheduler.attempt-number>`).
40 */
41 attemptNumber: string;
42 }
43
44 /**
45 * Narrow an arbitrary Lambda invocation payload to a schedule event produced
46 * by `consumeSchedule`.
47 */
48 export const isScheduleEvent = (event: any): event is ScheduleEvent =>
49 event?.source === "alchemy.scheduler" && typeof event?.scheduleId === "string";
50
51 export interface ScheduleRouteProps {
52 /**
53 * Optional schedule group the backing schedule is created in.
54 * @default the AWS default group
55 */
56 group?: ScheduleGroup;
57 /**
58 * Optional description on the backing schedule.
59 */
60 description?: string;
61 /**
62 * Desired schedule state (`ENABLED` / `DISABLED`).
63 */
64 state?: string;
65 /**
66 * Timezone for cron or at expressions.
67 */
68 timezone?: string;
69 /**
70 * Optional start date.
71 */
72 startDate?: Date;
73 /**
74 * Optional end date.
75 */
76 endDate?: Date;
77 /**
78 * Optional KMS key ARN.
79 */
80 kmsKeyArn?: string;
81 /**
82 * Flexible time window configuration.
83 * @default { Mode: "OFF" }
84 */
85 flexibleTimeWindow?: scheduler.FlexibleTimeWindow;
86 /**
87 * Action after a one-time schedule completes.
88 */
89 actionAfterCompletion?: string;
90 /**
91 * Retry policy for failed invocations.
92 */
93 retryPolicy?: scheduler.RetryPolicy;
94 /**
95 * Dead-letter queue for undeliverable invocations.
96 */
97 deadLetterConfig?: scheduler.DeadLetterConfig;
98 }
99
100 export interface ScheduleDescriptor {
101 /**
102 * Stable route id. Defaults to a hash of the schedule expression and the
103 * host Function's logical id.
104 */
105 id?: string;
106 /**
107 * Schedule expression: `rate(...)`, `cron(...)`, or `at(...)`.
108 */
109 expression: string;
110 props?: ScheduleRouteProps;
111 }
112
113 /**
114 * The cron-handler DX for EventBridge Scheduler: a Lambda consumes its own
115 * scheduled invocations. `consumeSchedule(every("5 minutes"), handler)`
116 * provisions the backing `Schedule` (plus the synthesized execution role that
117 * lets Scheduler invoke the host) and registers the runtime handler with a
118 * typed event guard.
119 *
120 * @binding
121 */
122 export interface ScheduleEventSource extends Binding.Service<
123 ScheduleEventSource,
124 "AWS.Scheduler.ScheduleEventSource",
125 ScheduleEventSourceService
126 > {}
127 export const ScheduleEventSource = Binding.Service<ScheduleEventSource>(
128 "AWS.Scheduler.ScheduleEventSource",
129 );
130
131 export type ScheduleEventSourceService = <Req = never>(
132 descriptor: ScheduleDescriptor,
133 process: (event: ScheduleEvent) => Effect.Effect<void, never, Req>,
134 ) => Effect.Effect<void, never, never>;
135
136 /**
137 * Consume a schedule's invocations on the host Lambda Function — the "cron
138 * handler" DX. Build the cadence with `every`/`cron`/`at` and pass the handler
139 * as the last argument; the runtime layer provisions the backing schedule,
140 * the execution role, and the typed event dispatch.
141 *
142 * @example Run a handler every 5 minutes
143 * ```typescript
144 * yield* AWS.Scheduler.consumeSchedule(
145 * AWS.Scheduler.every("5 minutes"),
146 * (event) => Effect.log(`fired at ${event.scheduledTime}`),
147 * );
148 * ```
149 *
150 * @example Name the backing schedule route deterministically
151 * ```typescript
152 * yield* AWS.Scheduler.consumeSchedule(
153 * "NightlyCleanup",
154 * AWS.Scheduler.cron("cron(0 3 * * ? *)"),
155 * (event) => Effect.log(`cleanup ${event.executionId}`),
156 * );
157 * ```
158 */
159 export function consumeSchedule<Req = never>(
160 builder: ScheduleBuilder,
161 process: (event: ScheduleEvent) => Effect.Effect<void, never, Req>,
162 ): Effect.Effect<void, never, ScheduleEventSource | Req>;
163 export function consumeSchedule<Req = never>(
164 id: string,
165 builder: ScheduleBuilder,
166 process: (event: ScheduleEvent) => Effect.Effect<void, never, Req>,
167 ): Effect.Effect<void, never, ScheduleEventSource | Req>;
168 export function consumeSchedule(...args: any[]) {
169 const process = args[args.length - 1] as (
170 event: ScheduleEvent,
171 ) => Effect.Effect<void, never, never>;
172 const head = args.slice(0, -1);
173 const id = typeof head[0] === "string" ? (head[0] as string) : undefined;
174 const builder = (id === undefined ? head[0] : head[1]) as ScheduleBuilder;
175 return ScheduleEventSource.use((source) =>
176 source(toScheduleDescriptor(id, builder.state), process),
177 );
178 }
179
180 const toScheduleDescriptor = (
181 id: string | undefined,
182 state: ScheduleBuilderState,
183 ): ScheduleDescriptor => ({
184 id: id ?? state.name,
185 expression: state.expression,
186 props: {
187 group: state.group,
188 description: state.description,
189 state: state.state,
190 timezone: state.timezone,
191 startDate: state.startDate,
192 endDate: state.endDate,
193 kmsKeyArn: state.kmsKeyArn,
194 flexibleTimeWindow: state.flexibleTimeWindow,
195 actionAfterCompletion: state.actionAfterCompletion,
196 },
197 });
198
199 /**
200 * Derive the stable route id for a schedule descriptor: the explicit id when
201 * given, otherwise a hash of the expression and the host Function's logical
202 * id. Computed identically at deploy time (to name the backing resources) and
203 * at runtime (to match incoming events to the handler).
204 */
205 export const createScheduleRouteId = (descriptor: ScheduleDescriptor, fn: LambdaFunction): string =>
206 descriptor.id ??
207 `Scheduler${createHash("sha1")
208 .update(
209 JSON.stringify({
210 expression: descriptor.expression,
211 host: fn.LogicalId,
212 }),
213 )
214 .digest("hex")
215 .slice(0, 10)}`;
216
217 /**
218 * Deploy-time half of `consumeSchedule`: synthesize the execution role that
219 * lets EventBridge Scheduler invoke the host Function and create the backing
220 * `Schedule` whose `Input` template carries the typed event envelope.
221 *
222 * @binding
223 */
224 export const createScheduleRoute = (
225 routeId: string,
226 descriptor: ScheduleDescriptor,
227 fn: LambdaFunction,
228 ) =>
229 Effect.gen(function* () {
230 const props = descriptor.props ?? {};
231
232 const role = yield* IAM.Role(`${routeId}Role`, {
233 assumeRolePolicyDocument: {
234 Version: "2012-10-17",
235 Statement: [
236 {
237 Effect: "Allow",
238 Principal: { Service: "scheduler.amazonaws.com" },
239 Action: ["sts:AssumeRole"],
240 },
241 ],
242 },
243 inlinePolicies: {
244 InvokeHost: {
245 Version: "2012-10-17",
246 Statement: [
247 {
248 Effect: "Allow",
249 Action: ["lambda:InvokeFunction"],
250 Resource: [qualifiedArnOf(fn)],
251 },
252 ],
253 },
254 },
255 });
256
257 return yield* Schedule(routeId, {
258 groupName: props.group?.scheduleGroupName,
259 scheduleExpression: descriptor.expression,
260 description: props.description,
261 scheduleExpressionTimezone: props.timezone,
262 startDate: props.startDate,
263 endDate: props.endDate,
264 state: props.state,
265 kmsKeyArn: props.kmsKeyArn,
266 flexibleTimeWindow: props.flexibleTimeWindow ?? { Mode: "OFF" },
267 actionAfterCompletion: props.actionAfterCompletion,
268 target: {
269 Arn: qualifiedArnOf(fn) as any,
270 RoleArn: role.roleArn as any,
271 // EventBridge Scheduler substitutes the <aws.scheduler.*> context
272 // attributes into this template at invocation time; the resulting
273 // JSON is the Lambda event payload matched by `isScheduleEvent`.
274 Input: JSON.stringify({
275 source: "alchemy.scheduler",
276 scheduleId: routeId,
277 scheduleArn: "<aws.scheduler.schedule-arn>",
278 scheduledTime: "<aws.scheduler.scheduled-time>",
279 executionId: "<aws.scheduler.execution-id>",
280 attemptNumber: "<aws.scheduler.attempt-number>",
281 }),
282 RetryPolicy: props.retryPolicy,
283 DeadLetterConfig: props.deadLetterConfig,
284 },
285 });
286 });