1import * as InternetMonitor from "@/AWS/InternetMonitor";
2import * as Lambda from "@/AWS/Lambda";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Result from "effect/Result";
7import * as Schedule from "effect/Schedule";
8import * as Stream from "effect/Stream";
9import { HttpServerRequest } from "effect/http/HttpServerRequest";
10import * as HttpServerResponse from "effect/http/HttpServerResponse";
11import path from "pathe";
12
13const main = path.resolve(import.meta.dirname, "handler.ts");
14
15// A syntactically-plausible but nonexistent event id.
16const BOGUS_EVENT_ID = "alchemy-nonexistent-internetmonitor-event-id";
17
18export class InternetMonitorBindingsFunction extends Lambda.Function<Lambda.Function>()(
19 "InternetMonitorBindingsFunction",
20) {}
21
22export 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 (
83 request.method === "GET" &&
84 pathname === "/health-events/typed-probe"
85 ) {
86 const tag = yield* bound
87 .getHealthEvent({ EventId: BOGUS_EVENT_ID })
88 .pipe(
89 Effect.map(() => "ok"),
90 Effect.catch((e) => Effect.succeed(e._tag)),
91 );
92 return yield* HttpServerResponse.json({ tag });
93 }
94
95 // Account-level list of global internet events.
96 if (request.method === "GET" && pathname === "/internet-events") {
97 const { InternetEvents } = yield* bound.listInternetEvents({
98 MaxResults: 10,
99 });
100 return yield* HttpServerResponse.json({
101 count: (InternetEvents ?? []).length,
102 });
103 }
104
105 if (
106 request.method === "GET" &&
107 pathname === "/internet-event/typed-probe"
108 ) {
109 const tag = yield* bound
110 .getInternetEvent({ EventId: BOGUS_EVENT_ID })
111 .pipe(
112 Effect.map(() => "ok"),
113 Effect.catch((e) => Effect.succeed(e._tag)),
114 );
115 return yield* HttpServerResponse.json({ tag });
116 }
117
118 // Full query-interface loop: start a MEASUREMENTS query over the
119 // trailing hour, poll (bounded) until terminal, read results when
120 // it succeeds, and probe StopQuery's grant on the finished query.
121 // Each step reports its typed failure so a single grant gap is
122 // diagnosable from the JSON instead of a generic 500.
123 if (request.method === "GET" && pathname === "/query") {
124 const now = yield* Effect.sync(() => Date.now());
125 const started = yield* Effect.result(
126 bound.startQuery({
127 StartTime: new Date(now - 3_600_000),
128 EndTime: new Date(now),
129 QueryType: "MEASUREMENTS",
130 }),
131 );
132 if (Result.isFailure(started)) {
133 return yield* HttpServerResponse.json({
134 step: "startQuery",
135 tag: started.failure._tag,
136 error: String(started.failure),
137 });
138 }
139 const QueryId = started.success.QueryId;
140 const polled = yield* Effect.result(
141 bound.getQueryStatus({ QueryId }).pipe(
142 Effect.repeat({
143 schedule: Schedule.spaced("2 seconds"),
144 until: (r): boolean =>
145 r.Status !== "QUEUED" && r.Status !== "RUNNING",
146 times: 20,
147 }),
148 ),
149 );
150 if (Result.isFailure(polled)) {
151 return yield* HttpServerResponse.json({
152 step: "getQueryStatus",
153 tag: polled.failure._tag,
154 error: String(polled.failure),
155 });
156 }
157 const Status = polled.success.Status;
158 const results = yield* Effect.result(
159 Status === "SUCCEEDED"
160 ? bound.getQueryResults({ QueryId })
161 : Effect.succeed({ Fields: [], Data: [] }),
162 );
163 if (Result.isFailure(results)) {
164 return yield* HttpServerResponse.json({
165 step: "getQueryResults",
166 tag: results.failure._tag,
167 error: String(results.failure),
168 });
169 }
170 // Stopping an already-terminal query may be rejected — either the
171 // success or the typed rejection proves internetmonitor:StopQuery.
172 const stopTag = yield* bound.stopQuery({ QueryId }).pipe(
173 Effect.map(() => "ok"),
174 Effect.catch((e) => Effect.succeed(e._tag)),
175 );
176 return yield* HttpServerResponse.json({
177 step: "ok",
178 queryId: QueryId,
179 status: Status,
180 fields: (results.success.Fields ?? []).length,
181 rows: (results.success.Data ?? []).length,
182 stopTag,
183 });
184 }
185
186 return yield* HttpServerResponse.json(
187 { error: "Not found", method: request.method, pathname },
188 { status: 404 },
189 );
190 }).pipe(Effect.orDie),
191 };
192 }).pipe(
193 Effect.provide(
194 Layer.mergeAll(
195 Lambda.EventSource,
196 InternetMonitor.GetHealthEventHttp,
197 InternetMonitor.ListHealthEventsHttp,
198 InternetMonitor.StartQueryHttp,
199 InternetMonitor.GetQueryStatusHttp,
200 InternetMonitor.GetQueryResultsHttp,
201 InternetMonitor.StopQueryHttp,
202 InternetMonitor.GetInternetEventHttp,
203 InternetMonitor.ListInternetEventsHttp,
204 ),
205 ),
206 ),
207);