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

main
ts 265 lines 10.1 KB
Raw
1 import * as DataExchange from "@alchemy.run/aws/DataExchange";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as S3 from "@alchemy.run/aws/S3";
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 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 const CSV = "date,price\n2026-07-14,42.5\n";
16 const KEY = "prices.csv";
17
18 export class DataExchangeTestFunction extends Lambda.Function<Lambda.Function>()(
19 "DataExchangeTestFunction",
20 ) {}
21
22 export default DataExchangeTestFunction.make(
23 {
24 main,
25 functionUrl: true,
26 // The /import route runs a full import job (create → start → poll to
27 // COMPLETED), which takes tens of seconds.
28 timeout: Duration.minutes(2),
29 },
30 Effect.gen(function* () {
31 // The owned data set + draft revision the scoped bindings are bound to,
32 // and the bucket the import job reads from.
33 const dataSet = yield* DataExchange.DataSet("BindingDataSet", {
34 description: "alchemy dataexchange bindings fixture",
35 });
36 const revision = yield* DataExchange.Revision("BindingRevision", {
37 dataSetId: dataSet.dataSetId,
38 comment: "bindings fixture revision",
39 });
40 const bucket = yield* S3.Bucket("BindingBucket", { forceDestroy: true });
41
42 // Event source: subscribe the host to Data Exchange revision events.
43 // The deploy proves the EventBridge rule + invoke permission wiring.
44 yield* DataExchange.consumeDataSetEvents(
45 { kinds: ["revision-published", "revision-revoked"] },
46 (events) =>
47 Stream.runForEach(events, (event) =>
48 Effect.log(`dataexchange event: ${event["detail-type"]}`),
49 ),
50 );
51
52 // Data-set-scoped bindings.
53 const getDataSet = yield* DataExchange.GetDataSet(dataSet);
54 const listDataSetRevisions = yield* DataExchange.ListDataSetRevisions(dataSet);
55 const sendDataSetNotification = yield* DataExchange.SendDataSetNotification(dataSet);
56 // Revision-scoped bindings.
57 const getRevision = yield* DataExchange.GetRevision(revision);
58 const listRevisionAssets = yield* DataExchange.ListRevisionAssets(revision);
59 const getAsset = yield* DataExchange.GetAsset(revision);
60 // Account-scoped bindings.
61 const listDataSets = yield* DataExchange.ListDataSets();
62 const createJob = yield* DataExchange.CreateJob();
63 const startJob = yield* DataExchange.StartJob();
64 const getJob = yield* DataExchange.GetJob();
65 const listJobs = yield* DataExchange.ListJobs();
66 const listDataGrants = yield* DataExchange.ListDataGrants();
67 const listReceivedDataGrants = yield* DataExchange.ListReceivedDataGrants();
68 const listEventActions = yield* DataExchange.ListEventActions();
69 // S3 access for the import job: the Lambda writes the source object and
70 // the Data Exchange import job reads it with the caller's permissions.
71 const putObject = yield* S3.PutObject(bucket);
72 const getObject = yield* S3.GetObject(bucket);
73
74 const bound = {
75 getDataSet,
76 listDataSetRevisions,
77 sendDataSetNotification,
78 getRevision,
79 listRevisionAssets,
80 getAsset,
81 listDataSets,
82 createJob,
83 startJob,
84 getJob,
85 listJobs,
86 listDataGrants,
87 listReceivedDataGrants,
88 listEventActions,
89 putObject,
90 getObject,
91 };
92
93 const BucketName = yield* bucket.bucketName;
94
95 return {
96 fetch: Effect.gen(function* () {
97 const request = yield* HttpServerRequest;
98 const url = new URL(request.originalUrl);
99 const pathname = url.pathname;
100
101 if (request.method === "GET" && pathname === "/bindings") {
102 return yield* HttpServerResponse.json({
103 bound: Object.keys(bound),
104 });
105 }
106
107 // Data-set-scoped read: the DataSetId is injected from the binding.
108 if (request.method === "GET" && pathname === "/data-set") {
109 const detail = yield* getDataSet();
110 return yield* HttpServerResponse.json({
111 id: detail.Id,
112 name: detail.Name,
113 assetType: detail.AssetType,
114 origin: detail.Origin,
115 });
116 }
117
118 if (request.method === "GET" && pathname === "/revisions") {
119 const { Revisions } = yield* listDataSetRevisions();
120 return yield* HttpServerResponse.json({
121 ids: (Revisions ?? []).map((entry) => entry.Id),
122 });
123 }
124
125 // Revision-scoped read: DataSetId + RevisionId are injected.
126 if (request.method === "GET" && pathname === "/revision") {
127 const detail = yield* getRevision();
128 return yield* HttpServerResponse.json({
129 id: detail.Id,
130 finalized: detail.Finalized ?? false,
131 });
132 }
133
134 if (request.method === "GET" && pathname === "/assets") {
135 const { Assets } = yield* listRevisionAssets();
136 return yield* HttpServerResponse.json({
137 count: (Assets ?? []).length,
138 });
139 }
140
141 // Account-level list, filtered down to owned data sets.
142 if (request.method === "GET" && pathname === "/data-sets") {
143 const { DataSets } = yield* listDataSets({ Origin: "OWNED" });
144 return yield* HttpServerResponse.json({
145 ids: (DataSets ?? []).map((entry) => entry.Id),
146 });
147 }
148
149 // Provider-generated notification about the bound data set.
150 if (request.method === "POST" && pathname === "/notify") {
151 const result = yield* sendDataSetNotification({
152 Type: "DATA_UPDATE",
153 Comment: "alchemy bindings fixture notification",
154 }).pipe(Effect.result);
155 return yield* HttpServerResponse.json({
156 ok: result._tag === "Success",
157 error: result._tag === "Failure" ? result.failure._tag : undefined,
158 message: result._tag === "Failure" ? String(result.failure) : undefined,
159 });
160 }
161
162 // Full import flow: put a CSV in S3, import it into the bound
163 // revision via a job, poll the job to COMPLETED, then read the
164 // imported asset back through the revision-scoped bindings. Typed
165 // failures are surfaced as JSON so the test can report the cause.
166 if (request.method === "POST" && pathname === "/import") {
167 const flow = Effect.gen(function* () {
168 yield* putObject({ Key: KEY, Body: CSV, ContentType: "text/csv" });
169
170 const dataSetDetail = yield* getDataSet();
171 const revisionDetail = yield* getRevision();
172 const job = yield* createJob({
173 Type: "IMPORT_ASSETS_FROM_S3",
174 Details: {
175 ImportAssetsFromS3: {
176 DataSetId: dataSetDetail.Id!,
177 RevisionId: revisionDetail.Id!,
178 AssetSources: [{ Bucket: yield* BucketName, Key: KEY }],
179 },
180 },
181 });
182 yield* startJob({ JobId: job.Id! });
183 const done = yield* getJob({ JobId: job.Id! }).pipe(
184 Effect.repeat({
185 schedule: Schedule.spaced("2 seconds"),
186 until: (j): boolean =>
187 j.State === "COMPLETED" || j.State === "ERROR" || j.State === "CANCELLED",
188 times: 40,
189 }),
190 );
191
192 const { Assets } = yield* listRevisionAssets();
193 const assetId = (Assets ?? [])[0]?.Id;
194 const asset = assetId !== undefined ? yield* getAsset({ AssetId: assetId }) : undefined;
195 return {
196 jobState: done.State,
197 jobErrors: done.Errors,
198 assetCount: (Assets ?? []).length,
199 assetName: asset?.Name,
200 };
201 });
202 const result = yield* flow.pipe(Effect.result);
203 return result._tag === "Success"
204 ? yield* HttpServerResponse.json(result.success)
205 : yield* HttpServerResponse.json({
206 error: result.failure._tag,
207 message: String(result.failure),
208 });
209 }
210
211 if (request.method === "GET" && pathname === "/jobs") {
212 const dataSetDetail = yield* getDataSet();
213 const { Jobs } = yield* listJobs({ DataSetId: dataSetDetail.Id! });
214 return yield* HttpServerResponse.json({
215 states: (Jobs ?? []).map((entry) => entry.State),
216 });
217 }
218
219 // Account-level data grant + event action enumerations.
220 if (request.method === "GET" && pathname === "/grants") {
221 const sent = yield* listDataGrants();
222 const received = yield* listReceivedDataGrants();
223 return yield* HttpServerResponse.json({
224 sent: (sent.DataGrantSummaries ?? []).length,
225 received: (received.DataGrantSummaries ?? []).length,
226 });
227 }
228
229 if (request.method === "GET" && pathname === "/event-actions") {
230 const { EventActions } = yield* listEventActions();
231 return yield* HttpServerResponse.json({
232 count: (EventActions ?? []).length,
233 });
234 }
235
236 return yield* HttpServerResponse.json(
237 { error: "Not found", method: request.method, pathname },
238 { status: 404 },
239 );
240 }).pipe(Effect.orDie),
241 };
242 }).pipe(
243 Effect.provide(
244 Layer.mergeAll(
245 Lambda.EventSource,
246 DataExchange.GetDataSetHttp,
247 DataExchange.ListDataSetRevisionsHttp,
248 DataExchange.SendDataSetNotificationHttp,
249 DataExchange.GetRevisionHttp,
250 DataExchange.ListRevisionAssetsHttp,
251 DataExchange.GetAssetHttp,
252 DataExchange.ListDataSetsHttp,
253 DataExchange.CreateJobHttp,
254 DataExchange.StartJobHttp,
255 DataExchange.GetJobHttp,
256 DataExchange.ListJobsHttp,
257 DataExchange.ListDataGrantsHttp,
258 DataExchange.ListReceivedDataGrantsHttp,
259 DataExchange.ListEventActionsHttp,
260 S3.PutObjectHttp,
261 S3.GetObjectHttp,
262 ),
263 ),
264 ),
265 );