@databricks/appkit 0.44.0 → 0.45.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/dist/appkit/package.js +1 -1
- 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/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/plugins/agents/agents.d.ts.map +1 -1
- 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.js +1 -1
- package/dist/shared/src/index.d.ts +1 -0
- 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/defaults.js +1 -1
- 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.map +1 -1
- package/dist/stream/stream-manager.js +15 -9
- package/dist/stream/stream-manager.js.map +1 -1
- package/dist/stream/types.js.map +1 -1
- package/dist/type-generator/query-registry.js +32 -2
- package/dist/type-generator/query-registry.js.map +1 -1
- 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.ServerError.md +55 -15
- package/docs/api/appkit/Class.TunnelError.md +56 -16
- package/docs/api/appkit/Class.ValidationError.md +55 -15
- package/package.json +1 -1
- package/sbom.cdx.json +1 -1
|
@@ -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 onCancell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,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,CAAC,QAAQ,KAAK,WAAW,EAAG,QAAO;AACvC,QAAO,KAAK,KAAK,GAAG,MAClB,EAAE,QAAQ,EAAE,KAAK,SAAS,IAAI,EAAE,OAAO,UAAU,IAClD;;;;;;;;;;;AAYH,MAAM,8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ACnD;;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"}
|
package/dist/errors/base.d.ts
CHANGED
|
@@ -31,10 +31,28 @@ declare abstract class AppKitError extends Error {
|
|
|
31
31
|
readonly cause?: Error;
|
|
32
32
|
/** Additional context for the error */
|
|
33
33
|
readonly context?: Record<string, unknown>;
|
|
34
|
+
/**
|
|
35
|
+
* Client-safe error message. When set, callers serializing the error to
|
|
36
|
+
* a client (SSE, HTTP body) MUST prefer `clientMessage` over `message`
|
|
37
|
+
* — `message` may contain raw upstream / SDK text including statement
|
|
38
|
+
* fragments, internal object names, and correlation IDs.
|
|
39
|
+
*
|
|
40
|
+
* Subclasses can set this in their constructor for a fixed sanitized
|
|
41
|
+
* string. When unset, `clientMessage` defaults to a generic per-code
|
|
42
|
+
* string (see the getter), and the raw `message` is kept server-side
|
|
43
|
+
* only.
|
|
44
|
+
*/
|
|
45
|
+
protected readonly _clientMessage?: string;
|
|
34
46
|
constructor(message: string, options?: {
|
|
35
47
|
cause?: Error;
|
|
36
48
|
context?: Record<string, unknown>;
|
|
49
|
+
clientMessage?: string;
|
|
37
50
|
});
|
|
51
|
+
/**
|
|
52
|
+
* Sanitized message safe to forward to clients. Override in subclasses
|
|
53
|
+
* if a more specific default is appropriate.
|
|
54
|
+
*/
|
|
55
|
+
get clientMessage(): string;
|
|
38
56
|
/**
|
|
39
57
|
* Convert error to JSON for logging/serialization.
|
|
40
58
|
* Sensitive values in context are automatically redacted.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.d.ts","names":[],"sources":["../../src/errors/base.ts"],"mappings":";;AAgCA;;;;;;;;;;;;;;;;;;;;uBAAsB,WAAA,SAAoB,KAAA;
|
|
1
|
+
{"version":3,"file":"base.d.ts","names":[],"sources":["../../src/errors/base.ts"],"mappings":";;AAgCA;;;;;;;;;;;;;;;;;;;;uBAAsB,WAAA,SAAoB,KAAA;EA8BtC;EAAA,kBA5BgB,IAAA;EA8BN;EAAA,kBA3BM,UAAA;EA4BJ;EAAA,kBAzBI,WAAA;EAuBhB;EAAA,SApBO,KAAA,GAAQ,KAAA;EAkDjB;EAAA,SA/CS,OAAA,GAAU,MAAA;EA+DnB;;;;;;;;;;;EAAA,mBAlDmB,cAAA;cAGjB,OAAA,UACA,OAAA;IACE,KAAA,GAAQ,KAAA;IACR,OAAA,GAAU,MAAA;IACV,aAAA;EAAA;;;;;MAmBA,aAAA,CAAA;;;;;EAQJ,MAAA,CAAA,GAAU,MAAA;;;;EAgBV,QAAA,CAAA;;;;UAWQ,eAAA;;;;UAwBA,gBAAA;AAAA"}
|
package/dist/errors/base.js
CHANGED
|
@@ -35,14 +35,34 @@ var AppKitError = class extends Error {
|
|
|
35
35
|
cause;
|
|
36
36
|
/** Additional context for the error */
|
|
37
37
|
context;
|
|
38
|
+
/**
|
|
39
|
+
* Client-safe error message. When set, callers serializing the error to
|
|
40
|
+
* a client (SSE, HTTP body) MUST prefer `clientMessage` over `message`
|
|
41
|
+
* — `message` may contain raw upstream / SDK text including statement
|
|
42
|
+
* fragments, internal object names, and correlation IDs.
|
|
43
|
+
*
|
|
44
|
+
* Subclasses can set this in their constructor for a fixed sanitized
|
|
45
|
+
* string. When unset, `clientMessage` defaults to a generic per-code
|
|
46
|
+
* string (see the getter), and the raw `message` is kept server-side
|
|
47
|
+
* only.
|
|
48
|
+
*/
|
|
49
|
+
_clientMessage;
|
|
38
50
|
constructor(message, options) {
|
|
39
51
|
super(message);
|
|
40
52
|
this.name = this.constructor.name;
|
|
41
53
|
this.cause = options?.cause;
|
|
42
54
|
this.context = options?.context;
|
|
55
|
+
this._clientMessage = options?.clientMessage;
|
|
43
56
|
if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
|
|
44
57
|
}
|
|
45
58
|
/**
|
|
59
|
+
* Sanitized message safe to forward to clients. Override in subclasses
|
|
60
|
+
* if a more specific default is appropriate.
|
|
61
|
+
*/
|
|
62
|
+
get clientMessage() {
|
|
63
|
+
return this._clientMessage ?? "An internal error occurred";
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
46
66
|
* Convert error to JSON for logging/serialization.
|
|
47
67
|
* Sensitive values in context are automatically redacted.
|
|
48
68
|
*/
|
package/dist/errors/base.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base.js","names":[],"sources":["../../src/errors/base.ts"],"sourcesContent":["/** Fields that should be redacted in logs/serialization for security */\nconst SENSITIVE_FIELD_PATTERNS = [\n /token/i,\n /password/i,\n /secret/i,\n /credential/i,\n /auth/i,\n /key$/i,\n /apikey/i,\n];\n\n/**\n * Base error class for all AppKit errors.\n * Provides a consistent structure for error handling across the framework.\n *\n * @example\n * ```typescript\n * // Catching errors by type\n * try {\n * await lakebase.query(\"...\");\n * } catch (e) {\n * if (e instanceof AuthenticationError) {\n * // Re-authenticate\n * } else if (e instanceof ConnectionError && e.isRetryable) {\n * // Retry with backoff\n * }\n * }\n *\n * // Logging errors\n * console.error(error.toJSON()); // Safe for logging, sensitive values redacted\n * ```\n */\nexport abstract class AppKitError extends Error {\n /** Error code for programmatic error handling */\n abstract readonly code: string;\n\n /** HTTP status code suggestion (can be overridden) */\n abstract readonly statusCode: number;\n\n /** Whether this error type is generally safe to retry */\n abstract readonly isRetryable: boolean;\n\n /** Optional cause of the error */\n readonly cause?: Error;\n\n /** Additional context for the error */\n readonly context?: Record<string, unknown>;\n\n constructor(\n message: string,\n options?: {
|
|
1
|
+
{"version":3,"file":"base.js","names":[],"sources":["../../src/errors/base.ts"],"sourcesContent":["/** Fields that should be redacted in logs/serialization for security */\nconst SENSITIVE_FIELD_PATTERNS = [\n /token/i,\n /password/i,\n /secret/i,\n /credential/i,\n /auth/i,\n /key$/i,\n /apikey/i,\n];\n\n/**\n * Base error class for all AppKit errors.\n * Provides a consistent structure for error handling across the framework.\n *\n * @example\n * ```typescript\n * // Catching errors by type\n * try {\n * await lakebase.query(\"...\");\n * } catch (e) {\n * if (e instanceof AuthenticationError) {\n * // Re-authenticate\n * } else if (e instanceof ConnectionError && e.isRetryable) {\n * // Retry with backoff\n * }\n * }\n *\n * // Logging errors\n * console.error(error.toJSON()); // Safe for logging, sensitive values redacted\n * ```\n */\nexport abstract class AppKitError extends Error {\n /** Error code for programmatic error handling */\n abstract readonly code: string;\n\n /** HTTP status code suggestion (can be overridden) */\n abstract readonly statusCode: number;\n\n /** Whether this error type is generally safe to retry */\n abstract readonly isRetryable: boolean;\n\n /** Optional cause of the error */\n readonly cause?: Error;\n\n /** Additional context for the error */\n readonly context?: Record<string, unknown>;\n\n /**\n * Client-safe error message. When set, callers serializing the error to\n * a client (SSE, HTTP body) MUST prefer `clientMessage` over `message`\n * — `message` may contain raw upstream / SDK text including statement\n * fragments, internal object names, and correlation IDs.\n *\n * Subclasses can set this in their constructor for a fixed sanitized\n * string. When unset, `clientMessage` defaults to a generic per-code\n * string (see the getter), and the raw `message` is kept server-side\n * only.\n */\n protected readonly _clientMessage?: string;\n\n constructor(\n message: string,\n options?: {\n cause?: Error;\n context?: Record<string, unknown>;\n clientMessage?: string;\n },\n ) {\n super(message);\n this.name = this.constructor.name;\n this.cause = options?.cause;\n this.context = options?.context;\n this._clientMessage = options?.clientMessage;\n\n // Maintains proper stack trace for where the error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n }\n\n /**\n * Sanitized message safe to forward to clients. Override in subclasses\n * if a more specific default is appropriate.\n */\n get clientMessage(): string {\n return this._clientMessage ?? \"An internal error occurred\";\n }\n\n /**\n * Convert error to JSON for logging/serialization.\n * Sensitive values in context are automatically redacted.\n */\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n statusCode: this.statusCode,\n isRetryable: this.isRetryable,\n context: this.sanitizeContext(this.context),\n cause: this.cause?.message,\n stack: this.stack,\n };\n }\n\n /**\n * Create a human-readable string representation\n */\n toString(): string {\n let str = `${this.name} [${this.code}]: ${this.message}`;\n if (this.cause) {\n str += ` (caused by: ${this.cause.message})`;\n }\n return str;\n }\n\n /**\n * Sanitize context by redacting sensitive field values\n */\n private sanitizeContext(\n context?: Record<string, unknown>,\n ): Record<string, unknown> | undefined {\n if (!context) return undefined;\n\n const sanitized: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(context)) {\n if (this.isSensitiveField(key)) {\n sanitized[key] = \"[REDACTED]\";\n } else if (typeof value === \"object\" && value !== null) {\n // Don't deep-sanitize nested objects, just indicate their type\n sanitized[key] = Array.isArray(value)\n ? `[Array(${value.length})]`\n : \"[Object]\";\n } else {\n sanitized[key] = value;\n }\n }\n return sanitized;\n }\n\n /**\n * Check if a field name matches sensitive patterns\n */\n private isSensitiveField(fieldName: string): boolean {\n return SENSITIVE_FIELD_PATTERNS.some((pattern) => pattern.test(fieldName));\n }\n}\n"],"mappings":";;AACA,MAAM,2BAA2B;CAC/B;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;;;;;;;;;;;;;AAuBD,IAAsB,cAAtB,cAA0C,MAAM;;CAW9C,AAAS;;CAGT,AAAS;;;;;;;;;;;;CAaT,AAAmB;CAEnB,YACE,SACA,SAKA;AACA,QAAM,QAAQ;AACd,OAAK,OAAO,KAAK,YAAY;AAC7B,OAAK,QAAQ,SAAS;AACtB,OAAK,UAAU,SAAS;AACxB,OAAK,iBAAiB,SAAS;AAG/B,MAAI,MAAM,kBACR,OAAM,kBAAkB,MAAM,KAAK,YAAY;;;;;;CAQnD,IAAI,gBAAwB;AAC1B,SAAO,KAAK,kBAAkB;;;;;;CAOhC,SAAkC;AAChC,SAAO;GACL,MAAM,KAAK;GACX,MAAM,KAAK;GACX,SAAS,KAAK;GACd,YAAY,KAAK;GACjB,aAAa,KAAK;GAClB,SAAS,KAAK,gBAAgB,KAAK,QAAQ;GAC3C,OAAO,KAAK,OAAO;GACnB,OAAO,KAAK;GACb;;;;;CAMH,WAAmB;EACjB,IAAI,MAAM,GAAG,KAAK,KAAK,IAAI,KAAK,KAAK,KAAK,KAAK;AAC/C,MAAI,KAAK,MACP,QAAO,gBAAgB,KAAK,MAAM,QAAQ;AAE5C,SAAO;;;;;CAMT,AAAQ,gBACN,SACqC;AACrC,MAAI,CAAC,QAAS,QAAO;EAErB,MAAM,YAAqC,EAAE;AAC7C,OAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,QAAQ,CAChD,KAAI,KAAK,iBAAiB,IAAI,CAC5B,WAAU,OAAO;WACR,OAAO,UAAU,YAAY,UAAU,KAEhD,WAAU,OAAO,MAAM,QAAQ,MAAM,GACjC,UAAU,MAAM,OAAO,MACvB;MAEJ,WAAU,OAAO;AAGrB,SAAO;;;;;CAMT,AAAQ,iBAAiB,WAA4B;AACnD,SAAO,yBAAyB,MAAM,YAAY,QAAQ,KAAK,UAAU,CAAC"}
|
|
@@ -16,9 +16,41 @@ declare class ExecutionError extends AppKitError {
|
|
|
16
16
|
readonly statusCode = 500;
|
|
17
17
|
readonly isRetryable = false;
|
|
18
18
|
/**
|
|
19
|
-
*
|
|
19
|
+
* Structured error code from the upstream source (typically the warehouse's
|
|
20
|
+
* `error_code` for statement-level failures, or the SDK's `ApiError.errorCode`
|
|
21
|
+
* for HTTP failures). Preserved through wrapping so callers can branch on a
|
|
22
|
+
* stable identifier without substring-matching the message.
|
|
20
23
|
*/
|
|
21
|
-
|
|
24
|
+
readonly errorCode?: string;
|
|
25
|
+
constructor(message: string, options?: {
|
|
26
|
+
cause?: Error;
|
|
27
|
+
context?: Record<string, unknown>;
|
|
28
|
+
errorCode?: string;
|
|
29
|
+
clientMessage?: string;
|
|
30
|
+
});
|
|
31
|
+
/**
|
|
32
|
+
* Execution errors default to a generic message — the raw warehouse /
|
|
33
|
+
* SDK text in `.message` often includes statement fragments, internal
|
|
34
|
+
* paths, and correlation IDs. UI code should branch on `errorCode`
|
|
35
|
+
* (`RESULT_TOO_LARGE_FOR_JSON_FALLBACK`, `NOT_IMPLEMENTED`, etc.) and not on
|
|
36
|
+
* the human string.
|
|
37
|
+
*/
|
|
38
|
+
get clientMessage(): string;
|
|
39
|
+
/**
|
|
40
|
+
* Create an execution error for statement failure.
|
|
41
|
+
* @param errorMessage Human-readable error from the warehouse / SDK.
|
|
42
|
+
* Goes into `.message` for server logs only — *never* echoed to the
|
|
43
|
+
* client. Pass `clientMessage` explicitly if a sanitized text should
|
|
44
|
+
* reach the UI.
|
|
45
|
+
* @param errorCode Structured code (e.g. "INVALID_PARAMETER_VALUE") to
|
|
46
|
+
* preserve through wrapping. Optional. Forwarded on SSE error
|
|
47
|
+
* payloads so UI can branch on it instead of substring-matching
|
|
48
|
+
* `error`.
|
|
49
|
+
* @param clientMessage Optional client-safe replacement for `.message`.
|
|
50
|
+
* Defaults to "Query execution failed" via the `clientMessage`
|
|
51
|
+
* getter. Set this only when the upstream text is known-safe.
|
|
52
|
+
*/
|
|
53
|
+
static statementFailed(errorMessage?: string, errorCode?: string, clientMessage?: string): ExecutionError;
|
|
22
54
|
/**
|
|
23
55
|
* Create an execution error for canceled operation
|
|
24
56
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.d.ts","names":[],"sources":["../../src/errors/execution.ts"],"mappings":";;;;;AAYA;;;;;;;;cAAa,cAAA,SAAuB,WAAA;EAAA,SACzB,IAAA;EAAA,SACA,UAAA;EAAA,SACA,WAAA;
|
|
1
|
+
{"version":3,"file":"execution.d.ts","names":[],"sources":["../../src/errors/execution.ts"],"mappings":";;;;;AAYA;;;;;;;;cAAa,cAAA,SAAuB,WAAA;EAAA,SACzB,IAAA;EAAA,SACA,UAAA;EAAA,SACA,WAAA;EAHoC;;;;;;EAAA,SAWpC,SAAA;cAGP,OAAA,UACA,OAAA;IACE,KAAA,GAAQ,KAAA;IACR,OAAA,GAAU,MAAA;IACV,SAAA;IACA,aAAA;EAAA;EAAA;;;;;;;EAAA,IAcS,aAAA,CAAA;EAgCN;;;;;;;;;;;;;;EAAA,OAdA,eAAA,CACL,YAAA,WACA,SAAA,WACA,aAAA,YACC,cAAA;;;;SAUI,QAAA,CAAA,GAAY,cAAA;;;;SASZ,aAAA,CAAA,GAAiB,cAAA;;;;SAUjB,YAAA,CAAa,KAAA,WAAgB,cAAA;;;;SAS7B,WAAA,CAAY,QAAA,WAAmB,cAAA;AAAA"}
|
package/dist/errors/execution.js
CHANGED
|
@@ -16,22 +16,57 @@ var ExecutionError = class ExecutionError extends AppKitError {
|
|
|
16
16
|
statusCode = 500;
|
|
17
17
|
isRetryable = false;
|
|
18
18
|
/**
|
|
19
|
-
*
|
|
19
|
+
* Structured error code from the upstream source (typically the warehouse's
|
|
20
|
+
* `error_code` for statement-level failures, or the SDK's `ApiError.errorCode`
|
|
21
|
+
* for HTTP failures). Preserved through wrapping so callers can branch on a
|
|
22
|
+
* stable identifier without substring-matching the message.
|
|
20
23
|
*/
|
|
21
|
-
|
|
22
|
-
|
|
24
|
+
errorCode;
|
|
25
|
+
constructor(message, options) {
|
|
26
|
+
super(message, options);
|
|
27
|
+
this.errorCode = options?.errorCode;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Execution errors default to a generic message — the raw warehouse /
|
|
31
|
+
* SDK text in `.message` often includes statement fragments, internal
|
|
32
|
+
* paths, and correlation IDs. UI code should branch on `errorCode`
|
|
33
|
+
* (`RESULT_TOO_LARGE_FOR_JSON_FALLBACK`, `NOT_IMPLEMENTED`, etc.) and not on
|
|
34
|
+
* the human string.
|
|
35
|
+
*/
|
|
36
|
+
get clientMessage() {
|
|
37
|
+
return this._clientMessage ?? "Query execution failed";
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Create an execution error for statement failure.
|
|
41
|
+
* @param errorMessage Human-readable error from the warehouse / SDK.
|
|
42
|
+
* Goes into `.message` for server logs only — *never* echoed to the
|
|
43
|
+
* client. Pass `clientMessage` explicitly if a sanitized text should
|
|
44
|
+
* reach the UI.
|
|
45
|
+
* @param errorCode Structured code (e.g. "INVALID_PARAMETER_VALUE") to
|
|
46
|
+
* preserve through wrapping. Optional. Forwarded on SSE error
|
|
47
|
+
* payloads so UI can branch on it instead of substring-matching
|
|
48
|
+
* `error`.
|
|
49
|
+
* @param clientMessage Optional client-safe replacement for `.message`.
|
|
50
|
+
* Defaults to "Query execution failed" via the `clientMessage`
|
|
51
|
+
* getter. Set this only when the upstream text is known-safe.
|
|
52
|
+
*/
|
|
53
|
+
static statementFailed(errorMessage, errorCode, clientMessage) {
|
|
54
|
+
return new ExecutionError(errorMessage ? `Statement failed: ${errorMessage}` : "Statement failed: Unknown error", {
|
|
55
|
+
errorCode,
|
|
56
|
+
clientMessage
|
|
57
|
+
});
|
|
23
58
|
}
|
|
24
59
|
/**
|
|
25
60
|
* Create an execution error for canceled operation
|
|
26
61
|
*/
|
|
27
62
|
static canceled() {
|
|
28
|
-
return new ExecutionError("Statement was canceled");
|
|
63
|
+
return new ExecutionError("Statement was canceled", { clientMessage: "Query was canceled" });
|
|
29
64
|
}
|
|
30
65
|
/**
|
|
31
66
|
* Create an execution error for closed/expired results
|
|
32
67
|
*/
|
|
33
68
|
static resultsClosed() {
|
|
34
|
-
return new ExecutionError("Statement execution completed but results are no longer available (CLOSED state)");
|
|
69
|
+
return new ExecutionError("Statement execution completed but results are no longer available (CLOSED state)", { clientMessage: "Query results expired" });
|
|
35
70
|
}
|
|
36
71
|
/**
|
|
37
72
|
* Create an execution error for unknown state
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.js","names":[],"sources":["../../src/errors/execution.ts"],"sourcesContent":["import { AppKitError } from \"./base\";\n\n/**\n * Error thrown when an operation execution fails.\n * Use for statement failures, canceled operations, or unexpected states.\n *\n * @example\n * ```typescript\n * throw new ExecutionError(\"Statement failed: syntax error\");\n * throw new ExecutionError(\"Statement was canceled\");\n * ```\n */\nexport class ExecutionError extends AppKitError {\n readonly code = \"EXECUTION_ERROR\";\n readonly statusCode = 500;\n readonly isRetryable = false;\n\n /**\n * Create an execution error for statement failure\n */\n static statementFailed(errorMessage?: string): ExecutionError {\n const message = errorMessage\n ? `Statement failed: ${errorMessage}`\n : \"Statement failed: Unknown error\";\n return new ExecutionError(message);\n }\n\n /**\n * Create an execution error for canceled operation\n */\n static canceled(): ExecutionError {\n return new ExecutionError(\"Statement was canceled\");\n }\n\n /**\n * Create an execution error for closed/expired results\n */\n static resultsClosed(): ExecutionError {\n return new ExecutionError(\n \"Statement execution completed but results are no longer available (CLOSED state)\",\n );\n }\n\n /**\n * Create an execution error for unknown state\n */\n static unknownState(state: string): ExecutionError {\n return new ExecutionError(`Unknown statement state: ${state}`, {\n context: { state },\n });\n }\n\n /**\n * Create an execution error for missing data\n */\n static missingData(dataType: string): ExecutionError {\n return new ExecutionError(`No ${dataType} found in response`, {\n context: { dataType },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,IAAa,iBAAb,MAAa,uBAAuB,YAAY;CAC9C,AAAS,OAAO;CAChB,AAAS,aAAa;CACtB,AAAS,cAAc
|
|
1
|
+
{"version":3,"file":"execution.js","names":[],"sources":["../../src/errors/execution.ts"],"sourcesContent":["import { AppKitError } from \"./base\";\n\n/**\n * Error thrown when an operation execution fails.\n * Use for statement failures, canceled operations, or unexpected states.\n *\n * @example\n * ```typescript\n * throw new ExecutionError(\"Statement failed: syntax error\");\n * throw new ExecutionError(\"Statement was canceled\");\n * ```\n */\nexport class ExecutionError extends AppKitError {\n readonly code = \"EXECUTION_ERROR\";\n readonly statusCode = 500;\n readonly isRetryable = false;\n\n /**\n * Structured error code from the upstream source (typically the warehouse's\n * `error_code` for statement-level failures, or the SDK's `ApiError.errorCode`\n * for HTTP failures). Preserved through wrapping so callers can branch on a\n * stable identifier without substring-matching the message.\n */\n readonly errorCode?: string;\n\n constructor(\n message: string,\n options?: {\n cause?: Error;\n context?: Record<string, unknown>;\n errorCode?: string;\n clientMessage?: string;\n },\n ) {\n super(message, options);\n this.errorCode = options?.errorCode;\n }\n\n /**\n * Execution errors default to a generic message — the raw warehouse /\n * SDK text in `.message` often includes statement fragments, internal\n * paths, and correlation IDs. UI code should branch on `errorCode`\n * (`RESULT_TOO_LARGE_FOR_JSON_FALLBACK`, `NOT_IMPLEMENTED`, etc.) and not on\n * the human string.\n */\n override get clientMessage(): string {\n return this._clientMessage ?? \"Query execution failed\";\n }\n\n /**\n * Create an execution error for statement failure.\n * @param errorMessage Human-readable error from the warehouse / SDK.\n * Goes into `.message` for server logs only — *never* echoed to the\n * client. Pass `clientMessage` explicitly if a sanitized text should\n * reach the UI.\n * @param errorCode Structured code (e.g. \"INVALID_PARAMETER_VALUE\") to\n * preserve through wrapping. Optional. Forwarded on SSE error\n * payloads so UI can branch on it instead of substring-matching\n * `error`.\n * @param clientMessage Optional client-safe replacement for `.message`.\n * Defaults to \"Query execution failed\" via the `clientMessage`\n * getter. Set this only when the upstream text is known-safe.\n */\n static statementFailed(\n errorMessage?: string,\n errorCode?: string,\n clientMessage?: string,\n ): ExecutionError {\n const message = errorMessage\n ? `Statement failed: ${errorMessage}`\n : \"Statement failed: Unknown error\";\n return new ExecutionError(message, { errorCode, clientMessage });\n }\n\n /**\n * Create an execution error for canceled operation\n */\n static canceled(): ExecutionError {\n return new ExecutionError(\"Statement was canceled\", {\n clientMessage: \"Query was canceled\",\n });\n }\n\n /**\n * Create an execution error for closed/expired results\n */\n static resultsClosed(): ExecutionError {\n return new ExecutionError(\n \"Statement execution completed but results are no longer available (CLOSED state)\",\n { clientMessage: \"Query results expired\" },\n );\n }\n\n /**\n * Create an execution error for unknown state\n */\n static unknownState(state: string): ExecutionError {\n return new ExecutionError(`Unknown statement state: ${state}`, {\n context: { state },\n });\n }\n\n /**\n * Create an execution error for missing data\n */\n static missingData(dataType: string): ExecutionError {\n return new ExecutionError(`No ${dataType} found in response`, {\n context: { dataType },\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,IAAa,iBAAb,MAAa,uBAAuB,YAAY;CAC9C,AAAS,OAAO;CAChB,AAAS,aAAa;CACtB,AAAS,cAAc;;;;;;;CAQvB,AAAS;CAET,YACE,SACA,SAMA;AACA,QAAM,SAAS,QAAQ;AACvB,OAAK,YAAY,SAAS;;;;;;;;;CAU5B,IAAa,gBAAwB;AACnC,SAAO,KAAK,kBAAkB;;;;;;;;;;;;;;;;CAiBhC,OAAO,gBACL,cACA,WACA,eACgB;AAIhB,SAAO,IAAI,eAHK,eACZ,qBAAqB,iBACrB,mCAC+B;GAAE;GAAW;GAAe,CAAC;;;;;CAMlE,OAAO,WAA2B;AAChC,SAAO,IAAI,eAAe,0BAA0B,EAClD,eAAe,sBAChB,CAAC;;;;;CAMJ,OAAO,gBAAgC;AACrC,SAAO,IAAI,eACT,oFACA,EAAE,eAAe,yBAAyB,CAC3C;;;;;CAMH,OAAO,aAAa,OAA+B;AACjD,SAAO,IAAI,eAAe,4BAA4B,SAAS,EAC7D,SAAS,EAAE,OAAO,EACnB,CAAC;;;;;CAMJ,OAAO,YAAY,UAAkC;AACnD,SAAO,IAAI,eAAe,MAAM,SAAS,qBAAqB,EAC5D,SAAS,EAAE,UAAU,EACtB,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agents.d.ts","names":[],"sources":["../../../src/plugins/agents/agents.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"agents.d.ts","names":[],"sources":["../../../src/plugins/agents/agents.ts"],"mappings":";;;;;;;;;;cAiIa,YAAA,SAAqB,MAAA,YAAkB,YAAA;EAAA,OAC3C,QAAA,EAAuB,cAAA;EAAA,OACvB,KAAA,EAAO,WAAA;EAAA,UAEI,MAAA,EAAQ,kBAAA;EAAA,QAElB,MAAA;EAAA,QACA,gBAAA;EAAA,QACA,aAAA;EARgB;;;;;;EAAA,QAkBhB,gBAAA;EAAA,QACA,SAAA;EAAA,QACA,WAAA;EAAA,Q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