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

main
ts 196 lines 7.53 KB
Raw
1 import * as InternetMonitor from "@alchemy.run/aws/InternetMonitor";
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 Result from "effect/Result";
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 // A syntactically-plausible but nonexistent event id.
16 const BOGUS_EVENT_ID = "alchemy-nonexistent-internetmonitor-event-id";
17
18 export class InternetMonitorBindingsFunction extends Lambda.Function<Lambda.Function>()(
19 "InternetMonitorBindingsFunction",
20 ) {}
21
22 export default InternetMonitorBindingsFunction.make(
23 {
24 main,
25 functionUrl: true,
26 timeout: Duration.seconds(120),
27 },
28 Effect.gen(function* () {
29 // An empty monitor is cheap (no monitored resources, 1 city-network
30 // cap) and still exercises the monitor-scoped grants + name injection.
31 const monitor = yield* InternetMonitor.Monitor("BindingsMonitor", {
32 resources: [],
33 maxCityNetworksToMonitor: 1,
34 });
35
36 // Event source: subscribe the host to this monitor's health events. The
37 // deploy proves the EventBridge rule + invoke permission wiring.
38 yield* InternetMonitor.consumeHealthEvents(
39 { monitorArns: [monitor.monitorArn], statuses: ["ACTIVE", "RESOLVED"] },
40 (events) =>
41 Stream.runForEach(events, (event) =>
42 Effect.log(
43 `internet-monitor health event: ${event.detail.summary} (${event.detail.impactType})`,
44 ),
45 ),
46 );
47
48 const bound = {
49 getHealthEvent: yield* InternetMonitor.GetHealthEvent(monitor),
50 listHealthEvents: yield* InternetMonitor.ListHealthEvents(monitor),
51 startQuery: yield* InternetMonitor.StartQuery(monitor),
52 getQueryStatus: yield* InternetMonitor.GetQueryStatus(monitor),
53 getQueryResults: yield* InternetMonitor.GetQueryResults(monitor),
54 stopQuery: yield* InternetMonitor.StopQuery(monitor),
55 getInternetEvent: yield* InternetMonitor.GetInternetEvent(),
56 listInternetEvents: yield* InternetMonitor.ListInternetEvents(),
57 };
58
59 return {
60 fetch: Effect.gen(function* () {
61 const request = yield* HttpServerRequest;
62 const url = new URL(request.originalUrl);
63 const pathname = url.pathname;
64
65 if (request.method === "GET" && pathname === "/bindings") {
66 return yield* HttpServerResponse.json({
67 bound: Object.keys(bound),
68 });
69 }
70
71 // Monitor-scoped list — the monitor name is injected; a fresh empty
72 // monitor has no health events.
73 if (request.method === "GET" && pathname === "/health-events") {
74 const { HealthEvents } = yield* bound.listHealthEvents();
75 return yield* HttpServerResponse.json({
76 count: (HealthEvents ?? []).length,
77 });
78 }
79
80 // Typed probe: the request round-trips to the monitor-scoped API
81 // (an IAM gap would surface AccessDeniedException instead).
82 if (request.method === "GET" && pathname === "/health-events/typed-probe") {
83 const tag = yield* bound.getHealthEvent({ EventId: BOGUS_EVENT_ID }).pipe(
84 Effect.map(() => "ok"),
85 Effect.catch((e) => Effect.succeed(e._tag)),
86 );
87 return yield* HttpServerResponse.json({ tag });
88 }
89
90 // Account-level list of global internet events.
91 if (request.method === "GET" && pathname === "/internet-events") {
92 const { InternetEvents } = yield* bound.listInternetEvents({
93 MaxResults: 10,
94 });
95 return yield* HttpServerResponse.json({
96 count: (InternetEvents ?? []).length,
97 });
98 }
99
100 if (request.method === "GET" && pathname === "/internet-event/typed-probe") {
101 const tag = yield* bound.getInternetEvent({ EventId: BOGUS_EVENT_ID }).pipe(
102 Effect.map(() => "ok"),
103 Effect.catch((e) => Effect.succeed(e._tag)),
104 );
105 return yield* HttpServerResponse.json({ tag });
106 }
107
108 // Full query-interface loop: start a MEASUREMENTS query over the
109 // trailing hour, poll (bounded) until terminal, read results when
110 // it succeeds, and probe StopQuery's grant on the finished query.
111 // Each step reports its typed failure so a single grant gap is
112 // diagnosable from the JSON instead of a generic 500.
113 if (request.method === "GET" && pathname === "/query") {
114 const now = yield* Effect.sync(() => Date.now());
115 const started = yield* Effect.result(
116 bound.startQuery({
117 StartTime: new Date(now - 3_600_000),
118 EndTime: new Date(now),
119 QueryType: "MEASUREMENTS",
120 }),
121 );
122 if (Result.isFailure(started)) {
123 return yield* HttpServerResponse.json({
124 step: "startQuery",
125 tag: started.failure._tag,
126 error: String(started.failure),
127 });
128 }
129 const QueryId = started.success.QueryId;
130 const polled = yield* Effect.result(
131 bound.getQueryStatus({ QueryId }).pipe(
132 Effect.repeat({
133 schedule: Schedule.spaced("2 seconds"),
134 until: (r): boolean => r.Status !== "QUEUED" && r.Status !== "RUNNING",
135 times: 20,
136 }),
137 ),
138 );
139 if (Result.isFailure(polled)) {
140 return yield* HttpServerResponse.json({
141 step: "getQueryStatus",
142 tag: polled.failure._tag,
143 error: String(polled.failure),
144 });
145 }
146 const Status = polled.success.Status;
147 const results = yield* Effect.result(
148 Status === "SUCCEEDED"
149 ? bound.getQueryResults({ QueryId })
150 : Effect.succeed({ Fields: [], Data: [] }),
151 );
152 if (Result.isFailure(results)) {
153 return yield* HttpServerResponse.json({
154 step: "getQueryResults",
155 tag: results.failure._tag,
156 error: String(results.failure),
157 });
158 }
159 // Stopping an already-terminal query may be rejected — either the
160 // success or the typed rejection proves internetmonitor:StopQuery.
161 const stopTag = yield* bound.stopQuery({ QueryId }).pipe(
162 Effect.map(() => "ok"),
163 Effect.catch((e) => Effect.succeed(e._tag)),
164 );
165 return yield* HttpServerResponse.json({
166 step: "ok",
167 queryId: QueryId,
168 status: Status,
169 fields: (results.success.Fields ?? []).length,
170 rows: (results.success.Data ?? []).length,
171 stopTag,
172 });
173 }
174
175 return yield* HttpServerResponse.json(
176 { error: "Not found", method: request.method, pathname },
177 { status: 404 },
178 );
179 }).pipe(Effect.orDie),
180 };
181 }).pipe(
182 Effect.provide(
183 Layer.mergeAll(
184 Lambda.EventSource,
185 InternetMonitor.GetHealthEventHttp,
186 InternetMonitor.ListHealthEventsHttp,
187 InternetMonitor.StartQueryHttp,
188 InternetMonitor.GetQueryStatusHttp,
189 InternetMonitor.GetQueryResultsHttp,
190 InternetMonitor.StopQueryHttp,
191 InternetMonitor.GetInternetEventHttp,
192 InternetMonitor.ListInternetEventsHttp,
193 ),
194 ),
195 ),
196 );