@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 225 lines 8.73 KB
Raw
1 import * as IAM from "@alchemy.run/aws/IAM";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Scheduler from "@alchemy.run/aws/Scheduler";
4 import * as SQS from "@alchemy.run/aws/SQS";
5 import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import { HttpServerRequest } from "effect/http/HttpServerRequest";
8 import * as HttpServerResponse from "effect/http/HttpServerResponse";
9 import * as Layer from "effect/Layer";
10 import path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "handler.ts");
13
14 // Shared Lambda fixture for the EventBridge Scheduler runtime surface:
15 // - CreateSchedule / GetSchedule / DeleteSchedule bindings, one HTTP route
16 // per operation. Runtime-minted one-shot schedules target the sink queue,
17 // so the test can observe the fire out-of-band.
18 // - consumeSchedule (the cron-handler DX): a rate(1 minute) schedule invokes
19 // this same Lambda; the handler forwards the typed event into the cron
20 // queue for out-of-band observation.
21 export class SchedulerTestFunction extends Lambda.Function<Lambda.Function>()(
22 "SchedulerTestFunction",
23 ) {}
24
25 export default SchedulerTestFunction.make(
26 {
27 main,
28 functionUrl: true,
29 // AWS's 3s default intermittently kills invocations that fan out SDK
30 // calls (create + describe schedules) — always set an explicit timeout.
31 timeout: Duration.seconds(30),
32 },
33 Effect.gen(function* () {
34 // Queue that runtime-minted one-shot schedules deliver into.
35 const sinkQueue = yield* SQS.Queue("SchedulerSinkQueue");
36 // Queue the consumeSchedule cron handler forwards its typed events into.
37 const cronQueue = yield* SQS.Queue("SchedulerCronQueue");
38
39 // Execution role for runtime-minted schedules: assumable by EventBridge
40 // Scheduler, allowed to send into the sink queue. The CreateSchedule
41 // binding contributes iam:PassRole on this role to the host's policy.
42 const executionRole = yield* IAM.Role("SchedulerExecutionRole", {
43 assumeRolePolicyDocument: {
44 Version: "2012-10-17",
45 Statement: [
46 {
47 Effect: "Allow",
48 Principal: { Service: "scheduler.amazonaws.com" },
49 Action: ["sts:AssumeRole"],
50 },
51 ],
52 },
53 inlinePolicies: {
54 ScheduleTarget: {
55 Version: "2012-10-17",
56 Statement: [
57 {
58 Effect: "Allow",
59 Action: ["sqs:SendMessage"],
60 Resource: [sinkQueue.queueArn],
61 },
62 ],
63 },
64 },
65 });
66
67 const createSchedule = yield* Scheduler.CreateSchedule(executionRole);
68 const updateSchedule = yield* Scheduler.UpdateSchedule(executionRole);
69 const getSchedule = yield* Scheduler.GetSchedule();
70 const deleteSchedule = yield* Scheduler.DeleteSchedule();
71 const listSchedules = yield* Scheduler.ListSchedules();
72 const sendCron = yield* SQS.SendMessage(cronQueue);
73
74 // The cron-handler DX: consume this Lambda's own scheduled invocations
75 // and forward the typed event into the cron queue.
76 yield* Scheduler.consumeSchedule(Scheduler.every("1 minute"), (event) =>
77 sendCron({
78 MessageBody: JSON.stringify({
79 marker: "alch-schedtest-cron-fired",
80 scheduleId: event.scheduleId,
81 scheduleArn: event.scheduleArn,
82 scheduledTime: event.scheduledTime,
83 executionId: event.executionId,
84 }),
85 }).pipe(Effect.orDie, Effect.asVoid),
86 );
87
88 const sinkQueueArn = yield* sinkQueue.queueArn;
89 const sinkQueueUrl = yield* sinkQueue.queueUrl;
90 const cronQueueUrl = yield* cronQueue.queueUrl;
91
92 return {
93 fetch: Effect.gen(function* () {
94 const request = yield* HttpServerRequest;
95 const url = new URL(request.originalUrl);
96 const pathname = url.pathname;
97
98 if (request.method === "GET" && pathname === "/info") {
99 return yield* HttpServerResponse.json({
100 ok: true,
101 sinkQueueUrl: yield* sinkQueueUrl,
102 cronQueueUrl: yield* cronQueueUrl,
103 });
104 }
105
106 if (request.method === "GET" && pathname === "/schedules") {
107 const namePrefix = url.searchParams.get("namePrefix") ?? undefined;
108 // Surface the typed failure in the body (424 so the test's 5xx
109 // retry doesn't mask a genuine error) instead of dying to a 500.
110 return yield* listSchedules({ NamePrefix: namePrefix }).pipe(
111 Effect.flatMap((listed) =>
112 HttpServerResponse.json({
113 names: (listed.Schedules ?? []).flatMap((s) => (s.Name ? [s.Name] : [])),
114 }),
115 ),
116 Effect.catch((e) =>
117 HttpServerResponse.json({ error: e._tag, message: String(e) }, { status: 424 }),
118 ),
119 );
120 }
121
122 if (pathname.startsWith("/schedules/")) {
123 const name = pathname.slice("/schedules/".length);
124
125 if (request.method === "POST") {
126 const delaySeconds = Number(url.searchParams.get("delaySeconds") ?? "30");
127 const fireAt = yield* Effect.sync(() => new Date(Date.now() + delaySeconds * 1000));
128 // One-shot at() expressions take second granularity, no timezone
129 // suffix (UTC by default): at(yyyy-mm-ddThh:mm:ss)
130 const expression = `at(${fireAt.toISOString().slice(0, 19)})`;
131
132 const created = yield* createSchedule({
133 Name: name,
134 ScheduleExpression: expression,
135 ActionAfterCompletion: "DELETE",
136 Target: {
137 Arn: yield* sinkQueueArn,
138 Input: JSON.stringify({ marker: name }),
139 },
140 }).pipe(Effect.catchTag("ConflictException", () => Effect.succeed(undefined)));
141
142 if (created === undefined) {
143 return yield* HttpServerResponse.json(
144 { error: "Schedule already exists", name },
145 { status: 409 },
146 );
147 }
148 return yield* HttpServerResponse.json({
149 scheduleArn: created.ScheduleArn,
150 expression,
151 });
152 }
153
154 if (request.method === "PUT") {
155 const delaySeconds = Number(url.searchParams.get("delaySeconds") ?? "900");
156 const description = url.searchParams.get("description") ?? undefined;
157 const fireAt = yield* Effect.sync(() => new Date(Date.now() + delaySeconds * 1000));
158 const expression = `at(${fireAt.toISOString().slice(0, 19)})`;
159
160 // UpdateSchedule is a full PUT — resend the complete config.
161 const updated = yield* updateSchedule({
162 Name: name,
163 ScheduleExpression: expression,
164 Description: description,
165 ActionAfterCompletion: "DELETE",
166 Target: {
167 Arn: yield* sinkQueueArn,
168 Input: JSON.stringify({ marker: name }),
169 },
170 }).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)));
171
172 if (updated === undefined) {
173 return yield* HttpServerResponse.json({ error: "Not found", name }, { status: 404 });
174 }
175 return yield* HttpServerResponse.json({
176 scheduleArn: updated.ScheduleArn,
177 expression,
178 });
179 }
180
181 if (request.method === "GET") {
182 const found = yield* getSchedule({ Name: name }).pipe(
183 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)),
184 );
185 if (found === undefined) {
186 return yield* HttpServerResponse.json({ error: "Not found", name }, { status: 404 });
187 }
188 return yield* HttpServerResponse.json({
189 arn: found.Arn,
190 name: found.Name,
191 state: found.State,
192 expression: found.ScheduleExpression,
193 actionAfterCompletion: found.ActionAfterCompletion,
194 });
195 }
196
197 if (request.method === "DELETE") {
198 const deleted = yield* deleteSchedule({ Name: name }).pipe(
199 Effect.as(true),
200 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(false)),
201 );
202 return yield* HttpServerResponse.json({ deleted }, { status: deleted ? 200 : 404 });
203 }
204 }
205
206 return yield* HttpServerResponse.json(
207 { error: "Not found", method: request.method, pathname },
208 { status: 404 },
209 );
210 }).pipe(Effect.orDie),
211 };
212 }).pipe(
213 Effect.provide(
214 Layer.mergeAll(
215 Scheduler.CreateScheduleHttp,
216 Scheduler.UpdateScheduleHttp,
217 Scheduler.GetScheduleHttp,
218 Scheduler.DeleteScheduleHttp,
219 Scheduler.ListSchedulesHttp,
220 Lambda.ScheduleEventSource,
221 SQS.SendMessageHttp,
222 ),
223 ),
224 ),
225 );