@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 246 lines 9.48 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as QuickSight from "@alchemy.run/aws/QuickSight";
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 Stream from "effect/Stream";
9 import path from "pathe";
10
11 const main = path.resolve(import.meta.dirname, "bindings-handler.ts");
12
13 export class QuickSightBindingsFunction extends Lambda.Function<Lambda.Function>()(
14 "QuickSightBindingsFunction",
15 ) {}
16
17 export default QuickSightBindingsFunction.make(
18 {
19 main,
20 functionUrl: true,
21 timeout: Duration.seconds(30),
22 },
23 Effect.gen(function* () {
24 const source = yield* QuickSight.DataSource("BindingsSource", {
25 name: "Alchemy QuickSight Bindings Source",
26 type: "ATHENA",
27 dataSourceParameters: { AthenaParameters: { WorkGroup: "primary" } },
28 });
29
30 const dataSet = yield* QuickSight.DataSet("BindingsDataSet", {
31 name: "Alchemy QuickSight Bindings DataSet",
32 importMode: "DIRECT_QUERY",
33 physicalTableMap: {
34 probe: {
35 CustomSql: {
36 DataSourceArn: source.arn,
37 Name: "probe",
38 SqlQuery: "SELECT 1 AS n",
39 Columns: [{ Name: "n", Type: "INTEGER" }],
40 },
41 },
42 },
43 });
44
45 const dashboard = yield* QuickSight.Dashboard("BindingsDashboard", {
46 name: "Alchemy QuickSight Bindings Dashboard",
47 definition: {
48 DataSetIdentifierDeclarations: [{ Identifier: "probe", DataSetArn: dataSet.arn }],
49 Sheets: [{ SheetId: "sheet1", Name: "Sheet 1" }],
50 },
51 });
52
53 const createIngestion = yield* QuickSight.CreateIngestion(dataSet);
54 const describeIngestion = yield* QuickSight.DescribeIngestion(dataSet);
55 const cancelIngestion = yield* QuickSight.CancelIngestion(dataSet);
56 const listIngestions = yield* QuickSight.ListIngestions(dataSet);
57 const startSnapshotJob = yield* QuickSight.StartDashboardSnapshotJob(dashboard);
58 const describeSnapshotJob = yield* QuickSight.DescribeDashboardSnapshotJob(dashboard);
59 const describeSnapshotJobResult =
60 yield* QuickSight.DescribeDashboardSnapshotJobResult(dashboard);
61 const generateEmbedUrlForRegisteredUser =
62 yield* QuickSight.GenerateEmbedUrlForRegisteredUser(dashboard);
63 const generateEmbedUrlForAnonymousUser =
64 yield* QuickSight.GenerateEmbedUrlForAnonymousUser(dashboard);
65
66 const bound = {
67 createIngestion,
68 describeIngestion,
69 cancelIngestion,
70 listIngestions,
71 startSnapshotJob,
72 describeSnapshotJob,
73 describeSnapshotJobResult,
74 generateEmbedUrlForRegisteredUser,
75 generateEmbedUrlForAnonymousUser,
76 };
77
78 return {
79 fetch: Effect.gen(function* () {
80 const request = yield* HttpServerRequest;
81 const url = new URL(request.originalUrl);
82 const pathname = url.pathname;
83
84 if (request.method === "GET" && pathname === "/bindings") {
85 return yield* HttpServerResponse.json({
86 bound: Object.keys(bound),
87 });
88 }
89
90 if (request.method === "GET" && pathname === "/ingestions") {
91 // DataSetId + AwsAccountId injection scope the call to the bound
92 // dataset.
93 const response = yield* listIngestions({ MaxResults: 10 });
94 return yield* HttpServerResponse.json({
95 count: (response.Ingestions ?? []).length,
96 });
97 }
98
99 if (request.method === "POST" && pathname === "/ingestion") {
100 // A DIRECT_QUERY dataset cannot be ingested into SPICE — the typed
101 // 400 proves the CreateIngestion grant + id injection end-to-end
102 // without mutating anything. An IAM gap would surface
103 // AccessDeniedException instead.
104 const ingestionId = yield* Effect.sync(() => crypto.randomUUID());
105 const created = yield* createIngestion({
106 IngestionId: ingestionId,
107 IngestionType: "FULL_REFRESH",
108 }).pipe(
109 Effect.map((r) => ({ started: true as const, id: r.IngestionId })),
110 Effect.catchTag(["InvalidParameterValueException", "ResourceNotFoundException"], (e) =>
111 Effect.succeed({ started: false as const, error: e._tag }),
112 ),
113 );
114 if (!created.started) {
115 return yield* HttpServerResponse.json(created);
116 }
117 // SPICE dataset path: observe then cancel the refresh.
118 const status = yield* describeIngestion({
119 IngestionId: ingestionId,
120 }).pipe(
121 Effect.map((r) => r.Ingestion?.IngestionStatus),
122 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)),
123 );
124 yield* cancelIngestion({ IngestionId: ingestionId }).pipe(
125 Effect.catchTag(
126 ["InvalidParameterValueException", "ResourceNotFoundException"],
127 () => Effect.void,
128 ),
129 );
130 return yield* HttpServerResponse.json({ ...created, status });
131 }
132
133 if (request.method === "GET" && pathname === "/snapshot-job/typed-not-found") {
134 // Both describe ops on a nonexistent job id surface the typed
135 // not-found, proving grant + DashboardId injection.
136 const describe = yield* describeSnapshotJob({
137 SnapshotJobId: "alchemy-nonexistent-snapshot-job",
138 }).pipe(
139 Effect.map(() => false),
140 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(true)),
141 );
142 const result = yield* describeSnapshotJobResult({
143 SnapshotJobId: "alchemy-nonexistent-snapshot-job",
144 }).pipe(
145 Effect.map(() => false),
146 Effect.catchTag(["ResourceNotFoundException", "InvalidParameterValueException"], () =>
147 Effect.succeed(true),
148 ),
149 );
150 return yield* HttpServerResponse.json({ describe, result });
151 }
152
153 if (request.method === "POST" && pathname === "/snapshot-job") {
154 // Snapshot export requires paginated-report entitlement on some
155 // accounts; either a started job or the typed rejection proves the
156 // grant.
157 const jobId = yield* Effect.sync(() => crypto.randomUUID());
158 const outcome = yield* startSnapshotJob({
159 SnapshotJobId: jobId,
160 UserConfiguration: { AnonymousUsers: [] },
161 SnapshotConfiguration: {
162 FileGroups: [
163 {
164 Files: [
165 {
166 FormatType: "PDF",
167 SheetSelections: [{ SheetId: "sheet1", SelectionScope: "ALL_VISUALS" }],
168 },
169 ],
170 },
171 ],
172 },
173 }).pipe(
174 Effect.map((r) => ({ started: true, jobId: r.SnapshotJobId })),
175 Effect.catchTag(
176 [
177 "InvalidParameterValueException",
178 "UnsupportedPricingPlanException",
179 "UnsupportedUserEditionException",
180 "LimitExceededException",
181 ],
182 (e) => Effect.succeed({ started: false, error: e._tag }),
183 ),
184 );
185 return yield* HttpServerResponse.json(outcome);
186 }
187
188 if (request.method === "GET" && pathname === "/embed-url") {
189 // A nonexistent user arn surfaces the typed user-not-found — the
190 // request reached the account-scoped embed API with the injected
191 // AwsAccountId.
192 const typed = yield* generateEmbedUrlForRegisteredUser({
193 UserArn: url.searchParams.get("userArn") ?? "arn:invalid",
194 }).pipe(
195 Effect.map(() => "EmbedUrl"),
196 Effect.catchTag(
197 [
198 "QuickSightUserNotFoundException",
199 "ResourceNotFoundException",
200 "InvalidParameterValueException",
201 ],
202 (e) => Effect.succeed(e._tag),
203 ),
204 );
205 return yield* HttpServerResponse.json({ typed });
206 }
207
208 if (request.method === "GET" && pathname === "/embed-url-anon") {
209 // Anonymous embedding needs session-capacity pricing; either the
210 // URL or the typed pricing-plan rejection proves the grant.
211 const outcome = yield* generateEmbedUrlForAnonymousUser().pipe(
212 Effect.map(() => ({ ok: true as const })),
213 Effect.catchTag(
214 [
215 "UnsupportedPricingPlanException",
216 "SessionLifetimeInMinutesInvalidException",
217 "InvalidParameterValueException",
218 ],
219 (e) => Effect.succeed({ ok: false as const, error: e._tag }),
220 ),
221 );
222 return yield* HttpServerResponse.json(outcome);
223 }
224
225 return yield* HttpServerResponse.json(
226 { error: "Not found", method: request.method, pathname },
227 { status: 404 },
228 );
229 }).pipe(Effect.orDie),
230 };
231 }).pipe(
232 Effect.provide(
233 Layer.mergeAll(
234 QuickSight.CreateIngestionHttp,
235 QuickSight.DescribeIngestionHttp,
236 QuickSight.CancelIngestionHttp,
237 QuickSight.ListIngestionsHttp,
238 QuickSight.StartDashboardSnapshotJobHttp,
239 QuickSight.DescribeDashboardSnapshotJobHttp,
240 QuickSight.DescribeDashboardSnapshotJobResultHttp,
241 QuickSight.GenerateEmbedUrlForRegisteredUserHttp,
242 QuickSight.GenerateEmbedUrlForAnonymousUserHttp,
243 ),
244 ),
245 ),
246 );