@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
@@ -14,50 +14,282 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
+ var __importDefault = (this && this.__importDefault) || function (mod) {
18
+ return (mod && mod.__esModule) ? mod : { "default": mod };
19
+ };
17
20
  Object.defineProperty(exports, "__esModule", { value: true });
18
21
  const IDBSQLLogger_1 = require("../contracts/IDBSQLLogger");
22
+ const CircuitBreaker_1 = require("./CircuitBreaker");
23
+ const DatabricksTelemetryExporter_1 = __importDefault(require("./DatabricksTelemetryExporter"));
24
+ const MetricsAggregator_1 = __importDefault(require("./MetricsAggregator"));
25
+ const FeatureFlagCache_1 = __importDefault(require("./FeatureFlagCache"));
19
26
  /**
20
- * Telemetry client for a specific host.
21
- * Managed by TelemetryClientProvider with reference counting.
22
- * One client instance is shared across all connections to the same host.
27
+ * Per-host telemetry resource owner. Held by `TelemetryClientProvider`
28
+ * (process-wide singleton) and shared across every `DBSQLClient` that
29
+ * connects to the same host.
30
+ *
31
+ * Owns the host-scoped triad — `MetricsAggregator`, `DatabricksTelemetryExporter`,
32
+ * `CircuitBreakerRegistry`, `FeatureFlagCache` — and implements `IClientContext`
33
+ * itself so those owned components have a stable context that outlives any
34
+ * single `DBSQLClient`. The first registered `DBSQLClient`'s logger and config
35
+ * are snapshotted; subsequent registrants donate their connection providers
36
+ * and auth providers, and the `TelemetryClient` falls through them in
37
+ * registration order when the current head closes.
38
+ *
39
+ * Why share at host granularity:
40
+ * - Circuit-breaker state for `host` is correct only if all clients hitting
41
+ * the same endpoint share counters (5 failures means 5 actual failures, not
42
+ * 5×N for N independent `DBSQLClient` instances).
43
+ * - Feature-flag cache has a per-host TTL; deduping the GET prevents
44
+ * thundering-herd on cold cache.
45
+ * - Metric batches mix events from every active client to the same host —
46
+ * one HTTP POST per `flushIntervalMs` instead of N.
23
47
  */
24
48
  class TelemetryClient {
25
- constructor(context, host) {
26
- this.context = context;
49
+ constructor(initialContext, host) {
50
+ var _a;
27
51
  this.host = host;
28
52
  this.closed = false;
29
- const logger = context.getLogger();
30
- logger.log(IDBSQLLogger_1.LogLevel.debug, `Created TelemetryClient for host: ${host}`);
53
+ // FIFO so the first-registered client's connection/auth providers are tried
54
+ // first. Falls through to later registrants when an earlier one is closed.
55
+ //
56
+ // The `authProvider` is snapshotted at register time (NOT re-fetched at
57
+ // unregister time). If a registrant's underlying `DBSQLClient` rotates its
58
+ // auth provider between register and unregister (token refresh that
59
+ // reconstructs the provider, lazy wrappers, etc.), filtering by referential
60
+ // equality against a freshly-fetched provider would never match the original,
61
+ // and the stale provider would remain in `authProviders` for the lifetime of
62
+ // the per-host singleton — keeping the exporter authenticating with revoked
63
+ // credentials.
64
+ this.contexts = [];
65
+ this.logger = initialContext.getLogger();
66
+ // Snapshot config at first registration. Subsequent clients with
67
+ // divergent telemetry knobs (`telemetryBatchSize` etc.) inherit the
68
+ // first-registrant's tuning — documented invariant.
69
+ this.config = initialContext.getConfig();
70
+ this.contexts.push({
71
+ context: initialContext,
72
+ authProvider: (_a = initialContext.getAuthProvider) === null || _a === void 0 ? void 0 : _a.call(initialContext),
73
+ });
74
+ this.circuitBreakerRegistry = new CircuitBreaker_1.CircuitBreakerRegistry(this);
75
+ this.featureFlagCache = new FeatureFlagCache_1.default(this);
76
+ // Register this host with the feature-flag cache so isTelemetryEnabled()
77
+ // does not short-circuit to false. close() releases via releaseContext().
78
+ this.featureFlagCache.getOrCreateContext(host);
79
+ this.exporter = new DatabricksTelemetryExporter_1.default(this, host, this.circuitBreakerRegistry);
80
+ this.aggregator = new MetricsAggregator_1.default(this, this.exporter);
81
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `Created TelemetryClient for host: ${host}`);
31
82
  }
32
83
  /**
33
- * Gets the host associated with this client.
84
+ * Add another `DBSQLClient`'s context to the pool. Tracked in registration
85
+ * order; `getConnectionProvider()` / `getAuthProvider()` walk the list and
86
+ * use the first entry that's still usable.
34
87
  */
35
- getHost() {
36
- return this.host;
88
+ registerContext(context) {
89
+ var _a, _b, _c;
90
+ if (this.contexts.some((entry) => entry.context === context)) {
91
+ // Re-snapshot the auth provider on a duplicate register call so a caller
92
+ // that intentionally rotated providers can refresh the entry.
93
+ const idx = this.contexts.findIndex((entry) => entry.context === context);
94
+ if (idx >= 0) {
95
+ this.contexts[idx] = { context, authProvider: (_a = context.getAuthProvider) === null || _a === void 0 ? void 0 : _a.call(context) };
96
+ }
97
+ return;
98
+ }
99
+ const newAuthProvider = (_b = context.getAuthProvider) === null || _b === void 0 ? void 0 : _b.call(context);
100
+ // Diverging auth providers across registrants on the same host is the
101
+ // multi-tenant FIFO bleed case. The first-registered auth wins; tenant B
102
+ // queries POST under tenant A's headers. Warn loudly — SaaS layers that
103
+ // see this in their logs should either:
104
+ // - set telemetryEnabled: false on all DBSQLClients, or
105
+ // - partition by host so each tenant owns its own TelemetryClient.
106
+ const firstAuthProvider = (_c = this.contexts[0]) === null || _c === void 0 ? void 0 : _c.authProvider;
107
+ if (this.contexts.length > 0 &&
108
+ newAuthProvider !== undefined &&
109
+ firstAuthProvider !== undefined &&
110
+ newAuthProvider !== firstAuthProvider) {
111
+ this.logger.log(IDBSQLLogger_1.LogLevel.warn, `TelemetryClient(${this.host}): a second DBSQLClient registered with a different auth provider. ` +
112
+ `Telemetry from this client will be POSTed under the first-registered client's auth headers. ` +
113
+ `Multi-tenant SaaS layers should set telemetryEnabled: false on all clients or partition by host. ` +
114
+ `See README "Multi-tenant SaaS deployments" for details.`);
115
+ }
116
+ this.contexts.push({
117
+ context,
118
+ authProvider: newAuthProvider,
119
+ });
120
+ // Warn when subsequent registrants pass telemetry knobs that diverge
121
+ // from the first-registrant's snapshot — those values are silently
122
+ // ignored. Privacy-relevant for telemetryAuthenticatedExport.
123
+ this.warnOnConfigDivergence(context.getConfig());
124
+ }
125
+ warnOnConfigDivergence(other) {
126
+ const keys = [
127
+ 'telemetryAuthenticatedExport',
128
+ 'telemetryBatchSize',
129
+ 'telemetryFlushIntervalMs',
130
+ 'telemetryMaxRetries',
131
+ 'telemetryCircuitBreakerThreshold',
132
+ 'telemetryCircuitBreakerTimeout',
133
+ // Privacy-relevant: User-Agent is snapshotted from the first registrant
134
+ // and shared across the host. Multi-tenant SaaS layers with per-tenant
135
+ // userAgentEntry values would otherwise silently ship under tenant-1's UA.
136
+ 'userAgentEntry',
137
+ ];
138
+ const diverged = keys.filter((k) => other[k] !== undefined && other[k] !== this.config[k]);
139
+ if (diverged.length > 0) {
140
+ this.logger.log(IDBSQLLogger_1.LogLevel.warn, `TelemetryClient(${this.host}): registered context's telemetry settings ` +
141
+ `[${diverged.join(', ')}] differ from the first registrant's; the new values will be ignored.`);
142
+ }
143
+ }
144
+ /**
145
+ * Remove a `DBSQLClient`'s context from the pool. Called by
146
+ * `TelemetryClientProvider.releaseClient` before refcount decrement so the
147
+ * exporter doesn't keep trying to use a closed context.
148
+ *
149
+ * Uses the cached snapshot pair (`context`, `authProvider`) from register
150
+ * time, not a fresh `context.getAuthProvider?.()` call. If the underlying
151
+ * client's auth provider was rotated, a fresh call would not match the
152
+ * original reference and the stale entry would leak.
153
+ */
154
+ unregisterContext(context) {
155
+ this.contexts = this.contexts.filter((entry) => entry.context !== context);
156
+ }
157
+ // -- IClientContext --
158
+ getConfig() {
159
+ return this.config;
160
+ }
161
+ getLogger() {
162
+ return this.logger;
163
+ }
164
+ async getConnectionProvider() {
165
+ return this.tryFallthrough((ctx) => ctx.getConnectionProvider(), 'connection provider');
166
+ }
167
+ async getClient() {
168
+ return this.tryFallthrough((ctx) => ctx.getClient(), 'client');
169
+ }
170
+ async getDriver() {
171
+ return this.tryFallthrough((ctx) => ctx.getDriver(), 'driver');
172
+ }
173
+ /**
174
+ * Walk `contexts` and return the first call site that succeeds. Contexts
175
+ * that throw on the same accessor for `MAX_CONSECUTIVE_CTX_FAILURES` calls
176
+ * in a row are pruned from the pool — otherwise a registrant whose
177
+ * underlying `DBSQLClient` is closed or has revoked auth would stay in the
178
+ * list forever and be retried on every export.
179
+ *
180
+ * Pruning is keyed by the `accessor` function identity so a context with a
181
+ * working `getConnectionProvider` but broken `getDriver` isn't dropped from
182
+ * the working accessor's path.
183
+ */
184
+ async tryFallthrough(accessor, accessorName) {
185
+ let lastErr;
186
+ const survivors = [];
187
+ /* eslint-disable no-await-in-loop */
188
+ for (const entry of this.contexts) {
189
+ try {
190
+ const result = await accessor(entry.context);
191
+ // Keep this entry and any not-yet-tried ones. We've found a working
192
+ // head; the tail might be fine too. The throwing entries already in
193
+ // `survivors`'s past iterations are dropped below.
194
+ survivors.push(entry);
195
+ for (const remaining of this.contexts.slice(this.contexts.indexOf(entry) + 1)) {
196
+ survivors.push(remaining);
197
+ }
198
+ this.contexts = survivors;
199
+ return result;
200
+ }
201
+ catch (err) {
202
+ lastErr = err;
203
+ // Drop this entry from the survivors set — repeatedly retrying a
204
+ // throwing context drains nothing useful from the FIFO.
205
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `TelemetryClient(${this.host}): pruning context that threw on ${accessorName}: ` +
206
+ `${err instanceof Error ? err.message : String(err)}`);
207
+ }
208
+ }
209
+ /* eslint-enable no-await-in-loop */
210
+ this.contexts = survivors;
211
+ throw lastErr instanceof Error
212
+ ? lastErr
213
+ : new Error(`TelemetryClient: no ${accessorName} available for host ${this.host}`);
214
+ }
215
+ getAuthProvider() {
216
+ // Walk the FIFO and return the first usable provider. The provider was
217
+ // snapshotted at register time, so even if the registrant's underlying
218
+ // client has since rotated credentials, the original entry can still be
219
+ // dropped by `unregisterContext` via cached-snapshot equality. A registered
220
+ // head with revoked credentials surfaces as an `authenticate()` failure
221
+ // inside the exporter retry loop.
222
+ for (const entry of this.contexts) {
223
+ if (entry.authProvider !== undefined) {
224
+ return entry.authProvider;
225
+ }
226
+ }
227
+ return undefined;
228
+ }
229
+ getTelemetryEmitter() {
230
+ // The shared TelemetryClient holds the aggregator; emitters remain
231
+ // per-DBSQLClient so each can respect its own `telemetryEnabled` flag.
232
+ return undefined;
233
+ }
234
+ getTelemetryAggregator() {
235
+ return this.aggregator;
236
+ }
237
+ // -- shared resource accessors --
238
+ getExporter() {
239
+ return this.exporter;
240
+ }
241
+ getAggregator() {
242
+ return this.aggregator;
243
+ }
244
+ getFeatureFlagCache() {
245
+ return this.featureFlagCache;
37
246
  }
38
247
  /**
39
- * Checks if the client has been closed.
248
+ * Operator-visible snapshot of telemetry state for this host. Synchronous,
249
+ * never throws — intended for health-check endpoints, shutdown banners,
250
+ * and operator dashboards.
40
251
  */
252
+ getTelemetryStats() {
253
+ return {
254
+ host: this.host,
255
+ ...this.aggregator.getStats(),
256
+ circuitBreakerState: this.circuitBreakerRegistry.getCircuitBreaker(this.host).getState(),
257
+ };
258
+ }
259
+ getHost() {
260
+ return this.host;
261
+ }
41
262
  isClosed() {
42
263
  return this.closed;
43
264
  }
44
265
  /**
45
- * Closes the telemetry client and releases resources.
46
- * Should only be called by TelemetryClientProvider when reference count reaches zero.
266
+ * Drain pending metrics and tear down owned resources. Called by
267
+ * `TelemetryClientProvider.releaseClient` when refCount hits zero.
47
268
  */
48
- close() {
49
- if (this.closed) {
269
+ async close() {
270
+ if (this.closed)
50
271
  return;
272
+ this.closed = true;
273
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `Closing TelemetryClient for host: ${this.host}`);
274
+ try {
275
+ await this.aggregator.close();
276
+ }
277
+ catch (err) {
278
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `TelemetryClient aggregator close error: ${err.message}`);
51
279
  }
52
280
  try {
53
- this.context.getLogger().log(IDBSQLLogger_1.LogLevel.debug, `Closing TelemetryClient for host: ${this.host}`);
281
+ this.exporter.dispose();
54
282
  }
55
- catch (_a) {
56
- // swallow
283
+ catch (err) {
284
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `TelemetryClient exporter dispose error: ${err.message}`);
285
+ }
286
+ try {
287
+ this.featureFlagCache.releaseContext(this.host);
57
288
  }
58
- finally {
59
- this.closed = true;
289
+ catch (err) {
290
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `TelemetryClient FFCache release error: ${err.message}`);
60
291
  }
292
+ this.logger.log(IDBSQLLogger_1.LogLevel.debug, `Closed TelemetryClient for host: ${this.host}`);
61
293
  }
62
294
  }
63
295
  exports.default = TelemetryClient;
@@ -1 +1 @@
1
- {"version":3,"file":"TelemetryClient.js","sourceRoot":"","sources":["../../lib/telemetry/TelemetryClient.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;AAGH,4DAAqD;AAErD;;;;GAIG;AACH,MAAM,eAAe;IAGnB,YAAoB,OAAuB,EAAU,IAAY;QAA7C,YAAO,GAAP,OAAO,CAAgB;QAAU,SAAI,GAAJ,IAAI,CAAQ;QAFzD,WAAM,GAAY,KAAK,CAAC;QAG9B,MAAM,MAAM,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;QACnC,MAAM,CAAC,GAAG,CAAC,uBAAQ,CAAC,KAAK,EAAE,qCAAqC,IAAI,EAAE,CAAC,CAAC;IAC1E,CAAC;IAED;;OAEG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED;;;OAGG;IACH,KAAK;QACH,IAAI,IAAI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;YACZ,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,uBAAQ,CAAC,KAAK,EAAE,0CAA2C,GAAa,CAAC,OAAO,EAAE,CAAC,CAAC;SACrG;QACD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,uBAAQ,CAAC,KAAK,EAAE,oCAAoC,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IACnF,CAAC;CACF;AAED,kBAAe,eAAe,CAAC"}
@@ -16,52 +16,47 @@
16
16
  import IClientContext from '../contracts/IClientContext';
17
17
  import TelemetryClient from './TelemetryClient';
18
18
  /**
19
- * Manages one telemetry client per host.
20
- * Prevents rate limiting by sharing clients across connections to the same host.
21
- * Instance-based (not singleton), stored in DBSQLClient.
19
+ * Process-wide registry of `TelemetryClient`s, one per host. Multiple
20
+ * `DBSQLClient` instances connecting to the same host share the same
21
+ * `TelemetryClient`, which owns the host-scoped circuit breaker, feature
22
+ * flag cache, exporter, and aggregator.
22
23
  *
23
- * Reference counts are incremented and decremented synchronously, and
24
- * `close()` is sync today, so there is no await between map mutation and
25
- * client teardown. The map entry is removed before `close()` runs so a
26
- * concurrent `getOrCreateClient` call for the same host gets a fresh
27
- * instance rather than receiving this closing one. When `close()` becomes
28
- * async (e.g. HTTP flush in [5/7]) the flow will need to `await` after the
29
- * delete to preserve the same invariant.
24
+ * Singleton because the resources we're sharing — circuit-breaker counters,
25
+ * batched HTTP exports — are correct only at process scope. Per-`DBSQLClient`
26
+ * provider scope (the previous design) deduplicates nothing.
27
+ *
28
+ * `getOrCreateClient` is sync: caller increments refcount, registers its
29
+ * context+auth, and walks away. `releaseClient` is `async` because the
30
+ * underlying `TelemetryClient.close()` awaits the final flush.
30
31
  */
31
32
  declare class TelemetryClientProvider {
32
- private context;
33
+ private static instance;
33
34
  private clients;
34
35
  private softLimitWarned;
35
- constructor(context: IClientContext);
36
- /**
37
- * Canonicalize host so aliases (scheme, default port, trailing slash, case,
38
- * trailing dot, surrounding whitespace) map to the same entry. Kept to a
39
- * lightweight lexical normalization — `buildTelemetryUrl` still performs
40
- * the strict security validation when a request is actually built.
41
- */
42
- private static normalizeHostKey;
36
+ static getInstance(): TelemetryClientProvider;
43
37
  /**
44
- * Gets or creates a telemetry client for the specified host.
45
- * Increments the reference count for the client.
38
+ * Reset the process-wide singleton. Test-only — name-prefixed so
39
+ * production callsites can't reach for it accidentally via autocomplete.
40
+ * Resetting in production drops every host's circuit-breaker counters,
41
+ * feature-flag cache, exporter, and pending-metric buffer at once.
46
42
  *
47
- * @param host The host identifier (e.g., "workspace.cloud.databricks.com")
48
- * @returns The telemetry client for the host
43
+ * @internal Test-only. Production code MUST NOT call this.
49
44
  */
50
- getOrCreateClient(host: string): TelemetryClient;
45
+ static __resetInstanceForTests(): void;
46
+ private static normalizeHostKey;
51
47
  /**
52
- * Releases a telemetry client for the specified host.
53
- * Decrements the reference count and closes the client when it reaches zero.
54
- *
55
- * @param host The host identifier
48
+ * Get or create the `TelemetryClient` for `host`, registering `context` as
49
+ * a participant. Increments refcount.
56
50
  */
57
- releaseClient(host: string): void;
51
+ getOrCreateClient(context: IClientContext, host: string): TelemetryClient;
58
52
  /**
59
- * @internal Exposed for testing only.
53
+ * Release `context`'s registration. When the last `DBSQLClient` releases,
54
+ * the underlying `TelemetryClient.close()` runs and the entry is removed.
60
55
  */
56
+ releaseClient(context: IClientContext, host: string): Promise<void>;
57
+ /** @internal Exposed for testing only. */
61
58
  getRefCount(host: string): number;
62
- /**
63
- * @internal Exposed for testing only.
64
- */
59
+ /** @internal Exposed for testing only. */
65
60
  getActiveClients(): Map<string, TelemetryClient>;
66
61
  }
67
62
  export default TelemetryClientProvider;
@@ -21,36 +21,49 @@ Object.defineProperty(exports, "__esModule", { value: true });
21
21
  const IDBSQLLogger_1 = require("../contracts/IDBSQLLogger");
22
22
  const TelemetryClient_1 = __importDefault(require("./TelemetryClient"));
23
23
  // Soft cap on distinct host entries. Above this the provider warns once so a
24
- // misconfigured caller (per-request hosts, unnormalized aliases) is visible in
25
- // logs rather than silently growing the map.
24
+ // misconfigured caller (per-request hosts, unnormalized aliases) is visible
25
+ // in logs rather than silently growing the map.
26
26
  const MAX_CLIENTS_SOFT_LIMIT = 128;
27
27
  /**
28
- * Manages one telemetry client per host.
29
- * Prevents rate limiting by sharing clients across connections to the same host.
30
- * Instance-based (not singleton), stored in DBSQLClient.
28
+ * Process-wide registry of `TelemetryClient`s, one per host. Multiple
29
+ * `DBSQLClient` instances connecting to the same host share the same
30
+ * `TelemetryClient`, which owns the host-scoped circuit breaker, feature
31
+ * flag cache, exporter, and aggregator.
31
32
  *
32
- * Reference counts are incremented and decremented synchronously, and
33
- * `close()` is sync today, so there is no await between map mutation and
34
- * client teardown. The map entry is removed before `close()` runs so a
35
- * concurrent `getOrCreateClient` call for the same host gets a fresh
36
- * instance rather than receiving this closing one. When `close()` becomes
37
- * async (e.g. HTTP flush in [5/7]) the flow will need to `await` after the
38
- * delete to preserve the same invariant.
33
+ * Singleton because the resources we're sharing — circuit-breaker counters,
34
+ * batched HTTP exports — are correct only at process scope. Per-`DBSQLClient`
35
+ * provider scope (the previous design) deduplicates nothing.
36
+ *
37
+ * `getOrCreateClient` is sync: caller increments refcount, registers its
38
+ * context+auth, and walks away. `releaseClient` is `async` because the
39
+ * underlying `TelemetryClient.close()` awaits the final flush.
39
40
  */
40
41
  class TelemetryClientProvider {
41
- constructor(context) {
42
- this.context = context;
43
- this.softLimitWarned = false;
42
+ constructor() {
44
43
  this.clients = new Map();
45
- const logger = context.getLogger();
46
- logger.log(IDBSQLLogger_1.LogLevel.debug, 'Created TelemetryClientProvider');
44
+ this.softLimitWarned = false;
45
+ }
46
+ // Production code should use `TelemetryClientProvider.getInstance()` for
47
+ // the process-wide singleton. The constructor remains public so unit tests
48
+ // can build an isolated provider with its own map. Deliberate no-op body —
49
+ // initial state is set inline on the field declarations above.
50
+ static getInstance() {
51
+ if (!TelemetryClientProvider.instance) {
52
+ TelemetryClientProvider.instance = new TelemetryClientProvider();
53
+ }
54
+ return TelemetryClientProvider.instance;
47
55
  }
48
56
  /**
49
- * Canonicalize host so aliases (scheme, default port, trailing slash, case,
50
- * trailing dot, surrounding whitespace) map to the same entry. Kept to a
51
- * lightweight lexical normalization — `buildTelemetryUrl` still performs
52
- * the strict security validation when a request is actually built.
57
+ * Reset the process-wide singleton. Test-only — name-prefixed so
58
+ * production callsites can't reach for it accidentally via autocomplete.
59
+ * Resetting in production drops every host's circuit-breaker counters,
60
+ * feature-flag cache, exporter, and pending-metric buffer at once.
61
+ *
62
+ * @internal Test-only. Production code MUST NOT call this.
53
63
  */
64
+ static __resetInstanceForTests() {
65
+ TelemetryClientProvider.instance = undefined;
66
+ }
54
67
  static normalizeHostKey(host) {
55
68
  return host
56
69
  .trim()
@@ -61,22 +74,16 @@ class TelemetryClientProvider {
61
74
  .replace(/:443$/, '');
62
75
  }
63
76
  /**
64
- * Gets or creates a telemetry client for the specified host.
65
- * Increments the reference count for the client.
66
- *
67
- * @param host The host identifier (e.g., "workspace.cloud.databricks.com")
68
- * @returns The telemetry client for the host
77
+ * Get or create the `TelemetryClient` for `host`, registering `context` as
78
+ * a participant. Increments refcount.
69
79
  */
70
- getOrCreateClient(host) {
71
- const logger = this.context.getLogger();
80
+ getOrCreateClient(context, host) {
81
+ const logger = context.getLogger();
72
82
  const key = TelemetryClientProvider.normalizeHostKey(host);
73
83
  let holder = this.clients.get(key);
74
84
  if (!holder) {
75
- const client = new TelemetryClient_1.default(this.context, key);
76
- holder = {
77
- client,
78
- refCount: 0,
79
- };
85
+ const client = new TelemetryClient_1.default(context, key);
86
+ holder = { client, refCount: 0 };
80
87
  this.clients.set(key, holder);
81
88
  logger.log(IDBSQLLogger_1.LogLevel.debug, `Created new TelemetryClient for host: ${host}`);
82
89
  if (!this.softLimitWarned && this.clients.size > MAX_CLIENTS_SOFT_LIMIT) {
@@ -84,40 +91,43 @@ class TelemetryClientProvider {
84
91
  logger.log(IDBSQLLogger_1.LogLevel.warn, `TelemetryClientProvider has ${this.clients.size} distinct hosts — possible alias or leak`);
85
92
  }
86
93
  }
94
+ else {
95
+ holder.client.registerContext(context);
96
+ }
87
97
  holder.refCount += 1;
88
98
  logger.log(IDBSQLLogger_1.LogLevel.debug, `TelemetryClient reference count for ${host}: ${holder.refCount}`);
89
99
  return holder.client;
90
100
  }
91
101
  /**
92
- * Releases a telemetry client for the specified host.
93
- * Decrements the reference count and closes the client when it reaches zero.
94
- *
95
- * @param host The host identifier
102
+ * Release `context`'s registration. When the last `DBSQLClient` releases,
103
+ * the underlying `TelemetryClient.close()` runs and the entry is removed.
96
104
  */
97
- releaseClient(host) {
98
- const logger = this.context.getLogger();
105
+ async releaseClient(context, host) {
106
+ const logger = context.getLogger();
99
107
  const key = TelemetryClientProvider.normalizeHostKey(host);
100
108
  const holder = this.clients.get(key);
101
109
  if (!holder) {
102
110
  logger.log(IDBSQLLogger_1.LogLevel.debug, `No TelemetryClient found for host: ${host}`);
103
111
  return;
104
112
  }
105
- // Guard against double-release: a caller releasing more times than it got
106
- // would otherwise drive refCount negative and close a client another
107
- // caller is still holding. Warn loudly and refuse to decrement further.
108
113
  if (holder.refCount <= 0) {
109
114
  logger.log(IDBSQLLogger_1.LogLevel.warn, `Unbalanced release for TelemetryClient host: ${host}`);
110
115
  return;
111
116
  }
117
+ // Skip unregister on the last release so close()'s final flush can still
118
+ // resolve auth/connection providers from the FIFO snapshot.
119
+ if (holder.refCount > 1) {
120
+ holder.client.unregisterContext(context);
121
+ }
112
122
  holder.refCount -= 1;
113
123
  logger.log(IDBSQLLogger_1.LogLevel.debug, `TelemetryClient reference count for ${host}: ${holder.refCount}`);
114
- // Close and remove client when reference count reaches zero.
115
- // Remove from map before calling close so a concurrent getOrCreateClient
116
- // creates a fresh client rather than receiving this closing one.
117
124
  if (holder.refCount <= 0) {
125
+ // Remove from map BEFORE awaiting close so a concurrent
126
+ // getOrCreateClient creates a fresh instance rather than receiving
127
+ // this closing one.
118
128
  this.clients.delete(key);
119
129
  try {
120
- holder.client.close();
130
+ await holder.client.close();
121
131
  logger.log(IDBSQLLogger_1.LogLevel.debug, `Closed and removed TelemetryClient for host: ${host}`);
122
132
  }
123
133
  catch (error) {
@@ -126,16 +136,12 @@ class TelemetryClientProvider {
126
136
  }
127
137
  }
128
138
  }
129
- /**
130
- * @internal Exposed for testing only.
131
- */
139
+ /** @internal Exposed for testing only. */
132
140
  getRefCount(host) {
133
141
  const holder = this.clients.get(TelemetryClientProvider.normalizeHostKey(host));
134
142
  return holder ? holder.refCount : 0;
135
143
  }
136
- /**
137
- * @internal Exposed for testing only.
138
- */
144
+ /** @internal Exposed for testing only. */
139
145
  getActiveClients() {
140
146
  const result = new Map();
141
147
  for (const [host, holder] of this.clients.entries()) {
@@ -1 +1 @@
1
- {"version":3,"file":"TelemetryClientProvider.js","sourceRoot":"","sources":["../../lib/telemetry/TelemetryClientProvider.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;AAGH,4DAAqD;AACrD,wEAAgD;AAWhD,6EAA6E;AAC7E,+EAA+E;AAC/E,6CAA6C;AAC7C,MAAM,sBAAsB,GAAG,GAAG,CAAC;AAEnC;;;;;;;;;;;;GAYG;AACH,MAAM,uBAAuB;IAK3B,YAAoB,OAAuB;QAAvB,YAAO,GAAP,OAAO,CAAgB;QAFnC,oBAAe,GAAG,KAAK,CAAC;QAG9B,IAAI,CAAC,OAAO,GAAG,IAAI,GAAG,EAAE,CAAC;QACzB,MAAM,MAAM,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;QACnC,MAAM,CAAC,GAAG,CAAC,uBAAQ,CAAC,KAAK,EAAE,iCAAiC,CAAC,CAAC;IAChE,CAAC;IAED;;;;;OAKG;IACK,MAAM,CAAC,gBAAgB,CAAC,IAAY;QAC1C,OAAO,IAAI;aACR,IAAI,EAAE;aACN,WAAW,EAAE;aACb,OAAO,CAAC,cAAc,EAAE,EAAE,CAAC;aAC3B,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;aACnB,OAAO,CAAC,KAAK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