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

main
ts 148 lines 5.67 KB
Raw
1 import * as CloudTrail from "@alchemy.run/aws/CloudTrail";
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 path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "lake-handler.ts");
13
14 /**
15 * Probe helper: run the bound operation and report either the success
16 * projection or the typed error tag, so the test can assert that operations
17 * rejected by CloudTrail fail with a TYPED tag (never an untyped catch-all).
18 */
19 const tagOr = <A, E extends { _tag: string }, R>(
20 effect: Effect.Effect<A, E, R>,
21 onSuccess: (value: A) => Record<string, unknown>,
22 ) =>
23 Effect.result(effect).pipe(
24 Effect.map((result) =>
25 Result.isSuccess(result) ? onSuccess(result.success) : { errorTag: result.failure._tag },
26 ),
27 );
28
29 export class CloudTrailLakeTestFunction extends Lambda.Function<Lambda.Function>()(
30 "CloudTrailLakeTestFunction",
31 ) {}
32
33 export default CloudTrailLakeTestFunction.make(
34 {
35 main,
36 functionUrl: true,
37 // A fresh store settles through CREATED/STARTING_INGESTION before the
38 // first query is accepted; the /query/run retry must fit the invocation.
39 timeout: Duration.seconds(60),
40 },
41 Effect.gen(function* () {
42 // GATED FIXTURE: deploying this requires a CloudTrail-Lake-onboarded
43 // account (Lake is closed to new customers — see the typed
44 // CloudTrailLakeOnboardingClosed probe in EventDataStore.test.ts).
45 const store = yield* CloudTrail.EventDataStore("BindingsLake", {
46 multiRegionEnabled: false,
47 retentionPeriod: "7 days",
48 terminationProtectionEnabled: false,
49 });
50
51 const startQuery = yield* CloudTrail.StartQuery(store);
52 const describeQuery = yield* CloudTrail.DescribeQuery(store);
53 const getQueryResults = yield* CloudTrail.GetQueryResults(store);
54 const cancelQuery = yield* CloudTrail.CancelQuery(store);
55 const listQueries = yield* CloudTrail.ListQueries(store);
56 const generateQuery = yield* CloudTrail.GenerateQuery(store);
57
58 return {
59 fetch: Effect.gen(function* () {
60 const request = yield* HttpServerRequest;
61 const url = new URL(request.originalUrl);
62 const pathname = url.pathname;
63 const param = (name: string) => url.searchParams.get(name) ?? "";
64
65 // Start a Lake query; the QueryStatement callback receives the bound
66 // store's ID for the FROM clause. Rides out the store's
67 // CREATED/STARTING_INGESTION settling window with a bounded retry.
68 if (request.method === "GET" && pathname === "/query/run") {
69 const result = yield* startQuery({
70 QueryStatement: (id) => `SELECT eventID FROM ${id} LIMIT 1`,
71 }).pipe(
72 Effect.retry({
73 while: (e): boolean =>
74 e._tag === "InactiveEventDataStoreException" ||
75 e._tag === "EventDataStoreNotFoundException" ||
76 e._tag === "MaxConcurrentQueriesException",
77 schedule: Schedule.spaced("2 seconds"),
78 times: 10,
79 }),
80 );
81 return yield* HttpServerResponse.json({ queryId: result.QueryId });
82 }
83
84 if (request.method === "GET" && pathname === "/query/describe") {
85 const result = yield* describeQuery({ QueryId: param("id") });
86 return yield* HttpServerResponse.json({
87 status: result.QueryStatus,
88 });
89 }
90
91 if (request.method === "GET" && pathname === "/query/results") {
92 const result = yield* getQueryResults({ QueryId: param("id") });
93 return yield* HttpServerResponse.json({
94 status: result.QueryStatus,
95 rows: (result.QueryResultRows ?? []).length,
96 });
97 }
98
99 // Cancelling an already-finished query fails with the typed
100 // InactiveQueryException — either outcome proves IAM + typed errors.
101 if (request.method === "POST" && pathname === "/query/cancel") {
102 return yield* HttpServerResponse.json(
103 yield* tagOr(cancelQuery({ QueryId: param("id") }), (result) => ({
104 status: result.QueryStatus,
105 })),
106 );
107 }
108
109 // The bound store is injected as the request's EventDataStore.
110 if (request.method === "GET" && pathname === "/query/list") {
111 const result = yield* listQueries({ MaxResults: 10 });
112 return yield* HttpServerResponse.json({
113 ids: (result.Queries ?? []).map((q) => q.QueryId),
114 });
115 }
116
117 // Natural-language SQL generation may be region/entitlement gated —
118 // a rejection must surface as a TYPED tag.
119 if (request.method === "POST" && pathname === "/query/generate") {
120 return yield* HttpServerResponse.json(
121 yield* tagOr(
122 generateQuery({
123 Prompt: "How many events were recorded in the last day?",
124 }),
125 (result) => ({ statement: result.QueryStatement }),
126 ),
127 );
128 }
129
130 return yield* HttpServerResponse.json(
131 { error: "Not found", method: request.method, pathname },
132 { status: 404 },
133 );
134 }).pipe(Effect.orDie),
135 };
136 }).pipe(
137 Effect.provide(
138 Layer.mergeAll(
139 CloudTrail.StartQueryHttp,
140 CloudTrail.DescribeQueryHttp,
141 CloudTrail.GetQueryResultsHttp,
142 CloudTrail.CancelQueryHttp,
143 CloudTrail.ListQueriesHttp,
144 CloudTrail.GenerateQueryHttp,
145 ),
146 ),
147 ),
148 );