@databricks/sql 1.14.0 → 1.16.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +12 -0
  2. package/dist/DBSQLClient.d.ts +102 -0
  3. package/dist/DBSQLClient.js +541 -55
  4. package/dist/DBSQLClient.js.map +1 -1
  5. package/dist/DBSQLLogger.d.ts +3 -0
  6. package/dist/DBSQLLogger.js +25 -0
  7. package/dist/DBSQLLogger.js.map +1 -1
  8. package/dist/DBSQLOperation.d.ts +67 -17
  9. package/dist/DBSQLOperation.js +245 -217
  10. package/dist/DBSQLOperation.js.map +1 -1
  11. package/dist/DBSQLParameter.d.ts +2 -0
  12. package/dist/DBSQLParameter.js +63 -7
  13. package/dist/DBSQLParameter.js.map +1 -1
  14. package/dist/DBSQLSession.d.ts +24 -16
  15. package/dist/DBSQLSession.js +77 -268
  16. package/dist/DBSQLSession.js.map +1 -1
  17. package/dist/connection/auth/DatabricksOAuth/OAuthManager.js +10 -6
  18. package/dist/connection/auth/DatabricksOAuth/OAuthManager.js.map +1 -1
  19. package/dist/connection/connections/HttpRetryPolicy.d.ts +3 -0
  20. package/dist/connection/connections/HttpRetryPolicy.js +116 -21
  21. package/dist/connection/connections/HttpRetryPolicy.js.map +1 -1
  22. package/dist/connection/connections/ThriftHttpConnection.js +18 -3
  23. package/dist/connection/connections/ThriftHttpConnection.js.map +1 -1
  24. package/dist/contracts/IBackend.d.ts +31 -0
  25. package/dist/contracts/IBackend.js +3 -0
  26. package/dist/contracts/IBackend.js.map +1 -0
  27. package/dist/contracts/IClientContext.d.ts +30 -0
  28. package/dist/contracts/IDBSQLClient.d.ts +115 -0
  29. package/dist/contracts/IDBSQLLogger.d.ts +17 -0
  30. package/dist/contracts/IDBSQLLogger.js.map +1 -1
  31. package/dist/contracts/IDBSQLSession.d.ts +24 -1
  32. package/dist/contracts/IOperation.d.ts +10 -1
  33. package/dist/contracts/IOperationBackend.d.ts +98 -0
  34. package/dist/contracts/IOperationBackend.js +3 -0
  35. package/dist/contracts/IOperationBackend.js.map +1 -0
  36. package/dist/contracts/ISessionBackend.d.ts +36 -0
  37. package/dist/contracts/ISessionBackend.js +3 -0
  38. package/dist/contracts/ISessionBackend.js.map +1 -0
  39. package/dist/contracts/InternalConnectionOptions.d.ts +72 -0
  40. package/dist/contracts/InternalConnectionOptions.js +3 -0
  41. package/dist/contracts/InternalConnectionOptions.js.map +1 -0
  42. package/dist/contracts/OperationStatus.d.ts +76 -0
  43. package/dist/contracts/OperationStatus.js +28 -0
  44. package/dist/contracts/OperationStatus.js.map +1 -0
  45. package/dist/contracts/ResultMetadata.d.ts +34 -0
  46. package/dist/contracts/ResultMetadata.js +16 -0
  47. package/dist/contracts/ResultMetadata.js.map +1 -0
  48. package/dist/errors/AuthenticationError.d.ts +1 -0
  49. package/dist/errors/AuthenticationError.js +4 -0
  50. package/dist/errors/AuthenticationError.js.map +1 -1
  51. package/dist/index.d.ts +2 -0
  52. package/dist/index.js +7 -3
  53. package/dist/index.js.map +1 -1
  54. package/dist/kernel/KernelArrowIpc.d.ts +54 -0
  55. package/dist/kernel/KernelArrowIpc.js +292 -0
  56. package/dist/kernel/KernelArrowIpc.js.map +1 -0
  57. package/dist/kernel/KernelArrowIpcDurationFix.d.ts +29 -0
  58. package/dist/kernel/KernelArrowIpcDurationFix.js +605 -0
  59. package/dist/kernel/KernelArrowIpcDurationFix.js.map +1 -0
  60. package/dist/kernel/KernelAuth.d.ts +300 -0
  61. package/dist/kernel/KernelAuth.js +463 -0
  62. package/dist/kernel/KernelAuth.js.map +1 -0
  63. package/dist/kernel/KernelBackend.d.ts +53 -0
  64. package/dist/kernel/KernelBackend.js +164 -0
  65. package/dist/kernel/KernelBackend.js.map +1 -0
  66. package/dist/kernel/KernelErrorMapping.d.ts +109 -0
  67. package/dist/kernel/KernelErrorMapping.js +249 -0
  68. package/dist/kernel/KernelErrorMapping.js.map +1 -0
  69. package/dist/kernel/KernelInputValidation.d.ts +16 -0
  70. package/dist/kernel/KernelInputValidation.js +49 -0
  71. package/dist/kernel/KernelInputValidation.js.map +1 -0
  72. package/dist/kernel/KernelLogging.d.ts +63 -0
  73. package/dist/kernel/KernelLogging.js +128 -0
  74. package/dist/kernel/KernelLogging.js.map +1 -0
  75. package/dist/kernel/KernelNativeLoader.d.ts +77 -0
  76. package/dist/kernel/KernelNativeLoader.js +178 -0
  77. package/dist/kernel/KernelNativeLoader.js.map +1 -0
  78. package/dist/kernel/KernelOperationBackend.d.ts +154 -0
  79. package/dist/kernel/KernelOperationBackend.js +640 -0
  80. package/dist/kernel/KernelOperationBackend.js.map +1 -0
  81. package/dist/kernel/KernelOperationLifecycle.d.ts +130 -0
  82. package/dist/kernel/KernelOperationLifecycle.js +245 -0
  83. package/dist/kernel/KernelOperationLifecycle.js.map +1 -0
  84. package/dist/kernel/KernelPositionalParams.d.ts +16 -0
  85. package/dist/kernel/KernelPositionalParams.js +120 -0
  86. package/dist/kernel/KernelPositionalParams.js.map +1 -0
  87. package/dist/kernel/KernelResultsProvider.d.ts +44 -0
  88. package/dist/kernel/KernelResultsProvider.js +102 -0
  89. package/dist/kernel/KernelResultsProvider.js.map +1 -0
  90. package/dist/kernel/KernelServerInfo.d.ts +44 -0
  91. package/dist/kernel/KernelServerInfo.js +73 -0
  92. package/dist/kernel/KernelServerInfo.js.map +1 -0
  93. package/dist/kernel/KernelSessionBackend.d.ts +100 -0
  94. package/dist/kernel/KernelSessionBackend.js +384 -0
  95. package/dist/kernel/KernelSessionBackend.js.map +1 -0
  96. package/dist/result/ArrowResultConverter.d.ts +31 -2
  97. package/dist/result/ArrowResultConverter.js +226 -14
  98. package/dist/result/ArrowResultConverter.js.map +1 -1
  99. package/dist/result/CloudFetchResultHandler.d.ts +8 -1
  100. package/dist/result/CloudFetchResultHandler.js +64 -10
  101. package/dist/result/CloudFetchResultHandler.js.map +1 -1
  102. package/dist/result/RowSetProvider.d.ts +8 -1
  103. package/dist/result/RowSetProvider.js +110 -1
  104. package/dist/result/RowSetProvider.js.map +1 -1
  105. package/dist/telemetry/DatabricksTelemetryExporter.js +101 -34
  106. package/dist/telemetry/DatabricksTelemetryExporter.js.map +1 -1
  107. package/dist/telemetry/FeatureFlagCache.js +10 -4
  108. package/dist/telemetry/FeatureFlagCache.js.map +1 -1
  109. package/dist/telemetry/MetricsAggregator.d.ts +38 -0
  110. package/dist/telemetry/MetricsAggregator.js +249 -14
  111. package/dist/telemetry/MetricsAggregator.js.map +1 -1
  112. package/dist/telemetry/TelemetryClient.d.ts +94 -14
  113. package/dist/telemetry/TelemetryClient.js +252 -20
  114. package/dist/telemetry/TelemetryClient.js.map +1 -1
  115. package/dist/telemetry/TelemetryClientProvider.d.ts +28 -33
  116. package/dist/telemetry/TelemetryClientProvider.js +58 -52
  117. package/dist/telemetry/TelemetryClientProvider.js.map +1 -1
  118. package/dist/telemetry/TelemetryEventEmitter.d.ts +52 -26
  119. package/dist/telemetry/TelemetryEventEmitter.js +88 -109
  120. package/dist/telemetry/TelemetryEventEmitter.js.map +1 -1
  121. package/dist/telemetry/{urlUtils.d.ts → telemetryTypeMappers.d.ts} +8 -5
  122. package/dist/telemetry/telemetryTypeMappers.js +72 -0
  123. package/dist/telemetry/telemetryTypeMappers.js.map +1 -0
  124. package/dist/telemetry/telemetryUtils.d.ts +14 -0
  125. package/dist/telemetry/telemetryUtils.js +52 -1
  126. package/dist/telemetry/telemetryUtils.js.map +1 -1
  127. package/dist/telemetry/types.d.ts +48 -1
  128. package/dist/telemetry/types.js +5 -2
  129. package/dist/telemetry/types.js.map +1 -1
  130. package/dist/thrift-backend/ThriftBackend.d.ts +17 -0
  131. package/dist/thrift-backend/ThriftBackend.js +80 -0
  132. package/dist/thrift-backend/ThriftBackend.js.map +1 -0
  133. package/dist/thrift-backend/ThriftOperationBackend.d.ts +70 -0
  134. package/dist/thrift-backend/ThriftOperationBackend.js +330 -0
  135. package/dist/thrift-backend/ThriftOperationBackend.js.map +1 -0
  136. package/dist/thrift-backend/ThriftSessionBackend.d.ts +36 -0
  137. package/dist/thrift-backend/ThriftSessionBackend.js +266 -0
  138. package/dist/thrift-backend/ThriftSessionBackend.js.map +1 -0
  139. package/dist/thrift-backend/wireSynthesis.d.ts +30 -0
  140. package/dist/thrift-backend/wireSynthesis.js +128 -0
  141. package/dist/thrift-backend/wireSynthesis.js.map +1 -0
  142. package/dist/version.d.ts +1 -1
  143. package/dist/version.js +1 -1
  144. package/dist/version.js.map +1 -1
  145. package/native/kernel/README.md +97 -0
  146. package/native/kernel/index.d.ts +1069 -0
  147. package/native/kernel/index.js +325 -0
  148. package/package.json +14 -3
  149. package/dist/telemetry/urlUtils.js +0 -35
  150. package/dist/telemetry/urlUtils.js.map +0 -1
@@ -27,38 +27,65 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
29
  const thrift_1 = __importDefault(require("thrift"));
30
- const node_int64_1 = __importDefault(require("node-int64"));
30
+ const os_1 = __importDefault(require("os"));
31
31
  const events_1 = require("events");
32
32
  const TCLIService_1 = __importDefault(require("../thrift/TCLIService"));
33
- const TCLIService_types_1 = require("../thrift/TCLIService_types");
34
33
  const HiveDriver_1 = __importDefault(require("./hive/HiveDriver"));
35
34
  const DBSQLSession_1 = __importDefault(require("./DBSQLSession"));
36
35
  const HttpConnection_1 = __importDefault(require("./connection/connections/HttpConnection"));
37
- const Status_1 = __importDefault(require("./dto/Status"));
38
36
  const HiveDriverError_1 = __importDefault(require("./errors/HiveDriverError"));
39
37
  const utils_1 = require("./utils");
38
+ const ThriftBackend_1 = __importDefault(require("./thrift-backend/ThriftBackend"));
39
+ const KernelBackend_1 = __importDefault(require("./kernel/KernelBackend"));
40
40
  const PlainHttpAuthentication_1 = __importDefault(require("./connection/auth/PlainHttpAuthentication"));
41
41
  const DatabricksOAuth_1 = __importStar(require("./connection/auth/DatabricksOAuth"));
42
42
  const tokenProvider_1 = require("./connection/auth/tokenProvider");
43
43
  const IDBSQLLogger_1 = require("./contracts/IDBSQLLogger");
44
44
  const DBSQLLogger_1 = __importDefault(require("./DBSQLLogger"));
45
45
  const CloseableCollection_1 = __importDefault(require("./utils/CloseableCollection"));
46
+ const TelemetryClientProvider_1 = __importDefault(require("./telemetry/TelemetryClientProvider"));
47
+ const TelemetryEventEmitter_1 = __importDefault(require("./telemetry/TelemetryEventEmitter"));
48
+ const types_1 = require("./telemetry/types");
49
+ const telemetryUtils_1 = require("./telemetry/telemetryUtils");
50
+ const version_1 = __importDefault(require("./version"));
46
51
  function prependSlash(str) {
47
52
  if (str.length > 0 && str.charAt(0) !== '/') {
48
53
  return `/${str}`;
49
54
  }
50
55
  return str;
51
56
  }
52
- function getInitialNamespaceOptions(catalogName, schemaName) {
53
- if (!catalogName && !schemaName) {
54
- return {};
55
- }
56
- return {
57
- initialNamespace: {
58
- catalogName,
59
- schemaName,
60
- },
61
- };
57
+ /**
58
+ * Copy any defined telemetry knob from `src` into `dst`. Both objects declare
59
+ * identical types for these keys, so the assignment is structurally typed —
60
+ * a wrong-shape value in `ConnectionOptions` is caught at the call site.
61
+ *
62
+ * Keep this in sync with the `telemetry*` knobs exposed in
63
+ * `ConnectionOptions` (lib/contracts/IDBSQLClient.ts) and `ClientConfig`
64
+ * (lib/contracts/IClientContext.ts). Adding a knob requires extending this
65
+ * list AND the public option surface; otherwise the user-supplied override
66
+ * silently does nothing.
67
+ */
68
+ function copyDefinedTelemetryOptions(src, dst) {
69
+ if (src.telemetryEnabled !== undefined)
70
+ dst.telemetryEnabled = src.telemetryEnabled;
71
+ if (src.telemetryBatchSize !== undefined)
72
+ dst.telemetryBatchSize = src.telemetryBatchSize;
73
+ if (src.telemetryFlushIntervalMs !== undefined)
74
+ dst.telemetryFlushIntervalMs = src.telemetryFlushIntervalMs;
75
+ if (src.telemetryMaxRetries !== undefined)
76
+ dst.telemetryMaxRetries = src.telemetryMaxRetries;
77
+ if (src.telemetryAuthenticatedExport !== undefined)
78
+ dst.telemetryAuthenticatedExport = src.telemetryAuthenticatedExport;
79
+ if (src.telemetryCircuitBreakerThreshold !== undefined)
80
+ dst.telemetryCircuitBreakerThreshold = src.telemetryCircuitBreakerThreshold;
81
+ if (src.telemetryCircuitBreakerTimeout !== undefined)
82
+ dst.telemetryCircuitBreakerTimeout = src.telemetryCircuitBreakerTimeout;
83
+ if (src.telemetryCloseTimeoutMs !== undefined)
84
+ dst.telemetryCloseTimeoutMs = src.telemetryCloseTimeoutMs;
85
+ if (src.telemetryMaxStatementMetrics !== undefined)
86
+ dst.telemetryMaxStatementMetrics = src.telemetryMaxStatementMetrics;
87
+ if (src.telemetryMaxPendingMetrics !== undefined)
88
+ dst.telemetryMaxPendingMetrics = src.telemetryMaxPendingMetrics;
62
89
  }
63
90
  class DBSQLClient extends events_1.EventEmitter {
64
91
  static getDefaultLogger() {
@@ -82,6 +109,31 @@ class DBSQLClient extends events_1.EventEmitter {
82
109
  cloudFetchConcurrentDownloads: 10,
83
110
  cloudFetchSpeedThresholdMBps: 0.1,
84
111
  useLZ4Compression: true,
112
+ preserveBigNumericPrecision: false,
113
+ // Telemetry defaults are sourced from DEFAULT_TELEMETRY_CONFIG so
114
+ // every component reads from the same single frozen const. Mapping the
115
+ // unprefixed TelemetryConfiguration keys to the `telemetry`-prefixed
116
+ // ClientConfig keys is mechanical; doing it once here means that adding
117
+ // a new knob to DEFAULT_TELEMETRY_CONFIG only requires extending the
118
+ // ClientConfig surface and (optionally) adding to telemetryOverrides.
119
+ // Previously this method declared 7 keys while DEFAULT_TELEMETRY_CONFIG
120
+ // declared 15 — silent desync risk every time someone touched one but
121
+ // not the other.
122
+ telemetryEnabled: types_1.DEFAULT_TELEMETRY_CONFIG.enabled,
123
+ telemetryBatchSize: types_1.DEFAULT_TELEMETRY_CONFIG.batchSize,
124
+ telemetryFlushIntervalMs: types_1.DEFAULT_TELEMETRY_CONFIG.flushIntervalMs,
125
+ telemetryMaxRetries: types_1.DEFAULT_TELEMETRY_CONFIG.maxRetries,
126
+ telemetryBackoffBaseMs: types_1.DEFAULT_TELEMETRY_CONFIG.backoffBaseMs,
127
+ telemetryBackoffMaxMs: types_1.DEFAULT_TELEMETRY_CONFIG.backoffMaxMs,
128
+ telemetryBackoffJitterMs: types_1.DEFAULT_TELEMETRY_CONFIG.backoffJitterMs,
129
+ telemetryAuthenticatedExport: types_1.DEFAULT_TELEMETRY_CONFIG.authenticatedExport,
130
+ telemetryCircuitBreakerThreshold: types_1.DEFAULT_TELEMETRY_CONFIG.circuitBreakerThreshold,
131
+ telemetryCircuitBreakerTimeout: types_1.DEFAULT_TELEMETRY_CONFIG.circuitBreakerTimeout,
132
+ telemetryMaxPendingMetrics: types_1.DEFAULT_TELEMETRY_CONFIG.maxPendingMetrics,
133
+ telemetryMaxErrorsPerStatement: types_1.DEFAULT_TELEMETRY_CONFIG.maxErrorsPerStatement,
134
+ telemetryStatementTtlMs: types_1.DEFAULT_TELEMETRY_CONFIG.statementTtlMs,
135
+ telemetryCloseTimeoutMs: types_1.DEFAULT_TELEMETRY_CONFIG.closeTimeoutMs,
136
+ telemetryMaxStatementMetrics: types_1.DEFAULT_TELEMETRY_CONFIG.maxStatementMetrics,
85
137
  };
86
138
  }
87
139
  constructor(options) {
@@ -92,6 +144,12 @@ class DBSQLClient extends events_1.EventEmitter {
92
144
  });
93
145
  this.thrift = thrift_1.default;
94
146
  this.sessions = new CloseableCollection_1.default();
147
+ // True once we've shipped the full DriverConfiguration on a CONNECTION_OPEN
148
+ // event for this client. Subsequent openSession events for the same client
149
+ // strip the (~1KB, static-for-the-process) blob — a long-running client
150
+ // opening N sessions would otherwise pay N×blob bytes for telemetry on data
151
+ // that hasn't changed since the first session.
152
+ this.driverConfigShipped = false;
95
153
  this.config = DBSQLClient.getDefaultConfig();
96
154
  this.logger = (_a = options === null || options === void 0 ? void 0 : options.logger) !== null && _a !== void 0 ? _a : DBSQLClient.getDefaultLogger();
97
155
  this.logger.log(IDBSQLLogger_1.LogLevel.info, 'Created DBSQLClient');
@@ -161,6 +219,259 @@ class DBSQLClient extends events_1.EventEmitter {
161
219
  createConnectionProvider(options) {
162
220
  return new HttpConnection_1.default(this.getConnectionOptions(options), this);
163
221
  }
222
+ /**
223
+ * Extract the numeric workspace ID for telemetry.
224
+ *
225
+ * Two URL shapes carry the workspace ID today:
226
+ * - Warehouse, query form: `/sql/1.0/warehouses/<id>?o=<wsId>`
227
+ * - All-purpose cluster, path form: `sql/protocolv1/o/<wsId>/<cluster-id>`
228
+ *
229
+ * Host-based extraction was tried previously but produced confidently-wrong
230
+ * values:
231
+ * - AWS `dbc-XXXXX-YYYY.cloud.databricks.com` → `dbc-XXXXX-YYYY`
232
+ * is the deployment shard prefix, not the workspace ID.
233
+ * - Azure `adb-NNNNNNNNNNNNN.NN.azuredatabricks.net` → the workspace ID is
234
+ * the numeric portion after the `adb-` prefix (and before the form-factor
235
+ * digit), not `adb-NNN`.
236
+ *
237
+ * Returns `undefined` when no workspace ID can be derived. Server-side
238
+ * attribution is better off seeing a missing field than a wrong value.
239
+ */
240
+ static extractWorkspaceId(httpPath) {
241
+ if (!httpPath) {
242
+ return undefined;
243
+ }
244
+ const queryIdx = httpPath.indexOf('?');
245
+ // Warehouse form: `?o=<digits>` in the query string.
246
+ if (queryIdx >= 0) {
247
+ const query = httpPath.slice(queryIdx + 1);
248
+ // Match `o=<digits>` as the first param, an inner `&o=<digits>`, etc.
249
+ // Workspace IDs are decimal integers; reject anything else so a stray
250
+ // `o=tenant_42` doesn't ship as a workspace ID.
251
+ const queryMatch = query.match(/(?:^|&)o=(\d+)(?:&|$)/);
252
+ if (queryMatch) {
253
+ return queryMatch[1];
254
+ }
255
+ }
256
+ // All-purpose cluster form: `/o/<digits>/<cluster-id>` as a path segment.
257
+ const pathOnly = queryIdx >= 0 ? httpPath.slice(0, queryIdx) : httpPath;
258
+ const pathMatch = pathOnly.match(/(?:^|\/)o\/(\d+)(?:\/|$)/);
259
+ return pathMatch ? pathMatch[1] : undefined;
260
+ }
261
+ // Detects an `o=<value>` or `/o/<value>` where `<value>` is present but
262
+ // non-numeric, so the caller can warn instead of silently dropping a
263
+ // malformed workspace param.
264
+ static hasMalformedOrgParam(httpPath) {
265
+ if (!httpPath) {
266
+ return false;
267
+ }
268
+ const queryIdx = httpPath.indexOf('?');
269
+ if (queryIdx >= 0) {
270
+ const query = httpPath.slice(queryIdx + 1);
271
+ const hasOrg = /(?:^|&)o=/.test(query);
272
+ const hasNumericOrg = /(?:^|&)o=\d+(?:&|$)/.test(query);
273
+ if (hasOrg && !hasNumericOrg) {
274
+ return true;
275
+ }
276
+ }
277
+ const pathOnly = queryIdx >= 0 ? httpPath.slice(0, queryIdx) : httpPath;
278
+ const hasPathOrg = /(?:^|\/)o\/[^/]+/.test(pathOnly);
279
+ const hasNumericPathOrg = /(?:^|\/)o\/\d+(?:\/|$)/.test(pathOnly);
280
+ return hasPathOrg && !hasNumericPathOrg;
281
+ }
282
+ /**
283
+ * Build the customHeaders map applied to telemetry POSTs and feature-flag
284
+ * GETs (SPOG / Single Panel of Glass support). When `httpPath` carries a
285
+ * workspace ID — either as a `?o=<wsId>` query (warehouse) or a
286
+ * `/o/<wsId>/<cluster-id>` path segment (all-purpose cluster) — endpoints
287
+ * that don't include the workspace in their URL path need it conveyed via
288
+ * the `x-databricks-org-id` header instead. A user-supplied value in
289
+ * `userHeaders` (case-insensitively keyed) wins over the parsed value.
290
+ *
291
+ * `httpPath` is passed explicitly (rather than read off `this.httpPath`) so
292
+ * the SPOG-routing dependency is visible in the signature — a future
293
+ * refactor that reorders connect() can't silently break injection.
294
+ */
295
+ buildCustomHeaders(httpPath, userHeaders) {
296
+ const merged = { ...(userHeaders !== null && userHeaders !== void 0 ? userHeaders : {}) };
297
+ const hasOrgIdAlready = Object.keys(merged).some((k) => k.toLowerCase() === 'x-databricks-org-id');
298
+ if (hasOrgIdAlready) {
299
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, 'SPOG: x-databricks-org-id supplied by caller; not extracting from httpPath');
300
+ }
301
+ else {
302
+ const orgId = DBSQLClient.extractWorkspaceId(httpPath);
303
+ if (orgId) {
304
+ merged['x-databricks-org-id'] = orgId;
305
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `SPOG: injecting x-databricks-org-id=${orgId} (extracted from httpPath)`);
306
+ }
307
+ else if (DBSQLClient.hasMalformedOrgParam(httpPath)) {
308
+ this.logger.log(IDBSQLLogger_1.LogLevel.warn, 'SPOG: httpPath contains non-numeric workspace ID; x-databricks-org-id not injected');
309
+ }
310
+ }
311
+ return Object.keys(merged).length > 0 ? merged : undefined;
312
+ }
313
+ /**
314
+ * Build driver configuration for telemetry reporting.
315
+ * @returns DriverConfiguration object with current driver settings
316
+ */
317
+ buildDriverConfiguration() {
318
+ var _a, _b, _c, _d, _e, _f;
319
+ return {
320
+ driverVersion: version_1.default,
321
+ driverName: types_1.DRIVER_NAME,
322
+ nodeVersion: process.version,
323
+ platform: process.platform,
324
+ osVersion: os_1.default.release(),
325
+ osArch: os_1.default.arch(),
326
+ runtimeVendor: 'Node.js Foundation',
327
+ localeName: this.getLocaleName(),
328
+ charSetEncoding: 'UTF-8',
329
+ processName: this.getProcessName(),
330
+ authType: this.authType || 'pat',
331
+ // Feature flags
332
+ cloudFetchEnabled: (_a = this.config.useCloudFetch) !== null && _a !== void 0 ? _a : false,
333
+ lz4Enabled: (_b = this.config.useLZ4Compression) !== null && _b !== void 0 ? _b : false,
334
+ arrowEnabled: (_c = this.config.arrowEnabled) !== null && _c !== void 0 ? _c : false,
335
+ directResultsEnabled: true,
336
+ // Configuration values
337
+ socketTimeout: (_d = this.config.socketTimeout) !== null && _d !== void 0 ? _d : 0,
338
+ retryMaxAttempts: (_e = this.config.retryMaxAttempts) !== null && _e !== void 0 ? _e : 0,
339
+ cloudFetchConcurrentDownloads: (_f = this.config.cloudFetchConcurrentDownloads) !== null && _f !== void 0 ? _f : 0,
340
+ // Connection parameters
341
+ httpPath: this.httpPath,
342
+ enableMetricViewMetadata: this.config.enableMetricViewMetadata,
343
+ useProxy: this.useProxy,
344
+ };
345
+ }
346
+ /**
347
+ * Map Node.js auth type to telemetry auth enum string.
348
+ * Distinguishes between U2M and M2M OAuth flows.
349
+ */
350
+ mapAuthType(options) {
351
+ switch (options.authType) {
352
+ case 'databricks-oauth':
353
+ return options.oauthClientSecret === undefined ? 'external-browser' : 'oauth-m2m';
354
+ case 'custom':
355
+ return 'custom';
356
+ case 'token-provider':
357
+ return 'token-provider';
358
+ case 'external-token':
359
+ return 'external-token';
360
+ case 'static-token':
361
+ return 'static-token';
362
+ case 'access-token':
363
+ case undefined:
364
+ return 'pat';
365
+ default:
366
+ return 'unknown';
367
+ }
368
+ }
369
+ /**
370
+ * Get locale name in format language_country (e.g., en_US).
371
+ * Matches JDBC format: user.language + '_' + user.country
372
+ */
373
+ getLocaleName() {
374
+ try {
375
+ // Try to get from environment variables
376
+ const lang = process.env.LANG || process.env.LC_ALL || process.env.LC_MESSAGES || '';
377
+ if (lang) {
378
+ // LANG format is typically "en_US.UTF-8", extract "en_US"
379
+ const match = lang.match(/^([a-z]{2}_[A-Z]{2})/);
380
+ if (match) {
381
+ return match[1];
382
+ }
383
+ }
384
+ // Fallback to en_US
385
+ return 'en_US';
386
+ }
387
+ catch (_a) {
388
+ return 'en_US';
389
+ }
390
+ }
391
+ /**
392
+ * Get process name, similar to JDBC's ProcessNameUtil.
393
+ * Returns the script name or process title.
394
+ */
395
+ getProcessName() {
396
+ var _a;
397
+ try {
398
+ // Try process.title first (can be set by application)
399
+ if (process.title && process.title !== 'node') {
400
+ return process.title;
401
+ }
402
+ // Try to get the main script name from argv[1]
403
+ if (process.argv && process.argv.length > 1) {
404
+ const scriptPath = process.argv[1];
405
+ // Extract filename without path
406
+ const filename = ((_a = scriptPath.split('/').pop()) === null || _a === void 0 ? void 0 : _a.split('\\').pop()) || '';
407
+ // Remove extension
408
+ const nameWithoutExt = filename.replace(/\.[^.]*$/, '');
409
+ if (nameWithoutExt) {
410
+ return nameWithoutExt;
411
+ }
412
+ }
413
+ return 'node';
414
+ }
415
+ catch (_b) {
416
+ return 'node';
417
+ }
418
+ }
419
+ /**
420
+ * Initialize telemetry components if enabled.
421
+ * CRITICAL: All errors swallowed and logged at LogLevel.debug ONLY.
422
+ * Driver NEVER throws exceptions due to telemetry.
423
+ */
424
+ async initializeTelemetry() {
425
+ var _a, _b;
426
+ if (!this.host) {
427
+ return;
428
+ }
429
+ try {
430
+ // Acquire (or create) the per-host TelemetryClient from the
431
+ // process-wide provider. The shared client owns the circuit-breaker
432
+ // registry, feature-flag cache, exporter, and aggregator. Multiple
433
+ // DBSQLClient instances on the same host share these resources so
434
+ // breaker counters and HTTP batches don't fragment per-instance.
435
+ this.telemetryClient = TelemetryClientProvider_1.default.getInstance().getOrCreateClient(this, this.host);
436
+ // Use the shared feature-flag cache (registered in the previous step).
437
+ const enabled = await this.telemetryClient.getFeatureFlagCache().isTelemetryEnabled(this.host);
438
+ if (!enabled) {
439
+ // Release our refcount immediately; we won't be emitting.
440
+ await TelemetryClientProvider_1.default.getInstance().releaseClient(this, this.host);
441
+ this.telemetryClient = undefined;
442
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, 'Telemetry: disabled');
443
+ return;
444
+ }
445
+ // Each DBSQLClient still owns its own emitter so it respects its own
446
+ // `telemetryEnabled` flag and feature-flag result. All emitters bridge
447
+ // into the SHARED aggregator on the TelemetryClient.
448
+ this.telemetryEmitter = new TelemetryEventEmitter_1.default(this);
449
+ const sharedAggregator = this.telemetryClient.getAggregator();
450
+ for (const eventType of Object.values(types_1.TelemetryEventType)) {
451
+ this.telemetryEmitter.on(eventType, (event) => {
452
+ sharedAggregator.processEvent(event);
453
+ });
454
+ }
455
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, 'Telemetry: enabled');
456
+ }
457
+ catch (error) {
458
+ // Swallow all telemetry initialization errors. If we acquired a refcount
459
+ // before the throw, release it — otherwise the per-host TelemetryClient
460
+ // (and its flush timer / exporter / FFCache) leaks for the lifetime of
461
+ // the process on long-running supervisors that retry-connect.
462
+ if (this.telemetryClient) {
463
+ try {
464
+ await TelemetryClientProvider_1.default.getInstance().releaseClient(this, this.host);
465
+ }
466
+ catch (releaseError) {
467
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `Telemetry release-after-init-failure error: ${(_a = releaseError === null || releaseError === void 0 ? void 0 : releaseError.message) !== null && _a !== void 0 ? _a : releaseError}`);
468
+ }
469
+ this.telemetryClient = undefined;
470
+ this.telemetryEmitter = undefined;
471
+ }
472
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `Telemetry initialization error: ${(_b = error === null || error === void 0 ? void 0 : error.message) !== null && _b !== void 0 ? _b : error}`);
473
+ }
474
+ }
164
475
  /**
165
476
  * Connects DBSQLClient to endpoint
166
477
  * @public
@@ -178,44 +489,159 @@ class DBSQLClient extends events_1.EventEmitter {
178
489
  options.userAgentEntry = deprecatedClientId;
179
490
  }
180
491
  }
492
+ // If connect() is being called a second time (reconnect, host switch),
493
+ // release the prior telemetry refcount and emitter so we don't leak a
494
+ // refcount in the process-wide TelemetryClientProvider for the old host.
495
+ if (this.host && this.telemetryClient) {
496
+ try {
497
+ await TelemetryClientProvider_1.default.getInstance().releaseClient(this, this.host);
498
+ }
499
+ catch (error) {
500
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `Telemetry release-on-reconnect error: ${error.message}`);
501
+ }
502
+ this.telemetryClient = undefined;
503
+ this.telemetryEmitter = undefined;
504
+ }
505
+ // Re-arm: the new connection is a fresh client-config lineage even if
506
+ // the host is the same.
507
+ this.driverConfigShipped = false;
508
+ // Store connection params for telemetry
509
+ this.host = options.host;
510
+ this.httpPath = options.path;
511
+ this.authType = this.mapAuthType(options);
512
+ this.useProxy = Boolean(options.proxy);
181
513
  // Store enableMetricViewMetadata configuration
182
514
  if (options.enableMetricViewMetadata !== undefined) {
183
515
  this.config.enableMetricViewMetadata = options.enableMetricViewMetadata;
184
516
  }
517
+ // Opt-in: preserve DECIMAL (string) / BIGINT (bigint) precision in results.
518
+ if (options.preserveBigNumericPrecision !== undefined) {
519
+ this.config.preserveBigNumericPrecision = options.preserveBigNumericPrecision;
520
+ }
521
+ // Retry-policy knobs. These live in ClientConfig (consumed by the Thrift
522
+ // HttpRetryPolicy and forwarded to the kernel on the SEA path), so copying
523
+ // them here makes them configurable from connect() on BOTH backends. A
524
+ // per-key narrowed copy (not a spread) keeps the structural type system
525
+ // honest, matching the metricView / precision / telemetry knobs above.
526
+ if (options.retryMaxAttempts !== undefined) {
527
+ this.config.retryMaxAttempts = options.retryMaxAttempts;
528
+ }
529
+ if (options.retriesTimeout !== undefined) {
530
+ this.config.retriesTimeout = options.retriesTimeout;
531
+ }
532
+ if (options.retryDelayMin !== undefined) {
533
+ this.config.retryDelayMin = options.retryDelayMin;
534
+ }
535
+ if (options.retryDelayMax !== undefined) {
536
+ this.config.retryDelayMax = options.retryDelayMax;
537
+ }
538
+ // Override telemetry config if provided in options. Per-key narrowed copy
539
+ // preserves the structural type system: `ConnectionOptions` and
540
+ // `ClientConfig` declare identical types for these knobs, so a user
541
+ // passing `telemetryBatchSize: "100"` (string) gets a TS error instead of
542
+ // silently writing a string into a number field that `MetricsAggregator`
543
+ // would later read and break aggregation thresholds at runtime.
544
+ copyDefinedTelemetryOptions(options, this.config);
185
545
  // Persist userAgentEntry so telemetry and feature-flag call sites reuse
186
546
  // the same value as the primary Thrift connection's User-Agent.
187
547
  if (options.userAgentEntry !== undefined) {
188
548
  this.config.userAgentEntry = options.userAgentEntry;
189
549
  }
550
+ // SPOG: parse `?o=<workspaceId>` out of httpPath and stash it as
551
+ // `x-databricks-org-id` for the telemetry + feature-flag clients, which
552
+ // hit endpoints that don't carry the workspace in their URL path.
553
+ this.config.customHeaders = this.buildCustomHeaders(options.path, options.customHeaders);
190
554
  this.authProvider = this.createAuthProvider(options, authProvider);
191
555
  this.connectionProvider = this.createConnectionProvider(options);
192
- const thriftConnection = await this.connectionProvider.getThriftConnection();
193
- thriftConnection.on('error', (error) => {
194
- // Error.stack already contains error type and message, so log stack if available,
195
- // otherwise fall back to just error type + message
196
- this.logger.log(IDBSQLLogger_1.LogLevel.error, error.stack || `${error.name}: ${error.message}`);
556
+ // M0: `useKernel` is consumed via a non-exported internal-options cast so it
557
+ // doesn't ship in the public `.d.ts`. Mirrors Python's `kwargs.get("use_kernel")`
558
+ // pattern (see databricks-sql-python/src/databricks/sql/session.py).
559
+ const internalOptions = options;
560
+ const backend = internalOptions.useKernel
561
+ ? new KernelBackend_1.default({ context: this })
562
+ : new ThriftBackend_1.default({
563
+ context: this,
564
+ onConnectionEvent: (event, payload) => this.forwardConnectionEvent(event, payload),
565
+ });
566
+ // Publish `this.backend` only after a successful `connect()`. Otherwise a
567
+ // failed connect would leave a half-initialized backend in place, and the
568
+ // next `openSession()` would slip past the `!this.backend` guard and
569
+ // surface a misleading "backend not implemented" / partial-state error
570
+ // instead of the accurate "DBSQLClient: not connected".
571
+ try {
572
+ await backend.connect(options);
573
+ }
574
+ catch (err) {
575
+ // `IBackend.close()` is documented as safe on a partially-initialized
576
+ // backend; best-effort cleanup so we don't leak sockets / state.
197
577
  try {
198
- this.emit('error', error);
578
+ await backend.close();
199
579
  }
200
- catch (e) {
201
- // EventEmitter will throw unhandled error when emitting 'error' event.
202
- // Since we already logged it few lines above, just suppress this behaviour
580
+ catch (closeErr) {
581
+ // Swallow; the original error is what the caller needs to see.
203
582
  }
204
- });
205
- thriftConnection.on('reconnecting', (params) => {
206
- this.logger.log(IDBSQLLogger_1.LogLevel.debug, `Reconnecting, params: ${JSON.stringify(params)}`);
207
- this.emit('reconnecting', params);
208
- });
209
- thriftConnection.on('close', () => {
210
- this.logger.log(IDBSQLLogger_1.LogLevel.debug, 'Closing connection.');
211
- this.emit('close');
212
- });
213
- thriftConnection.on('timeout', () => {
214
- this.logger.log(IDBSQLLogger_1.LogLevel.debug, 'Connection timed out.');
215
- this.emit('timeout');
216
- });
583
+ throw err;
584
+ }
585
+ this.backend = backend;
586
+ // Initialize telemetry if enabled. The env var DATABRICKS_TELEMETRY_DISABLED
587
+ // is a hard kill switch for ops/IT teams who can't redeploy app code.
588
+ // Recognized truthy values: 1, true, yes, on (case-insensitive). Anything
589
+ // else (empty, "0", "false", "no", "off") leaves the runtime config in
590
+ // charge — avoiding the footgun where a sysadmin sets the var to "false"
591
+ // expecting to enable telemetry.
592
+ const envKill = process.env.DATABRICKS_TELEMETRY_DISABLED;
593
+ const trimmedEnvKill = typeof envKill === 'string' ? envKill.trim() : '';
594
+ const envDisabled = trimmedEnvKill.length > 0 && /^(1|true|yes|on)$/i.test(trimmedEnvKill);
595
+ // Surface the misconfiguration: an ops engineer who sees the var name and
596
+ // tries to "set it to false to keep telemetry on" otherwise gets the
597
+ // opposite of what they expect (the var is then silently ignored, runtime
598
+ // config stays in charge — default `true`). Warn on any non-empty value
599
+ // that isn't recognized so the disable-failed shape is visible in logs.
600
+ if (trimmedEnvKill.length > 0 && !envDisabled) {
601
+ this.logger.log(IDBSQLLogger_1.LogLevel.warn, `DATABRICKS_TELEMETRY_DISABLED='${trimmedEnvKill}' was ignored. ` +
602
+ `To disable telemetry, set the variable to one of: 1, true, yes, on. ` +
603
+ `Telemetry remains controlled by the runtime config and feature flag.`);
604
+ }
605
+ if (this.config.telemetryEnabled && !envDisabled) {
606
+ await this.initializeTelemetry();
607
+ }
217
608
  return this;
218
609
  }
610
+ forwardConnectionEvent(event, payload) {
611
+ switch (event) {
612
+ case 'error': {
613
+ // `payload` is typed `unknown` because the cross-backend
614
+ // `IBackend.onConnectionEvent` doesn't constrain the error shape.
615
+ // Normalize to `Error` so the stack/name/message access below is safe
616
+ // for any backend that emits a non-Error value (e.g. a bare string).
617
+ const error = payload instanceof Error ? payload : new Error(String(payload));
618
+ this.logger.log(IDBSQLLogger_1.LogLevel.error, error.stack || `${error.name}: ${error.message}`);
619
+ try {
620
+ this.emit('error', error);
621
+ }
622
+ catch (e) {
623
+ // EventEmitter throws when 'error' has no listeners; we've already logged it.
624
+ }
625
+ return;
626
+ }
627
+ case 'reconnecting':
628
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `Reconnecting, params: ${JSON.stringify(payload)}`);
629
+ this.emit('reconnecting', payload);
630
+ return;
631
+ case 'close':
632
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, 'Closing connection.');
633
+ this.emit('close');
634
+ return;
635
+ case 'timeout':
636
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, 'Connection timed out.');
637
+ this.emit('timeout');
638
+ // Explicit return mirrors the other cases and protects against
639
+ // fall-through if a new event is added below.
640
+ // eslint-disable-next-line no-useless-return
641
+ return;
642
+ // no default
643
+ }
644
+ }
219
645
  /**
220
646
  * Starts new session
221
647
  * @public
@@ -226,39 +652,76 @@ class DBSQLClient extends events_1.EventEmitter {
226
652
  * const session = await client.openSession();
227
653
  */
228
654
  async openSession(request = {}) {
655
+ if (!this.backend) {
656
+ throw new HiveDriverError_1.default('DBSQLClient: not connected');
657
+ }
658
+ // Track connection open latency
659
+ const startTime = Date.now();
229
660
  // Prepare session configuration
230
661
  const configuration = request.configuration ? { ...request.configuration } : {};
231
662
  // Add metric view metadata config if enabled
232
663
  if (this.config.enableMetricViewMetadata) {
233
664
  configuration['spark.sql.thriftserver.metadata.metricview.enabled'] = 'true';
234
665
  }
235
- // Serialize queryTags dict and set in configuration; takes precedence over configuration.QUERY_TAGS
236
- if (request.queryTags !== undefined) {
237
- const serialized = (0, utils_1.serializeQueryTags)(request.queryTags);
238
- if (serialized) {
239
- configuration.QUERY_TAGS = serialized;
240
- }
241
- else {
242
- delete configuration.QUERY_TAGS;
243
- }
244
- }
245
- const response = await this.driver.openSession({
246
- client_protocol_i64: new node_int64_1.default(TCLIService_types_1.TProtocolVersion.SPARK_CLI_SERVICE_PROTOCOL_V8),
247
- ...getInitialNamespaceOptions(request.initialCatalog, request.initialSchema),
666
+ const sessionBackend = await this.backend.openSession({
667
+ ...request,
248
668
  configuration,
249
- canUseMultipleCatalogs: true,
250
- });
251
- Status_1.default.assert(response.status);
252
- const session = new DBSQLSession_1.default({
253
- handle: (0, utils_1.definedOrError)(response.sessionHandle),
254
- context: this,
255
- serverProtocolVersion: response.serverProtocolVersion,
256
669
  });
670
+ const session = new DBSQLSession_1.default({ backend: sessionBackend, context: this });
257
671
  this.sessions.add(session);
672
+ // Emit connection.open telemetry event. The DriverConfiguration blob
673
+ // (~1KB: runtime/OS/locale/process info) is static for the lifetime of
674
+ // this DBSQLClient — ship it once, on the first openSession, and omit
675
+ // on subsequent sessions for the same client. Server-side correlation
676
+ // by sessionId still groups N sessions under the first event's config.
677
+ (0, telemetryUtils_1.safeEmit)(this, (emitter) => {
678
+ if (!this.host)
679
+ return;
680
+ const latencyMs = Date.now() - startTime;
681
+ const workspaceId = DBSQLClient.extractWorkspaceId(this.httpPath);
682
+ const driverConfig = this.driverConfigShipped ? undefined : this.buildDriverConfiguration();
683
+ if (driverConfig) {
684
+ this.driverConfigShipped = true;
685
+ }
686
+ emitter.emitConnectionOpen({
687
+ sessionId: session.id,
688
+ workspaceId,
689
+ driverConfig,
690
+ latencyMs,
691
+ });
692
+ });
258
693
  return session;
259
694
  }
695
+ /**
696
+ * Closes the client, releasing sessions and telemetry resources.
697
+ *
698
+ * The internal telemetry flush timer uses `setInterval(...).unref()` so it
699
+ * cannot keep the Node.js process alive on its own. As a consequence, any
700
+ * telemetry buffered between flush ticks is lost if the process exits
701
+ * without calling `close()`. Long-lived applications should `await` this
702
+ * method on shutdown so the aggregator drains its remaining metrics.
703
+ */
260
704
  async close() {
705
+ var _a;
261
706
  await this.sessions.closeAll();
707
+ await ((_a = this.backend) === null || _a === void 0 ? void 0 : _a.close());
708
+ this.backend = undefined;
709
+ // Cleanup telemetry. Releasing our refcount on the shared TelemetryClient
710
+ // is awaited because the underlying close() drains the final HTTP POST —
711
+ // a caller doing `await client.close(); process.exit(0)` would otherwise
712
+ // truncate the in-flight request when this is the last refcount holder.
713
+ if (this.host && this.telemetryClient) {
714
+ try {
715
+ await TelemetryClientProvider_1.default.getInstance().releaseClient(this, this.host);
716
+ }
717
+ catch (error) {
718
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `Telemetry cleanup error: ${error.message}`);
719
+ }
720
+ this.telemetryClient = undefined;
721
+ }
722
+ // Drop the emitter ref so post-close calls (e.g. session.close racing
723
+ // with client.close) cannot smuggle events into the closed aggregator.
724
+ this.telemetryEmitter = undefined;
262
725
  this.client = undefined;
263
726
  this.connectionProvider = undefined;
264
727
  this.authProvider = undefined;
@@ -300,6 +763,29 @@ class DBSQLClient extends events_1.EventEmitter {
300
763
  getAuthProvider() {
301
764
  return this.authProvider;
302
765
  }
766
+ /** @internal */
767
+ getTelemetryEmitter() {
768
+ return this.telemetryEmitter;
769
+ }
770
+ /** @internal */
771
+ getTelemetryAggregator() {
772
+ var _a;
773
+ return (_a = this.telemetryClient) === null || _a === void 0 ? void 0 : _a.getAggregator();
774
+ }
775
+ /**
776
+ * Operator-visible snapshot of the client's telemetry state: current
777
+ * buffer depth, in-flight statement aggregations, cumulative drops/
778
+ * evictions, and circuit-breaker state. Returns `undefined` when
779
+ * telemetry is disabled (config, env-kill, or feature-flag).
780
+ *
781
+ * Use this in health-check endpoints or shutdown banners to verify that
782
+ * telemetry is flowing. A non-zero `droppedMetrics` between observations
783
+ * means buffer overflow — raise `telemetryMaxPendingMetrics`.
784
+ */
785
+ getTelemetryStats() {
786
+ var _a;
787
+ return (_a = this.telemetryClient) === null || _a === void 0 ? void 0 : _a.getTelemetryStats();
788
+ }
303
789
  }
304
790
  exports.default = DBSQLClient;
305
791
  //# sourceMappingURL=DBSQLClient.js.map