@databricks/appkit 0.44.0 → 0.46.0
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.
- package/CLAUDE.md +1 -0
- package/dist/agents/databricks.d.ts +25 -1
- package/dist/agents/databricks.d.ts.map +1 -1
- package/dist/agents/databricks.js +20 -1
- package/dist/agents/databricks.js.map +1 -1
- package/dist/appkit/package.js +1 -1
- package/dist/beta.d.ts +2 -2
- package/dist/connectors/sql-warehouse/arrow-schema.js +283 -0
- package/dist/connectors/sql-warehouse/arrow-schema.js.map +1 -0
- package/dist/connectors/sql-warehouse/client.js +166 -60
- package/dist/connectors/sql-warehouse/client.js.map +1 -1
- package/dist/core/agent/load-agents.d.ts.map +1 -1
- package/dist/core/agent/load-agents.js +52 -0
- package/dist/core/agent/load-agents.js.map +1 -1
- package/dist/core/agent/types.d.ts +11 -0
- package/dist/core/agent/types.d.ts.map +1 -1
- package/dist/core/agent/types.js.map +1 -1
- package/dist/core/appkit.d.ts.map +1 -1
- package/dist/core/appkit.js +2 -0
- package/dist/core/appkit.js.map +1 -1
- package/dist/core/lifecycle-manager.js +183 -0
- package/dist/core/lifecycle-manager.js.map +1 -0
- package/dist/core/plugin-context.d.ts +19 -1
- package/dist/core/plugin-context.d.ts.map +1 -1
- package/dist/core/plugin-context.js +9 -3
- package/dist/core/plugin-context.js.map +1 -1
- package/dist/errors/base.d.ts +18 -0
- package/dist/errors/base.d.ts.map +1 -1
- package/dist/errors/base.js +20 -0
- package/dist/errors/base.js.map +1 -1
- package/dist/errors/execution.d.ts +34 -2
- package/dist/errors/execution.d.ts.map +1 -1
- package/dist/errors/execution.js +40 -5
- package/dist/errors/execution.js.map +1 -1
- package/dist/plugin/plugin.d.ts.map +1 -1
- package/dist/plugin/plugin.js +2 -1
- package/dist/plugin/plugin.js.map +1 -1
- package/dist/plugins/agents/agents.d.ts.map +1 -1
- package/dist/plugins/agents/agents.js +3 -3
- package/dist/plugins/agents/agents.js.map +1 -1
- package/dist/plugins/analytics/analytics.d.ts +84 -8
- package/dist/plugins/analytics/analytics.d.ts.map +1 -1
- package/dist/plugins/analytics/analytics.js +296 -61
- package/dist/plugins/analytics/analytics.js.map +1 -1
- package/dist/plugins/analytics/index.js +1 -1
- package/dist/plugins/analytics/result-delivery.js +287 -0
- package/dist/plugins/analytics/result-delivery.js.map +1 -0
- package/dist/plugins/analytics/types.d.ts +8 -0
- package/dist/plugins/analytics/types.d.ts.map +1 -1
- package/dist/plugins/analytics/types.js.map +1 -1
- package/dist/plugins/files/plugin.js +1 -1
- package/dist/plugins/genie/genie.js +1 -1
- package/dist/plugins/jobs/types.d.ts +1 -1
- package/dist/plugins/lakebase/lakebase.d.ts +10 -2
- package/dist/plugins/lakebase/lakebase.d.ts.map +1 -1
- package/dist/plugins/lakebase/lakebase.js +19 -8
- package/dist/plugins/lakebase/lakebase.js.map +1 -1
- package/dist/plugins/server/index.d.ts +51 -1
- package/dist/plugins/server/index.d.ts.map +1 -1
- package/dist/plugins/server/index.js +110 -23
- package/dist/plugins/server/index.js.map +1 -1
- package/dist/registry/resource-registry.d.ts +9 -1
- package/dist/registry/resource-registry.d.ts.map +1 -1
- package/dist/registry/resource-registry.js +22 -5
- package/dist/registry/resource-registry.js.map +1 -1
- package/dist/shared/src/execute.d.ts +1 -3
- package/dist/shared/src/execute.d.ts.map +1 -1
- package/dist/shared/src/index.d.ts +1 -0
- package/dist/shared/src/plugin.d.ts +16 -0
- package/dist/shared/src/plugin.d.ts.map +1 -1
- package/dist/shared/src/sse/analytics.d.ts +1 -0
- package/dist/shared/src/sse/analytics.js +40 -0
- package/dist/shared/src/sse/analytics.js.map +1 -0
- package/dist/stream/arrow-stream-processor.js +93 -117
- package/dist/stream/arrow-stream-processor.js.map +1 -1
- package/dist/stream/buffers.js +1 -1
- package/dist/stream/buffers.js.map +1 -1
- package/dist/stream/defaults.js +1 -3
- package/dist/stream/defaults.js.map +1 -1
- package/dist/stream/sse-writer.js +3 -2
- package/dist/stream/sse-writer.js.map +1 -1
- package/dist/stream/stream-manager.d.ts +2 -2
- package/dist/stream/stream-manager.d.ts.map +1 -1
- package/dist/stream/stream-manager.js +41 -33
- package/dist/stream/stream-manager.js.map +1 -1
- package/dist/stream/stream-registry.js +30 -23
- package/dist/stream/stream-registry.js.map +1 -1
- package/dist/stream/timers.js +17 -0
- package/dist/stream/timers.js.map +1 -0
- package/dist/stream/types.js.map +1 -1
- package/dist/telemetry/telemetry-manager.js +19 -13
- package/dist/telemetry/telemetry-manager.js.map +1 -1
- package/dist/type-generator/query-registry.js +32 -2
- package/dist/type-generator/query-registry.js.map +1 -1
- package/dist/utils/safe-handler.js +28 -0
- package/dist/utils/safe-handler.js.map +1 -0
- package/docs/api/appkit/Class.AppKitError.md +40 -8
- package/docs/api/appkit/Class.AuthenticationError.md +56 -16
- package/docs/api/appkit/Class.ConfigurationError.md +57 -17
- package/docs/api/appkit/Class.ConnectionError.md +57 -17
- package/docs/api/appkit/Class.ExecutionError.md +80 -22
- package/docs/api/appkit/Class.InitializationError.md +55 -15
- package/docs/api/appkit/Class.Plugin.md +2 -0
- package/docs/api/appkit/Class.ResourceRegistry.md +1 -1
- package/docs/api/appkit/Class.ServerError.md +55 -15
- package/docs/api/appkit/Class.TunnelError.md +56 -16
- package/docs/api/appkit/Class.ValidationError.md +55 -15
- package/docs/api/appkit/Interface.AgentDefinition.md +11 -0
- package/docs/api/appkit/Interface.GenerationParams.md +58 -0
- package/docs/api/appkit/Interface.RegisteredAgent.md +11 -0
- package/docs/api/appkit.md +1 -0
- package/llms.txt +1 -0
- package/package.json +1 -1
- package/sbom.cdx.json +1 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"arrow-schema.js","names":[],"sources":["../../../src/connectors/sql-warehouse/arrow-schema.ts"],"sourcesContent":["import {\n Binary,\n Bool,\n type DataType,\n DateDay,\n Decimal,\n DurationMicrosecond,\n Field,\n Float32,\n Float64,\n Int8,\n Int16,\n Int32,\n Int64,\n IntervalYearMonth,\n List,\n Map_,\n Null,\n Schema,\n Struct,\n Table,\n TimestampMicrosecond,\n tableToIPC,\n Utf8,\n} from \"apache-arrow\";\n\n/**\n * Parse a Databricks SQL type text (the value returned by the Statement\n * Execution API in `ColumnInfo.type_text`) into an Apache Arrow DataType.\n *\n * Supports:\n * - All scalar types (STRING, INT, BIGINT, DECIMAL, TIMESTAMP, etc.)\n * - Parameterized scalars: DECIMAL(p,s), VARCHAR(n), CHAR(n)\n * - Nested types: ARRAY<T>, MAP<K,V>, STRUCT<f1:T1, f2:T2 COMMENT '...', ...>\n * - INTERVAL year-month and day-time variants\n * - Backtick-quoted struct field names with embedded `` `` `` escapes\n *\n * Unknown or unparseable types fall back to Utf8 — empty-Table consumers\n * still see a column with the right name; only the inner type is degraded.\n */\nexport function parseDatabricksType(typeText: string): DataType {\n const parser = new TypeParser(typeText);\n const result = parser.parseType();\n parser.expectEnd();\n return result;\n}\n\n/**\n * Build an empty Arrow IPC stream (base64-encoded) matching the column schema\n * returned by the warehouse. Used so ARROW_STREAM responses with no rows still\n * deliver a real Arrow Table to the client, preserving the hook's typed\n * contract.\n */\nexport function buildEmptyArrowIPCBase64(\n columns: Array<{\n name?: string;\n type_text?: string;\n type_name?: string;\n }>,\n): string {\n const fields = columns.map((col, index) => {\n const typeText = col.type_text ?? col.type_name ?? \"STRING\";\n let dataType: DataType;\n try {\n dataType = parseDatabricksType(typeText);\n } catch {\n dataType = new Utf8();\n }\n const name = col.name && col.name.length > 0 ? col.name : `column_${index}`;\n return new Field(name, dataType, true);\n });\n const schema = new Schema(fields);\n const table = new Table(schema);\n const ipc = tableToIPC(table, \"stream\");\n return Buffer.from(ipc).toString(\"base64\");\n}\n\n// ============================================================================\n// Recursive-descent parser\n// ============================================================================\n\nclass TypeParser {\n private readonly input: string;\n private pos = 0;\n\n constructor(input: string) {\n this.input = input;\n }\n\n parseType(): DataType {\n this.skipWs();\n\n let name: string;\n if (this.peek() === \"`\") {\n name = this.consumeBacktickIdent();\n } else {\n name = this.consumeIdent();\n }\n const upper = name.toUpperCase();\n\n this.skipWs();\n\n if (upper === \"INTERVAL\") {\n return this.parseInterval();\n }\n\n if (this.peek() === \"(\") {\n this.consume(\"(\");\n const args = this.parseNumberArgs();\n this.consume(\")\");\n this.skipWs();\n return this.makeParameterized(upper, args);\n }\n\n if (this.peek() === \"<\") {\n this.consume(\"<\");\n const result = this.makeGeneric(upper);\n this.skipWs();\n this.consume(\">\");\n return result;\n }\n\n return this.makeScalar(upper);\n }\n\n expectEnd(): void {\n this.skipWs();\n if (this.pos < this.input.length) {\n throw new Error(\n `Unexpected trailing input at position ${this.pos}: \"${this.input.slice(this.pos)}\"`,\n );\n }\n }\n\n // ─── Type constructors ───────────────────────────────────\n\n private makeScalar(upper: string): DataType {\n switch (upper) {\n case \"STRING\":\n case \"VARIANT\":\n return new Utf8();\n case \"VARCHAR\":\n case \"CHAR\":\n return new Utf8();\n case \"BINARY\":\n case \"GEOGRAPHY\":\n case \"GEOMETRY\":\n return new Binary();\n case \"BOOLEAN\":\n case \"BOOL\":\n return new Bool();\n case \"TINYINT\":\n case \"BYTE\":\n return new Int8();\n case \"SMALLINT\":\n case \"SHORT\":\n return new Int16();\n case \"INT\":\n case \"INTEGER\":\n return new Int32();\n case \"BIGINT\":\n case \"LONG\":\n return new Int64();\n case \"FLOAT\":\n case \"REAL\":\n return new Float32();\n case \"DOUBLE\":\n return new Float64();\n case \"DECIMAL\":\n case \"NUMERIC\":\n case \"DEC\":\n return new Decimal(0, 10, 128);\n case \"DATE\":\n return new DateDay();\n case \"TIMESTAMP\":\n case \"TIMESTAMP_LTZ\":\n return new TimestampMicrosecond(\"UTC\");\n case \"TIMESTAMP_NTZ\":\n return new TimestampMicrosecond();\n case \"VOID\":\n case \"NULL\":\n return new Null();\n default:\n return new Utf8();\n }\n }\n\n private makeParameterized(upper: string, args: number[]): DataType {\n switch (upper) {\n case \"DECIMAL\":\n case \"NUMERIC\":\n case \"DEC\": {\n const precision = args[0] ?? 10;\n const scale = args[1] ?? 0;\n // Arrow JS Decimal constructor signature is (scale, precision, bitWidth).\n return new Decimal(scale, precision, 128);\n }\n case \"VARCHAR\":\n case \"CHAR\":\n return new Utf8();\n default:\n return new Utf8();\n }\n }\n\n private makeGeneric(upper: string): DataType {\n switch (upper) {\n case \"ARRAY\": {\n const inner = this.parseType();\n return new List(new Field(\"item\", inner, true));\n }\n case \"MAP\": {\n const keyType = this.parseType();\n this.skipWs();\n this.consume(\",\");\n this.skipWs();\n const valueType = this.parseType();\n const entriesStruct = new Struct([\n new Field(\"key\", keyType, false),\n new Field(\"value\", valueType, true),\n ]);\n return new Map_(new Field(\"entries\", entriesStruct, false), false);\n }\n case \"STRUCT\":\n return this.parseStructFields();\n default:\n // Unknown generic — skip to matching '>' and fall back.\n this.skipBalancedAngles();\n return new Utf8();\n }\n }\n\n private parseStructFields(): DataType {\n const fields: Field[] = [];\n while (true) {\n this.skipWs();\n if (this.peek() === \">\") break;\n\n let name: string;\n if (this.peek() === \"`\") {\n name = this.consumeBacktickIdent();\n } else {\n name = this.consumeIdent();\n }\n\n this.skipWs();\n this.consume(\":\");\n this.skipWs();\n\n const type = this.parseType();\n\n // Optional `NOT NULL` and `COMMENT '...'`. Both are accepted by\n // Databricks DDL and may appear in `type_text`.\n this.skipWs();\n while (this.peekKeyword(\"NOT\")) {\n this.consumeIdent();\n this.skipWs();\n if (this.peekKeyword(\"NULL\")) {\n this.consumeIdent();\n }\n this.skipWs();\n }\n if (this.peekKeyword(\"COMMENT\")) {\n this.consumeIdent();\n this.skipWs();\n this.consumeStringLiteral();\n this.skipWs();\n }\n\n fields.push(new Field(name, type, true));\n\n this.skipWs();\n if (this.peek() === \",\") {\n this.consume(\",\");\n } else {\n break;\n }\n }\n return new Struct(fields);\n }\n\n private parseInterval(): DataType {\n // Grammar: INTERVAL <unit> [TO <unit>]\n // YEAR / MONTH variants -> IntervalYearMonth\n // DAY / HOUR / MINUTE / SECOND variants -> Duration(microsecond)\n const seen: string[] = [];\n while (this.pos < this.input.length) {\n this.skipWs();\n const c = this.peek();\n if (c === \"\" || c === \",\" || c === \">\" || c === \")\") break;\n const word = this.consumeIdent().toUpperCase();\n seen.push(word);\n }\n const isYearMonth = seen.some((w) => w === \"YEAR\" || w === \"MONTH\");\n return isYearMonth ? new IntervalYearMonth() : new DurationMicrosecond();\n }\n\n private parseNumberArgs(): number[] {\n const args: number[] = [];\n while (true) {\n this.skipWs();\n if (this.peek() === \")\") break;\n args.push(this.consumeNumber());\n this.skipWs();\n if (this.peek() === \",\") {\n this.consume(\",\");\n } else {\n break;\n }\n }\n return args;\n }\n\n // ─── Token utilities ─────────────────────────────────────\n\n private peek(): string {\n return this.input[this.pos] ?? \"\";\n }\n\n private peekKeyword(word: string): boolean {\n const slice = this.input.slice(this.pos, this.pos + word.length);\n if (slice.toUpperCase() !== word.toUpperCase()) return false;\n // Must be followed by a non-identifier character (boundary check).\n const next = this.input[this.pos + word.length] ?? \"\";\n return !/[A-Za-z0-9_]/.test(next);\n }\n\n private consume(expected: string): void {\n if (this.peek() !== expected) {\n throw new Error(\n `Expected \"${expected}\" at position ${this.pos}, got \"${this.peek()}\" in \"${this.input}\"`,\n );\n }\n this.pos++;\n }\n\n private skipWs(): void {\n while (\n this.pos < this.input.length &&\n /\\s/.test(this.input[this.pos] ?? \"\")\n ) {\n this.pos++;\n }\n }\n\n private consumeIdent(): string {\n const start = this.pos;\n while (\n this.pos < this.input.length &&\n /[A-Za-z0-9_]/.test(this.input[this.pos] ?? \"\")\n ) {\n this.pos++;\n }\n if (this.pos === start) {\n throw new Error(\n `Expected identifier at position ${this.pos}, got \"${this.peek()}\" in \"${this.input}\"`,\n );\n }\n return this.input.slice(start, this.pos);\n }\n\n private consumeBacktickIdent(): string {\n this.consume(\"`\");\n let value = \"\";\n while (this.pos < this.input.length) {\n if (this.input[this.pos] === \"`\") {\n if (this.input[this.pos + 1] === \"`\") {\n value += \"`\";\n this.pos += 2;\n continue;\n }\n break;\n }\n value += this.input[this.pos];\n this.pos++;\n }\n this.consume(\"`\");\n return value;\n }\n\n private consumeNumber(): number {\n const start = this.pos;\n while (\n this.pos < this.input.length &&\n /[0-9]/.test(this.input[this.pos] ?? \"\")\n ) {\n this.pos++;\n }\n if (this.pos === start) {\n throw new Error(\n `Expected number at position ${this.pos}, got \"${this.peek()}\" in \"${this.input}\"`,\n );\n }\n return Number.parseInt(this.input.slice(start, this.pos), 10);\n }\n\n private consumeStringLiteral(): string {\n const quote = this.peek();\n if (quote !== \"'\" && quote !== '\"') {\n throw new Error(\n `Expected string literal at position ${this.pos}, got \"${quote}\" in \"${this.input}\"`,\n );\n }\n this.pos++;\n let value = \"\";\n while (this.pos < this.input.length) {\n const c = this.input[this.pos];\n if (c === \"\\\\\") {\n // Escape sequence: keep the next char verbatim.\n const next = this.input[this.pos + 1];\n if (next !== undefined) {\n value += next;\n this.pos += 2;\n continue;\n }\n this.pos++;\n continue;\n }\n if (c === quote) {\n this.pos++;\n return value;\n }\n value += c;\n this.pos++;\n }\n throw new Error(`Unterminated string literal in \"${this.input}\"`);\n }\n\n private skipBalancedAngles(): void {\n let depth = 1;\n while (this.pos < this.input.length && depth > 0) {\n const c = this.peek();\n if (c === \"<\") depth++;\n else if (c === \">\") {\n depth--;\n if (depth === 0) return;\n }\n this.pos++;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwCA,SAAgB,oBAAoB,UAA4B;CAC9D,MAAM,SAAS,IAAI,WAAW,SAAS;CACvC,MAAM,SAAS,OAAO,WAAW;AACjC,QAAO,WAAW;AAClB,QAAO;;;;;;;;AAST,SAAgB,yBACd,SAKQ;CAcR,MAAM,MAAM,WADE,IAAI,MADH,IAAI,OAXJ,QAAQ,KAAK,KAAK,UAAU;EACzC,MAAM,WAAW,IAAI,aAAa,IAAI,aAAa;EACnD,IAAI;AACJ,MAAI;AACF,cAAW,oBAAoB,SAAS;UAClC;AACN,cAAW,IAAI,MAAM;;AAGvB,SAAO,IAAI,MADE,IAA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AACrB,OAAI,MAAM,IAAK;YACN,MAAM,KAAK;AAClB;AACA,QAAI,UAAU,EAAG;;AAEnB,QAAK"}
|
|
@@ -8,6 +8,7 @@ import "../../errors/index.js";
|
|
|
8
8
|
import { TelemetryManager } from "../../telemetry/telemetry-manager.js";
|
|
9
9
|
import { SpanKind, SpanStatusCode } from "../../telemetry/index.js";
|
|
10
10
|
import { ArrowStreamProcessor } from "../../stream/arrow-stream-processor.js";
|
|
11
|
+
import { buildEmptyArrowIPCBase64 } from "./arrow-schema.js";
|
|
11
12
|
import { executeStatementDefaults } from "./defaults.js";
|
|
12
13
|
import { WarehousePollBackoff } from "./warehouse-poll-backoff.js";
|
|
13
14
|
import { WarehouseStatusEmitter } from "./warehouse-status-emitter.js";
|
|
@@ -16,6 +17,35 @@ import { Context } from "@databricks/sdk-experimental";
|
|
|
16
17
|
//#region src/connectors/sql-warehouse/client.ts
|
|
17
18
|
const logger = createLogger("connectors:sql-warehouse");
|
|
18
19
|
/**
|
|
20
|
+
* Real column names from a statement's result manifest (positional
|
|
21
|
+
* `column_N` fallback for any blank ones). Databricks encodes ARROW_STREAM
|
|
22
|
+
* schemas positionally (`col_0`, …); these names let consumers relabel an
|
|
23
|
+
* Arrow result to match the JSON path. Returns `undefined` when the manifest
|
|
24
|
+
* carries no columns.
|
|
25
|
+
*/
|
|
26
|
+
function arrowColumnNames(response) {
|
|
27
|
+
const cols = response.manifest?.schema?.columns;
|
|
28
|
+
if (!cols || cols.length === 0) return void 0;
|
|
29
|
+
return cols.map((c, i) => c.name && c.name.length > 0 ? c.name : `column_${i}`);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Maximum size for inline Arrow IPC attachments (25 MiB decoded — the
|
|
33
|
+
* Databricks Statement Execution API hard cap on INLINE responses).
|
|
34
|
+
*
|
|
35
|
+
* The analytics route streams the decoded attachment straight back on the
|
|
36
|
+
* query response body; this cap bounds the single in-memory copy. Larger
|
|
37
|
+
* results fall through to `disposition: "EXTERNAL_LINKS"`, which streams
|
|
38
|
+
* chunk-by-chunk and is not bound by this limit.
|
|
39
|
+
*/
|
|
40
|
+
const MAX_INLINE_ATTACHMENT_BYTES = 25 * 1024 * 1024;
|
|
41
|
+
/**
|
|
42
|
+
* Safety cap on how many additional EXTERNAL_LINKS chunks
|
|
43
|
+
* {@link SQLWarehouseConnector._resolveAllExternalLinks} will follow when the
|
|
44
|
+
* manifest omits `total_chunk_count`. High enough to cover any real result;
|
|
45
|
+
* only bounds a misbehaving warehouse with a cyclic `next_chunk_index`.
|
|
46
|
+
*/
|
|
47
|
+
const MAX_EXTERNAL_CHUNK_FOLLOWS = 1e4;
|
|
48
|
+
/**
|
|
19
49
|
* Default ceiling for how long {@link SQLWarehouseConnector.ensureWarehouseRunning}
|
|
20
50
|
* will wait for a warehouse to reach the RUNNING state before giving up.
|
|
21
51
|
*
|
|
@@ -66,7 +96,6 @@ var SQLWarehouseConnector = class {
|
|
|
66
96
|
get arrowProcessor() {
|
|
67
97
|
if (!this._arrowProcessor) this._arrowProcessor = new ArrowStreamProcessor({
|
|
68
98
|
timeout: this.config.timeout || executeStatementDefaults.timeout,
|
|
69
|
-
maxConcurrentDownloads: ArrowStreamProcessor.DEFAULT_MAX_CONCURRENT_DOWNLOADS,
|
|
70
99
|
retries: ArrowStreamProcessor.DEFAULT_RETRIES
|
|
71
100
|
});
|
|
72
101
|
return this._arrowProcessor;
|
|
@@ -135,9 +164,9 @@ var SQLWarehouseConnector = class {
|
|
|
135
164
|
result = await this._pollForStatementResult(workspaceClient, statementId, this.config.timeout, signal);
|
|
136
165
|
break;
|
|
137
166
|
case "SUCCEEDED":
|
|
138
|
-
result = this._transformDataArray(response);
|
|
167
|
+
result = await this._transformDataArray(response, workspaceClient, signal);
|
|
139
168
|
break;
|
|
140
|
-
case "FAILED": throw ExecutionError.statementFailed(status.error?.message);
|
|
169
|
+
case "FAILED": throw ExecutionError.statementFailed(status.error?.message, status.error?.error_code);
|
|
141
170
|
case "CANCELED": throw ExecutionError.canceled();
|
|
142
171
|
case "CLOSED": throw ExecutionError.resultsClosed();
|
|
143
172
|
default: throw ExecutionError.unknownState(String(status?.state ?? "unknown"));
|
|
@@ -163,9 +192,7 @@ var SQLWarehouseConnector = class {
|
|
|
163
192
|
});
|
|
164
193
|
logger.error("Statement execution failed: %s", error instanceof Error ? error.message : String(error));
|
|
165
194
|
}
|
|
166
|
-
|
|
167
|
-
if (error instanceof AppKitError) throw error;
|
|
168
|
-
throw ExecutionError.statementFailed(error instanceof Error ? error.message : String(error));
|
|
195
|
+
this._rethrowStatementError(error);
|
|
169
196
|
} finally {
|
|
170
197
|
if (abortHandler && signal) signal.removeEventListener("abort", abortHandler);
|
|
171
198
|
const duration = Date.now() - startTime;
|
|
@@ -462,8 +489,8 @@ var SQLWarehouseConnector = class {
|
|
|
462
489
|
"poll.duration_ms": elapsedTime
|
|
463
490
|
});
|
|
464
491
|
span.setStatus({ code: SpanStatusCode.OK });
|
|
465
|
-
return this._transformDataArray(response);
|
|
466
|
-
case "FAILED": throw ExecutionError.statementFailed(status.error?.message);
|
|
492
|
+
return this._transformDataArray(response, workspaceClient, signal);
|
|
493
|
+
case "FAILED": throw ExecutionError.statementFailed(status.error?.message, status.error?.error_code);
|
|
467
494
|
case "CANCELED": throw ExecutionError.canceled();
|
|
468
495
|
case "CLOSED": throw ExecutionError.resultsClosed();
|
|
469
496
|
default: throw ExecutionError.unknownState(String(status?.state ?? "unknown"));
|
|
@@ -477,9 +504,7 @@ var SQLWarehouseConnector = class {
|
|
|
477
504
|
code: SpanStatusCode.ERROR,
|
|
478
505
|
message: error instanceof Error ? error.message : String(error)
|
|
479
506
|
});
|
|
480
|
-
|
|
481
|
-
if (error instanceof AppKitError) throw error;
|
|
482
|
-
throw ExecutionError.statementFailed(error instanceof Error ? error.message : String(error));
|
|
507
|
+
this._rethrowStatementError(error);
|
|
483
508
|
} finally {
|
|
484
509
|
span.end();
|
|
485
510
|
}
|
|
@@ -488,8 +513,22 @@ var SQLWarehouseConnector = class {
|
|
|
488
513
|
includePrefix: true
|
|
489
514
|
});
|
|
490
515
|
}
|
|
491
|
-
_transformDataArray(response) {
|
|
492
|
-
if (response.manifest?.format === "ARROW_STREAM")
|
|
516
|
+
async _transformDataArray(response, workspaceClient, signal) {
|
|
517
|
+
if (response.manifest?.format === "ARROW_STREAM") {
|
|
518
|
+
const result = response.result;
|
|
519
|
+
if (result?.attachment) return this._validateArrowAttachment(response, result.attachment);
|
|
520
|
+
if (result?.external_links && result.external_links.length > 0) return this.updateWithArrowStatus(response, workspaceClient, signal);
|
|
521
|
+
if ((!result?.data_array || Array.isArray(result.data_array) && result.data_array.length === 0) && response.manifest?.schema?.columns) {
|
|
522
|
+
const synthesized = buildEmptyArrowIPCBase64(response.manifest.schema.columns);
|
|
523
|
+
return {
|
|
524
|
+
...response,
|
|
525
|
+
result: {
|
|
526
|
+
...result ?? {},
|
|
527
|
+
attachment: synthesized
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
}
|
|
493
532
|
if (!response.result?.data_array || !response.manifest?.schema?.columns) return response;
|
|
494
533
|
const columns = response.manifest.schema.columns;
|
|
495
534
|
const transformedData = response.result.data_array.map((row) => {
|
|
@@ -515,59 +554,126 @@ var SQLWarehouseConnector = class {
|
|
|
515
554
|
}
|
|
516
555
|
};
|
|
517
556
|
}
|
|
518
|
-
|
|
557
|
+
/**
|
|
558
|
+
* Validate a base64 Arrow IPC attachment (INLINE ARROW_STREAM) and attach
|
|
559
|
+
* the real column names from the result manifest.
|
|
560
|
+
*
|
|
561
|
+
* Databricks warehouses encode the Arrow schema positionally (`col_0`, …);
|
|
562
|
+
* the real, aliased names live only in `manifest.schema.columns`. Rather
|
|
563
|
+
* than decode/re-encode the payload server-side, we carry the names on the
|
|
564
|
+
* result (`columnNames`) so the route can hand them to the client in a
|
|
565
|
+
* response header and the client relabels the decoded Table — the one
|
|
566
|
+
* mechanism used for both INLINE and EXTERNAL_LINKS.
|
|
567
|
+
*/
|
|
568
|
+
_validateArrowAttachment(response, attachment) {
|
|
569
|
+
const stripped = attachment.replace(/\s+/g, "");
|
|
570
|
+
const padding = stripped.endsWith("==") ? 2 : stripped.endsWith("=") ? 1 : 0;
|
|
571
|
+
const decodedSize = Math.floor(stripped.length * 3 / 4) - padding;
|
|
572
|
+
if (decodedSize > MAX_INLINE_ATTACHMENT_BYTES) throw ExecutionError.statementFailed(`Inline Arrow attachment exceeds maximum size (${decodedSize} > ${MAX_INLINE_ATTACHMENT_BYTES} bytes)`);
|
|
573
|
+
const columnNames = arrowColumnNames(response);
|
|
574
|
+
if (columnNames) return {
|
|
575
|
+
...response,
|
|
576
|
+
result: {
|
|
577
|
+
...response.result,
|
|
578
|
+
statement_id: response.statement_id,
|
|
579
|
+
columnNames
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
return response;
|
|
583
|
+
}
|
|
584
|
+
async updateWithArrowStatus(response, workspaceClient, signal) {
|
|
585
|
+
const statementId = response.statement_id;
|
|
519
586
|
return { result: {
|
|
520
|
-
statement_id:
|
|
587
|
+
statement_id: statementId,
|
|
521
588
|
status: {
|
|
522
589
|
state: response.status?.state,
|
|
523
590
|
error: response.status?.error
|
|
524
|
-
}
|
|
591
|
+
},
|
|
592
|
+
columnNames: arrowColumnNames(response),
|
|
593
|
+
external_links: await this._resolveAllExternalLinks(workspaceClient, statementId, response, signal),
|
|
594
|
+
refreshChunkLink: this._makeChunkLinkRefresher(workspaceClient, statementId)
|
|
525
595
|
} };
|
|
526
596
|
}
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
597
|
+
/**
|
|
598
|
+
* Resolve pre-signed links for EVERY chunk of an EXTERNAL_LINKS result.
|
|
599
|
+
*
|
|
600
|
+
* The execute/getStatement response carries only the first chunk's links
|
|
601
|
+
* (each link, except the last, exposes `next_chunk_index`); the remaining
|
|
602
|
+
* chunks are fetched with `getStatementResultChunkN`. Runs in the caller's
|
|
603
|
+
* identity context (user creds for `.obo.sql`), so there is no cross-identity
|
|
604
|
+
* fetch. Only the tiny link metadata is resolved eagerly — the bytes still
|
|
605
|
+
* stream one chunk at a time downstream. Without this a multi-chunk result
|
|
606
|
+
* would be silently truncated to its first chunk.
|
|
607
|
+
*/
|
|
608
|
+
async _resolveAllExternalLinks(workspaceClient, statementId, response, signal) {
|
|
609
|
+
const first = response.result?.external_links;
|
|
610
|
+
if (!first || first.length === 0) return first;
|
|
611
|
+
const links = [...first];
|
|
612
|
+
const maxFetches = response.manifest?.total_chunk_count ?? MAX_EXTERNAL_CHUNK_FOLLOWS;
|
|
613
|
+
let next = this._nextChunkIndex(first);
|
|
614
|
+
for (let fetches = 0; next != null && fetches < maxFetches; fetches++) {
|
|
615
|
+
if (signal?.aborted) throw ExecutionError.canceled();
|
|
616
|
+
const chunkLinks = (await workspaceClient.statementExecution.getStatementResultChunkN({
|
|
617
|
+
statement_id: statementId,
|
|
618
|
+
chunk_index: next
|
|
619
|
+
}, this._createContext(signal))).external_links ?? [];
|
|
620
|
+
if (chunkLinks.length === 0) break;
|
|
621
|
+
links.push(...chunkLinks);
|
|
622
|
+
next = this._nextChunkIndex(chunkLinks);
|
|
623
|
+
}
|
|
624
|
+
return links;
|
|
625
|
+
}
|
|
626
|
+
/** The `next_chunk_index` advertised by a chunk's links, if any. */
|
|
627
|
+
_nextChunkIndex(links) {
|
|
628
|
+
for (const link of links) if (link.next_chunk_index != null) return link.next_chunk_index;
|
|
629
|
+
}
|
|
630
|
+
/**
|
|
631
|
+
* A closure that re-mints a single chunk's pre-signed link via
|
|
632
|
+
* `getStatementResultChunkN`, bound to the caller's workspace client +
|
|
633
|
+
* statement id. Created here (in the caller's identity context) so the
|
|
634
|
+
* streamer — which runs outside that context — can refresh an expired link
|
|
635
|
+
* for `.obo.sql` statements without a cross-identity `getStatement`.
|
|
636
|
+
*/
|
|
637
|
+
_makeChunkLinkRefresher(workspaceClient, statementId) {
|
|
638
|
+
return async (chunkIndex, signal) => {
|
|
639
|
+
return (await workspaceClient.statementExecution.getStatementResultChunkN({
|
|
640
|
+
statement_id: statementId,
|
|
641
|
+
chunk_index: chunkIndex
|
|
642
|
+
}, this._createContext(signal))).external_links?.find((l) => l.chunk_index === chunkIndex);
|
|
643
|
+
};
|
|
644
|
+
}
|
|
645
|
+
/**
|
|
646
|
+
* Stream already-resolved EXTERNAL_LINKS chunks as raw Arrow IPC bytes, one
|
|
647
|
+
* chunk in memory at a time. Takes the `external_links` the caller already
|
|
648
|
+
* has from `executeStatement` (see {@link updateWithArrowStatus}), so there
|
|
649
|
+
* is no extra `getStatement` round-trip and no execution-context mismatch —
|
|
650
|
+
* the pre-signed URLs need no auth to download.
|
|
651
|
+
*/
|
|
652
|
+
streamExternalLinks(chunks, signal, refresh) {
|
|
653
|
+
return this.arrowProcessor.streamChunks(chunks, signal, refresh);
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* Fetch just the real column names for a completed statement from its result
|
|
657
|
+
* manifest — no result data. Backs the `/columns/:statementId` fallback the
|
|
658
|
+
* client uses when a very wide schema's names exceed the response-header
|
|
659
|
+
* size limit. Stateless: re-derives from the warehouse, no server cache.
|
|
660
|
+
*/
|
|
661
|
+
async getColumnNames(workspaceClient, jobId, signal) {
|
|
662
|
+
return arrowColumnNames(await workspaceClient.statementExecution.getStatement({ statement_id: jobId }, this._createContext(signal)));
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Normalize an error caught during statement execution/polling and rethrow.
|
|
666
|
+
* Abort and already-structured `AppKitError`s pass through untouched;
|
|
667
|
+
* anything else is wrapped as an `ExecutionError`, preserving the SDK's
|
|
668
|
+
* structured `ApiError.errorCode` (e.g. "INVALID_PARAMETER_VALUE",
|
|
669
|
+
* "BAD_REQUEST") so callers can branch on a stable identifier rather than
|
|
670
|
+
* substring-matching the message.
|
|
671
|
+
*/
|
|
672
|
+
_rethrowStatementError(error) {
|
|
673
|
+
if (error instanceof Error && error.name === "AbortError") throw error;
|
|
674
|
+
if (error instanceof AppKitError) throw error;
|
|
675
|
+
const sdkErrorCode = error && typeof error === "object" && "errorCode" in error ? error.errorCode : void 0;
|
|
676
|
+
throw ExecutionError.statementFailed(error instanceof Error ? error.message : String(error), typeof sdkErrorCode === "string" ? sdkErrorCode : void 0);
|
|
571
677
|
}
|
|
572
678
|
_createContext(signal) {
|
|
573
679
|
return new Context({ cancellationToken: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../../src/connectors/sql-warehouse/client.ts"],"sourcesContent":["import {\n Context,\n type sql,\n type WorkspaceClient,\n} from \"@databricks/sdk-experimental\";\nimport type { TelemetryOptions } from \"shared\";\nimport {\n AppKitError,\n ConfigurationError,\n ConnectionError,\n ExecutionError,\n ValidationError,\n} from \"../../errors\";\nimport { createLogger } from \"../../logging/logger\";\nimport { ArrowStreamProcessor } from \"../../stream/arrow-stream-processor\";\nimport type { TelemetryProvider } from \"../../telemetry\";\nimport {\n type Counter,\n type Histogram,\n type Span,\n SpanKind,\n SpanStatusCode,\n TelemetryManager,\n} from \"../../telemetry\";\nimport { executeStatementDefaults } from \"./defaults\";\nimport { WarehousePollBackoff } from \"./warehouse-poll-backoff\";\nimport { WarehouseStatusEmitter } from \"./warehouse-status-emitter\";\n\nconst logger = createLogger(\"connectors:sql-warehouse\");\n\ninterface SQLWarehouseConfig {\n timeout?: number;\n telemetry?: TelemetryOptions;\n}\n\n/**\n * Default ceiling for how long {@link SQLWarehouseConnector.ensureWarehouseRunning}\n * will wait for a warehouse to reach the RUNNING state before giving up.\n *\n * Five minutes covers a cold-start of a classic warehouse on most workspaces;\n * serverless typically reaches RUNNING within ~30s.\n */\nexport const DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS = 5 * 60 * 1000;\n\n/**\n * Window during which a recent `RUNNING` observation lets subsequent calls\n * to {@link SQLWarehouseConnector.ensureWarehouseRunning} short-circuit\n * without making any SDK calls. Sized to roughly the upper bound of how\n * long Databricks keeps a warehouse \"stickily\" available between requests\n * — past that, we re-verify.\n */\nconst WAREHOUSE_RUNNING_CACHE_TTL_MS = 30_000;\n\n/**\n * A single observation of the warehouse state, emitted by\n * {@link SQLWarehouseConnector.ensureWarehouseRunning} so callers can stream\n * progress to clients (e.g. over SSE).\n *\n * Note: `health.summary` from the SDK is intentionally NOT exposed on this\n * type. It's free-form operator-oriented diagnostic text (cluster IDs,\n * capacity-failure reasons, internal RPC errors) that must not reach end\n * users. The raw value stays in the OTel span attributes for server-side\n * debugging only.\n */\nexport interface WarehouseStatusUpdate {\n /** Current state from the SDK (RUNNING | STARTING | STOPPED | STOPPING | DELETED | DELETING). */\n state: sql.State;\n /** Milliseconds elapsed since `ensureWarehouseRunning` was called. */\n elapsedMs: number;\n /** 1-based attempt counter — useful for tests and telemetry. */\n attempt: number;\n}\n\n/** Options for {@link SQLWarehouseConnector.ensureWarehouseRunning}. */\ninterface EnsureWarehouseRunningOptions {\n /** Invoked every time the warehouse state changes during the wait. */\n onStatus: (update: WarehouseStatusUpdate) => void;\n /** Aborts the wait. The connector treats abort as `ExecutionError.canceled()`. */\n signal?: AbortSignal;\n /** Hard ceiling on the total wait. Defaults to {@link DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS}. */\n timeoutMs?: number;\n /**\n * When `true` (default), a `STOPPED` warehouse is auto-started.\n * When `false`, `STOPPED` surfaces as `ConfigurationError` immediately —\n * useful for cost-controlled deployments that don't want any caller to\n * trigger billable warehouse starts.\n */\n autoStart?: boolean;\n /** @internal Fired once when `warehouses.start` is issued for this poll. */\n onWarehouseStartIssued?: () => void;\n}\n\n/** In-flight warehouse readiness work shared across concurrent callers. */\ninterface WarehouseReadinessInFlight {\n promise: Promise<void>;\n refCount: number;\n sharedController: AbortController;\n subscribers: Set<(update: WarehouseStatusUpdate) => void>;\n /** Last emitted update; replayed to late joiners. */\n lastUpdate: WarehouseStatusUpdate | null;\n /** `true` once this poll has called `warehouses.start`. */\n warehouseStartIssued: boolean;\n}\n\nexport class SQLWarehouseConnector {\n private readonly name = \"sql-warehouse\";\n\n private config: SQLWarehouseConfig;\n\n // Lazy-initialized: only created when Arrow format is used\n private _arrowProcessor: ArrowStreamProcessor | null = null;\n\n /**\n * Per-warehouse cache of the last RUNNING observation timestamp. Used by\n * {@link ensureWarehouseRunning} to short-circuit warm-path callers; see\n * {@link WAREHOUSE_RUNNING_CACHE_TTL_MS}.\n */\n private _recentlyRunning = new Map<string, number>();\n /** Per-warehouse readiness singleflight — one poll loop per cold start. */\n private _readinessInFlight = new Map<string, WarehouseReadinessInFlight>();\n // telemetry\n private readonly telemetry: TelemetryProvider;\n private readonly telemetryMetrics: {\n queryCount: Counter;\n queryDuration: Histogram;\n };\n\n constructor(config: SQLWarehouseConfig) {\n this.config = config;\n\n this.telemetry = TelemetryManager.getProvider(\n this.name,\n this.config.telemetry,\n );\n this.telemetryMetrics = {\n queryCount: this.telemetry.getMeter().createCounter(\"query.count\", {\n description: \"Total number of queries executed\",\n unit: \"1\",\n }),\n queryDuration: this.telemetry\n .getMeter()\n .createHistogram(\"query.duration\", {\n description: \"Duration of queries executed\",\n unit: \"ms\",\n }),\n };\n }\n\n /**\n * Lazily initializes and returns the ArrowStreamProcessor.\n * Only created on first Arrow format query to avoid unnecessary allocation.\n */\n private get arrowProcessor(): ArrowStreamProcessor {\n if (!this._arrowProcessor) {\n this._arrowProcessor = new ArrowStreamProcessor({\n timeout: this.config.timeout || executeStatementDefaults.timeout,\n maxConcurrentDownloads:\n ArrowStreamProcessor.DEFAULT_MAX_CONCURRENT_DOWNLOADS,\n retries: ArrowStreamProcessor.DEFAULT_RETRIES,\n });\n }\n return this._arrowProcessor;\n }\n\n async executeStatement(\n workspaceClient: WorkspaceClient,\n input: sql.ExecuteStatementRequest,\n signal?: AbortSignal,\n ) {\n const startTime = Date.now();\n let success = false;\n\n // if signal is aborted, throw an error\n if (signal?.aborted) {\n throw ExecutionError.canceled();\n }\n\n return this.telemetry.startActiveSpan(\n \"sql.query\",\n {\n kind: SpanKind.CLIENT,\n attributes: {\n \"db.system\": \"databricks\",\n \"db.warehouse_id\": input.warehouse_id || \"\",\n \"db.catalog\": input.catalog ?? \"\",\n \"db.schema\": input.schema ?? \"\",\n \"db.statement\": input.statement?.substring(0, 500) || \"\",\n \"db.has_parameters\": !!input.parameters,\n },\n },\n async (span: Span) => {\n let abortHandler: (() => void) | undefined;\n let isAborted = false;\n\n if (signal) {\n abortHandler = () => {\n // abort span if not recording\n if (!span.isRecording()) return;\n isAborted = true;\n span.setAttribute(\"cancelled\", true);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: \"Query cancelled by client\",\n });\n span.end();\n };\n signal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n\n try {\n // validate required fields\n if (!input.statement) {\n throw ValidationError.missingField(\"statement\");\n }\n\n if (!input.warehouse_id) {\n throw ValidationError.missingField(\"warehouse_id\");\n }\n\n const body: sql.ExecuteStatementRequest = {\n statement: input.statement,\n parameters: input.parameters,\n warehouse_id: input.warehouse_id,\n catalog: input.catalog,\n schema: input.schema,\n wait_timeout:\n input.wait_timeout || executeStatementDefaults.wait_timeout,\n disposition:\n input.disposition || executeStatementDefaults.disposition,\n format: input.format || executeStatementDefaults.format,\n byte_limit: input.byte_limit,\n row_limit: input.row_limit,\n on_wait_timeout:\n input.on_wait_timeout || executeStatementDefaults.on_wait_timeout,\n };\n\n span.addEvent(\"statement.submitting\", {\n \"db.warehouse_id\": input.warehouse_id,\n });\n\n const response =\n await workspaceClient.statementExecution.executeStatement(\n body,\n this._createContext(signal),\n );\n\n if (!response) {\n throw ConnectionError.apiFailure(\"SQL Warehouse\");\n }\n const status = response.status;\n const statementId = response.statement_id as string;\n\n span.setAttribute(\"db.statement_id\", statementId);\n span.addEvent(\"statement.submitted\", {\n \"db.statement_id\": response.statement_id,\n \"db.status\": status?.state,\n });\n\n let result:\n | sql.StatementResponse\n | { result: { statement_id: string; status: sql.StatementStatus } };\n\n switch (status?.state) {\n case \"RUNNING\":\n case \"PENDING\":\n span.addEvent(\"statement.polling_started\", {\n \"db.status\": response.status?.state,\n });\n result = await this._pollForStatementResult(\n workspaceClient,\n statementId,\n this.config.timeout,\n signal,\n );\n break;\n case \"SUCCEEDED\":\n result = this._transformDataArray(response);\n break;\n case \"FAILED\":\n throw ExecutionError.statementFailed(status.error?.message);\n case \"CANCELED\":\n throw ExecutionError.canceled();\n case \"CLOSED\":\n throw ExecutionError.resultsClosed();\n default:\n throw ExecutionError.unknownState(\n String(status?.state ?? \"unknown\"),\n );\n }\n\n const resultData = result.result as any;\n const rowCount =\n resultData?.data?.length ?? resultData?.data_array?.length ?? 0;\n\n if (rowCount > 0) {\n span.setAttribute(\"db.result.row_count\", rowCount);\n }\n\n const duration = Date.now() - startTime;\n logger.event()?.setContext(\"sql-warehouse\", {\n warehouse_id: input.warehouse_id,\n rows_returned: rowCount,\n query_duration_ms: duration,\n });\n\n success = true;\n // only set success status if not aborted\n if (!isAborted) {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n return result;\n } catch (error) {\n // only record error if not already handled by abort\n if (!isAborted) {\n span.recordException(error as Error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n\n logger.error(\n \"Statement execution failed: %s\",\n error instanceof Error ? error.message : String(error),\n );\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n throw error;\n }\n if (error instanceof AppKitError) {\n throw error;\n }\n throw ExecutionError.statementFailed(\n error instanceof Error ? error.message : String(error),\n );\n } finally {\n // remove abort handler\n if (abortHandler && signal) {\n signal.removeEventListener(\"abort\", abortHandler);\n }\n\n const duration = Date.now() - startTime;\n\n // end span if not already ended by abort handler\n if (!isAborted) {\n span.end();\n }\n\n const attributes = {\n \"db.warehouse_id\": input.warehouse_id,\n \"db.catalog\": input.catalog ?? \"\",\n \"db.schema\": input.schema ?? \"\",\n \"db.statement\": input.statement?.substring(0, 500) || \"\",\n success: success.toString(),\n };\n\n this.telemetryMetrics.queryCount.add(1, attributes);\n this.telemetryMetrics.queryDuration.record(duration, attributes);\n }\n },\n { name: this.name, includePrefix: true },\n );\n }\n\n /**\n * Wait until the SQL warehouse is in the `RUNNING` state, auto-starting it\n * if currently `STOPPED`. Emits a {@link WarehouseStatusUpdate} whenever\n * the observed state changes, so callers can surface progress (e.g. over\n * SSE) instead of letting the UI freeze on a cold warehouse. Equal\n * successive observations are de-duplicated.\n *\n * Fast path: if this connector recently observed the warehouse RUNNING\n * (within {@link WAREHOUSE_RUNNING_CACHE_TTL_MS}), the call returns\n * immediately without any SDK round-trip or status emission. This keeps\n * cache-hit analytics requests off the Databricks control plane.\n *\n * Concurrent callers for the same `warehouseId` share a single in-flight\n * poll loop (singleflight): only the owner issues `get`/`start`; joiners\n * receive broadcast `onStatus` updates and share the result promise.\n * When every waiter disconnects before `warehouses.start`, the shared poll\n * is aborted on the next microtask if still unclaimed (kills true orphans\n * without a fixed grace window). After `start` is issued, the poll runs to\n * completion even with no waiters.\n *\n * Behaviour by initial state:\n * - `RUNNING`: emits one update, caches the observation, returns.\n * - `STOPPED`: emits a synthetic `STARTING` update, calls\n * `workspaceClient.warehouses.start`, then polls until `RUNNING`.\n * When `autoStart: false`, throws `ConfigurationError` instead.\n * - `STARTING` / `STOPPING`: polls until `RUNNING`.\n * - `DELETED` / `DELETING`: throws `ConfigurationError.resourceNotFound`.\n *\n * Aborts and timeouts surface as `ExecutionError`. The poll loop uses\n * exponential backoff with ±15% jitter (1s → 30s cap) and runs inside a\n * `sql.warehouseReady` telemetry span.\n */\n async ensureWarehouseRunning(\n workspaceClient: WorkspaceClient,\n warehouseId: string,\n opts: EnsureWarehouseRunningOptions,\n ): Promise<void> {\n const {\n onStatus,\n signal,\n timeoutMs = DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS,\n autoStart = true,\n } = opts;\n\n if (signal?.aborted) throw ExecutionError.canceled();\n if (!warehouseId) throw ValidationError.missingField(\"warehouse_id\");\n if (this._isRecentlyRunning(warehouseId)) return;\n\n const existing = this._readinessInFlight.get(warehouseId);\n if (existing && !existing.sharedController.signal.aborted) {\n return this._waitOnReadiness(existing, onStatus, signal, true);\n }\n\n const entry = this._spawnReadinessInFlight(workspaceClient, warehouseId, {\n timeoutMs,\n autoStart,\n });\n this._readinessInFlight.set(warehouseId, entry);\n return this._waitOnReadiness(entry, onStatus, signal, false);\n }\n\n private _waitOnReadiness(\n entry: WarehouseReadinessInFlight,\n onStatus: (update: WarehouseStatusUpdate) => void,\n signal: AbortSignal | undefined,\n join: boolean,\n ): Promise<void> {\n if (signal?.aborted) throw ExecutionError.canceled();\n if (join) entry.refCount++;\n entry.subscribers.add(onStatus);\n if (entry.lastUpdate) onStatus(entry.lastUpdate);\n return this._joinWarehouseReadiness(entry, signal);\n }\n\n private _spawnReadinessInFlight(\n workspaceClient: WorkspaceClient,\n warehouseId: string,\n opts: { timeoutMs: number; autoStart: boolean },\n ): WarehouseReadinessInFlight {\n const sharedController = new AbortController();\n const entry: WarehouseReadinessInFlight = {\n refCount: 1,\n sharedController,\n subscribers: new Set(),\n lastUpdate: null,\n warehouseStartIssued: false,\n promise: Promise.resolve(),\n };\n\n entry.promise = this.telemetry\n .startActiveSpan(\n \"sql.warehouseReady\",\n {\n kind: SpanKind.CLIENT,\n attributes: {\n \"db.system\": \"databricks\",\n \"db.warehouse_id\": warehouseId,\n \"db.warehouse.startup_timeout_ms\": opts.timeoutMs,\n },\n },\n async (span: Span) => {\n try {\n await this._pollUntilWarehouseRunning(\n workspaceClient,\n warehouseId,\n {\n onStatus: (update) => this._broadcastReadiness(entry, update),\n signal: sharedController.signal,\n timeoutMs: opts.timeoutMs,\n autoStart: opts.autoStart,\n onWarehouseStartIssued: () => {\n entry.warehouseStartIssued = true;\n },\n },\n span,\n );\n span.setStatus({ code: SpanStatusCode.OK });\n } catch (error) {\n this._throwSanitizedReadinessError(error, warehouseId, span);\n } finally {\n span.end();\n }\n },\n { name: this.name, includePrefix: true },\n )\n .finally(() => {\n if (this._readinessInFlight.get(warehouseId) === entry) {\n this._readinessInFlight.delete(warehouseId);\n }\n });\n\n entry.promise.catch(() => {});\n return entry;\n }\n\n private _broadcastReadiness(\n entry: WarehouseReadinessInFlight,\n update: WarehouseStatusUpdate,\n ): void {\n entry.lastUpdate = update;\n for (const subscriber of entry.subscribers) {\n try {\n subscriber(update);\n } catch {\n // One consumer must not block updates to the rest.\n }\n }\n }\n\n /** Ref-counted await; caller abort rejects locally. */\n private _joinWarehouseReadiness(\n entry: WarehouseReadinessInFlight,\n callerSignal?: AbortSignal,\n ): Promise<void> {\n if (!callerSignal) return entry.promise;\n\n return new Promise<void>((resolve, reject) => {\n let done = false;\n const finish = (outcome: \"ok\" | \"abort\" | \"err\", error?: unknown) => {\n if (done) return;\n done = true;\n callerSignal.removeEventListener(\"abort\", onAbort);\n if (outcome === \"ok\") resolve();\n else if (outcome === \"abort\") reject(ExecutionError.canceled());\n else reject(error);\n };\n const onAbort = () => {\n this._releaseReadinessWaiter(entry);\n finish(\"abort\");\n };\n callerSignal.addEventListener(\"abort\", onAbort, { once: true });\n entry.promise.then(\n () => finish(\"ok\"),\n (error) => finish(\"err\", error),\n );\n });\n }\n\n private _releaseReadinessWaiter(entry: WarehouseReadinessInFlight): void {\n if (entry.refCount > 0) entry.refCount--;\n if (entry.refCount > 0 || entry.sharedController.signal.aborted) return;\n\n if (entry.warehouseStartIssued) {\n // Start already issued — finish warming for the process.\n return;\n }\n\n // Defer abort to the next microtask so a synchronous StrictMode\n // remount can rejoin before the shared poll is cancelled.\n queueMicrotask(() => {\n if (entry.refCount <= 0 && !entry.sharedController.signal.aborted) {\n entry.sharedController.abort(\"all warehouse readiness waiters aborted\");\n }\n });\n }\n\n private async _pollUntilWarehouseRunning(\n workspaceClient: WorkspaceClient,\n warehouseId: string,\n opts: EnsureWarehouseRunningOptions,\n span: Span,\n ): Promise<void> {\n const {\n onStatus,\n signal,\n timeoutMs = DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS,\n autoStart = true,\n onWarehouseStartIssued,\n } = opts;\n const startTime = Date.now();\n const emitter = new WarehouseStatusEmitter(span, startTime, onStatus);\n let didStart = false;\n const backoff = new WarehousePollBackoff();\n\n while (true) {\n if (signal?.aborted) throw ExecutionError.canceled();\n if (Date.now() - startTime > timeoutMs) {\n throw ExecutionError.statementFailed(\n `SQL warehouse did not reach RUNNING within ${timeoutMs}ms`,\n );\n }\n\n const info = await workspaceClient.warehouses.get(\n { id: warehouseId },\n this._createContext(signal),\n );\n const state = info?.state;\n const summary = info?.health?.summary;\n\n switch (state) {\n case \"RUNNING\":\n emitter.emit(state, summary);\n this._recentlyRunning.set(warehouseId, Date.now());\n span.setAttribute(\"db.warehouse.attempts\", emitter.attempt);\n return;\n case \"DELETED\":\n case \"DELETING\":\n throw ConfigurationError.resourceNotFound(\n \"Warehouse ID\",\n `The configured SQL warehouse is ${state}. Update DATABRICKS_WAREHOUSE_ID to point at an active warehouse.`,\n );\n case \"STOPPED\":\n if (!autoStart) {\n throw new ConfigurationError(\n \"The configured SQL warehouse is STOPPED and analytics auto-start is disabled. Start the warehouse manually or set analytics.autoStartWarehouse=true.\",\n );\n }\n if (!didStart) {\n emitter.emit(\"STARTING\", summary);\n onWarehouseStartIssued?.();\n await workspaceClient.warehouses.start(\n { id: warehouseId },\n this._createContext(signal),\n );\n didStart = true;\n } else {\n emitter.emit(state, summary);\n }\n break;\n case \"STARTING\":\n case \"STOPPING\":\n emitter.emit(state, summary);\n break;\n default:\n throw ExecutionError.unknownState(String(state ?? \"unknown\"));\n }\n\n const sleepMs = backoff.next();\n if (Date.now() + sleepMs - startTime >= timeoutMs) {\n throw ExecutionError.statementFailed(\n `SQL warehouse did not reach RUNNING within ${timeoutMs}ms`,\n );\n }\n await this._sleepRespectingAbort(sleepMs, signal);\n }\n }\n\n /**\n * `true` if this connector observed `warehouseId` in the RUNNING state\n * within the recent-cache TTL.\n */\n private _isRecentlyRunning(warehouseId: string): boolean {\n const observedAt = this._recentlyRunning.get(warehouseId);\n return (\n observedAt !== undefined &&\n Date.now() - observedAt < WAREHOUSE_RUNNING_CACHE_TTL_MS\n );\n }\n\n /**\n * Final landing for any error thrown by the readiness poll loop. Records\n * the original on the span and (at debug level) on the logger, then\n * rethrows either the structured AppKitError unchanged or a curated\n * ExecutionError — never the raw SDK message, which can contain operator\n * internals.\n *\n * The `logger.debug` covers environments where OTel isn't configured\n * (common in dev) so the raw error isn't lost just because no span\n * exporter is hooked up.\n */\n private _throwSanitizedReadinessError(\n error: unknown,\n warehouseId: string,\n span: Span,\n ): never {\n if (error instanceof AppKitError) {\n span.recordException(error);\n span.setStatus({ code: SpanStatusCode.ERROR, message: error.code });\n throw error;\n }\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n logger.debug(\n \"Warehouse readiness check raw error for %s: %O\",\n warehouseId,\n error,\n );\n const wrapped = ExecutionError.statementFailed(\n \"Warehouse readiness check failed\",\n );\n span.setStatus({ code: SpanStatusCode.ERROR, message: wrapped.code });\n throw wrapped;\n }\n\n /**\n * Sleep for `ms` milliseconds, but resolve early (and reject with\n * `ExecutionError.canceled()`) if `signal` aborts mid-sleep. Used by the\n * warehouse readiness loop so that client disconnects don't keep the loop\n * polling for the full interval.\n */\n private _sleepRespectingAbort(\n ms: number,\n signal?: AbortSignal,\n ): Promise<void> {\n if (signal?.aborted) return Promise.reject(ExecutionError.canceled());\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(ExecutionError.canceled());\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n private async _pollForStatementResult(\n workspaceClient: WorkspaceClient,\n statementId: string,\n timeout = executeStatementDefaults.timeout,\n signal?: AbortSignal,\n ) {\n return this.telemetry.startActiveSpan(\n \"sql.poll\",\n {\n attributes: {\n \"db.statement_id\": statementId,\n \"db.polling.timeout\": timeout,\n },\n },\n async (span: Span) => {\n try {\n const startTime = Date.now();\n let delay = 1000;\n const maxDelayBetweenPolls = 5000; // max 5 seconds between polls\n let pollCount = 0;\n\n while (true) {\n pollCount++;\n span.setAttribute(\"db.polling.current_attempt\", pollCount);\n\n // check if timeout exceeded\n const elapsedTime = Date.now() - startTime;\n if (elapsedTime > timeout) {\n const error = ExecutionError.statementFailed(\n `Polling timeout exceeded after ${timeout}ms (elapsed: ${elapsedTime}ms)`,\n );\n span.recordException(error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n }\n\n if (signal?.aborted) {\n const error = ExecutionError.canceled();\n span.recordException(error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n }\n\n span.addEvent(\"polling.attempt\", {\n \"poll.attempt\": pollCount,\n \"poll.delay_ms\": delay,\n \"poll.elapsed_ms\": elapsedTime,\n });\n\n const response =\n await workspaceClient.statementExecution.getStatement(\n {\n statement_id: statementId,\n },\n this._createContext(signal),\n );\n if (!response) {\n throw ConnectionError.apiFailure(\"SQL Warehouse\");\n }\n\n const status = response.status;\n\n span.addEvent(\"polling.status_check\", {\n \"db.status\": status?.state,\n \"poll.attempt\": pollCount,\n });\n\n switch (status?.state) {\n case \"PENDING\":\n case \"RUNNING\":\n // continue polling\n break;\n case \"SUCCEEDED\":\n span.setAttribute(\"db.polling.attempts\", pollCount);\n span.setAttribute(\"db.polling.total_duration_ms\", elapsedTime);\n span.addEvent(\"polling.completed\", {\n \"poll.attempts\": pollCount,\n \"poll.duration_ms\": elapsedTime,\n });\n span.setStatus({ code: SpanStatusCode.OK });\n return this._transformDataArray(response);\n case \"FAILED\":\n throw ExecutionError.statementFailed(status.error?.message);\n case \"CANCELED\":\n throw ExecutionError.canceled();\n case \"CLOSED\":\n throw ExecutionError.resultsClosed();\n default:\n throw ExecutionError.unknownState(\n String(status?.state ?? \"unknown\"),\n );\n }\n\n // continue polling after delay\n await new Promise((resolve) => setTimeout(resolve, delay));\n delay = Math.min(delay * 2, maxDelayBetweenPolls);\n }\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n\n // error logging is handled by executeStatement's catch block (gated on isAborted)\n if (error instanceof Error && error.name === \"AbortError\") {\n throw error;\n }\n if (error instanceof AppKitError) {\n throw error;\n }\n throw ExecutionError.statementFailed(\n error instanceof Error ? error.message : String(error),\n );\n } finally {\n span.end();\n }\n },\n { name: this.name, includePrefix: true },\n );\n }\n\n private _transformDataArray(response: sql.StatementResponse) {\n if (response.manifest?.format === \"ARROW_STREAM\") {\n return this.updateWithArrowStatus(response);\n }\n\n if (!response.result?.data_array || !response.manifest?.schema?.columns) {\n return response;\n }\n\n const columns = response.manifest.schema.columns;\n\n const transformedData = response.result.data_array.map((row) => {\n const obj: Record<string, unknown> = {};\n row.forEach((value, index) => {\n const column = columns[index];\n const columnName = column?.name || `column_${index}`;\n\n // attempt to parse JSON strings for string columns\n if (\n column?.type_name === \"STRING\" &&\n typeof value === \"string\" &&\n value &&\n (value[0] === \"{\" || value[0] === \"[\")\n ) {\n try {\n obj[columnName] = JSON.parse(value);\n } catch {\n // if parsing fails, keep as string\n obj[columnName] = value;\n }\n } else {\n obj[columnName] = value;\n }\n });\n return obj;\n });\n\n // remove data_array\n const { data_array: _data_array, ...restResult } = response.result;\n return {\n ...response,\n result: {\n ...restResult,\n data: transformedData,\n },\n };\n }\n\n private updateWithArrowStatus(response: sql.StatementResponse): {\n result: { statement_id: string; status: sql.StatementStatus };\n } {\n return {\n result: {\n statement_id: response.statement_id as string,\n status: {\n state: response.status?.state,\n error: response.status?.error,\n } as sql.StatementStatus,\n },\n };\n }\n\n async getArrowData(\n workspaceClient: WorkspaceClient,\n jobId: string,\n signal?: AbortSignal,\n ): Promise<ReturnType<typeof this.arrowProcessor.processChunks>> {\n const startTime = Date.now();\n\n return this.telemetry.startActiveSpan(\n \"arrow.getData\",\n {\n kind: SpanKind.CLIENT,\n attributes: {\n \"db.system\": \"databricks\",\n \"arrow.job_id\": jobId,\n },\n },\n async (span: Span) => {\n try {\n const response =\n await workspaceClient.statementExecution.getStatement(\n { statement_id: jobId },\n this._createContext(signal),\n );\n\n const chunks = response.result?.external_links;\n const schema = response.manifest?.schema;\n\n if (!chunks || !schema) {\n throw ExecutionError.missingData(\"chunks or schema\");\n }\n\n span.setAttribute(\"arrow.chunk_count\", chunks.length);\n\n const result = await this.arrowProcessor.processChunks(\n chunks,\n schema,\n signal,\n );\n\n span.setAttribute(\"arrow.data_size_bytes\", result.data.length);\n span.setStatus({ code: SpanStatusCode.OK });\n\n const duration = Date.now() - startTime;\n this.telemetryMetrics.queryDuration.record(duration, {\n operation: \"arrow.getData\",\n status: \"success\",\n });\n\n logger.event()?.setContext(\"sql-warehouse\", {\n arrow_data_size_bytes: result.data.length,\n arrow_job_id: jobId,\n });\n\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : \"Unknown error\",\n });\n span.recordException(error as Error);\n\n const duration = Date.now() - startTime;\n this.telemetryMetrics.queryDuration.record(duration, {\n operation: \"arrow.getData\",\n status: \"error\",\n });\n\n logger.error(\"Failed Arrow job: %s %O\", jobId, error);\n\n if (error instanceof AppKitError) {\n throw error;\n }\n throw ExecutionError.statementFailed(\n error instanceof Error ? error.message : String(error),\n );\n }\n },\n );\n }\n\n // create context for cancellation token\n private _createContext(signal?: AbortSignal) {\n return new Context({\n cancellationToken: {\n isCancellationRequested: signal?.aborted ?? false,\n onCancellationRequested: (cb: () => void) => {\n signal?.addEventListener(\"abort\", cb, { once: true });\n },\n },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,SAAS,aAAa,2BAA2B;;;;;;;;AAcvD,MAAa,uCAAuC,MAAS;;;;;;;;AAS7D,MAAM,iCAAiC;AAqDvC,IAAa,wBAAb,MAAmC;CACjC,AAAiB,OAAO;CAExB,AAAQ;CAGR,AAAQ,kBAA+C;;;;;;CAOvD,AAAQ,mCAAmB,IAAI,KAAqB;;CAEpD,AAAQ,qCAAqB,IAAI,KAAyC;CAE1E,AAAiB;CACjB,AAAiB;CAKjB,YAAY,QAA4B;AACtC,OAAK,SAAS;AAEd,OAAK,YAAY,iBAAiB,YAChC,KAAK,MACL,KAAK,OAAO,UACb;AACD,OAAK,mBAAmB;GACtB,YAAY,KAAK,UAAU,UAAU,CAAC,cAAc,eAAe;IACjE,aAAa;IACb,MAAM;IACP,CAAC;GACF,eAAe,KAAK,UACjB,UAAU,CACV,gBAAgB,kBAAkB;IACjC,aAAa;IACb,MAAM;IACP,CAAC;GACL;;;;;;CAOH,IAAY,iBAAuC;AACjD,MAAI,CAAC,KAAK,gBACR,MAAK,kBAAkB,IAAI,qBAAqB;GAC9C,SAAS,KAAK,OAAO,WAAW,yBAAyB;GACzD,wBACE,qBAAqB;GACvB,SAAS,qBAAqB;GAC/B,CAAC;AAEJ,SAAO,KAAK;;CAGd,MAAM,iBACJ,iBACA,OACA,QACA;EACA,MAAM,YAAY,KAAK,KAAK;EAC5B,IAAI,UAAU;AAGd,MAAI,QAAQ,QACV,OAAM,eAAe,UAAU;AAGjC,SAAO,KAAK,UAAU,gBACpB,aACA;GACE,MAAM,SAAS;GACf,YAAY;IACV,aAAa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AiB;KAC1C,uBAAuB,OAAO,KAAK;KACnC,cAAc;KACf,CAAC;AAEF,WAAO;YACA,OAAO;AACd,SAAK,UAAU;KACb,MAAM,eAAe;KACrB,SAAS,iBAAiB,QAAQ,MAAM,UAAU;KACnD,CAAC;AACF,SAAK,gBAAgB,MAAe;IAEpC,MAAM,WAAW,KAAK,KAAK,GAAG;AAC9B,SAAK,iBAAiB,cAAc,OAAO,UAAU;KACnD,WAAW;KACX,QAAQ;KACT,CAAC;AAEF,WAAO,MAAM,2BAA2B,OAAO,MAAM;AAErD,QAAI,iBAAiB,YACnB,OAAM;AAER,UAAM,eAAe,gBACnB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,CACvD;;IAGN;;CAIH,AAAQ,eAAe,QAAsB;AAC3C,SAAO,IAAI,QAAQ,EACjB,mBAAmB;GACjB,yBAAyB,QAAQ,WAAW;GAC5C,0BAA0B,OAAmB;AAC3C,YAAQ,iBAAiB,SAAS,IAAI,EAAE,MAAM,MAAM,CAAC;;GAExD,EACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../../src/connectors/sql-warehouse/client.ts"],"sourcesContent":["import {\n Context,\n type sql,\n type WorkspaceClient,\n} from \"@databricks/sdk-experimental\";\nimport type { TelemetryOptions } from \"shared\";\nimport {\n AppKitError,\n ConfigurationError,\n ConnectionError,\n ExecutionError,\n ValidationError,\n} from \"../../errors\";\nimport { createLogger } from \"../../logging/logger\";\nimport {\n ArrowStreamProcessor,\n type RefreshChunkLink,\n} from \"../../stream/arrow-stream-processor\";\nimport type { TelemetryProvider } from \"../../telemetry\";\nimport {\n type Counter,\n type Histogram,\n type Span,\n SpanKind,\n SpanStatusCode,\n TelemetryManager,\n} from \"../../telemetry\";\nimport { buildEmptyArrowIPCBase64 } from \"./arrow-schema\";\nimport { executeStatementDefaults } from \"./defaults\";\nimport { WarehousePollBackoff } from \"./warehouse-poll-backoff\";\nimport { WarehouseStatusEmitter } from \"./warehouse-status-emitter\";\n\nconst logger = createLogger(\"connectors:sql-warehouse\");\n\n/**\n * Real column names from a statement's result manifest (positional\n * `column_N` fallback for any blank ones). Databricks encodes ARROW_STREAM\n * schemas positionally (`col_0`, …); these names let consumers relabel an\n * Arrow result to match the JSON path. Returns `undefined` when the manifest\n * carries no columns.\n */\nfunction arrowColumnNames(\n response: sql.StatementResponse,\n): string[] | undefined {\n const cols = response.manifest?.schema?.columns;\n if (!cols || cols.length === 0) return undefined;\n return cols.map((c, i) =>\n c.name && c.name.length > 0 ? c.name : `column_${i}`,\n );\n}\n\n/**\n * Maximum size for inline Arrow IPC attachments (25 MiB decoded — the\n * Databricks Statement Execution API hard cap on INLINE responses).\n *\n * The analytics route streams the decoded attachment straight back on the\n * query response body; this cap bounds the single in-memory copy. Larger\n * results fall through to `disposition: \"EXTERNAL_LINKS\"`, which streams\n * chunk-by-chunk and is not bound by this limit.\n */\nconst MAX_INLINE_ATTACHMENT_BYTES = 25 * 1024 * 1024;\n\n/**\n * Safety cap on how many additional EXTERNAL_LINKS chunks\n * {@link SQLWarehouseConnector._resolveAllExternalLinks} will follow when the\n * manifest omits `total_chunk_count`. High enough to cover any real result;\n * only bounds a misbehaving warehouse with a cyclic `next_chunk_index`.\n */\nconst MAX_EXTERNAL_CHUNK_FOLLOWS = 10_000;\n\ninterface SQLWarehouseConfig {\n timeout?: number;\n telemetry?: TelemetryOptions;\n}\n\n/**\n * Default ceiling for how long {@link SQLWarehouseConnector.ensureWarehouseRunning}\n * will wait for a warehouse to reach the RUNNING state before giving up.\n *\n * Five minutes covers a cold-start of a classic warehouse on most workspaces;\n * serverless typically reaches RUNNING within ~30s.\n */\nexport const DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS = 5 * 60 * 1000;\n\n/**\n * Window during which a recent `RUNNING` observation lets subsequent calls\n * to {@link SQLWarehouseConnector.ensureWarehouseRunning} short-circuit\n * without making any SDK calls. Sized to roughly the upper bound of how\n * long Databricks keeps a warehouse \"stickily\" available between requests\n * — past that, we re-verify.\n */\nconst WAREHOUSE_RUNNING_CACHE_TTL_MS = 30_000;\n\n/**\n * A single observation of the warehouse state, emitted by\n * {@link SQLWarehouseConnector.ensureWarehouseRunning} so callers can stream\n * progress to clients (e.g. over SSE).\n *\n * Note: `health.summary` from the SDK is intentionally NOT exposed on this\n * type. It's free-form operator-oriented diagnostic text (cluster IDs,\n * capacity-failure reasons, internal RPC errors) that must not reach end\n * users. The raw value stays in the OTel span attributes for server-side\n * debugging only.\n */\nexport interface WarehouseStatusUpdate {\n /** Current state from the SDK (RUNNING | STARTING | STOPPED | STOPPING | DELETED | DELETING). */\n state: sql.State;\n /** Milliseconds elapsed since `ensureWarehouseRunning` was called. */\n elapsedMs: number;\n /** 1-based attempt counter — useful for tests and telemetry. */\n attempt: number;\n}\n\n/** Options for {@link SQLWarehouseConnector.ensureWarehouseRunning}. */\ninterface EnsureWarehouseRunningOptions {\n /** Invoked every time the warehouse state changes during the wait. */\n onStatus: (update: WarehouseStatusUpdate) => void;\n /** Aborts the wait. The connector treats abort as `ExecutionError.canceled()`. */\n signal?: AbortSignal;\n /** Hard ceiling on the total wait. Defaults to {@link DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS}. */\n timeoutMs?: number;\n /**\n * When `true` (default), a `STOPPED` warehouse is auto-started.\n * When `false`, `STOPPED` surfaces as `ConfigurationError` immediately —\n * useful for cost-controlled deployments that don't want any caller to\n * trigger billable warehouse starts.\n */\n autoStart?: boolean;\n /** @internal Fired once when `warehouses.start` is issued for this poll. */\n onWarehouseStartIssued?: () => void;\n}\n\n/** In-flight warehouse readiness work shared across concurrent callers. */\ninterface WarehouseReadinessInFlight {\n promise: Promise<void>;\n refCount: number;\n sharedController: AbortController;\n subscribers: Set<(update: WarehouseStatusUpdate) => void>;\n /** Last emitted update; replayed to late joiners. */\n lastUpdate: WarehouseStatusUpdate | null;\n /** `true` once this poll has called `warehouses.start`. */\n warehouseStartIssued: boolean;\n}\n\nexport class SQLWarehouseConnector {\n private readonly name = \"sql-warehouse\";\n\n private config: SQLWarehouseConfig;\n\n // Lazy-initialized: only created when Arrow format is used\n private _arrowProcessor: ArrowStreamProcessor | null = null;\n\n /**\n * Per-warehouse cache of the last RUNNING observation timestamp. Used by\n * {@link ensureWarehouseRunning} to short-circuit warm-path callers; see\n * {@link WAREHOUSE_RUNNING_CACHE_TTL_MS}.\n */\n private _recentlyRunning = new Map<string, number>();\n /** Per-warehouse readiness singleflight — one poll loop per cold start. */\n private _readinessInFlight = new Map<string, WarehouseReadinessInFlight>();\n // telemetry\n private readonly telemetry: TelemetryProvider;\n private readonly telemetryMetrics: {\n queryCount: Counter;\n queryDuration: Histogram;\n };\n\n constructor(config: SQLWarehouseConfig) {\n this.config = config;\n\n this.telemetry = TelemetryManager.getProvider(\n this.name,\n this.config.telemetry,\n );\n this.telemetryMetrics = {\n queryCount: this.telemetry.getMeter().createCounter(\"query.count\", {\n description: \"Total number of queries executed\",\n unit: \"1\",\n }),\n queryDuration: this.telemetry\n .getMeter()\n .createHistogram(\"query.duration\", {\n description: \"Duration of queries executed\",\n unit: \"ms\",\n }),\n };\n }\n\n /**\n * Lazily initializes and returns the ArrowStreamProcessor.\n * Only created on first Arrow format query to avoid unnecessary allocation.\n */\n private get arrowProcessor(): ArrowStreamProcessor {\n if (!this._arrowProcessor) {\n this._arrowProcessor = new ArrowStreamProcessor({\n timeout: this.config.timeout || executeStatementDefaults.timeout,\n retries: ArrowStreamProcessor.DEFAULT_RETRIES,\n });\n }\n return this._arrowProcessor;\n }\n\n async executeStatement(\n workspaceClient: WorkspaceClient,\n input: sql.ExecuteStatementRequest,\n signal?: AbortSignal,\n ) {\n const startTime = Date.now();\n let success = false;\n\n // if signal is aborted, throw an error\n if (signal?.aborted) {\n throw ExecutionError.canceled();\n }\n\n return this.telemetry.startActiveSpan(\n \"sql.query\",\n {\n kind: SpanKind.CLIENT,\n attributes: {\n \"db.system\": \"databricks\",\n \"db.warehouse_id\": input.warehouse_id || \"\",\n \"db.catalog\": input.catalog ?? \"\",\n \"db.schema\": input.schema ?? \"\",\n \"db.statement\": input.statement?.substring(0, 500) || \"\",\n \"db.has_parameters\": !!input.parameters,\n },\n },\n async (span: Span) => {\n let abortHandler: (() => void) | undefined;\n let isAborted = false;\n\n if (signal) {\n abortHandler = () => {\n // abort span if not recording\n if (!span.isRecording()) return;\n isAborted = true;\n span.setAttribute(\"cancelled\", true);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: \"Query cancelled by client\",\n });\n span.end();\n };\n signal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n\n try {\n // validate required fields\n if (!input.statement) {\n throw ValidationError.missingField(\"statement\");\n }\n\n if (!input.warehouse_id) {\n throw ValidationError.missingField(\"warehouse_id\");\n }\n\n const body: sql.ExecuteStatementRequest = {\n statement: input.statement,\n parameters: input.parameters,\n warehouse_id: input.warehouse_id,\n catalog: input.catalog,\n schema: input.schema,\n wait_timeout:\n input.wait_timeout || executeStatementDefaults.wait_timeout,\n disposition:\n input.disposition || executeStatementDefaults.disposition,\n format: input.format || executeStatementDefaults.format,\n byte_limit: input.byte_limit,\n row_limit: input.row_limit,\n on_wait_timeout:\n input.on_wait_timeout || executeStatementDefaults.on_wait_timeout,\n };\n\n span.addEvent(\"statement.submitting\", {\n \"db.warehouse_id\": input.warehouse_id,\n });\n\n const response =\n await workspaceClient.statementExecution.executeStatement(\n body,\n this._createContext(signal),\n );\n\n if (!response) {\n throw ConnectionError.apiFailure(\"SQL Warehouse\");\n }\n const status = response.status;\n const statementId = response.statement_id as string;\n\n span.setAttribute(\"db.statement_id\", statementId);\n span.addEvent(\"statement.submitted\", {\n \"db.statement_id\": response.statement_id,\n \"db.status\": status?.state,\n });\n\n let result:\n | sql.StatementResponse\n | { result: { statement_id: string; status: sql.StatementStatus } };\n\n switch (status?.state) {\n case \"RUNNING\":\n case \"PENDING\":\n span.addEvent(\"statement.polling_started\", {\n \"db.status\": response.status?.state,\n });\n result = await this._pollForStatementResult(\n workspaceClient,\n statementId,\n this.config.timeout,\n signal,\n );\n break;\n case \"SUCCEEDED\":\n result = await this._transformDataArray(\n response,\n workspaceClient,\n signal,\n );\n break;\n case \"FAILED\":\n throw ExecutionError.statementFailed(\n status.error?.message,\n status.error?.error_code,\n );\n case \"CANCELED\":\n throw ExecutionError.canceled();\n case \"CLOSED\":\n throw ExecutionError.resultsClosed();\n default:\n throw ExecutionError.unknownState(\n String(status?.state ?? \"unknown\"),\n );\n }\n\n const resultData = result.result as any;\n const rowCount =\n resultData?.data?.length ?? resultData?.data_array?.length ?? 0;\n\n if (rowCount > 0) {\n span.setAttribute(\"db.result.row_count\", rowCount);\n }\n\n const duration = Date.now() - startTime;\n logger.event()?.setContext(\"sql-warehouse\", {\n warehouse_id: input.warehouse_id,\n rows_returned: rowCount,\n query_duration_ms: duration,\n });\n\n success = true;\n // only set success status if not aborted\n if (!isAborted) {\n span.setStatus({ code: SpanStatusCode.OK });\n }\n return result;\n } catch (error) {\n // only record error if not already handled by abort\n if (!isAborted) {\n span.recordException(error as Error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n\n logger.error(\n \"Statement execution failed: %s\",\n error instanceof Error ? error.message : String(error),\n );\n }\n\n this._rethrowStatementError(error);\n } finally {\n // remove abort handler\n if (abortHandler && signal) {\n signal.removeEventListener(\"abort\", abortHandler);\n }\n\n const duration = Date.now() - startTime;\n\n // end span if not already ended by abort handler\n if (!isAborted) {\n span.end();\n }\n\n const attributes = {\n \"db.warehouse_id\": input.warehouse_id,\n \"db.catalog\": input.catalog ?? \"\",\n \"db.schema\": input.schema ?? \"\",\n \"db.statement\": input.statement?.substring(0, 500) || \"\",\n success: success.toString(),\n };\n\n this.telemetryMetrics.queryCount.add(1, attributes);\n this.telemetryMetrics.queryDuration.record(duration, attributes);\n }\n },\n { name: this.name, includePrefix: true },\n );\n }\n\n /**\n * Wait until the SQL warehouse is in the `RUNNING` state, auto-starting it\n * if currently `STOPPED`. Emits a {@link WarehouseStatusUpdate} whenever\n * the observed state changes, so callers can surface progress (e.g. over\n * SSE) instead of letting the UI freeze on a cold warehouse. Equal\n * successive observations are de-duplicated.\n *\n * Fast path: if this connector recently observed the warehouse RUNNING\n * (within {@link WAREHOUSE_RUNNING_CACHE_TTL_MS}), the call returns\n * immediately without any SDK round-trip or status emission. This keeps\n * cache-hit analytics requests off the Databricks control plane.\n *\n * Concurrent callers for the same `warehouseId` share a single in-flight\n * poll loop (singleflight): only the owner issues `get`/`start`; joiners\n * receive broadcast `onStatus` updates and share the result promise.\n * When every waiter disconnects before `warehouses.start`, the shared poll\n * is aborted on the next microtask if still unclaimed (kills true orphans\n * without a fixed grace window). After `start` is issued, the poll runs to\n * completion even with no waiters.\n *\n * Behaviour by initial state:\n * - `RUNNING`: emits one update, caches the observation, returns.\n * - `STOPPED`: emits a synthetic `STARTING` update, calls\n * `workspaceClient.warehouses.start`, then polls until `RUNNING`.\n * When `autoStart: false`, throws `ConfigurationError` instead.\n * - `STARTING` / `STOPPING`: polls until `RUNNING`.\n * - `DELETED` / `DELETING`: throws `ConfigurationError.resourceNotFound`.\n *\n * Aborts and timeouts surface as `ExecutionError`. The poll loop uses\n * exponential backoff with ±15% jitter (1s → 30s cap) and runs inside a\n * `sql.warehouseReady` telemetry span.\n */\n async ensureWarehouseRunning(\n workspaceClient: WorkspaceClient,\n warehouseId: string,\n opts: EnsureWarehouseRunningOptions,\n ): Promise<void> {\n const {\n onStatus,\n signal,\n timeoutMs = DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS,\n autoStart = true,\n } = opts;\n\n if (signal?.aborted) throw ExecutionError.canceled();\n if (!warehouseId) throw ValidationError.missingField(\"warehouse_id\");\n if (this._isRecentlyRunning(warehouseId)) return;\n\n const existing = this._readinessInFlight.get(warehouseId);\n if (existing && !existing.sharedController.signal.aborted) {\n return this._waitOnReadiness(existing, onStatus, signal, true);\n }\n\n const entry = this._spawnReadinessInFlight(workspaceClient, warehouseId, {\n timeoutMs,\n autoStart,\n });\n this._readinessInFlight.set(warehouseId, entry);\n return this._waitOnReadiness(entry, onStatus, signal, false);\n }\n\n private _waitOnReadiness(\n entry: WarehouseReadinessInFlight,\n onStatus: (update: WarehouseStatusUpdate) => void,\n signal: AbortSignal | undefined,\n join: boolean,\n ): Promise<void> {\n if (signal?.aborted) throw ExecutionError.canceled();\n if (join) entry.refCount++;\n entry.subscribers.add(onStatus);\n if (entry.lastUpdate) onStatus(entry.lastUpdate);\n return this._joinWarehouseReadiness(entry, signal);\n }\n\n private _spawnReadinessInFlight(\n workspaceClient: WorkspaceClient,\n warehouseId: string,\n opts: { timeoutMs: number; autoStart: boolean },\n ): WarehouseReadinessInFlight {\n const sharedController = new AbortController();\n const entry: WarehouseReadinessInFlight = {\n refCount: 1,\n sharedController,\n subscribers: new Set(),\n lastUpdate: null,\n warehouseStartIssued: false,\n promise: Promise.resolve(),\n };\n\n entry.promise = this.telemetry\n .startActiveSpan(\n \"sql.warehouseReady\",\n {\n kind: SpanKind.CLIENT,\n attributes: {\n \"db.system\": \"databricks\",\n \"db.warehouse_id\": warehouseId,\n \"db.warehouse.startup_timeout_ms\": opts.timeoutMs,\n },\n },\n async (span: Span) => {\n try {\n await this._pollUntilWarehouseRunning(\n workspaceClient,\n warehouseId,\n {\n onStatus: (update) => this._broadcastReadiness(entry, update),\n signal: sharedController.signal,\n timeoutMs: opts.timeoutMs,\n autoStart: opts.autoStart,\n onWarehouseStartIssued: () => {\n entry.warehouseStartIssued = true;\n },\n },\n span,\n );\n span.setStatus({ code: SpanStatusCode.OK });\n } catch (error) {\n this._throwSanitizedReadinessError(error, warehouseId, span);\n } finally {\n span.end();\n }\n },\n { name: this.name, includePrefix: true },\n )\n .finally(() => {\n if (this._readinessInFlight.get(warehouseId) === entry) {\n this._readinessInFlight.delete(warehouseId);\n }\n });\n\n entry.promise.catch(() => {});\n return entry;\n }\n\n private _broadcastReadiness(\n entry: WarehouseReadinessInFlight,\n update: WarehouseStatusUpdate,\n ): void {\n entry.lastUpdate = update;\n for (const subscriber of entry.subscribers) {\n try {\n subscriber(update);\n } catch {\n // One consumer must not block updates to the rest.\n }\n }\n }\n\n /** Ref-counted await; caller abort rejects locally. */\n private _joinWarehouseReadiness(\n entry: WarehouseReadinessInFlight,\n callerSignal?: AbortSignal,\n ): Promise<void> {\n if (!callerSignal) return entry.promise;\n\n return new Promise<void>((resolve, reject) => {\n let done = false;\n const finish = (outcome: \"ok\" | \"abort\" | \"err\", error?: unknown) => {\n if (done) return;\n done = true;\n callerSignal.removeEventListener(\"abort\", onAbort);\n if (outcome === \"ok\") resolve();\n else if (outcome === \"abort\") reject(ExecutionError.canceled());\n else reject(error);\n };\n const onAbort = () => {\n this._releaseReadinessWaiter(entry);\n finish(\"abort\");\n };\n callerSignal.addEventListener(\"abort\", onAbort, { once: true });\n entry.promise.then(\n () => finish(\"ok\"),\n (error) => finish(\"err\", error),\n );\n });\n }\n\n private _releaseReadinessWaiter(entry: WarehouseReadinessInFlight): void {\n if (entry.refCount > 0) entry.refCount--;\n if (entry.refCount > 0 || entry.sharedController.signal.aborted) return;\n\n if (entry.warehouseStartIssued) {\n // Start already issued — finish warming for the process.\n return;\n }\n\n // Defer abort to the next microtask so a synchronous StrictMode\n // remount can rejoin before the shared poll is cancelled.\n queueMicrotask(() => {\n if (entry.refCount <= 0 && !entry.sharedController.signal.aborted) {\n entry.sharedController.abort(\"all warehouse readiness waiters aborted\");\n }\n });\n }\n\n private async _pollUntilWarehouseRunning(\n workspaceClient: WorkspaceClient,\n warehouseId: string,\n opts: EnsureWarehouseRunningOptions,\n span: Span,\n ): Promise<void> {\n const {\n onStatus,\n signal,\n timeoutMs = DEFAULT_WAREHOUSE_STARTUP_TIMEOUT_MS,\n autoStart = true,\n onWarehouseStartIssued,\n } = opts;\n const startTime = Date.now();\n const emitter = new WarehouseStatusEmitter(span, startTime, onStatus);\n let didStart = false;\n const backoff = new WarehousePollBackoff();\n\n while (true) {\n if (signal?.aborted) throw ExecutionError.canceled();\n if (Date.now() - startTime > timeoutMs) {\n throw ExecutionError.statementFailed(\n `SQL warehouse did not reach RUNNING within ${timeoutMs}ms`,\n );\n }\n\n const info = await workspaceClient.warehouses.get(\n { id: warehouseId },\n this._createContext(signal),\n );\n const state = info?.state;\n const summary = info?.health?.summary;\n\n switch (state) {\n case \"RUNNING\":\n emitter.emit(state, summary);\n this._recentlyRunning.set(warehouseId, Date.now());\n span.setAttribute(\"db.warehouse.attempts\", emitter.attempt);\n return;\n case \"DELETED\":\n case \"DELETING\":\n throw ConfigurationError.resourceNotFound(\n \"Warehouse ID\",\n `The configured SQL warehouse is ${state}. Update DATABRICKS_WAREHOUSE_ID to point at an active warehouse.`,\n );\n case \"STOPPED\":\n if (!autoStart) {\n throw new ConfigurationError(\n \"The configured SQL warehouse is STOPPED and analytics auto-start is disabled. Start the warehouse manually or set analytics.autoStartWarehouse=true.\",\n );\n }\n if (!didStart) {\n emitter.emit(\"STARTING\", summary);\n onWarehouseStartIssued?.();\n await workspaceClient.warehouses.start(\n { id: warehouseId },\n this._createContext(signal),\n );\n didStart = true;\n } else {\n emitter.emit(state, summary);\n }\n break;\n case \"STARTING\":\n case \"STOPPING\":\n emitter.emit(state, summary);\n break;\n default:\n throw ExecutionError.unknownState(String(state ?? \"unknown\"));\n }\n\n const sleepMs = backoff.next();\n if (Date.now() + sleepMs - startTime >= timeoutMs) {\n throw ExecutionError.statementFailed(\n `SQL warehouse did not reach RUNNING within ${timeoutMs}ms`,\n );\n }\n await this._sleepRespectingAbort(sleepMs, signal);\n }\n }\n\n /**\n * `true` if this connector observed `warehouseId` in the RUNNING state\n * within the recent-cache TTL.\n */\n private _isRecentlyRunning(warehouseId: string): boolean {\n const observedAt = this._recentlyRunning.get(warehouseId);\n return (\n observedAt !== undefined &&\n Date.now() - observedAt < WAREHOUSE_RUNNING_CACHE_TTL_MS\n );\n }\n\n /**\n * Final landing for any error thrown by the readiness poll loop. Records\n * the original on the span and (at debug level) on the logger, then\n * rethrows either the structured AppKitError unchanged or a curated\n * ExecutionError — never the raw SDK message, which can contain operator\n * internals.\n *\n * The `logger.debug` covers environments where OTel isn't configured\n * (common in dev) so the raw error isn't lost just because no span\n * exporter is hooked up.\n */\n private _throwSanitizedReadinessError(\n error: unknown,\n warehouseId: string,\n span: Span,\n ): never {\n if (error instanceof AppKitError) {\n span.recordException(error);\n span.setStatus({ code: SpanStatusCode.ERROR, message: error.code });\n throw error;\n }\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n logger.debug(\n \"Warehouse readiness check raw error for %s: %O\",\n warehouseId,\n error,\n );\n const wrapped = ExecutionError.statementFailed(\n \"Warehouse readiness check failed\",\n );\n span.setStatus({ code: SpanStatusCode.ERROR, message: wrapped.code });\n throw wrapped;\n }\n\n /**\n * Sleep for `ms` milliseconds, but resolve early (and reject with\n * `ExecutionError.canceled()`) if `signal` aborts mid-sleep. Used by the\n * warehouse readiness loop so that client disconnects don't keep the loop\n * polling for the full interval.\n */\n private _sleepRespectingAbort(\n ms: number,\n signal?: AbortSignal,\n ): Promise<void> {\n if (signal?.aborted) return Promise.reject(ExecutionError.canceled());\n return new Promise<void>((resolve, reject) => {\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(ExecutionError.canceled());\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n private async _pollForStatementResult(\n workspaceClient: WorkspaceClient,\n statementId: string,\n timeout = executeStatementDefaults.timeout,\n signal?: AbortSignal,\n ) {\n return this.telemetry.startActiveSpan(\n \"sql.poll\",\n {\n attributes: {\n \"db.statement_id\": statementId,\n \"db.polling.timeout\": timeout,\n },\n },\n async (span: Span) => {\n try {\n const startTime = Date.now();\n let delay = 1000;\n const maxDelayBetweenPolls = 5000; // max 5 seconds between polls\n let pollCount = 0;\n\n while (true) {\n pollCount++;\n span.setAttribute(\"db.polling.current_attempt\", pollCount);\n\n // check if timeout exceeded\n const elapsedTime = Date.now() - startTime;\n if (elapsedTime > timeout) {\n const error = ExecutionError.statementFailed(\n `Polling timeout exceeded after ${timeout}ms (elapsed: ${elapsedTime}ms)`,\n );\n span.recordException(error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n }\n\n if (signal?.aborted) {\n const error = ExecutionError.canceled();\n span.recordException(error);\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n }\n\n span.addEvent(\"polling.attempt\", {\n \"poll.attempt\": pollCount,\n \"poll.delay_ms\": delay,\n \"poll.elapsed_ms\": elapsedTime,\n });\n\n const response =\n await workspaceClient.statementExecution.getStatement(\n {\n statement_id: statementId,\n },\n this._createContext(signal),\n );\n if (!response) {\n throw ConnectionError.apiFailure(\"SQL Warehouse\");\n }\n\n const status = response.status;\n\n span.addEvent(\"polling.status_check\", {\n \"db.status\": status?.state,\n \"poll.attempt\": pollCount,\n });\n\n switch (status?.state) {\n case \"PENDING\":\n case \"RUNNING\":\n // continue polling\n break;\n case \"SUCCEEDED\":\n span.setAttribute(\"db.polling.attempts\", pollCount);\n span.setAttribute(\"db.polling.total_duration_ms\", elapsedTime);\n span.addEvent(\"polling.completed\", {\n \"poll.attempts\": pollCount,\n \"poll.duration_ms\": elapsedTime,\n });\n span.setStatus({ code: SpanStatusCode.OK });\n return this._transformDataArray(\n response,\n workspaceClient,\n signal,\n );\n case \"FAILED\":\n throw ExecutionError.statementFailed(\n status.error?.message,\n status.error?.error_code,\n );\n case \"CANCELED\":\n throw ExecutionError.canceled();\n case \"CLOSED\":\n throw ExecutionError.resultsClosed();\n default:\n throw ExecutionError.unknownState(\n String(status?.state ?? \"unknown\"),\n );\n }\n\n // continue polling after delay\n await new Promise((resolve) => setTimeout(resolve, delay));\n delay = Math.min(delay * 2, maxDelayBetweenPolls);\n }\n } catch (error) {\n span.recordException(error as Error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n\n // error logging is handled by executeStatement's catch block (gated on isAborted)\n this._rethrowStatementError(error);\n } finally {\n span.end();\n }\n },\n { name: this.name, includePrefix: true },\n );\n }\n\n private async _transformDataArray(\n response: sql.StatementResponse,\n workspaceClient: WorkspaceClient,\n signal?: AbortSignal,\n ) {\n if (response.manifest?.format === \"ARROW_STREAM\") {\n const result = response.result as\n | (sql.ResultData & { attachment?: string })\n | undefined;\n\n // Inline Arrow: pass the base64 IPC attachment through unmodified so\n // the analytics route can stream it to the client, where the existing\n // ArrowClient infrastructure decodes it into a Table. Validate size\n // here to fail fast on runaway payloads.\n if (result?.attachment) {\n return this._validateArrowAttachment(response, result.attachment);\n }\n\n // External links: data fetched separately via statement_id. An empty\n // array is a zero-row result (some warehouses emit `external_links: []`\n // rather than omitting it) — it must NOT go down the streaming path\n // (`streamChunks([])` rejects), so fall through to synthesize an empty\n // Arrow table below.\n if (result?.external_links && result.external_links.length > 0) {\n return this.updateWithArrowStatus(response, workspaceClient, signal);\n }\n\n // Empty result with a known schema: synthesize a zero-row Arrow IPC\n // attachment so the client always receives an Arrow Table for\n // ARROW_STREAM, regardless of whether the warehouse returned data.\n // Note: an empty array (`data_array: []`) is truthy, so length-check\n // explicitly — otherwise zero-row responses fall through to the JSON\n // row transform below and return `[]` JSON rows instead of an Arrow\n // table.\n const hasNoRows =\n !result?.data_array ||\n (Array.isArray(result.data_array) && result.data_array.length === 0);\n if (hasNoRows && response.manifest?.schema?.columns) {\n const synthesized = buildEmptyArrowIPCBase64(\n response.manifest.schema.columns,\n );\n return {\n ...response,\n result: { ...(result ?? {}), attachment: synthesized },\n };\n }\n\n // Inline data_array under ARROW_STREAM (rare): fall through to the\n // row transform below. The hook will receive `type: \"result\"` rows;\n // callers asking for ARROW_STREAM should not hit this path with\n // current Databricks warehouses.\n }\n\n if (!response.result?.data_array || !response.manifest?.schema?.columns) {\n return response;\n }\n\n const columns = response.manifest.schema.columns;\n\n const transformedData = response.result.data_array.map((row) => {\n const obj: Record<string, unknown> = {};\n row.forEach((value, index) => {\n const column = columns[index];\n const columnName = column?.name || `column_${index}`;\n\n // attempt to parse JSON strings for string columns\n if (\n column?.type_name === \"STRING\" &&\n typeof value === \"string\" &&\n value &&\n (value[0] === \"{\" || value[0] === \"[\")\n ) {\n try {\n obj[columnName] = JSON.parse(value);\n } catch {\n // if parsing fails, keep as string\n obj[columnName] = value;\n }\n } else {\n obj[columnName] = value;\n }\n });\n return obj;\n });\n\n // remove data_array\n const { data_array: _data_array, ...restResult } = response.result;\n return {\n ...response,\n result: {\n ...restResult,\n data: transformedData,\n },\n };\n }\n\n /**\n * Validate a base64 Arrow IPC attachment (INLINE ARROW_STREAM) and attach\n * the real column names from the result manifest.\n *\n * Databricks warehouses encode the Arrow schema positionally (`col_0`, …);\n * the real, aliased names live only in `manifest.schema.columns`. Rather\n * than decode/re-encode the payload server-side, we carry the names on the\n * result (`columnNames`) so the route can hand them to the client in a\n * response header and the client relabels the decoded Table — the one\n * mechanism used for both INLINE and EXTERNAL_LINKS.\n */\n private _validateArrowAttachment(\n response: sql.StatementResponse,\n attachment: string,\n ) {\n // Cap the size to protect against unbounded inline payloads from\n // misbehaving warehouses. `MAX_INLINE_ATTACHMENT_BYTES` tracks the API's\n // ~25 MiB inline hard cap and bounds memory if a server returns a runaway\n // response.\n //\n // Strip whitespace (rare but legal in base64) and account for trailing\n // `=` padding so the byte count is exact rather than an upper bound.\n const stripped = attachment.replace(/\\s+/g, \"\");\n const padding = stripped.endsWith(\"==\")\n ? 2\n : stripped.endsWith(\"=\")\n ? 1\n : 0;\n const decodedSize = Math.floor((stripped.length * 3) / 4) - padding;\n if (decodedSize > MAX_INLINE_ATTACHMENT_BYTES) {\n throw ExecutionError.statementFailed(\n `Inline Arrow attachment exceeds maximum size (${decodedSize} > ${MAX_INLINE_ATTACHMENT_BYTES} bytes)`,\n );\n }\n\n const columnNames = arrowColumnNames(response);\n if (columnNames) {\n return {\n ...response,\n result: {\n ...(response.result as sql.ResultData & {\n attachment?: string;\n columnNames?: string[];\n }),\n // `statement_id` is a top-level field, not on `ResultData` — carry it\n // onto the result (as the EXTERNAL_LINKS path does) so the route can\n // advertise it in `X-Appkit-Arrow-Columns-Ref` for wide inline schemas.\n statement_id: response.statement_id,\n columnNames,\n },\n };\n }\n\n return response;\n }\n\n private async updateWithArrowStatus(\n response: sql.StatementResponse,\n workspaceClient: WorkspaceClient,\n signal?: AbortSignal,\n ): Promise<{\n result: {\n statement_id: string;\n status: sql.StatementStatus;\n columnNames?: string[];\n external_links?: sql.ExternalLink[];\n refreshChunkLink?: RefreshChunkLink;\n };\n }> {\n const statementId = response.statement_id as string;\n return {\n result: {\n statement_id: statementId,\n status: {\n state: response.status?.state,\n error: response.status?.error,\n } as sql.StatementStatus,\n columnNames: arrowColumnNames(response),\n // Resolve the pre-signed links for EVERY chunk in the caller's own\n // execution context. Streaming these directly (see\n // {@link streamExternalLinks}) avoids a second `getStatement` under\n // the ambient service-principal context — which would fail for\n // `.obo.sql` (user-owned) statements.\n external_links: await this._resolveAllExternalLinks(\n workspaceClient,\n statementId,\n response,\n signal,\n ),\n // Bound to this caller's identity so the streamer can re-mint an\n // expired chunk link mid-download (links live <= 15 min; a large/slow\n // result can outlast the earliest ones).\n refreshChunkLink: this._makeChunkLinkRefresher(\n workspaceClient,\n statementId,\n ),\n },\n };\n }\n\n /**\n * Resolve pre-signed links for EVERY chunk of an EXTERNAL_LINKS result.\n *\n * The execute/getStatement response carries only the first chunk's links\n * (each link, except the last, exposes `next_chunk_index`); the remaining\n * chunks are fetched with `getStatementResultChunkN`. Runs in the caller's\n * identity context (user creds for `.obo.sql`), so there is no cross-identity\n * fetch. Only the tiny link metadata is resolved eagerly — the bytes still\n * stream one chunk at a time downstream. Without this a multi-chunk result\n * would be silently truncated to its first chunk.\n */\n private async _resolveAllExternalLinks(\n workspaceClient: WorkspaceClient,\n statementId: string,\n response: sql.StatementResponse,\n signal?: AbortSignal,\n ): Promise<sql.ExternalLink[] | undefined> {\n const first = response.result?.external_links;\n if (!first || first.length === 0) return first;\n\n const links: sql.ExternalLink[] = [...first];\n // Bound the follow loop so a warehouse returning a cyclic/never-ending\n // `next_chunk_index` can't spin forever. The manifest's chunk count is the\n // natural bound; fall back to a generous safety cap if it's absent (real\n // results still terminate earlier when `next_chunk_index` becomes null) so\n // a missing count doesn't silently truncate a genuine multi-chunk result.\n const maxFetches =\n response.manifest?.total_chunk_count ?? MAX_EXTERNAL_CHUNK_FOLLOWS;\n let next = this._nextChunkIndex(first);\n for (let fetches = 0; next != null && fetches < maxFetches; fetches++) {\n if (signal?.aborted) throw ExecutionError.canceled();\n const chunk =\n await workspaceClient.statementExecution.getStatementResultChunkN(\n { statement_id: statementId, chunk_index: next },\n this._createContext(signal),\n );\n const chunkLinks = chunk.external_links ?? [];\n if (chunkLinks.length === 0) break;\n links.push(...chunkLinks);\n next = this._nextChunkIndex(chunkLinks);\n }\n return links;\n }\n\n /** The `next_chunk_index` advertised by a chunk's links, if any. */\n private _nextChunkIndex(links: sql.ExternalLink[]): number | undefined {\n for (const link of links) {\n if (link.next_chunk_index != null) return link.next_chunk_index;\n }\n return undefined;\n }\n\n /**\n * A closure that re-mints a single chunk's pre-signed link via\n * `getStatementResultChunkN`, bound to the caller's workspace client +\n * statement id. Created here (in the caller's identity context) so the\n * streamer — which runs outside that context — can refresh an expired link\n * for `.obo.sql` statements without a cross-identity `getStatement`.\n */\n private _makeChunkLinkRefresher(\n workspaceClient: WorkspaceClient,\n statementId: string,\n ): RefreshChunkLink {\n return async (chunkIndex, signal) => {\n const chunk =\n await workspaceClient.statementExecution.getStatementResultChunkN(\n { statement_id: statementId, chunk_index: chunkIndex },\n this._createContext(signal),\n );\n return chunk.external_links?.find((l) => l.chunk_index === chunkIndex);\n };\n }\n\n /**\n * Stream already-resolved EXTERNAL_LINKS chunks as raw Arrow IPC bytes, one\n * chunk in memory at a time. Takes the `external_links` the caller already\n * has from `executeStatement` (see {@link updateWithArrowStatus}), so there\n * is no extra `getStatement` round-trip and no execution-context mismatch —\n * the pre-signed URLs need no auth to download.\n */\n streamExternalLinks(\n chunks: sql.ExternalLink[],\n signal?: AbortSignal,\n refresh?: RefreshChunkLink,\n ): AsyncGenerator<Uint8Array, void, unknown> {\n return this.arrowProcessor.streamChunks(chunks, signal, refresh);\n }\n\n /**\n * Fetch just the real column names for a completed statement from its result\n * manifest — no result data. Backs the `/columns/:statementId` fallback the\n * client uses when a very wide schema's names exceed the response-header\n * size limit. Stateless: re-derives from the warehouse, no server cache.\n */\n async getColumnNames(\n workspaceClient: WorkspaceClient,\n jobId: string,\n signal?: AbortSignal,\n ): Promise<string[] | undefined> {\n const response = await workspaceClient.statementExecution.getStatement(\n { statement_id: jobId },\n this._createContext(signal),\n );\n return arrowColumnNames(response);\n }\n\n /**\n * Normalize an error caught during statement execution/polling and rethrow.\n * Abort and already-structured `AppKitError`s pass through untouched;\n * anything else is wrapped as an `ExecutionError`, preserving the SDK's\n * structured `ApiError.errorCode` (e.g. \"INVALID_PARAMETER_VALUE\",\n * \"BAD_REQUEST\") so callers can branch on a stable identifier rather than\n * substring-matching the message.\n */\n private _rethrowStatementError(error: unknown): never {\n if (error instanceof Error && error.name === \"AbortError\") {\n throw error;\n }\n if (error instanceof AppKitError) {\n throw error;\n }\n const sdkErrorCode =\n error && typeof error === \"object\" && \"errorCode\" in error\n ? (error as { errorCode?: unknown }).errorCode\n : undefined;\n throw ExecutionError.statementFailed(\n error instanceof Error ? error.message : String(error),\n typeof sdkErrorCode === \"string\" ? sdkErrorCode : undefined,\n );\n }\n\n // create context for cancellation token\n private _createContext(signal?: AbortSignal) {\n return new Context({\n cancellationToken: {\n isCancellationRequested: signal?.aborted ?? false,\n onCancellationRequested: (cb: () => void) => {\n signal?.addEventListener(\"abort\", cb, { once: true });\n },\n },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,MAAM,SAAS,aAAa,2BAA2B;;;;;;;;AASvD,SAAS,iBACP,UACsB;CACtB,MAAM,OAAO,SAAS,UAAU,QAAQ;AACxC,KAAI,CAA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AM,eACJ,SAAS,OAAO,UAAU,YAAY,eAAe,QAChD,MAAkC,YACnC;AACN,QAAM,eAAe,gBACnB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM,EACtD,OAAO,iBAAiB,WAAW,eAAe,OACnD;;CAIH,AAAQ,eAAe,QAAsB;AAC3C,SAAO,IAAI,QAAQ,EACjB,mBAAmB;GACjB,yBAAyB,QAAQ,WAAW;GAC5C,0BAA0B,OAAmB;AAC3C,YAAQ,iBAAiB,SAAS,IAAI,EAAE,MAAM,MAAM,CAAC;;GAExD,EACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-agents.d.ts","names":[],"sources":["../../../src/core/agent/load-agents.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"load-agents.d.ts","names":[],"sources":["../../../src/core/agent/load-agents.ts"],"mappings":";;;;;UAkBU,eAAA;EACR,OAAA,GAAU,IAAA,GAAO,cAAA,KAAmB,MAAA;AAAA;AAAA,UAGrB,WAAA;EAJQ;EAMvB,YAAA,GAAe,YAAA,GAAe,OAAA,CAAQ,YAAA;EALI;EAO1C,cAAA,GAAiB,MAAA,SAAe,SAAA;EAPf;;;;;AAGnB;EAWE,OAAA,GAAU,GAAA,SAAY,eAAA;;;;;;;;EAQtB,UAAA,GAAa,MAAA,SAAe,eAAA;AAAA;AAAA,UAGb,UAAA;EAHI;EAKnB,IAAA,EAAM,MAAA,SAAe,eAAA;EAtBrB;EAwBA,YAAA;AAAA;;;;;;iBAgEc,uBAAA,CAAwB,QAAA;;;;;;;;;iBA+BlB,iBAAA,CACpB,QAAA,UACA,GAAA,EAAK,WAAA,GACJ,OAAA,CAAQ,eAAA;;;;;;;;;;;;;;;;;;;iBAgCW,iBAAA,CACpB,GAAA,UACA,GAAA,EAAK,WAAA,GACJ,OAAA,CAAQ,UAAA"}
|