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

main
ts 150 lines 5.33 KB
Raw
1 import * as EMRContainers from "@alchemy.run/aws/EMRContainers";
2 import { Role } from "@alchemy.run/aws/IAM";
3 import * as Lambda from "@alchemy.run/aws/Lambda";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import path from "pathe";
12
13 const main = path.resolve(import.meta.dirname, "handler.ts");
14
15 export class EmrcTestFunction extends Lambda.Function<Lambda.Function>()("EmrcTestFunction") {}
16
17 export default EmrcTestFunction.make(
18 {
19 main,
20 functionUrl: true,
21 timeout: Duration.seconds(30),
22 },
23 Effect.gen(function* () {
24 // The job template the template-scoped binding is bound to. Templates
25 // are free, account-level, and never run anything by themselves.
26 const jobRole = yield* Role("JobRole", {
27 assumeRolePolicyDocument: {
28 Version: "2012-10-17",
29 Statement: [
30 {
31 Effect: "Allow",
32 Principal: { Service: "pods.eks.amazonaws.com" },
33 Action: ["sts:AssumeRole", "sts:TagSession"],
34 },
35 ],
36 },
37 });
38 const template = yield* EMRContainers.JobTemplate("BindingTemplate", {
39 jobTemplateData: {
40 executionRoleArn: jobRole.roleArn,
41 releaseLabel: "emr-7.5.0-latest",
42 jobDriver: {
43 sparkSubmitJobDriver: {
44 entryPoint: "s3://alchemy-test-emrc/scripts/etl.py",
45 },
46 },
47 },
48 });
49
50 // Event source: subscribe the host to EMR on EKS job run state changes.
51 // The deploy proves the EventBridge rule + invoke permission wiring.
52 yield* EMRContainers.consumeJobRunEvents({ states: ["FAILED", "COMPLETED"] }, (events) =>
53 Stream.runForEach(events, (event) =>
54 Effect.log(`job run ${event.detail.id} -> ${event.detail.state}`),
55 ),
56 );
57
58 const describeJobTemplate = yield* EMRContainers.DescribeJobTemplate(template);
59 const listJobTemplates = yield* EMRContainers.ListJobTemplates();
60 const listVirtualClusters = yield* EMRContainers.ListVirtualClusters();
61 const templateId = yield* template.jobTemplateId;
62
63 const bound = {
64 describeJobTemplate,
65 listJobTemplates,
66 listVirtualClusters,
67 };
68
69 // Drain a bounded number of pages on every observation. AWS list APIs may
70 // return a short (or empty) page with a continuation token while the
71 // account is being mutated by other test files, so repeatedly reading only
72 // page one makes the full-concurrency sweep flaky.
73 const listAllJobTemplates = Effect.fn(function* () {
74 const templates: Array<{ readonly id?: string }> = [];
75 let nextToken: string | undefined;
76 for (let page = 0; page < 10; page++) {
77 const response = yield* listJobTemplates({
78 maxResults: 100,
79 nextToken,
80 });
81 templates.push(...(response.templates ?? []));
82 nextToken = response.nextToken;
83 if (nextToken === undefined) break;
84 }
85 return templates;
86 });
87
88 return {
89 fetch: Effect.gen(function* () {
90 const request = yield* HttpServerRequest;
91 const url = new URL(request.originalUrl);
92 const pathname = url.pathname;
93
94 if (request.method === "GET" && pathname === "/bindings") {
95 return yield* HttpServerResponse.json({
96 bound: Object.keys(bound),
97 });
98 }
99
100 // Template-scoped read: the template id is injected by the binding.
101 if (request.method === "GET" && pathname === "/template") {
102 const { jobTemplate } = yield* describeJobTemplate();
103 return yield* HttpServerResponse.json({
104 id: jobTemplate?.id,
105 name: jobTemplate?.name,
106 releaseLabel: jobTemplate?.jobTemplateData.releaseLabel,
107 });
108 }
109
110 // Account-level list.
111 if (request.method === "GET" && pathname === "/templates") {
112 const expectedTemplateId = yield* templateId;
113 const templates = yield* Effect.repeat(listAllJobTemplates(), {
114 schedule: Schedule.fixed("2 seconds"),
115 until: (items) => items.some((item) => item.id === expectedTemplateId),
116 times: 10,
117 });
118 return yield* HttpServerResponse.json({
119 ids: templates.map((template) => template.id),
120 });
121 }
122
123 // Account-level virtual cluster list (proves IAM grant + call path
124 // without needing an EKS-backed virtual cluster to exist).
125 if (request.method === "GET" && pathname === "/virtual-clusters") {
126 const { virtualClusters } = yield* listVirtualClusters({
127 states: ["RUNNING"],
128 });
129 return yield* HttpServerResponse.json({
130 ids: (virtualClusters ?? []).map((vc) => vc.id),
131 });
132 }
133
134 return yield* HttpServerResponse.json(
135 { error: "Not found", method: request.method, pathname },
136 { status: 404 },
137 );
138 }).pipe(Effect.orDie),
139 };
140 }).pipe(
141 Effect.provide(
142 Layer.mergeAll(
143 Lambda.EventSource,
144 EMRContainers.DescribeJobTemplateHttp,
145 EMRContainers.ListJobTemplatesHttp,
146 EMRContainers.ListVirtualClustersHttp,
147 ),
148 ),
149 ),
150 );