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

main
ts 371 lines 13.3 KB
Raw
1 import * as Deadline from "@alchemy.run/aws/Deadline";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Stream from "effect/Stream";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "handler.ts");
12
13 /**
14 * Minimal valid Open Job Description template. With no fleet associated to
15 * the queue the job simply sits READY — nothing ever runs (or costs money).
16 */
17 const JOB_TEMPLATE = JSON.stringify({
18 specificationVersion: "jobtemplate-2023-09",
19 name: "AlchemyDeadlineBindingsJob",
20 steps: [
21 {
22 name: "Echo",
23 script: {
24 actions: { onRun: { command: "/bin/echo", args: ["hello"] } },
25 },
26 },
27 ],
28 });
29
30 export class DeadlineTestFunction extends Lambda.Function<Lambda.Function>()(
31 "DeadlineTestFunction",
32 ) {}
33
34 export default DeadlineTestFunction.make(
35 {
36 main,
37 functionUrl: true,
38 timeout: Duration.seconds(30),
39 },
40 Effect.gen(function* () {
41 // The farm + queue the bindings are bound to. No fleet is associated,
42 // so submitted jobs stay READY and never provision workers.
43 const farm = yield* Deadline.Farm("BindingsFarm", {
44 description: "alchemy deadline bindings fixture farm",
45 });
46 const queue = yield* Deadline.Queue("BindingsQueue", {
47 farmId: farm.farmId,
48 description: "alchemy deadline bindings fixture queue",
49 jobRunAsUser: { runAs: "WORKER_AGENT_USER" },
50 });
51 const QueueId = yield* queue.queueId;
52
53 // Event source: subscribe the host to Deadline job status changes. The
54 // deploy proves the EventBridge rule + invoke permission wiring.
55 yield* Deadline.consumeFarmEvents({ kinds: ["job-run", "job-lifecycle"] }, (events) =>
56 Stream.runForEach(events, (event) =>
57 Effect.log(`deadline job event: ${event.detail.jobId} -> ${event.detail.status}`),
58 ),
59 );
60
61 const createJob = yield* Deadline.CreateJob(queue);
62 const getJob = yield* Deadline.GetJob(queue);
63 const updateJob = yield* Deadline.UpdateJob(queue);
64 const listJobs = yield* Deadline.ListJobs(queue);
65 const listJobParameterDefinitions = yield* Deadline.ListJobParameterDefinitions(queue);
66 const searchJobs = yield* Deadline.SearchJobs(queue);
67 const searchSteps = yield* Deadline.SearchSteps(queue);
68 const searchTasks = yield* Deadline.SearchTasks(queue);
69 const getSession = yield* Deadline.GetSession(queue);
70 const listSessions = yield* Deadline.ListSessions(queue);
71 const getSessionAction = yield* Deadline.GetSessionAction(queue);
72 const listSessionActions = yield* Deadline.ListSessionActions(queue);
73 const getStep = yield* Deadline.GetStep(queue);
74 const listSteps = yield* Deadline.ListSteps(queue);
75 const updateStep = yield* Deadline.UpdateStep(queue);
76 const getTask = yield* Deadline.GetTask(queue);
77 const listTasks = yield* Deadline.ListTasks(queue);
78 const updateTask = yield* Deadline.UpdateTask(queue);
79 const startAggregation = yield* Deadline.StartSessionsStatisticsAggregation(farm);
80 const getAggregation = yield* Deadline.GetSessionsStatisticsAggregation(farm);
81
82 const bound = {
83 createJob,
84 getJob,
85 updateJob,
86 listJobs,
87 listJobParameterDefinitions,
88 searchJobs,
89 searchSteps,
90 searchTasks,
91 getSession,
92 listSessions,
93 getSessionAction,
94 listSessionActions,
95 getStep,
96 listSteps,
97 updateStep,
98 getTask,
99 listTasks,
100 updateTask,
101 startAggregation,
102 getAggregation,
103 };
104
105 return {
106 fetch: Effect.gen(function* () {
107 const request = yield* HttpServerRequest;
108 const url = new URL(request.originalUrl);
109 const pathname = url.pathname;
110 const param = (name: string) => url.searchParams.get(name) ?? "";
111
112 if (request.method === "GET" && pathname === "/bindings") {
113 return yield* HttpServerResponse.json({
114 bound: Object.keys(bound),
115 });
116 }
117
118 if (request.method === "GET" && pathname === "/queue") {
119 return yield* HttpServerResponse.json({ queueId: yield* QueueId });
120 }
121
122 // Submit a render job from the fixture template (farm/queue ids are
123 // injected by the binding).
124 if (request.method === "POST" && pathname === "/jobs") {
125 const { jobId } = yield* createJob({
126 // The outer HTTP fixture retries transient 5xx responses. Keep
127 // CreateJob idempotent if AWS accepted the first request but the
128 // Lambda response was lost.
129 clientToken: "alchemy-deadline-bindings-job",
130 template: JOB_TEMPLATE,
131 templateType: "JSON",
132 priority: 50,
133 });
134 return yield* HttpServerResponse.json({ jobId });
135 }
136
137 if (request.method === "GET" && pathname === "/job") {
138 const job = yield* getJob({ jobId: param("jobId") });
139 return yield* HttpServerResponse.json({
140 jobId: job.jobId,
141 name: job.name,
142 lifecycleStatus: job.lifecycleStatus,
143 priority: job.priority,
144 });
145 }
146
147 if (request.method === "POST" && pathname === "/priority") {
148 yield* updateJob({
149 jobId: param("jobId"),
150 priority: Number(param("priority")),
151 });
152 return yield* HttpServerResponse.json({ ok: true });
153 }
154
155 if (request.method === "GET" && pathname === "/jobs") {
156 const { jobs } = yield* listJobs();
157 return yield* HttpServerResponse.json({
158 ids: (jobs ?? []).map((job) => job.jobId),
159 });
160 }
161
162 // Search the queue's jobs; summaries include the queueId, which the
163 // test feeds back into the statistics aggregation route.
164 if (request.method === "POST" && pathname === "/search") {
165 const { jobs } = yield* searchJobs({ itemOffset: 0 });
166 return yield* HttpServerResponse.json({
167 ids: (jobs ?? []).map((job) => job.jobId),
168 queueIds: (jobs ?? []).map((job) => job.queueId),
169 });
170 }
171
172 if (request.method === "POST" && pathname === "/search/steps") {
173 const { steps } = yield* searchSteps({
174 itemOffset: 0,
175 jobId: param("jobId"),
176 });
177 return yield* HttpServerResponse.json({
178 ids: (steps ?? []).map((step) => step.stepId),
179 });
180 }
181
182 if (request.method === "POST" && pathname === "/search/tasks") {
183 const { tasks } = yield* searchTasks({
184 itemOffset: 0,
185 jobId: param("jobId"),
186 });
187 return yield* HttpServerResponse.json({
188 ids: (tasks ?? []).map((task) => task.taskId),
189 });
190 }
191
192 if (request.method === "GET" && pathname === "/params") {
193 const { jobParameterDefinitions } = yield* listJobParameterDefinitions({
194 jobId: param("jobId"),
195 });
196 return yield* HttpServerResponse.json({
197 count: (jobParameterDefinitions ?? []).length,
198 });
199 }
200
201 if (request.method === "GET" && pathname === "/steps") {
202 const { steps } = yield* listSteps({ jobId: param("jobId") });
203 return yield* HttpServerResponse.json({
204 ids: (steps ?? []).map((step) => step.stepId),
205 names: (steps ?? []).map((step) => step.name),
206 });
207 }
208
209 if (request.method === "GET" && pathname === "/step") {
210 const step = yield* getStep({
211 jobId: param("jobId"),
212 stepId: param("stepId"),
213 });
214 return yield* HttpServerResponse.json({
215 stepId: step.stepId,
216 name: step.name,
217 lifecycleStatus: step.lifecycleStatus,
218 });
219 }
220
221 if (request.method === "GET" && pathname === "/tasks") {
222 const { tasks } = yield* listTasks({
223 jobId: param("jobId"),
224 stepId: param("stepId"),
225 });
226 return yield* HttpServerResponse.json({
227 ids: (tasks ?? []).map((task) => task.taskId),
228 });
229 }
230
231 if (request.method === "GET" && pathname === "/task") {
232 const task = yield* getTask({
233 jobId: param("jobId"),
234 stepId: param("stepId"),
235 taskId: param("taskId"),
236 });
237 return yield* HttpServerResponse.json({
238 taskId: task.taskId,
239 runStatus: task.runStatus,
240 });
241 }
242
243 // Cancel a single READY task (nothing runs — no fleet).
244 if (request.method === "POST" && pathname === "/task/cancel") {
245 yield* updateTask({
246 jobId: param("jobId"),
247 stepId: param("stepId"),
248 taskId: param("taskId"),
249 targetRunStatus: "CANCELED",
250 });
251 return yield* HttpServerResponse.json({ ok: true });
252 }
253
254 // Requeue the whole step's tasks back to READY.
255 if (request.method === "POST" && pathname === "/step/requeue") {
256 yield* updateStep({
257 jobId: param("jobId"),
258 stepId: param("stepId"),
259 targetTaskRunStatus: "READY",
260 });
261 return yield* HttpServerResponse.json({ ok: true });
262 }
263
264 // With no fleet there are never sessions — proves the op + IAM wire
265 // up and returns an empty page.
266 if (request.method === "GET" && pathname === "/sessions") {
267 const { sessions } = yield* listSessions({ jobId: param("jobId") });
268 return yield* HttpServerResponse.json({
269 ids: (sessions ?? []).map((session) => session.sessionId),
270 });
271 }
272
273 if (request.method === "GET" && pathname === "/session") {
274 const session = yield* getSession({
275 jobId: param("jobId"),
276 sessionId: param("sessionId"),
277 });
278 return yield* HttpServerResponse.json({
279 sessionId: session.sessionId,
280 });
281 }
282
283 // No workers means no sessions and therefore no session actions —
284 // proves the op + IAM wire up and returns an empty page. The API
285 // requires a sessionId or taskId to scope the query.
286 if (request.method === "GET" && pathname === "/session-actions") {
287 const { sessionActions } = yield* listSessionActions({
288 jobId: param("jobId"),
289 taskId: param("taskId"),
290 });
291 return yield* HttpServerResponse.json({
292 ids: (sessionActions ?? []).map((action) => action.sessionActionId),
293 });
294 }
295
296 if (request.method === "GET" && pathname === "/session-action") {
297 const action = yield* getSessionAction({
298 jobId: param("jobId"),
299 sessionActionId: param("sessionActionId"),
300 });
301 return yield* HttpServerResponse.json({
302 sessionActionId: action.sessionActionId,
303 status: action.status,
304 });
305 }
306
307 if (request.method === "POST" && pathname === "/stats") {
308 // The API rejects timestamps whose minutes/seconds are not zero —
309 // align the window to whole hours.
310 const hourMs = 3600 * 1000;
311 const endTime = new Date(Math.floor(Date.now() / hourMs) * hourMs);
312 const startTime = new Date(endTime.getTime() - 24 * hourMs);
313 const { aggregationId } = yield* startAggregation({
314 resourceIds: { queueIds: [param("queueId")] },
315 startTime,
316 endTime,
317 groupBy: ["QUEUE_ID"],
318 statistics: ["SUM"],
319 });
320 return yield* HttpServerResponse.json({ aggregationId });
321 }
322
323 if (request.method === "GET" && pathname === "/stats") {
324 const result = yield* getAggregation({
325 aggregationId: param("aggregationId"),
326 });
327 return yield* HttpServerResponse.json({
328 status: result.status,
329 count: (result.statistics ?? []).length,
330 });
331 }
332
333 return yield* HttpServerResponse.json(
334 { error: "Not found", method: request.method, pathname },
335 { status: 404 },
336 );
337 }).pipe(
338 // Surface typed operation errors as a JSON 500 so the test log
339 // shows the real cause instead of an opaque crash.
340 Effect.catch((error) => HttpServerResponse.json({ error: String(error) }, { status: 500 })),
341 Effect.orDie,
342 ),
343 };
344 }).pipe(
345 Effect.provide(
346 Layer.mergeAll(
347 Lambda.EventSource,
348 Deadline.CreateJobHttp,
349 Deadline.GetJobHttp,
350 Deadline.UpdateJobHttp,
351 Deadline.ListJobsHttp,
352 Deadline.ListJobParameterDefinitionsHttp,
353 Deadline.SearchJobsHttp,
354 Deadline.SearchStepsHttp,
355 Deadline.SearchTasksHttp,
356 Deadline.GetSessionHttp,
357 Deadline.ListSessionsHttp,
358 Deadline.GetSessionActionHttp,
359 Deadline.ListSessionActionsHttp,
360 Deadline.GetStepHttp,
361 Deadline.ListStepsHttp,
362 Deadline.UpdateStepHttp,
363 Deadline.GetTaskHttp,
364 Deadline.ListTasksHttp,
365 Deadline.UpdateTaskHttp,
366 Deadline.StartSessionsStatisticsAggregationHttp,
367 Deadline.GetSessionsStatisticsAggregationHttp,
368 ),
369 ),
370 ),
371 );