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

main
ts 171 lines 6.5 KB
Raw
1 import * as EC2 from "@alchemy.run/aws/EC2";
2 import * as GlobalAccelerator from "@alchemy.run/aws/GlobalAccelerator";
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 Result from "effect/Result";
10 import * as Schedule from "effect/Schedule";
11 import path from "pathe";
12
13 const main = path.resolve(import.meta.dirname, "handler.ts");
14
15 export class GaTestFunction extends Lambda.Function<Lambda.Function>()("GaTestFunction") {}
16
17 // Global Accelerator serializes config changes per accelerator; a mutation
18 // racing an in-flight transaction is rejected with
19 // TransactionInProgressException. Retry briefly inside the Lambda (bounded
20 // well under the function timeout).
21 const retryGaTransaction = <A, E extends { _tag: string }, R>(
22 self: Effect.Effect<A, E, R>,
23 ): Effect.Effect<A, E, R> =>
24 Effect.retry(self, {
25 while: (e): boolean =>
26 e._tag === "TransactionInProgressException" || e._tag === "ConflictException",
27 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
28 });
29
30 export default GaTestFunction.make(
31 {
32 main,
33 functionUrl: true,
34 timeout: Duration.seconds(60),
35 },
36 Effect.gen(function* () {
37 // The accelerator/listener/endpoint group the bindings are bound to. The
38 // endpoint group starts empty; the Add/RemoveEndpoints bindings register
39 // and deregister the Elastic IP below at runtime.
40 const accelerator = yield* GlobalAccelerator.Accelerator("BindingAccelerator", {});
41 const listener = yield* GlobalAccelerator.Listener("BindingListener", {
42 acceleratorArn: accelerator.acceleratorArn,
43 portRanges: [{ fromPort: 80, toPort: 80 }],
44 protocol: "TCP",
45 });
46 const group = yield* GlobalAccelerator.EndpointGroup("BindingGroup", {
47 listenerArn: listener.listenerArn,
48 endpointGroupRegion: "us-west-2",
49 });
50 // An Elastic IP is the cheapest endpoint type Global Accelerator accepts
51 // (no instance/load balancer required).
52 const eip = yield* EC2.EIP("BindingEip", {});
53 const AllocationId = yield* eip.allocationId;
54
55 const describeAccelerator = yield* GlobalAccelerator.DescribeAccelerator(accelerator);
56 const describeEndpointGroup = yield* GlobalAccelerator.DescribeEndpointGroup(group);
57 const addEndpoints = yield* GlobalAccelerator.AddEndpoints(group);
58 const removeEndpoints = yield* GlobalAccelerator.RemoveEndpoints(group);
59
60 const bound = {
61 describeAccelerator,
62 describeEndpointGroup,
63 addEndpoints,
64 removeEndpoints,
65 };
66
67 return {
68 fetch: Effect.gen(function* () {
69 const request = yield* HttpServerRequest;
70 const url = new URL(request.originalUrl);
71 const pathname = url.pathname;
72
73 if (request.method === "GET" && pathname === "/bindings") {
74 return yield* HttpServerResponse.json({
75 bound: Object.keys(bound),
76 });
77 }
78
79 // The Elastic IP the test uses to drive Add/RemoveEndpoints.
80 if (request.method === "GET" && pathname === "/context") {
81 const allocationId = yield* AllocationId;
82 return yield* HttpServerResponse.json({ allocationId });
83 }
84
85 // Accelerator-scoped read: the ARN is injected from the binding.
86 if (request.method === "GET" && pathname === "/accelerator") {
87 const { Accelerator } = yield* describeAccelerator();
88 return yield* HttpServerResponse.json({
89 name: Accelerator?.Name,
90 status: Accelerator?.Status,
91 dnsName: Accelerator?.DnsName,
92 enabled: Accelerator?.Enabled,
93 });
94 }
95
96 // Endpoint-group-scoped read: per-endpoint health.
97 if (request.method === "GET" && pathname === "/group") {
98 const { EndpointGroup } = yield* describeEndpointGroup({});
99 return yield* HttpServerResponse.json({
100 region: EndpointGroup?.EndpointGroupRegion,
101 endpoints: (EndpointGroup?.EndpointDescriptions ?? []).map((endpoint) => ({
102 endpointId: endpoint.EndpointId,
103 healthState: endpoint.HealthState,
104 })),
105 });
106 }
107
108 // Register the Elastic IP as an endpoint at runtime. Failures are
109 // surfaced as a 400 JSON body (with the typed tag) so the test fails
110 // fast and diagnostically instead of retrying an opaque 5xx.
111 if (request.method === "POST" && pathname === "/endpoints/add") {
112 const allocationId = yield* AllocationId;
113 const added = yield* Effect.result(
114 retryGaTransaction(
115 addEndpoints({
116 EndpointConfigurations: [{ EndpointId: allocationId, Weight: 64 }],
117 }),
118 ),
119 );
120 if (Result.isFailure(added)) {
121 return yield* HttpServerResponse.json(
122 { error: "addEndpoints", failure: JSON.stringify(added.failure) },
123 { status: 400 },
124 );
125 }
126 return yield* HttpServerResponse.json({
127 added: (added.success.EndpointDescriptions ?? []).map(
128 (endpoint) => endpoint.EndpointId,
129 ),
130 });
131 }
132
133 // Deregister the Elastic IP endpoint.
134 if (request.method === "POST" && pathname === "/endpoints/remove") {
135 const allocationId = yield* AllocationId;
136 const removed = yield* Effect.result(
137 retryGaTransaction(
138 removeEndpoints({
139 EndpointIdentifiers: [{ EndpointId: allocationId }],
140 }),
141 ),
142 );
143 if (Result.isFailure(removed)) {
144 return yield* HttpServerResponse.json(
145 {
146 error: "removeEndpoints",
147 failure: JSON.stringify(removed.failure),
148 },
149 { status: 400 },
150 );
151 }
152 return yield* HttpServerResponse.json({ removed: allocationId });
153 }
154
155 return yield* HttpServerResponse.json(
156 { error: "Not found", method: request.method, pathname },
157 { status: 404 },
158 );
159 }).pipe(Effect.orDie),
160 };
161 }).pipe(
162 Effect.provide(
163 Layer.mergeAll(
164 GlobalAccelerator.DescribeAcceleratorHttp,
165 GlobalAccelerator.DescribeEndpointGroupHttp,
166 GlobalAccelerator.AddEndpointsHttp,
167 GlobalAccelerator.RemoveEndpointsHttp,
168 ),
169 ),
170 ),
171 );