@databricks/sql 1.12.0 → 1.14.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.
Files changed (95) hide show
  1. package/dist/DBSQLClient.d.ts +13 -0
  2. package/dist/DBSQLClient.js +58 -1
  3. package/dist/DBSQLClient.js.map +1 -1
  4. package/dist/DBSQLOperation.d.ts +1 -0
  5. package/dist/DBSQLOperation.js +23 -2
  6. package/dist/DBSQLOperation.js.map +1 -1
  7. package/dist/DBSQLSession.js +5 -1
  8. package/dist/DBSQLSession.js.map +1 -1
  9. package/dist/connection/auth/tokenProvider/CachedTokenProvider.d.ts +37 -0
  10. package/dist/connection/auth/tokenProvider/CachedTokenProvider.js +79 -0
  11. package/dist/connection/auth/tokenProvider/CachedTokenProvider.js.map +1 -0
  12. package/dist/connection/auth/tokenProvider/ExternalTokenProvider.d.ts +28 -0
  13. package/dist/connection/auth/tokenProvider/ExternalTokenProvider.js +37 -0
  14. package/dist/connection/auth/tokenProvider/ExternalTokenProvider.js.map +1 -0
  15. package/dist/connection/auth/tokenProvider/FederationProvider.d.ts +57 -0
  16. package/dist/connection/auth/tokenProvider/FederationProvider.js +218 -0
  17. package/dist/connection/auth/tokenProvider/FederationProvider.js.map +1 -0
  18. package/dist/connection/auth/tokenProvider/ITokenProvider.d.ts +17 -0
  19. package/dist/connection/auth/tokenProvider/ITokenProvider.js +3 -0
  20. package/dist/connection/auth/tokenProvider/ITokenProvider.js.map +1 -0
  21. package/dist/connection/auth/tokenProvider/StaticTokenProvider.d.ts +24 -0
  22. package/dist/connection/auth/tokenProvider/StaticTokenProvider.js +43 -0
  23. package/dist/connection/auth/tokenProvider/StaticTokenProvider.js.map +1 -0
  24. package/dist/connection/auth/tokenProvider/Token.d.ts +75 -0
  25. package/dist/connection/auth/tokenProvider/Token.js +120 -0
  26. package/dist/connection/auth/tokenProvider/Token.js.map +1 -0
  27. package/dist/connection/auth/tokenProvider/TokenProviderAuthenticator.d.ts +21 -0
  28. package/dist/connection/auth/tokenProvider/TokenProviderAuthenticator.js +38 -0
  29. package/dist/connection/auth/tokenProvider/TokenProviderAuthenticator.js.map +1 -0
  30. package/dist/connection/auth/tokenProvider/index.d.ts +8 -0
  31. package/dist/connection/auth/tokenProvider/index.js +23 -0
  32. package/dist/connection/auth/tokenProvider/index.js.map +1 -0
  33. package/dist/connection/auth/tokenProvider/utils.d.ts +24 -0
  34. package/dist/connection/auth/tokenProvider/utils.js +83 -0
  35. package/dist/connection/auth/tokenProvider/utils.js.map +1 -0
  36. package/dist/contracts/IClientContext.d.ts +15 -0
  37. package/dist/contracts/IDBSQLClient.d.ts +24 -0
  38. package/dist/contracts/IDBSQLSession.d.ts +6 -0
  39. package/dist/index.d.ts +9 -0
  40. package/dist/index.js +15 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/result/ArrowResultHandler.js +2 -2
  43. package/dist/result/ArrowResultHandler.js.map +1 -1
  44. package/dist/result/CloudFetchResultHandler.js +2 -2
  45. package/dist/result/CloudFetchResultHandler.js.map +1 -1
  46. package/dist/telemetry/CircuitBreaker.d.ts +73 -0
  47. package/dist/telemetry/CircuitBreaker.js +176 -0
  48. package/dist/telemetry/CircuitBreaker.js.map +1 -0
  49. package/dist/telemetry/DatabricksTelemetryExporter.d.ts +76 -0
  50. package/dist/telemetry/DatabricksTelemetryExporter.js +324 -0
  51. package/dist/telemetry/DatabricksTelemetryExporter.js.map +1 -0
  52. package/dist/telemetry/ExceptionClassifier.d.ts +48 -0
  53. package/dist/telemetry/ExceptionClassifier.js +112 -0
  54. package/dist/telemetry/ExceptionClassifier.js.map +1 -0
  55. package/dist/telemetry/FeatureFlagCache.d.ts +61 -0
  56. package/dist/telemetry/FeatureFlagCache.js +208 -0
  57. package/dist/telemetry/FeatureFlagCache.js.map +1 -0
  58. package/dist/telemetry/MetricsAggregator.d.ts +72 -0
  59. package/dist/telemetry/MetricsAggregator.js +375 -0
  60. package/dist/telemetry/MetricsAggregator.js.map +1 -0
  61. package/dist/telemetry/TelemetryClient.d.ts +41 -0
  62. package/dist/telemetry/TelemetryClient.js +64 -0
  63. package/dist/telemetry/TelemetryClient.js.map +1 -0
  64. package/dist/telemetry/TelemetryClientProvider.d.ts +67 -0
  65. package/dist/telemetry/TelemetryClientProvider.js +148 -0
  66. package/dist/telemetry/TelemetryClientProvider.js.map +1 -0
  67. package/dist/telemetry/TelemetryEventEmitter.d.ts +93 -0
  68. package/dist/telemetry/TelemetryEventEmitter.js +172 -0
  69. package/dist/telemetry/TelemetryEventEmitter.js.map +1 -0
  70. package/dist/telemetry/telemetryUtils.d.ts +56 -0
  71. package/dist/telemetry/telemetryUtils.js +222 -0
  72. package/dist/telemetry/telemetryUtils.js.map +1 -0
  73. package/dist/telemetry/types.d.ts +209 -0
  74. package/dist/telemetry/types.js +52 -0
  75. package/dist/telemetry/types.js.map +1 -0
  76. package/dist/telemetry/urlUtils.d.ts +22 -0
  77. package/dist/telemetry/urlUtils.js +35 -0
  78. package/dist/telemetry/urlUtils.js.map +1 -0
  79. package/dist/utils/agentDetector.d.ts +20 -0
  80. package/dist/utils/agentDetector.js +39 -0
  81. package/dist/utils/agentDetector.js.map +1 -0
  82. package/dist/utils/buildUserAgentString.js +7 -1
  83. package/dist/utils/buildUserAgentString.js.map +1 -1
  84. package/dist/utils/index.d.ts +2 -1
  85. package/dist/utils/index.js +3 -1
  86. package/dist/utils/index.js.map +1 -1
  87. package/dist/utils/lz4.d.ts +2 -2
  88. package/dist/utils/lz4.js +13 -1
  89. package/dist/utils/lz4.js.map +1 -1
  90. package/dist/utils/queryTags.d.ts +12 -0
  91. package/dist/utils/queryTags.js +35 -0
  92. package/dist/utils/queryTags.js.map +1 -0
  93. package/dist/version.d.ts +1 -1
  94. package/dist/version.js +1 -1
  95. package/package.json +1 -1
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Databricks Contributors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
18
+ if (k2 === undefined) k2 = k;
19
+ var desc = Object.getOwnPropertyDescriptor(m, k);
20
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
21
+ desc = { enumerable: true, get: function() { return m[k]; } };
22
+ }
23
+ Object.defineProperty(o, k2, desc);
24
+ }) : (function(o, m, k, k2) {
25
+ if (k2 === undefined) k2 = k;
26
+ o[k2] = m[k];
27
+ }));
28
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
29
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
30
+ }) : function(o, v) {
31
+ o["default"] = v;
32
+ });
33
+ var __importStar = (this && this.__importStar) || function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ var __importDefault = (this && this.__importDefault) || function (mod) {
41
+ return (mod && mod.__esModule) ? mod : { "default": mod };
42
+ };
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ const node_fetch_1 = __importStar(require("node-fetch"));
45
+ const IDBSQLLogger_1 = require("../contracts/IDBSQLLogger");
46
+ const telemetryUtils_1 = require("./telemetryUtils");
47
+ const buildUserAgentString_1 = __importDefault(require("../utils/buildUserAgentString"));
48
+ const version_1 = __importDefault(require("../version"));
49
+ /**
50
+ * Per-host feature-flag cache used to gate telemetry emission. Responsibilities:
51
+ * - dedupe in-flight fetches (thundering-herd protection);
52
+ * - ref-count so context goes away when the last consumer closes;
53
+ * - clamp server-provided TTL into a safe band.
54
+ *
55
+ * Shares HTTP plumbing (agent, user agent) with DatabricksTelemetryExporter.
56
+ * Consumer wiring lands in a later PR in this stack (see PR description).
57
+ */
58
+ class FeatureFlagCache {
59
+ constructor(context, authProvider) {
60
+ this.context = context;
61
+ this.authProvider = authProvider;
62
+ this.fetchPromises = new Map();
63
+ this.CACHE_DURATION_MS = 15 * 60 * 1000;
64
+ this.MIN_CACHE_DURATION_S = 60;
65
+ this.MAX_CACHE_DURATION_S = 3600;
66
+ this.FEATURE_FLAG_NAME = 'databricks.partnerplatform.clientConfigsFeatureFlags.enableTelemetryForNodeJs';
67
+ this.contexts = new Map();
68
+ this.userAgent = (0, buildUserAgentString_1.default)(this.context.getConfig().userAgentEntry);
69
+ }
70
+ getOrCreateContext(host) {
71
+ let ctx = this.contexts.get(host);
72
+ if (!ctx) {
73
+ ctx = {
74
+ refCount: 0,
75
+ cacheDuration: this.CACHE_DURATION_MS,
76
+ };
77
+ this.contexts.set(host, ctx);
78
+ }
79
+ ctx.refCount += 1;
80
+ return ctx;
81
+ }
82
+ releaseContext(host) {
83
+ const ctx = this.contexts.get(host);
84
+ if (ctx) {
85
+ ctx.refCount -= 1;
86
+ if (ctx.refCount <= 0) {
87
+ this.contexts.delete(host);
88
+ this.fetchPromises.delete(host);
89
+ }
90
+ }
91
+ }
92
+ async isTelemetryEnabled(host) {
93
+ var _a;
94
+ const logger = this.context.getLogger();
95
+ const ctx = this.contexts.get(host);
96
+ if (!ctx) {
97
+ return false;
98
+ }
99
+ const isExpired = !ctx.lastFetched || Date.now() - ctx.lastFetched.getTime() > ctx.cacheDuration;
100
+ if (isExpired) {
101
+ if (!this.fetchPromises.has(host)) {
102
+ const fetchPromise = this.fetchFeatureFlag(host)
103
+ .then((enabled) => {
104
+ ctx.telemetryEnabled = enabled;
105
+ ctx.lastFetched = new Date();
106
+ return enabled;
107
+ })
108
+ .catch((error) => {
109
+ var _a;
110
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Error fetching feature flag: ${error.message}`);
111
+ return (_a = ctx.telemetryEnabled) !== null && _a !== void 0 ? _a : false;
112
+ })
113
+ .finally(() => {
114
+ this.fetchPromises.delete(host);
115
+ });
116
+ this.fetchPromises.set(host, fetchPromise);
117
+ }
118
+ await this.fetchPromises.get(host);
119
+ }
120
+ return (_a = ctx.telemetryEnabled) !== null && _a !== void 0 ? _a : false;
121
+ }
122
+ /**
123
+ * Strips the `-oss` suffix the feature-flag API does not accept. The server
124
+ * keys off the SemVer triplet only, so anything appended would 404.
125
+ */
126
+ getDriverVersion() {
127
+ return version_1.default.replace(/-oss$/, '');
128
+ }
129
+ async fetchFeatureFlag(host) {
130
+ const logger = this.context.getLogger();
131
+ try {
132
+ const endpoint = (0, telemetryUtils_1.buildTelemetryUrl)(host, `/api/2.0/connector-service/feature-flags/NODEJS/${this.getDriverVersion()}`);
133
+ if (!endpoint) {
134
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Feature flag fetch skipped: invalid host ${host}`);
135
+ return false;
136
+ }
137
+ const headers = {
138
+ 'Content-Type': 'application/json',
139
+ 'User-Agent': this.userAgent,
140
+ ...(await this.getAuthHeaders()),
141
+ };
142
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Fetching feature flags from ${endpoint}`);
143
+ const response = await this.fetchWithRetry(endpoint, {
144
+ method: 'GET',
145
+ headers,
146
+ timeout: 10000,
147
+ });
148
+ if (!response.ok) {
149
+ await response.text().catch(() => { });
150
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Feature flag fetch failed: ${response.status} ${response.statusText}`);
151
+ return false;
152
+ }
153
+ const data = await response.json();
154
+ if (data && data.flags && Array.isArray(data.flags)) {
155
+ const ctx = this.contexts.get(host);
156
+ if (ctx && typeof data.ttl_seconds === 'number' && data.ttl_seconds > 0) {
157
+ const clampedTtl = Math.max(this.MIN_CACHE_DURATION_S, Math.min(this.MAX_CACHE_DURATION_S, data.ttl_seconds));
158
+ ctx.cacheDuration = clampedTtl * 1000;
159
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Updated cache duration to ${clampedTtl} seconds`);
160
+ }
161
+ const flag = data.flags.find((f) => f.name === this.FEATURE_FLAG_NAME);
162
+ if (flag) {
163
+ const enabled = String(flag.value).toLowerCase() === 'true';
164
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Feature flag ${this.FEATURE_FLAG_NAME}: ${enabled}`);
165
+ return enabled;
166
+ }
167
+ }
168
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Feature flag ${this.FEATURE_FLAG_NAME} not found in response`);
169
+ return false;
170
+ }
171
+ catch (error) {
172
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Error fetching feature flag from ${host}: ${error.message}`);
173
+ return false;
174
+ }
175
+ }
176
+ /**
177
+ * Retries transient network errors once before giving up. Without a retry
178
+ * a single hiccup would leave telemetry disabled for the full cache TTL
179
+ * (15 min). One retry gives an ephemeral DNS / connection-reset failure
180
+ * a second chance without pushing sustained load at a broken endpoint.
181
+ */
182
+ async fetchWithRetry(url, init) {
183
+ const connectionProvider = await this.context.getConnectionProvider();
184
+ const agent = await connectionProvider.getAgent();
185
+ const retryPolicy = await connectionProvider.getRetryPolicy();
186
+ const requestConfig = { agent, ...init };
187
+ const result = await retryPolicy.invokeWithRetry(() => {
188
+ const request = new node_fetch_1.Request(url, requestConfig);
189
+ return (0, node_fetch_1.default)(request).then((response) => ({ request, response }));
190
+ });
191
+ return result.response;
192
+ }
193
+ async getAuthHeaders() {
194
+ var _a;
195
+ if (!this.authProvider) {
196
+ return {};
197
+ }
198
+ try {
199
+ return (0, telemetryUtils_1.normalizeHeaders)(await this.authProvider.authenticate());
200
+ }
201
+ catch (error) {
202
+ this.context.getLogger().log(IDBSQLLogger_1.LogLevel.debug, `Feature flag auth failed: ${(_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : error}`);
203
+ return {};
204
+ }
205
+ }
206
+ }
207
+ exports.default = FeatureFlagCache;
208
+ //# sourceMappingURL=FeatureFlagCache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FeatureFlagCache.js","sourceRoot":"","sources":["../../lib/telemetry/FeatureFlagCache.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,yDAAmE;AAEnE,4DAAqD;AAErD,qDAAuE;AACvE,yFAAiE;AACjE,yDAAuC;AASvC;;;;;;;;GAQG;AACH,MAAqB,gBAAgB;IAenC,YAAoB,OAAuB,EAAU,YAA8B;QAA/D,YAAO,GAAP,OAAO,CAAgB;QAAU,iBAAY,GAAZ,YAAY,CAAkB;QAZ3E,kBAAa,GAAkC,IAAI,GAAG,EAAE,CAAC;QAIhD,sBAAiB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;QAEnC,yBAAoB,GAAG,EAAE,CAAC;QAE1B,yBAAoB,GAAG,IAAI,CAAC;QAE5B,sBAAiB,GAAG,+EAA+E,CAAC;QAGnH,IAAI,CAAC,QAAQ,GAAG,IAAI,GAAG,EAAE,CAAC;QAC1B,IAAI,CAAC,SAAS,GAAG,IAAA,8BAAoB,EAAC,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,cAAc,CAAC,CAAC;IACjF,CAAC;IAED,kBAAkB,CAAC,IAAY;QAC7B,IAAI,GAAG,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAClC,IAAI,CAAC,GAAG,EAAE;YACR,GAAG,GAAG;gBACJ,QAAQ,EAAE,CAAC;gBACX,aAAa,EAAE,IAAI,CAAC,iBAAiB;aACtC,CAAC;YACF,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;SAC9B;QACD,GAAG,CAAC,QAAQ,IAAI,CAAC,CAAC;QAClB,OAAO,G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MAAM,CAAC,QAAQ,CAAC;IACzB,CAAC;IAEO,KAAK,CAAC,cAAc;;QAC1B,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE;YACtB,OAAO,EAAE,CAAC;SACX;QACD,IAAI;YACF,OAAO,IAAA,iCAAgB,EAAC,MAAM,IAAI,CAAC,YAAY,CAAC,YAAY,EAAE,CAAC,CAAC;SACjE;QAAC,OAAO,KAAU,EAAE;YACnB,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,CAAC,GAAG,CAAC,uBAAQ,CAAC,KAAK,EAAE,6BAA6B,MAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,OAAO,mCAAI,KAAK,EAAE,CAAC,CAAC;YACrG,OAAO,EAAE,CAAC;SACX;IACH,CAAC;CACF;AA9KD,mCA8KC"}
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Copyright (c) 2025 Databricks Contributors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import IClientContext from '../contracts/IClientContext';
17
+ import { TelemetryEvent } from './types';
18
+ import DatabricksTelemetryExporter from './DatabricksTelemetryExporter';
19
+ /**
20
+ * Aggregates telemetry events by statement_id and manages batching/flushing.
21
+ *
22
+ * Overflow policy — when the pending buffer hits `maxPendingMetrics`, error
23
+ * metrics are preserved preferentially over connection/statement metrics.
24
+ * The first-failure error is usually the most valuable signal in post-mortem
25
+ * debugging; dropping it FIFO would defeat the purpose of capture.
26
+ */
27
+ export default class MetricsAggregator {
28
+ private context;
29
+ private exporter;
30
+ private statementMetrics;
31
+ private pendingMetrics;
32
+ private flushTimer;
33
+ private closed;
34
+ private closing;
35
+ private batchSize;
36
+ private flushIntervalMs;
37
+ private maxPendingMetrics;
38
+ private maxErrorsPerStatement;
39
+ private statementTtlMs;
40
+ constructor(context: IClientContext, exporter: DatabricksTelemetryExporter);
41
+ processEvent(event: TelemetryEvent): void;
42
+ private processConnectionEvent;
43
+ private processErrorEvent;
44
+ private pushBoundedError;
45
+ private processStatementEvent;
46
+ private getOrCreateStatementDetails;
47
+ /**
48
+ * Drop entries older than `statementTtlMs`, emitting their buffered error
49
+ * events as standalone metrics first so the first-failure signal survives
50
+ * the eviction. Called from the periodic flush timer so idle clients
51
+ * don't leak orphan entries.
52
+ */
53
+ private evictExpiredStatements;
54
+ completeStatement(statementId: string): void;
55
+ /**
56
+ * Append `metric` to the pending buffer, enforcing `maxPendingMetrics`.
57
+ *
58
+ * Overflow drops the oldest non-error entry (single `splice` — no new
59
+ * allocation). Under an all-error buffer it falls back to dropping the
60
+ * oldest entry at index 0.
61
+ */
62
+ private addPendingMetric;
63
+ private findDropIndex;
64
+ /**
65
+ * Drain the pending buffer and return a promise that resolves when the
66
+ * exporter finishes with the drained batch. `close()` awaits this so
67
+ * `process.exit()` after `client.close()` doesn't truncate the POST.
68
+ */
69
+ flush(resetTimer?: boolean): Promise<void>;
70
+ private startFlushTimer;
71
+ close(): Promise<void>;
72
+ }
@@ -0,0 +1,375 @@
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) 2025 Databricks Contributors
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ const IDBSQLLogger_1 = require("../contracts/IDBSQLLogger");
19
+ const types_1 = require("./types");
20
+ /**
21
+ * Aggregates telemetry events by statement_id and manages batching/flushing.
22
+ *
23
+ * Overflow policy — when the pending buffer hits `maxPendingMetrics`, error
24
+ * metrics are preserved preferentially over connection/statement metrics.
25
+ * The first-failure error is usually the most valuable signal in post-mortem
26
+ * debugging; dropping it FIFO would defeat the purpose of capture.
27
+ */
28
+ class MetricsAggregator {
29
+ constructor(context, exporter) {
30
+ var _a, _b, _c, _d, _e;
31
+ this.context = context;
32
+ this.exporter = exporter;
33
+ this.statementMetrics = new Map();
34
+ this.pendingMetrics = [];
35
+ this.flushTimer = null;
36
+ this.closed = false;
37
+ this.closing = false;
38
+ try {
39
+ const config = context.getConfig();
40
+ this.batchSize = (_a = config.telemetryBatchSize) !== null && _a !== void 0 ? _a : types_1.DEFAULT_TELEMETRY_CONFIG.batchSize;
41
+ this.flushIntervalMs = (_b = config.telemetryFlushIntervalMs) !== null && _b !== void 0 ? _b : types_1.DEFAULT_TELEMETRY_CONFIG.flushIntervalMs;
42
+ this.maxPendingMetrics = (_c = config.telemetryMaxPendingMetrics) !== null && _c !== void 0 ? _c : types_1.DEFAULT_TELEMETRY_CONFIG.maxPendingMetrics;
43
+ this.maxErrorsPerStatement =
44
+ (_d = config.telemetryMaxErrorsPerStatement) !== null && _d !== void 0 ? _d : types_1.DEFAULT_TELEMETRY_CONFIG.maxErrorsPerStatement;
45
+ this.statementTtlMs = (_e = config.telemetryStatementTtlMs) !== null && _e !== void 0 ? _e : types_1.DEFAULT_TELEMETRY_CONFIG.statementTtlMs;
46
+ this.startFlushTimer();
47
+ }
48
+ catch (error) {
49
+ const logger = this.context.getLogger();
50
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `MetricsAggregator constructor error: ${error.message}`);
51
+ this.batchSize = types_1.DEFAULT_TELEMETRY_CONFIG.batchSize;
52
+ this.flushIntervalMs = types_1.DEFAULT_TELEMETRY_CONFIG.flushIntervalMs;
53
+ this.maxPendingMetrics = types_1.DEFAULT_TELEMETRY_CONFIG.maxPendingMetrics;
54
+ this.maxErrorsPerStatement = types_1.DEFAULT_TELEMETRY_CONFIG.maxErrorsPerStatement;
55
+ this.statementTtlMs = types_1.DEFAULT_TELEMETRY_CONFIG.statementTtlMs;
56
+ }
57
+ }
58
+ processEvent(event) {
59
+ if (this.closed)
60
+ return;
61
+ const logger = this.context.getLogger();
62
+ try {
63
+ if (event.eventType === types_1.TelemetryEventType.CONNECTION_OPEN) {
64
+ this.processConnectionEvent(event);
65
+ return;
66
+ }
67
+ if (event.eventType === types_1.TelemetryEventType.ERROR) {
68
+ this.processErrorEvent(event);
69
+ return;
70
+ }
71
+ if (event.statementId) {
72
+ this.processStatementEvent(event);
73
+ }
74
+ }
75
+ catch (error) {
76
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `MetricsAggregator.processEvent error: ${error.message}`);
77
+ }
78
+ }
79
+ processConnectionEvent(event) {
80
+ const metric = {
81
+ metricType: 'connection',
82
+ timestamp: event.timestamp,
83
+ sessionId: event.sessionId,
84
+ workspaceId: event.workspaceId,
85
+ driverConfig: event.driverConfig,
86
+ };
87
+ this.addPendingMetric(metric);
88
+ }
89
+ processErrorEvent(event) {
90
+ const logger = this.context.getLogger();
91
+ // `isTerminal` is carried on the event by the emitter (it knows the
92
+ // call site's taxonomy). If callers ever drop it we default to
93
+ // retryable — buffering by statement is the safer choice.
94
+ const isTerminal = event.isTerminal === true;
95
+ if (isTerminal) {
96
+ logger.log(IDBSQLLogger_1.LogLevel.debug, 'Terminal error detected - flushing immediately');
97
+ if (event.statementId && this.statementMetrics.has(event.statementId)) {
98
+ const details = this.statementMetrics.get(event.statementId);
99
+ this.pushBoundedError(details, event);
100
+ this.completeStatement(event.statementId);
101
+ }
102
+ else {
103
+ const metric = {
104
+ metricType: 'error',
105
+ timestamp: event.timestamp,
106
+ sessionId: event.sessionId,
107
+ statementId: event.statementId,
108
+ workspaceId: event.workspaceId,
109
+ errorName: event.errorName,
110
+ errorMessage: event.errorMessage,
111
+ errorStack: event.errorStack,
112
+ };
113
+ this.addPendingMetric(metric);
114
+ }
115
+ // Fire-and-forget on the terminal-error path so customer code doesn't
116
+ // stall on telemetry HTTP. Do NOT reset the periodic flush timer:
117
+ // under burst failures that would keep the tail-drain timer from
118
+ // ever firing.
119
+ Promise.resolve(this.flush(false)).catch((err) => {
120
+ var _a;
121
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Terminal-error flush failed: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);
122
+ });
123
+ }
124
+ else if (event.statementId) {
125
+ const details = this.getOrCreateStatementDetails(event);
126
+ this.pushBoundedError(details, event);
127
+ }
128
+ }
129
+ pushBoundedError(details, event) {
130
+ if (details.errors.length >= this.maxErrorsPerStatement) {
131
+ details.errors.shift();
132
+ }
133
+ details.errors.push(event);
134
+ }
135
+ processStatementEvent(event) {
136
+ var _a, _b, _c, _d;
137
+ const details = this.getOrCreateStatementDetails(event);
138
+ switch (event.eventType) {
139
+ case types_1.TelemetryEventType.STATEMENT_START:
140
+ details.operationType = event.operationType;
141
+ details.startTime = event.timestamp;
142
+ break;
143
+ case types_1.TelemetryEventType.STATEMENT_COMPLETE:
144
+ details.executionLatencyMs = event.latencyMs;
145
+ details.resultFormat = event.resultFormat;
146
+ details.chunkCount = (_a = event.chunkCount) !== null && _a !== void 0 ? _a : 0;
147
+ details.bytesDownloaded = (_b = event.bytesDownloaded) !== null && _b !== void 0 ? _b : 0;
148
+ details.pollCount = (_c = event.pollCount) !== null && _c !== void 0 ? _c : 0;
149
+ break;
150
+ case types_1.TelemetryEventType.CLOUDFETCH_CHUNK:
151
+ details.chunkCount += 1;
152
+ details.bytesDownloaded += (_d = event.bytes) !== null && _d !== void 0 ? _d : 0;
153
+ if (event.compressed !== undefined) {
154
+ details.compressionEnabled = event.compressed;
155
+ }
156
+ break;
157
+ default:
158
+ break;
159
+ }
160
+ }
161
+ getOrCreateStatementDetails(event) {
162
+ const statementId = event.statementId;
163
+ if (!this.statementMetrics.has(statementId)) {
164
+ this.statementMetrics.set(statementId, {
165
+ statementId,
166
+ sessionId: event.sessionId,
167
+ workspaceId: event.workspaceId,
168
+ startTime: event.timestamp,
169
+ chunkCount: 0,
170
+ bytesDownloaded: 0,
171
+ pollCount: 0,
172
+ errors: [],
173
+ });
174
+ }
175
+ return this.statementMetrics.get(statementId);
176
+ }
177
+ /**
178
+ * Drop entries older than `statementTtlMs`, emitting their buffered error
179
+ * events as standalone metrics first so the first-failure signal survives
180
+ * the eviction. Called from the periodic flush timer so idle clients
181
+ * don't leak orphan entries.
182
+ */
183
+ evictExpiredStatements() {
184
+ const cutoff = Date.now() - this.statementTtlMs;
185
+ let evicted = 0;
186
+ for (const [id, details] of this.statementMetrics) {
187
+ if (details.startTime < cutoff) {
188
+ for (const errorEvent of details.errors) {
189
+ this.addPendingMetric({
190
+ metricType: 'error',
191
+ timestamp: errorEvent.timestamp,
192
+ sessionId: details.sessionId,
193
+ statementId: details.statementId,
194
+ workspaceId: details.workspaceId,
195
+ errorName: errorEvent.errorName,
196
+ errorMessage: errorEvent.errorMessage,
197
+ errorStack: errorEvent.errorStack,
198
+ });
199
+ }
200
+ this.statementMetrics.delete(id);
201
+ evicted += 1;
202
+ }
203
+ }
204
+ if (evicted > 0) {
205
+ this.context
206
+ .getLogger()
207
+ .log(IDBSQLLogger_1.LogLevel.debug, `Evicted ${evicted} abandoned statement(s) past ${this.statementTtlMs}ms TTL`);
208
+ }
209
+ }
210
+ completeStatement(statementId) {
211
+ if (this.closed)
212
+ return;
213
+ const logger = this.context.getLogger();
214
+ try {
215
+ const details = this.statementMetrics.get(statementId);
216
+ if (!details) {
217
+ return;
218
+ }
219
+ const metric = {
220
+ metricType: 'statement',
221
+ timestamp: details.startTime,
222
+ sessionId: details.sessionId,
223
+ statementId: details.statementId,
224
+ workspaceId: details.workspaceId,
225
+ latencyMs: details.executionLatencyMs,
226
+ resultFormat: details.resultFormat,
227
+ chunkCount: details.chunkCount,
228
+ bytesDownloaded: details.bytesDownloaded,
229
+ pollCount: details.pollCount,
230
+ };
231
+ this.addPendingMetric(metric);
232
+ for (const errorEvent of details.errors) {
233
+ const errorMetric = {
234
+ metricType: 'error',
235
+ timestamp: errorEvent.timestamp,
236
+ sessionId: details.sessionId,
237
+ statementId: details.statementId,
238
+ workspaceId: details.workspaceId,
239
+ errorName: errorEvent.errorName,
240
+ errorMessage: errorEvent.errorMessage,
241
+ errorStack: errorEvent.errorStack,
242
+ };
243
+ this.addPendingMetric(errorMetric);
244
+ }
245
+ this.statementMetrics.delete(statementId);
246
+ }
247
+ catch (error) {
248
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `MetricsAggregator.completeStatement error: ${error.message}`);
249
+ }
250
+ }
251
+ /**
252
+ * Append `metric` to the pending buffer, enforcing `maxPendingMetrics`.
253
+ *
254
+ * Overflow drops the oldest non-error entry (single `splice` — no new
255
+ * allocation). Under an all-error buffer it falls back to dropping the
256
+ * oldest entry at index 0.
257
+ */
258
+ addPendingMetric(metric) {
259
+ if (this.closed)
260
+ return;
261
+ this.pendingMetrics.push(metric);
262
+ if (this.pendingMetrics.length > this.maxPendingMetrics) {
263
+ const dropIndex = this.findDropIndex();
264
+ this.pendingMetrics.splice(dropIndex, 1);
265
+ const logger = this.context.getLogger();
266
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Dropped 1 oldest non-error telemetry metric (buffer full at ${this.maxPendingMetrics})`);
267
+ }
268
+ if (this.pendingMetrics.length >= this.batchSize && !this.closing) {
269
+ // resetTimer=false so the periodic tail-drain keeps its cadence even
270
+ // under sustained batch-size bursts.
271
+ const logger = this.context.getLogger();
272
+ Promise.resolve(this.flush(false)).catch((err) => {
273
+ var _a;
274
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Batch-trigger flush failed: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);
275
+ });
276
+ }
277
+ }
278
+ findDropIndex() {
279
+ for (let i = 0; i < this.pendingMetrics.length; i += 1) {
280
+ if (this.pendingMetrics[i].metricType !== 'error') {
281
+ return i;
282
+ }
283
+ }
284
+ return 0;
285
+ }
286
+ /**
287
+ * Drain the pending buffer and return a promise that resolves when the
288
+ * exporter finishes with the drained batch. `close()` awaits this so
289
+ * `process.exit()` after `client.close()` doesn't truncate the POST.
290
+ */
291
+ async flush(resetTimer = true) {
292
+ var _a;
293
+ const logger = this.context.getLogger();
294
+ let exportPromise = null;
295
+ try {
296
+ if (this.pendingMetrics.length === 0) {
297
+ if (resetTimer && !this.closed) {
298
+ this.startFlushTimer();
299
+ }
300
+ return;
301
+ }
302
+ const metricsToExport = this.pendingMetrics;
303
+ this.pendingMetrics = [];
304
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Flushing ${metricsToExport.length} telemetry metrics`);
305
+ exportPromise = this.exporter.export(metricsToExport);
306
+ if (resetTimer && !this.closed) {
307
+ this.startFlushTimer();
308
+ }
309
+ }
310
+ catch (error) {
311
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `MetricsAggregator.flush error: ${error.message}`);
312
+ }
313
+ if (exportPromise) {
314
+ try {
315
+ await exportPromise;
316
+ }
317
+ catch (err) {
318
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Unexpected export error: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);
319
+ }
320
+ }
321
+ }
322
+ startFlushTimer() {
323
+ if (this.closed)
324
+ return;
325
+ const logger = this.context.getLogger();
326
+ try {
327
+ if (this.flushTimer) {
328
+ clearInterval(this.flushTimer);
329
+ }
330
+ this.flushTimer = setInterval(() => {
331
+ var _a;
332
+ // Idle eviction: run before the flush so orphan-error metrics have
333
+ // a chance to batch into this drain rather than wait for the next.
334
+ try {
335
+ this.evictExpiredStatements();
336
+ }
337
+ catch (err) {
338
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `evictExpiredStatements error: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);
339
+ }
340
+ Promise.resolve(this.flush(false)).catch((err) => {
341
+ var _a;
342
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `Periodic flush failed: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : err}`);
343
+ });
344
+ }, this.flushIntervalMs);
345
+ this.flushTimer.unref();
346
+ }
347
+ catch (error) {
348
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `MetricsAggregator.startFlushTimer error: ${error.message}`);
349
+ }
350
+ }
351
+ async close() {
352
+ const logger = this.context.getLogger();
353
+ try {
354
+ // Suppress batch-triggered fire-and-forget flushes from addPendingMetric
355
+ // so no promises escape past the single awaited flush below.
356
+ this.closing = true;
357
+ if (this.flushTimer) {
358
+ clearInterval(this.flushTimer);
359
+ this.flushTimer = null;
360
+ }
361
+ // closed is still false here so completeStatement → addPendingMetric works normally.
362
+ const remainingStatements = [...this.statementMetrics.keys()];
363
+ for (const statementId of remainingStatements) {
364
+ this.completeStatement(statementId);
365
+ }
366
+ this.closed = true;
367
+ await this.flush(false);
368
+ }
369
+ catch (error) {
370
+ logger.log(IDBSQLLogger_1.LogLevel.debug, `MetricsAggregator.close error: ${error.message}`);
371
+ }
372
+ }
373
+ }
374
+ exports.default = MetricsAggregator;
375
+ //# sourceMappingURL=MetricsAggregator.js.map