@brainbox-labs/sdk 0.0.0-stage → 0.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,178 @@
1
+ // src/ingest/athena.ts
2
+ var DEFAULT_POLL_TIMEOUT_MS = 3e5;
3
+ function parseAthenaUrl(url) {
4
+ let u;
5
+ try {
6
+ u = new URL(url);
7
+ } catch {
8
+ throw new Error("[BrainBox] Invalid Athena connection URL \u2014 expected athena://region/database.");
9
+ }
10
+ const scheme = u.protocol.replace(/:$/, "").toLowerCase();
11
+ if (scheme !== "athena" && scheme !== "awsathena") {
12
+ throw new Error(`[BrainBox] Not an Athena connection URL (scheme "${scheme}") \u2014 expected athena:// or awsathena://.`);
13
+ }
14
+ const region = u.hostname;
15
+ if (region === "") {
16
+ throw new Error("[BrainBox] Athena connection URL must include a region: athena://region/database.");
17
+ }
18
+ const segments = u.pathname.split("/").filter((s) => s.length > 0);
19
+ const database = segments[0];
20
+ if (database === void 0) {
21
+ throw new Error("[BrainBox] Athena connection URL must include a database: athena://region/database.");
22
+ }
23
+ const outputLocation = u.searchParams.get("output") ?? void 0;
24
+ const rawPollTimeout = u.searchParams.get("pollTimeoutMs");
25
+ const pollTimeoutMs = rawPollTimeout !== null ? Number(rawPollTimeout) : DEFAULT_POLL_TIMEOUT_MS;
26
+ if (!Number.isFinite(pollTimeoutMs) || pollTimeoutMs <= 0) {
27
+ throw new Error('[BrainBox] Athena connection URL "pollTimeoutMs" must be a positive number of milliseconds.');
28
+ }
29
+ const target = {
30
+ region: decodeURIComponent(region),
31
+ catalog: u.searchParams.get("catalog") ?? "AwsDataCatalog",
32
+ database: decodeURIComponent(database),
33
+ workgroup: u.searchParams.get("workgroup") ?? "primary",
34
+ pollTimeoutMs
35
+ };
36
+ if (outputLocation !== void 0) target.outputLocation = outputLocation;
37
+ return target;
38
+ }
39
+ var TERMINAL_STATES = /* @__PURE__ */ new Set(["SUCCEEDED", "FAILED", "CANCELLED"]);
40
+ async function openAthenaConnection(url) {
41
+ const target = parseAthenaUrl(url);
42
+ let mod;
43
+ try {
44
+ mod = await import("@aws-sdk/client-athena");
45
+ } catch {
46
+ throw new Error(
47
+ '[BrainBox] Athena support requires the optional dependency "@aws-sdk/client-athena". Install it with: npm install @aws-sdk/client-athena'
48
+ );
49
+ }
50
+ const client = new mod.AthenaClient({ region: target.region });
51
+ const runQuery = async (sql) => {
52
+ const startResult = await client.send(
53
+ new mod.StartQueryExecutionCommand({
54
+ QueryString: sql,
55
+ QueryExecutionContext: { Catalog: target.catalog, Database: target.database },
56
+ WorkGroup: target.workgroup,
57
+ ...target.outputLocation !== void 0 ? { ResultConfiguration: { OutputLocation: target.outputLocation } } : {}
58
+ })
59
+ );
60
+ const queryExecutionId = startResult.QueryExecutionId;
61
+ if (queryExecutionId === void 0) {
62
+ throw new Error("[BrainBox] Athena query did not return a QueryExecutionId.");
63
+ }
64
+ const deadline = Date.now() + target.pollTimeoutMs;
65
+ let state;
66
+ let reason;
67
+ for (; ; ) {
68
+ const status = await client.send(
69
+ new mod.GetQueryExecutionCommand({ QueryExecutionId: queryExecutionId })
70
+ );
71
+ state = status.QueryExecution?.Status?.State;
72
+ reason = status.QueryExecution?.Status?.StateChangeReason;
73
+ if (state !== void 0 && TERMINAL_STATES.has(state)) break;
74
+ if (Date.now() >= deadline) {
75
+ throw new Error(
76
+ `[BrainBox] Athena query ${queryExecutionId} did not reach a terminal state within ${target.pollTimeoutMs}ms (last state: ${state ?? "unknown"}). Increase pollTimeoutMs on the connection URL if the query is expected to run longer, or cancel it in the Athena console.`
77
+ );
78
+ }
79
+ await new Promise((resolve) => setTimeout(resolve, 500));
80
+ }
81
+ if (state !== "SUCCEEDED") {
82
+ throw new Error(`[BrainBox] Athena query ${state?.toLowerCase() ?? "failed"}: ${reason ?? "unknown error"}`);
83
+ }
84
+ const rows = [];
85
+ let columnNames;
86
+ let nextToken;
87
+ let firstPage = true;
88
+ do {
89
+ const page = await client.send(
90
+ new mod.GetQueryResultsCommand({ QueryExecutionId: queryExecutionId, NextToken: nextToken })
91
+ );
92
+ if (columnNames === void 0) {
93
+ columnNames = (page.ResultSet?.ResultSetMetadata?.ColumnInfo ?? []).map((c) => c.Name ?? "");
94
+ }
95
+ const pageRows = page.ResultSet?.Rows ?? [];
96
+ const startIndex = firstPage ? 1 : 0;
97
+ for (let i = startIndex; i < pageRows.length; i++) {
98
+ const values = pageRows[i]?.Data ?? [];
99
+ const row = {};
100
+ columnNames.forEach((name, idx) => {
101
+ row[name] = values[idx]?.VarCharValue ?? null;
102
+ });
103
+ rows.push(row);
104
+ }
105
+ nextToken = page.NextToken;
106
+ firstPage = false;
107
+ } while (nextToken !== void 0);
108
+ return rows;
109
+ };
110
+ return {
111
+ queryRows: runQuery,
112
+ // The AWS SDK client is a stateless HTTP wrapper — nothing to close.
113
+ close: async () => {
114
+ }
115
+ };
116
+ }
117
+ function escapeLiteral(value) {
118
+ return `'${value.replace(/'/g, "''")}'`;
119
+ }
120
+ async function introspectAthenaSchemaWithConnection(conn, database) {
121
+ const schemaCond = ` AND table_schema = ${escapeLiteral(database)}`;
122
+ const tableRows = await conn.queryRows(
123
+ `SELECT table_schema, table_name
124
+ FROM information_schema.tables
125
+ WHERE table_type = 'BASE TABLE'${schemaCond}
126
+ ORDER BY table_schema, table_name`
127
+ );
128
+ const columnRows = await conn.queryRows(
129
+ `SELECT table_schema, table_name, column_name, data_type, is_nullable, column_default
130
+ FROM information_schema.columns
131
+ WHERE 1=1${schemaCond}
132
+ ORDER BY table_schema, table_name, ordinal_position`
133
+ );
134
+ const columnsByTable = /* @__PURE__ */ new Map();
135
+ for (const col of columnRows) {
136
+ const key = `${col.table_schema}.${col.table_name}`;
137
+ const column = {
138
+ name: col.column_name,
139
+ type: col.data_type,
140
+ nullable: col.is_nullable === "YES",
141
+ isPrimaryKey: false,
142
+ isForeignKey: false
143
+ };
144
+ if (col.column_default !== null && col.column_default !== void 0) {
145
+ column.defaultValue = col.column_default;
146
+ }
147
+ const existing = columnsByTable.get(key);
148
+ if (existing !== void 0) {
149
+ existing.push(column);
150
+ } else {
151
+ columnsByTable.set(key, [column]);
152
+ }
153
+ }
154
+ const tables = tableRows.map((t) => ({
155
+ name: t.table_name,
156
+ schema: t.table_schema,
157
+ columns: columnsByTable.get(`${t.table_schema}.${t.table_name}`) ?? [],
158
+ indexes: [],
159
+ constraints: []
160
+ }));
161
+ return { tables, extractedAt: (/* @__PURE__ */ new Date()).toISOString() };
162
+ }
163
+ async function introspectAthenaSchema(connectionString) {
164
+ const target = parseAthenaUrl(connectionString);
165
+ const conn = await openAthenaConnection(connectionString);
166
+ try {
167
+ return await introspectAthenaSchemaWithConnection(conn, target.database);
168
+ } finally {
169
+ await conn.close();
170
+ }
171
+ }
172
+
173
+ export {
174
+ parseAthenaUrl,
175
+ openAthenaConnection,
176
+ introspectAthenaSchemaWithConnection,
177
+ introspectAthenaSchema
178
+ };