@google-cloud/spanner 8.13.0 → 9.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -16
- package/build/src/batch-transaction.js +15 -12
- package/build/src/codec.d.ts +18 -30
- package/build/src/codec.js +197 -79
- package/build/src/common.d.ts +14 -0
- package/build/src/common.js +28 -3
- package/build/src/database.d.ts +31 -41
- package/build/src/database.js +147 -315
- package/build/src/helper.d.ts +12 -0
- package/build/src/helper.js +44 -0
- package/build/src/index.d.ts +24 -8
- package/build/src/index.js +303 -147
- package/build/src/instance.d.ts +15 -2
- package/build/src/instance.js +11 -2
- package/build/src/instrument.d.ts +12 -1
- package/build/src/instrument.js +13 -0
- package/build/src/metrics/constants.d.ts +13 -6
- package/build/src/metrics/constants.js +24 -14
- package/build/src/metrics/external-types.d.ts +14 -0
- package/build/src/metrics/interceptor.js +39 -44
- package/build/src/metrics/metrics-tracer-factory.d.ts +25 -14
- package/build/src/metrics/metrics-tracer-factory.js +119 -78
- package/build/src/metrics/metrics-tracer.d.ts +19 -6
- package/build/src/metrics/metrics-tracer.js +147 -55
- package/build/src/metrics/spanner-metrics-exporter.js +4 -0
- package/build/src/metrics/transform.d.ts +3 -4
- package/build/src/metrics/transform.js +16 -10
- package/build/src/multiplexed-session.d.ts +26 -2
- package/build/src/multiplexed-session.js +39 -11
- package/build/src/partial-result-stream.d.ts +26 -33
- package/build/src/partial-result-stream.js +263 -283
- package/build/src/request-stream-coordinator.d.ts +88 -0
- package/build/src/request-stream-coordinator.js +229 -0
- package/build/src/request_id_header.d.ts +6 -4
- package/build/src/request_id_header.js +24 -24
- package/build/src/session-factory.d.ts +62 -60
- package/build/src/session-factory.js +46 -86
- package/build/src/session-pool.d.ts +97 -227
- package/build/src/session-pool.js +74 -547
- package/build/src/session.js +1 -1
- package/build/src/transaction-runner.js +1 -12
- package/build/src/transaction.d.ts +21 -5
- package/build/src/transaction.js +107 -136
- package/package.json +28 -37
|
@@ -15,9 +15,8 @@
|
|
|
15
15
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
16
16
|
exports.MetricsTracer = void 0;
|
|
17
17
|
const grpc_js_1 = require("@grpc/grpc-js");
|
|
18
|
-
const metrics_tracer_factory_1 = require("./metrics-tracer-factory");
|
|
19
18
|
const constants_1 = require("./constants");
|
|
20
|
-
const
|
|
19
|
+
const common_1 = require("../common");
|
|
21
20
|
/**
|
|
22
21
|
* MetricAttemptTracer tracks the start time and status of a single gRPC attempt.
|
|
23
22
|
*
|
|
@@ -93,6 +92,76 @@ class MetricOperationTracer {
|
|
|
93
92
|
this._currentAttempt = new MetricAttemptTracer();
|
|
94
93
|
}
|
|
95
94
|
}
|
|
95
|
+
const GFE_METRIC_PREFIX = 'gfet4t7; dur=';
|
|
96
|
+
const AFE_METRIC_PREFIX = 'afe; dur=';
|
|
97
|
+
/**
|
|
98
|
+
* Checks whether a character code represents an entry delimiter or whitespace in a
|
|
99
|
+
* 'server-timing' header (start of string, space, comma, or tab).
|
|
100
|
+
*
|
|
101
|
+
* @param charCode The character code to check.
|
|
102
|
+
* @returns True if the character code is a valid entry separator or whitespace.
|
|
103
|
+
*/
|
|
104
|
+
function isEntryDelimiter(charCode) {
|
|
105
|
+
return (charCode === 32 /* ' ' */ ||
|
|
106
|
+
charCode === 44 /* ',' */ ||
|
|
107
|
+
charCode === 9 /* '\t' */);
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Parses consecutive ASCII digit characters into an integer starting from the given index.
|
|
111
|
+
* Returns null if the character at startIndex is not a digit (e.g. non-numeric, negative, or empty).
|
|
112
|
+
* Parsing stops at the first non-digit (e.g. ',', ';', or decimal point), matching the legacy
|
|
113
|
+
* regex `([0-9]+)` behavior without intermediate string slice allocations.
|
|
114
|
+
*
|
|
115
|
+
* @param header The 'server-timing' header string.
|
|
116
|
+
* @param startIndex The index where numeric digits are expected to begin.
|
|
117
|
+
* @returns The parsed non-negative integer, or null if no valid digits were found.
|
|
118
|
+
*/
|
|
119
|
+
function parseConsecutiveDigits(header, startIndex) {
|
|
120
|
+
if (startIndex >= header.length) {
|
|
121
|
+
return null;
|
|
122
|
+
}
|
|
123
|
+
const firstCharCode = header.charCodeAt(startIndex);
|
|
124
|
+
if (firstCharCode < 48 || firstCharCode > 57) {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
let value = firstCharCode - 48;
|
|
128
|
+
for (let index = startIndex + 1; index < header.length; index++) {
|
|
129
|
+
const code = header.charCodeAt(index);
|
|
130
|
+
if (code >= 48 && code <= 57) {
|
|
131
|
+
value = value * 10 + (code - 48);
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return value;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Extracts a numeric latency value in milliseconds for a given metric prefix from a
|
|
141
|
+
* 'server-timing' header string without regex allocations or intermediate substring slices.
|
|
142
|
+
*
|
|
143
|
+
* @param header The 'server-timing' header string.
|
|
144
|
+
* @param prefix The metric prefix (e.g. 'gfet4t7; dur=').
|
|
145
|
+
* @returns The extracted latency in milliseconds, or null if not found.
|
|
146
|
+
*/
|
|
147
|
+
function extractServerTimingLatency(header, prefix) {
|
|
148
|
+
if (!header || typeof header !== 'string') {
|
|
149
|
+
return null;
|
|
150
|
+
}
|
|
151
|
+
let prefixIndex = header.indexOf(prefix);
|
|
152
|
+
while (prefixIndex !== -1) {
|
|
153
|
+
// Ensure prefix is not part of a longer metric name (e.g., 'safe; dur=' matching 'afe; dur=')
|
|
154
|
+
if (prefixIndex === 0 ||
|
|
155
|
+
isEntryDelimiter(header.charCodeAt(prefixIndex - 1))) {
|
|
156
|
+
const latency = parseConsecutiveDigits(header, prefixIndex + prefix.length);
|
|
157
|
+
if (latency !== null) {
|
|
158
|
+
return latency;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
prefixIndex = header.indexOf(prefix, prefixIndex + 1);
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
96
165
|
/**
|
|
97
166
|
* MetricsTracer is responsible for recording and managing metrics related to
|
|
98
167
|
* gRPC Spanner operations and attempts counters, and latencies,
|
|
@@ -126,6 +195,11 @@ class MetricsTracer {
|
|
|
126
195
|
* Stores client and resource attributes for labeling metrics.
|
|
127
196
|
*/
|
|
128
197
|
_clientAttributes = {};
|
|
198
|
+
/**
|
|
199
|
+
* Cached OTel attribute objects keyed by status name, avoiding repeated
|
|
200
|
+
* object allocations on every metric recording call.
|
|
201
|
+
*/
|
|
202
|
+
_attributesByStatus;
|
|
129
203
|
/*
|
|
130
204
|
* The current GFE latency associated with this tracer.
|
|
131
205
|
*/
|
|
@@ -147,7 +221,7 @@ class MetricsTracer {
|
|
|
147
221
|
* @param _instrumentAfeLatency Histogram for AFE latency metrics.
|
|
148
222
|
* @param enabled Whether metrics recording is enabled.
|
|
149
223
|
*/
|
|
150
|
-
constructor(_instrumentAttemptCounter, _instrumentAttemptLatency, _instrumentOperationCounter, _instrumentOperationLatency, _instrumentGfeConnectivityErrorCount, _instrumentGfeLatency, _instrumentAfeConnectivityErrorCount, _instrumentAfeLatency, enabled, _database, _instance, _projectId, _methodName, _request) {
|
|
224
|
+
constructor(_instrumentAttemptCounter, _instrumentAttemptLatency, _instrumentOperationCounter, _instrumentOperationLatency, _instrumentGfeConnectivityErrorCount, _instrumentGfeLatency, _instrumentAfeConnectivityErrorCount, _instrumentAfeLatency, enabled, _database, _instance, _projectId, _methodName, _request, attributesCache) {
|
|
151
225
|
this._instrumentAttemptCounter = _instrumentAttemptCounter;
|
|
152
226
|
this._instrumentAttemptLatency = _instrumentAttemptLatency;
|
|
153
227
|
this._instrumentOperationCounter = _instrumentOperationCounter;
|
|
@@ -165,6 +239,8 @@ class MetricsTracer {
|
|
|
165
239
|
this._clientAttributes[constants_1.METRIC_LABEL_KEY_DATABASE] = _database;
|
|
166
240
|
this._clientAttributes[constants_1.METRIC_LABEL_KEY_METHOD] = _methodName;
|
|
167
241
|
this._clientAttributes[constants_1.MONITORED_RES_LABEL_KEY_INSTANCE] = _instance;
|
|
242
|
+
this._attributesByStatus =
|
|
243
|
+
attributesCache ?? new Map();
|
|
168
244
|
}
|
|
169
245
|
/**
|
|
170
246
|
* Returns the difference in milliseconds between two times.
|
|
@@ -210,7 +286,7 @@ class MetricsTracer {
|
|
|
210
286
|
* Increments the attempt count and creates a new MetricAttemptTracer.
|
|
211
287
|
*/
|
|
212
288
|
recordAttemptStart() {
|
|
213
|
-
if (!this.enabled)
|
|
289
|
+
if (!this.enabled || !this.currentOperation)
|
|
214
290
|
return;
|
|
215
291
|
this.currentOperation.createNewAttempt();
|
|
216
292
|
}
|
|
@@ -220,12 +296,13 @@ class MetricsTracer {
|
|
|
220
296
|
* @param status The status code of the attempt (default: Status.OK).
|
|
221
297
|
*/
|
|
222
298
|
recordAttemptCompletion(statusCode = grpc_js_1.status.OK) {
|
|
223
|
-
if (!this.enabled)
|
|
299
|
+
if (!this.enabled || !this.currentOperation?.currentAttempt)
|
|
224
300
|
return;
|
|
225
|
-
this.currentOperation.currentAttempt
|
|
301
|
+
const currentAttempt = this.currentOperation.currentAttempt;
|
|
302
|
+
currentAttempt.status = grpc_js_1.status[statusCode] ?? grpc_js_1.status[grpc_js_1.status.UNKNOWN];
|
|
226
303
|
const attemptAttributes = this._createAttemptOtelAttributes();
|
|
227
304
|
const endTime = performance.now();
|
|
228
|
-
const attemptLatencyMilliseconds = this._getMillisecondTimeDifference(
|
|
305
|
+
const attemptLatencyMilliseconds = this._getMillisecondTimeDifference(currentAttempt.startTime, endTime);
|
|
229
306
|
this.instrumentAttemptLatency?.record(attemptLatencyMilliseconds, attemptAttributes);
|
|
230
307
|
this.instrumentAttemptCounter?.add(1, attemptAttributes);
|
|
231
308
|
}
|
|
@@ -252,7 +329,7 @@ class MetricsTracer {
|
|
|
252
329
|
const operationLatencyMilliseconds = this._getMillisecondTimeDifference(this.currentOperation.startTime, endTime);
|
|
253
330
|
this.instrumentOperationCounter?.add(1, operationAttributes);
|
|
254
331
|
this.instrumentOperationLatency?.record(operationLatencyMilliseconds, operationAttributes);
|
|
255
|
-
|
|
332
|
+
this.currentOperation = null;
|
|
256
333
|
}
|
|
257
334
|
/**
|
|
258
335
|
* Extracts the GFE latency value (in milliseconds) from a 'server-timing' header string.
|
|
@@ -262,13 +339,7 @@ class MetricsTracer {
|
|
|
262
339
|
* @returns The extracted GFE latency in milliseconds, or null if not found.
|
|
263
340
|
*/
|
|
264
341
|
extractGfeLatency(header) {
|
|
265
|
-
|
|
266
|
-
if (header === undefined)
|
|
267
|
-
return null;
|
|
268
|
-
const match = header.match(regex);
|
|
269
|
-
if (!match)
|
|
270
|
-
return null;
|
|
271
|
-
return Number(match[1]);
|
|
342
|
+
return extractServerTimingLatency(header, GFE_METRIC_PREFIX);
|
|
272
343
|
}
|
|
273
344
|
/**
|
|
274
345
|
* Extracts the AFE latency value (in milliseconds) from a 'server-timing' header string.
|
|
@@ -278,66 +349,91 @@ class MetricsTracer {
|
|
|
278
349
|
* @returns The extracted AFE latency in milliseconds, or null if not found.
|
|
279
350
|
*/
|
|
280
351
|
extractAfeLatency(header) {
|
|
281
|
-
if (!
|
|
352
|
+
if (!(0, common_1.isAFEServerTimingEnabled)())
|
|
282
353
|
return null;
|
|
283
|
-
|
|
284
|
-
if (header === undefined)
|
|
285
|
-
return null;
|
|
286
|
-
const match = header.match(regex);
|
|
287
|
-
if (!match)
|
|
288
|
-
return null;
|
|
289
|
-
return Number(match[1]);
|
|
354
|
+
return extractServerTimingLatency(header, AFE_METRIC_PREFIX);
|
|
290
355
|
}
|
|
291
356
|
/**
|
|
292
|
-
*
|
|
293
|
-
*
|
|
357
|
+
* Returns a cached set of OTEL attributes for the given status, avoiding
|
|
358
|
+
* repeated object cloning on every metric record/add call.
|
|
359
|
+
*
|
|
360
|
+
* @param status Optional status code (as numeric Status enum or status name string).
|
|
361
|
+
* @returns The cached attributes object.
|
|
362
|
+
*/
|
|
363
|
+
_getAttributesForStatus(status) {
|
|
364
|
+
const statusString = typeof status === 'number'
|
|
365
|
+
? (grpc_js_1.status[status] ?? grpc_js_1.status[grpc_js_1.status.UNKNOWN])
|
|
366
|
+
: typeof status === 'string'
|
|
367
|
+
? status
|
|
368
|
+
: undefined;
|
|
369
|
+
const cacheKey = statusString ?? '';
|
|
370
|
+
let attributes = this._attributesByStatus.get(cacheKey);
|
|
371
|
+
if (!attributes) {
|
|
372
|
+
const newAttributes = { ...this._clientAttributes };
|
|
373
|
+
if (statusString !== undefined) {
|
|
374
|
+
newAttributes[constants_1.METRIC_LABEL_KEY_STATUS] = statusString;
|
|
375
|
+
}
|
|
376
|
+
attributes = Object.freeze(newAttributes);
|
|
377
|
+
this._attributesByStatus.set(cacheKey, attributes);
|
|
378
|
+
}
|
|
379
|
+
return attributes;
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Records the GFE latency for this attempt.
|
|
383
|
+
* @param statusCode The gRPC status code of the attempt.
|
|
294
384
|
*/
|
|
295
385
|
recordGfeLatency(statusCode) {
|
|
296
|
-
if (!this.enabled)
|
|
386
|
+
if (!this.enabled || !this._instrumentGfeLatency)
|
|
297
387
|
return;
|
|
298
|
-
if (
|
|
388
|
+
if (typeof this.gfeLatency !== 'number' ||
|
|
389
|
+
!Number.isFinite(this.gfeLatency) ||
|
|
390
|
+
this.gfeLatency < 0) {
|
|
299
391
|
console.error('ERROR: Attempted to record GFE metric with no latency value.');
|
|
300
392
|
return;
|
|
301
393
|
}
|
|
302
|
-
const attributes =
|
|
303
|
-
|
|
304
|
-
this._instrumentGfeLatency?.record(this.gfeLatency, attributes);
|
|
394
|
+
const attributes = this._getAttributesForStatus(statusCode);
|
|
395
|
+
this._instrumentGfeLatency.record(this.gfeLatency, attributes);
|
|
305
396
|
this.gfeLatency = null; // Reset latency value
|
|
306
397
|
}
|
|
307
398
|
/**
|
|
308
399
|
* Increments the GFE connectivity error count metric.
|
|
309
400
|
*/
|
|
310
401
|
recordGfeConnectivityErrorCount(statusCode) {
|
|
311
|
-
if (!this.enabled)
|
|
402
|
+
if (!this.enabled || !this._instrumentGfeConnectivityErrorCount)
|
|
312
403
|
return;
|
|
313
|
-
const attributes =
|
|
314
|
-
|
|
315
|
-
this._instrumentGfeConnectivityErrorCount?.add(1, attributes);
|
|
404
|
+
const attributes = this._getAttributesForStatus(statusCode);
|
|
405
|
+
this._instrumentGfeConnectivityErrorCount.add(1, attributes);
|
|
316
406
|
}
|
|
317
407
|
/**
|
|
318
408
|
* Increments the AFE connectivity error count metric.
|
|
319
409
|
*/
|
|
320
410
|
recordAfeConnectivityErrorCount(statusCode) {
|
|
321
|
-
if (!this.enabled ||
|
|
411
|
+
if (!this.enabled ||
|
|
412
|
+
!this._instrumentAfeConnectivityErrorCount ||
|
|
413
|
+
!(0, common_1.isAFEServerTimingEnabled)()) {
|
|
322
414
|
return;
|
|
323
|
-
|
|
324
|
-
attributes
|
|
325
|
-
this._instrumentAfeConnectivityErrorCount
|
|
415
|
+
}
|
|
416
|
+
const attributes = this._getAttributesForStatus(statusCode);
|
|
417
|
+
this._instrumentAfeConnectivityErrorCount.add(1, attributes);
|
|
326
418
|
}
|
|
327
419
|
/**
|
|
328
|
-
* Records the
|
|
329
|
-
* @param
|
|
420
|
+
* Records the AFE latency for this attempt.
|
|
421
|
+
* @param statusCode The gRPC status code of the attempt.
|
|
330
422
|
*/
|
|
331
423
|
recordAfeLatency(statusCode) {
|
|
332
|
-
if (!this.enabled ||
|
|
424
|
+
if (!this.enabled ||
|
|
425
|
+
!this._instrumentAfeLatency ||
|
|
426
|
+
!(0, common_1.isAFEServerTimingEnabled)()) {
|
|
333
427
|
return;
|
|
334
|
-
|
|
428
|
+
}
|
|
429
|
+
if (typeof this.afeLatency !== 'number' ||
|
|
430
|
+
!Number.isFinite(this.afeLatency) ||
|
|
431
|
+
this.afeLatency < 0) {
|
|
335
432
|
console.error('ERROR: Attempted to record AFE metric with no latency value.');
|
|
336
433
|
return;
|
|
337
434
|
}
|
|
338
|
-
const attributes =
|
|
339
|
-
|
|
340
|
-
this._instrumentAfeLatency?.record(this.afeLatency, attributes);
|
|
435
|
+
const attributes = this._getAttributesForStatus(statusCode);
|
|
436
|
+
this._instrumentAfeLatency.record(this.afeLatency, attributes);
|
|
341
437
|
this.afeLatency = null; // Reset latency value
|
|
342
438
|
}
|
|
343
439
|
/**
|
|
@@ -347,10 +443,8 @@ class MetricsTracer {
|
|
|
347
443
|
_createOperationOtelAttributes() {
|
|
348
444
|
if (!this.enabled)
|
|
349
445
|
return {};
|
|
350
|
-
const
|
|
351
|
-
|
|
352
|
-
this.currentOperation.currentAttempt?.status ?? grpc_js_1.status[grpc_js_1.status.UNKNOWN];
|
|
353
|
-
return attributes;
|
|
446
|
+
const status = this.currentOperation?.currentAttempt?.status ?? grpc_js_1.status[grpc_js_1.status.UNKNOWN];
|
|
447
|
+
return this._getAttributesForStatus(status);
|
|
354
448
|
}
|
|
355
449
|
/**
|
|
356
450
|
* Creates and returns a set of OTEL attributes for attempt-level metrics.
|
|
@@ -361,12 +455,10 @@ class MetricsTracer {
|
|
|
361
455
|
_createAttemptOtelAttributes() {
|
|
362
456
|
if (!this.enabled)
|
|
363
457
|
return {};
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
this.currentOperation.currentAttempt.status;
|
|
369
|
-
return attributes;
|
|
458
|
+
if (!this.currentOperation?.currentAttempt) {
|
|
459
|
+
return this._getAttributesForStatus();
|
|
460
|
+
}
|
|
461
|
+
return this._getAttributesForStatus(this.currentOperation.currentAttempt.status);
|
|
370
462
|
}
|
|
371
463
|
}
|
|
372
464
|
exports.MetricsTracer = MetricsTracer;
|
|
@@ -47,6 +47,7 @@ class CloudMonitoringMetricsExporter {
|
|
|
47
47
|
const now = new Date();
|
|
48
48
|
if (now.getTime() - this._lastExported.getTime() <=
|
|
49
49
|
constants_1.MIN_EXPORT_FREQUENCY_MS) {
|
|
50
|
+
resultCallback({ code: core_1.ExportResultCode.SUCCESS });
|
|
50
51
|
return;
|
|
51
52
|
}
|
|
52
53
|
this._lastExported = now;
|
|
@@ -66,6 +67,9 @@ class CloudMonitoringMetricsExporter {
|
|
|
66
67
|
* @param resourceMetrics Metrics to be sent to the Google Cloud Monitoring backend
|
|
67
68
|
*/
|
|
68
69
|
async _exportAsync(resourceMetrics) {
|
|
70
|
+
if (resourceMetrics?.resource?.asyncAttributesPending) {
|
|
71
|
+
await resourceMetrics.resource.waitForAsyncAttributes?.();
|
|
72
|
+
}
|
|
69
73
|
const timeSeriesList = (0, transform_1.transformResourceMetricToTimeSeriesArray)(resourceMetrics, this._projectId);
|
|
70
74
|
let failure = {
|
|
71
75
|
sendFailed: false,
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { MetricData, DataPoint, ResourceMetrics } from '@opentelemetry/sdk-metrics';
|
|
2
2
|
import { Resource } from '@opentelemetry/resources';
|
|
3
|
-
import { MonitoredResource } from '
|
|
4
|
-
import { MetricKind, ValueType } from './external-types';
|
|
3
|
+
import { MetricKind, MonitoredResource, ValueType } from './external-types';
|
|
5
4
|
/** Transforms a OpenTelemetry instrument type to a GCM MetricKind. */
|
|
6
5
|
declare function _transformMetricKind(metric: MetricData): MetricKind;
|
|
7
6
|
/** Transforms resource to Google Cloud Monitoring monitored resource */
|
|
@@ -120,8 +119,8 @@ declare function _transformPoint<T>(metric: MetricData, dataPoint: DataPoint<T>)
|
|
|
120
119
|
startTime?: undefined;
|
|
121
120
|
};
|
|
122
121
|
};
|
|
123
|
-
/** Extracts metric and monitored resource labels from data point */
|
|
124
|
-
declare function _extractLabels<T>({ attributes }: DataPoint<T> | Resource, projectId: string): {
|
|
122
|
+
/** Extracts metric and monitored resource labels from data point or resource */
|
|
123
|
+
declare function _extractLabels<T>({ attributes }: DataPoint<T> | Resource, projectId: string, isResource?: boolean): {
|
|
125
124
|
metricLabels: {};
|
|
126
125
|
monitoredResourceLabels: {};
|
|
127
126
|
};
|
|
@@ -83,9 +83,9 @@ function transformResourceMetricToTimeSeriesArray(resourceMetrics, projectId) {
|
|
|
83
83
|
function _createTimeSeries(metric, dataPoint, resource, projectId) {
|
|
84
84
|
const type = path.posix.join(constants_1.CLIENT_METRICS_PREFIX, metric.descriptor.name);
|
|
85
85
|
const resourceLabels = resource
|
|
86
|
-
? _extractLabels(resource, projectId)
|
|
86
|
+
? _extractLabels(resource, projectId, true)
|
|
87
87
|
: { metricLabels: {}, monitoredResourceLabels: {} };
|
|
88
|
-
const dataLabels = _extractLabels(dataPoint, projectId);
|
|
88
|
+
const dataLabels = _extractLabels(dataPoint, projectId, false);
|
|
89
89
|
const labels = {
|
|
90
90
|
...resourceLabels.metricLabels,
|
|
91
91
|
...dataLabels.metricLabels,
|
|
@@ -152,15 +152,21 @@ function _transformPoint(metric, dataPoint) {
|
|
|
152
152
|
};
|
|
153
153
|
}
|
|
154
154
|
}
|
|
155
|
-
/** Extracts metric and monitored resource labels from data point */
|
|
156
|
-
function _extractLabels({ attributes = {} }, projectId) {
|
|
155
|
+
/** Extracts metric and monitored resource labels from data point or resource */
|
|
156
|
+
function _extractLabels({ attributes = {} }, projectId, isResource = false) {
|
|
157
157
|
const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(projectId);
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
factory?.clientUid ?? constants_1.UNKNOWN_ATTRIBUTE
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
158
|
+
const combinedAttributes = {
|
|
159
|
+
...attributes,
|
|
160
|
+
[constants_1.METRIC_LABEL_KEY_CLIENT_UID]: factory?.clientUid ?? constants_1.UNKNOWN_ATTRIBUTE,
|
|
161
|
+
[constants_1.METRIC_LABEL_KEY_CLIENT_NAME]: factory?.clientName ?? constants_1.UNKNOWN_ATTRIBUTE,
|
|
162
|
+
};
|
|
163
|
+
if (isResource &&
|
|
164
|
+
factory?.location &&
|
|
165
|
+
(!combinedAttributes[constants_1.MONITORED_RES_LABEL_KEY_LOCATION] ||
|
|
166
|
+
combinedAttributes[constants_1.MONITORED_RES_LABEL_KEY_LOCATION] === 'global')) {
|
|
167
|
+
combinedAttributes[constants_1.MONITORED_RES_LABEL_KEY_LOCATION] = factory.location;
|
|
168
|
+
}
|
|
169
|
+
return Object.entries(combinedAttributes).reduce((result, [key, value]) => {
|
|
164
170
|
const normalizedKey = _normalizeLabelKey(key);
|
|
165
171
|
const val = value?.toString();
|
|
166
172
|
if (constants_1.METRIC_LABELS.has(key))
|
|
@@ -42,6 +42,18 @@ export interface MultiplexedSessionInterface extends EventEmitter {
|
|
|
42
42
|
* @param {GetSessionCallback} callback The callback function.
|
|
43
43
|
*/
|
|
44
44
|
getSession(callback: GetSessionCallback): void;
|
|
45
|
+
/**
|
|
46
|
+
* When called returns a cached multiplexed session synchronously if available.
|
|
47
|
+
*
|
|
48
|
+
* @name MultiplexedSessionInterface#getSessionSync
|
|
49
|
+
*/
|
|
50
|
+
getSessionSync(): Session | null;
|
|
51
|
+
/**
|
|
52
|
+
* When called closes the multiplexed session and stops background maintenance.
|
|
53
|
+
*
|
|
54
|
+
* @name MultiplexedSessionInterface#close
|
|
55
|
+
*/
|
|
56
|
+
close?(): void;
|
|
45
57
|
}
|
|
46
58
|
/**
|
|
47
59
|
* Class used to manage connections to Spanner using multiplexed session.
|
|
@@ -59,6 +71,7 @@ export declare class MultiplexedSession extends EventEmitter implements Multiple
|
|
|
59
71
|
_refreshHandle: NodeJS.Timeout;
|
|
60
72
|
_observabilityOptions?: ObservabilityOptions;
|
|
61
73
|
_sharedMuxSessionWaitPromise: Promise<void> | null;
|
|
74
|
+
private _isClosed;
|
|
62
75
|
constructor(database: Database);
|
|
63
76
|
/**
|
|
64
77
|
* Creates a new multiplexed session and manages its maintenance.
|
|
@@ -98,11 +111,22 @@ export declare class MultiplexedSession extends EventEmitter implements Multiple
|
|
|
98
111
|
*
|
|
99
112
|
*/
|
|
100
113
|
_maintain(): void;
|
|
114
|
+
/**
|
|
115
|
+
* Closes the multiplexed session by stopping the periodic refresh interval.
|
|
116
|
+
*/
|
|
117
|
+
close(): void;
|
|
118
|
+
/**
|
|
119
|
+
* Synchronously returns the cached multiplexed session if available,
|
|
120
|
+
* or null if no session is currently cached.
|
|
121
|
+
*
|
|
122
|
+
* @returns {Session|null} The cached multiplexed session or null.
|
|
123
|
+
*/
|
|
124
|
+
getSessionSync(): Session | null;
|
|
101
125
|
/**
|
|
102
126
|
* Retrieves a session asynchronously and invokes a callback with the session details.
|
|
103
127
|
* Note: The callback receives `(null, session)`. To prevent unnecessary allocations on
|
|
104
|
-
* read query paths, a `Transaction` is not created here
|
|
105
|
-
* transaction
|
|
128
|
+
* read query paths, a `Transaction` is not created here; callers requiring a read-write
|
|
129
|
+
* transaction instantiate it via `session.transaction()`.
|
|
106
130
|
*
|
|
107
131
|
* @param {GetSessionCallback} callback - The callback to be invoked once the session is acquired or an error occurs.
|
|
108
132
|
*
|
|
@@ -18,6 +18,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
18
18
|
exports.MultiplexedSession = void 0;
|
|
19
19
|
const events_1 = require("events");
|
|
20
20
|
const api_1 = require("@opentelemetry/api");
|
|
21
|
+
const google_gax_1 = require("google-gax");
|
|
21
22
|
const instrument_1 = require("./instrument");
|
|
22
23
|
/**
|
|
23
24
|
* Class used to manage connections to Spanner using multiplexed session.
|
|
@@ -37,6 +38,7 @@ class MultiplexedSession extends events_1.EventEmitter {
|
|
|
37
38
|
_observabilityOptions;
|
|
38
39
|
// shared promise lock to handle concurrent session creation requests
|
|
39
40
|
_sharedMuxSessionWaitPromise;
|
|
41
|
+
_isClosed = false;
|
|
40
42
|
constructor(database) {
|
|
41
43
|
super();
|
|
42
44
|
this.database = database;
|
|
@@ -56,7 +58,9 @@ class MultiplexedSession extends events_1.EventEmitter {
|
|
|
56
58
|
createSession() {
|
|
57
59
|
this._createSession()
|
|
58
60
|
.then(() => {
|
|
59
|
-
this.
|
|
61
|
+
if (!this._isClosed) {
|
|
62
|
+
this._maintain();
|
|
63
|
+
}
|
|
60
64
|
return null;
|
|
61
65
|
})
|
|
62
66
|
// Ignore errors here. If this fails, the next user request will
|
|
@@ -144,11 +148,34 @@ class MultiplexedSession extends events_1.EventEmitter {
|
|
|
144
148
|
// force the process to stay open.
|
|
145
149
|
this._refreshHandle.unref();
|
|
146
150
|
}
|
|
151
|
+
/**
|
|
152
|
+
* Closes the multiplexed session by stopping the periodic refresh interval.
|
|
153
|
+
*/
|
|
154
|
+
close() {
|
|
155
|
+
this._isClosed = true;
|
|
156
|
+
if (this._refreshHandle) {
|
|
157
|
+
clearInterval(this._refreshHandle);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Synchronously returns the cached multiplexed session if available,
|
|
162
|
+
* or null if no session is currently cached.
|
|
163
|
+
*
|
|
164
|
+
* @returns {Session|null} The cached multiplexed session or null.
|
|
165
|
+
*/
|
|
166
|
+
getSessionSync() {
|
|
167
|
+
if (!this._isClosed && this._multiplexedSession !== null) {
|
|
168
|
+
const span = (0, instrument_1.getActiveOrNoopSpan)();
|
|
169
|
+
span.addEvent('Cache hit: has usable multiplexed session');
|
|
170
|
+
return this._multiplexedSession;
|
|
171
|
+
}
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
147
174
|
/**
|
|
148
175
|
* Retrieves a session asynchronously and invokes a callback with the session details.
|
|
149
176
|
* Note: The callback receives `(null, session)`. To prevent unnecessary allocations on
|
|
150
|
-
* read query paths, a `Transaction` is not created here
|
|
151
|
-
* transaction
|
|
177
|
+
* read query paths, a `Transaction` is not created here; callers requiring a read-write
|
|
178
|
+
* transaction instantiate it via `session.transaction()`.
|
|
152
179
|
*
|
|
153
180
|
* @param {GetSessionCallback} callback - The callback to be invoked once the session is acquired or an error occurs.
|
|
154
181
|
*
|
|
@@ -156,10 +183,8 @@ class MultiplexedSession extends events_1.EventEmitter {
|
|
|
156
183
|
*
|
|
157
184
|
*/
|
|
158
185
|
getSession(callback) {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
const span = (0, instrument_1.getActiveOrNoopSpan)();
|
|
162
|
-
span.addEvent('Cache hit: has usable multiplexed session');
|
|
186
|
+
const session = this.getSessionSync();
|
|
187
|
+
if (session !== null) {
|
|
163
188
|
// Use process.nextTick to guarantee asynchronous callback execution ("never release Zalgo").
|
|
164
189
|
// This avoids microtask and Promise allocation overhead while preventing race conditions
|
|
165
190
|
// where callers (such as Database.prototype.runStream) need to return their stream and
|
|
@@ -196,12 +221,15 @@ class MultiplexedSession extends events_1.EventEmitter {
|
|
|
196
221
|
*
|
|
197
222
|
*/
|
|
198
223
|
async _getSession() {
|
|
199
|
-
|
|
224
|
+
if (this._isClosed) {
|
|
225
|
+
throw new google_gax_1.GoogleError('Database is closed.');
|
|
226
|
+
}
|
|
200
227
|
// Check if the multiplexed session is already available
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
return
|
|
228
|
+
const cachedSession = this.getSessionSync();
|
|
229
|
+
if (cachedSession !== null) {
|
|
230
|
+
return cachedSession;
|
|
204
231
|
}
|
|
232
|
+
const span = (0, instrument_1.getActiveOrNoopSpan)();
|
|
205
233
|
span.addEvent('Waiting for a multiplexed session to become available');
|
|
206
234
|
// If initialization is ALREADY in progress, join the existing line!
|
|
207
235
|
if (this._sharedMuxSessionWaitPromise) {
|
|
@@ -32,11 +32,9 @@ interface RequestFunction {
|
|
|
32
32
|
* @property {boolean} [json=false] Indicates if the Row objects should be
|
|
33
33
|
* formatted into JSON.
|
|
34
34
|
* @property {JSONOptions} [jsonOptions] JSON options.
|
|
35
|
-
* @property {number} [maxResumeRetries=20]
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
* experience 'Stream is still not ready to receive data' errors as a
|
|
39
|
-
* result of a slow writer in your receiving stream.
|
|
35
|
+
* @property {number} [maxResumeRetries=20] Deprecated. This option is no longer
|
|
36
|
+
* used. Backpressure is now handled natively via Node.js stream flow
|
|
37
|
+
* control without polling or retry limits.
|
|
40
38
|
* @property {object} [columnsMetadata] An object map that can be used to pass
|
|
41
39
|
* additional properties for each column type which can help in deserializing
|
|
42
40
|
* the data coming from backend. (Eg: We need to pass Proto Function and Enum
|
|
@@ -45,6 +43,10 @@ interface RequestFunction {
|
|
|
45
43
|
export interface RowOptions {
|
|
46
44
|
json?: boolean;
|
|
47
45
|
jsonOptions?: JSONOptions;
|
|
46
|
+
/**
|
|
47
|
+
* @deprecated Backpressure is now handled natively via Node.js stream flow
|
|
48
|
+
* control without polling or retry limits.
|
|
49
|
+
*/
|
|
48
50
|
maxResumeRetries?: number;
|
|
49
51
|
/**
|
|
50
52
|
* An object where column names as keys and custom objects as corresponding
|
|
@@ -190,14 +192,13 @@ interface ResultEvents {
|
|
|
190
192
|
* @param {RowOptions} [options] The row options.
|
|
191
193
|
*/
|
|
192
194
|
export declare class PartialResultStream extends Transform implements ResultEvents {
|
|
193
|
-
private _destroyed;
|
|
194
195
|
private _fields;
|
|
195
196
|
private _decoders;
|
|
196
197
|
private _options;
|
|
197
198
|
private _pendingValue?;
|
|
198
|
-
private
|
|
199
|
-
private
|
|
200
|
-
private
|
|
199
|
+
private _rowValues?;
|
|
200
|
+
private _valueIndex;
|
|
201
|
+
private _resumeCallback?;
|
|
201
202
|
private _isFirstChunk;
|
|
202
203
|
constructor(options?: {});
|
|
203
204
|
/**
|
|
@@ -216,14 +217,25 @@ export declare class PartialResultStream extends Transform implements ResultEven
|
|
|
216
217
|
* @param {function} next Function to be called upon completion.
|
|
217
218
|
*/
|
|
218
219
|
_transform(chunk: google.spanner.v1.PartialResultSet, enc: string, next: Function): void;
|
|
219
|
-
|
|
220
|
-
|
|
220
|
+
_flush(callback: Function): void;
|
|
221
|
+
_read(size: number): void;
|
|
221
222
|
/**
|
|
222
|
-
* Manages
|
|
223
|
+
* Manages stream chunks, chunked value merging across chunk boundaries,
|
|
224
|
+
* row assembly, and resume token checkpoints.
|
|
223
225
|
*
|
|
224
|
-
*
|
|
226
|
+
* Processing follows 4 distinct stages:
|
|
227
|
+
* 1. Single-chunk fast path: If the entire stream response is in this first chunk,
|
|
228
|
+
* decode rows directly and bypass incremental chunk buffering.
|
|
229
|
+
* 2. Pending value merge: If the previous chunk ended with an incomplete chunked
|
|
230
|
+
* value, merge it with the incoming continuation value at chunkValues[0].
|
|
231
|
+
* 3. Chunked value hold: If this chunk ends with a chunked value, hold the tail
|
|
232
|
+
* value (chunkValues[numValues - 1]) in `this._pendingValue` for the next chunk.
|
|
233
|
+
* 4. Complete value decoding: Iterate from `startIndex` to `endIndex`, decoding
|
|
234
|
+
* and adding values into row buffers via `_addValue`.
|
|
225
235
|
*
|
|
226
|
-
* @
|
|
236
|
+
* @private
|
|
237
|
+
* @param {google.spanner.v1.PartialResultSet} chunk The partial result set.
|
|
238
|
+
* @returns {boolean} Whether downstream can accept more data.
|
|
227
239
|
*/
|
|
228
240
|
private _addChunk;
|
|
229
241
|
/**
|
|
@@ -244,25 +256,6 @@ export declare class PartialResultStream extends Transform implements ResultEven
|
|
|
244
256
|
* @param {*} value The complete value.
|
|
245
257
|
*/
|
|
246
258
|
private _addValue;
|
|
247
|
-
/**
|
|
248
|
-
* Directly creates a plain JSON object from row cell values, bypassing
|
|
249
|
-
* Struct, Row, and WrappedNumber class wrappers when possible.
|
|
250
|
-
*
|
|
251
|
-
* @private
|
|
252
|
-
*
|
|
253
|
-
* @param {Value[]} values The raw cell values for the current row.
|
|
254
|
-
* @returns {Json} The plain JavaScript object representing the row.
|
|
255
|
-
*/
|
|
256
|
-
private _createJsonRow;
|
|
257
|
-
/**
|
|
258
|
-
* Converts an array of values into a row.
|
|
259
|
-
*
|
|
260
|
-
* @private
|
|
261
|
-
*
|
|
262
|
-
* @param {Array.<*>} values The row values.
|
|
263
|
-
* @returns {Row}
|
|
264
|
-
*/
|
|
265
|
-
private _createRow;
|
|
266
259
|
/**
|
|
267
260
|
* Attempts to merge chunked values together.
|
|
268
261
|
*
|