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

main
ts 147 lines 5.29 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import { Bucket } from "@alchemy.run/aws/S3";
3 import * as Synthetics from "@alchemy.run/aws/Synthetics";
4 import * as Output from "alchemy/Output";
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 * as Stream from "effect/Stream";
11 import path from "pathe";
12
13 const main = path.resolve(import.meta.dirname, "handler.ts");
14
15 // Trivial heartbeat script — a single successful step, no page load.
16 const HEARTBEAT_SCRIPT = `
17 const synthetics = require("Synthetics");
18 exports.handler = async function () {
19 return await synthetics.executeStep("heartbeat", async function () {});
20 };
21 `;
22
23 export class SyntheticsBindingsFunction extends Lambda.Function<Lambda.Function>()(
24 "SyntheticsBindingsFunction",
25 ) {}
26
27 export default SyntheticsBindingsFunction.make(
28 {
29 main,
30 functionUrl: true,
31 timeout: Duration.seconds(120),
32 },
33 Effect.gen(function* () {
34 const bucket = yield* Bucket("SynthBindingsArtifacts", {
35 forceDestroy: true,
36 });
37 // `rate(0 minute)` = run exactly once when started, so /start does not
38 // leave a continuously-running canary behind.
39 const canary = yield* Synthetics.Canary("BindingsCanary", {
40 script: HEARTBEAT_SCRIPT,
41 artifactS3Location: Output.interpolate`s3://${bucket.bucketName}/bindings`,
42 schedule: { expression: "rate(0 minute)" },
43 runConfig: { timeout: "60 seconds" },
44 successRetentionPeriod: "1 day",
45 failureRetentionPeriod: "1 day",
46 });
47
48 // Event source: subscribe the host to this canary's status/run events.
49 // The deploy proves the EventBridge rule + invoke permission wiring.
50 yield* Synthetics.consumeCanaryEvents({ canaryNames: [canary.canaryName] }, (events) =>
51 Stream.runForEach(events, (event) =>
52 Effect.log(`synthetics event: ${event["detail-type"]} for ${event.detail["canary-name"]}`),
53 ),
54 );
55
56 const bound = {
57 getCanary: yield* Synthetics.GetCanary(canary),
58 getCanaryRuns: yield* Synthetics.GetCanaryRuns(canary),
59 startCanary: yield* Synthetics.StartCanary(canary),
60 stopCanary: yield* Synthetics.StopCanary(canary),
61 describeCanariesLastRun: yield* Synthetics.DescribeCanariesLastRun(),
62 };
63
64 return {
65 fetch: Effect.gen(function* () {
66 const request = yield* HttpServerRequest;
67 const url = new URL(request.originalUrl);
68 const pathname = url.pathname;
69
70 if (request.method === "GET" && pathname === "/bindings") {
71 return yield* HttpServerResponse.json({
72 bound: Object.keys(bound),
73 });
74 }
75
76 // Canary-scoped read — the canary name is injected.
77 if (request.method === "GET" && pathname === "/canary") {
78 const result = yield* bound.getCanary().pipe(
79 Effect.map((r) => ({
80 tag: "ok",
81 state: r.Canary?.Status?.State,
82 })),
83 Effect.catch((e) => Effect.succeed({ tag: e._tag, state: undefined })),
84 );
85 return yield* HttpServerResponse.json(result);
86 }
87
88 if (request.method === "GET" && pathname === "/runs") {
89 const result = yield* bound.getCanaryRuns({ MaxResults: 10 }).pipe(
90 Effect.map((r) => ({
91 tag: "ok",
92 count: (r.CanaryRuns ?? []).length,
93 })),
94 Effect.catch((e) => Effect.succeed({ tag: e._tag, count: undefined })),
95 );
96 return yield* HttpServerResponse.json(result);
97 }
98
99 // Account-level read across every canary.
100 if (request.method === "GET" && pathname === "/last-run") {
101 const result = yield* bound.describeCanariesLastRun().pipe(
102 Effect.map((r) => ({
103 tag: "ok",
104 count: (r.CanariesLastRun ?? []).length,
105 })),
106 Effect.catch((e) => Effect.succeed({ tag: e._tag, count: undefined })),
107 );
108 return yield* HttpServerResponse.json(result);
109 }
110
111 // Control plane: start the (READY) canary / stop it. A typed
112 // ConflictException still proves the grant round-tripped.
113 if (request.method === "GET" && pathname === "/start") {
114 const tag = yield* bound.startCanary().pipe(
115 Effect.map(() => "ok"),
116 Effect.catch((e) => Effect.succeed(e._tag)),
117 );
118 return yield* HttpServerResponse.json({ tag });
119 }
120
121 if (request.method === "GET" && pathname === "/stop") {
122 const tag = yield* bound.stopCanary().pipe(
123 Effect.map(() => "ok"),
124 Effect.catch((e) => Effect.succeed(e._tag)),
125 );
126 return yield* HttpServerResponse.json({ tag });
127 }
128
129 return yield* HttpServerResponse.json(
130 { error: "Not found", method: request.method, pathname },
131 { status: 404 },
132 );
133 }).pipe(Effect.orDie),
134 };
135 }).pipe(
136 Effect.provide(
137 Layer.mergeAll(
138 Lambda.EventSource,
139 Synthetics.GetCanaryHttp,
140 Synthetics.GetCanaryRunsHttp,
141 Synthetics.StartCanaryHttp,
142 Synthetics.StopCanaryHttp,
143 Synthetics.DescribeCanariesLastRunHttp,
144 ),
145 ),
146 ),
147 );