@google-cloud/spanner 8.12.0 → 9.0.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/build/src/codec.d.ts +12 -30
- package/build/src/codec.js +98 -45
- package/build/src/common.js +2 -3
- package/build/src/database.d.ts +31 -0
- package/build/src/database.js +128 -6
- package/build/src/index.d.ts +8 -0
- package/build/src/index.js +99 -63
- package/build/src/instrument.js +4 -1
- package/build/src/metrics/constants.d.ts +7 -6
- package/build/src/metrics/constants.js +18 -13
- package/build/src/metrics/external-types.d.ts +14 -0
- package/build/src/metrics/interceptor.js +12 -18
- package/build/src/metrics/metrics-tracer-factory.d.ts +19 -3
- package/build/src/metrics/metrics-tracer-factory.js +57 -14
- package/build/src/metrics/spanner-metrics-exporter.js +7 -1
- package/build/src/metrics/transform.d.ts +3 -4
- package/build/src/metrics/transform.js +16 -10
- package/build/src/multiplexed-session.d.ts +13 -0
- package/build/src/multiplexed-session.js +20 -8
- package/build/src/partial-result-stream.d.ts +43 -0
- package/build/src/partial-result-stream.js +148 -55
- package/build/src/session-factory.d.ts +13 -0
- package/build/src/session-factory.js +12 -1
- package/build/src/transaction.d.ts +38 -6
- package/build/src/transaction.js +365 -41
- package/package.json +24 -32
package/build/src/index.js
CHANGED
|
@@ -246,6 +246,8 @@ class Spanner extends service_1.GrpcService {
|
|
|
246
246
|
scopes,
|
|
247
247
|
// Add grpc keep alive setting
|
|
248
248
|
'grpc.keepalive_time_ms': 120000,
|
|
249
|
+
// Disable Channelz by default to reduce per-RPC tracking and allocation overhead
|
|
250
|
+
'grpc.enable_channelz': 0,
|
|
249
251
|
// Enable grpc-gcp support
|
|
250
252
|
'grpc.callInvocationTransformer': grpcGcp.gcpCallInvocationTransformer,
|
|
251
253
|
'grpc.channelFactoryOverride': grpcGcp.gcpChannelFactoryOverride,
|
|
@@ -334,7 +336,7 @@ class Spanner extends service_1.GrpcService {
|
|
|
334
336
|
getInstanceAdminClient() {
|
|
335
337
|
const clientName = 'InstanceAdminClient';
|
|
336
338
|
if (!this.clients_.has(clientName)) {
|
|
337
|
-
this.clients_.set(clientName, new v1
|
|
339
|
+
this.clients_.set(clientName, new v1.InstanceAdminClient(this.options));
|
|
338
340
|
}
|
|
339
341
|
return this.clients_.get(clientName);
|
|
340
342
|
}
|
|
@@ -354,7 +356,7 @@ class Spanner extends service_1.GrpcService {
|
|
|
354
356
|
getDatabaseAdminClient() {
|
|
355
357
|
const clientName = 'DatabaseAdminClient';
|
|
356
358
|
if (!this.clients_.has(clientName)) {
|
|
357
|
-
this.clients_.set(clientName, new v1
|
|
359
|
+
this.clients_.set(clientName, new v1.DatabaseAdminClient(this.options));
|
|
358
360
|
}
|
|
359
361
|
return this.clients_.get(clientName);
|
|
360
362
|
}
|
|
@@ -391,11 +393,12 @@ class Spanner extends service_1.GrpcService {
|
|
|
391
393
|
const res = performTeardown();
|
|
392
394
|
if (callback) {
|
|
393
395
|
// process.nextTick prevents Unhandled Promise Rejections if callback throws
|
|
394
|
-
res
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
return
|
|
396
|
+
res
|
|
397
|
+
.then(() => process.nextTick(() => callback(null)))
|
|
398
|
+
.catch(err => process.nextTick(() => callback(err)));
|
|
399
|
+
return;
|
|
398
400
|
}
|
|
401
|
+
return res;
|
|
399
402
|
}
|
|
400
403
|
createInstance(name, config, callback) {
|
|
401
404
|
if (!name) {
|
|
@@ -817,28 +820,39 @@ class Spanner extends service_1.GrpcService {
|
|
|
817
820
|
!metricsExplicitlyDisabled && !this._isInSecureCredentials;
|
|
818
821
|
metrics_tracer_factory_1.MetricsTracerFactory.enabled = this._metricsEnabled;
|
|
819
822
|
if (this._metricsEnabled) {
|
|
820
|
-
|
|
821
|
-
this.
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
|
|
831
|
-
exporter: new spanner_metrics_exporter_1.CloudMonitoringMetricsExporter({ auth: this.auth }, projectId),
|
|
832
|
-
exportIntervalMillis: 60000,
|
|
823
|
+
const initializeMetrics = (projectId) => {
|
|
824
|
+
this.projectId_ = projectId;
|
|
825
|
+
const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(projectId);
|
|
826
|
+
if (factory && !factory.hasMetricReaders()) {
|
|
827
|
+
api_1.context.with(api_1.ROOT_CONTEXT, () => {
|
|
828
|
+
const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
|
|
829
|
+
exporter: new spanner_metrics_exporter_1.CloudMonitoringMetricsExporter({ auth: this.auth }, projectId),
|
|
830
|
+
exportIntervalMillis: 60000,
|
|
831
|
+
});
|
|
832
|
+
factory.getMeterProvider([periodicReader]);
|
|
833
833
|
});
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
834
|
+
}
|
|
835
|
+
};
|
|
836
|
+
if (this.projectId_ && this.projectId_ !== '{{projectId}}') {
|
|
837
|
+
initializeMetrics(this.projectId_);
|
|
837
838
|
}
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
839
|
+
else {
|
|
840
|
+
try {
|
|
841
|
+
this.auth.getProjectId((err, projectId) => {
|
|
842
|
+
if (err || !projectId) {
|
|
843
|
+
console.error('Unable to get Project Id for client side metrics, will skip exporting client' +
|
|
844
|
+
' side metrics' +
|
|
845
|
+
err);
|
|
846
|
+
return;
|
|
847
|
+
}
|
|
848
|
+
initializeMetrics(projectId);
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
catch (err) {
|
|
852
|
+
console.error('Unable to configure client side metrics, will skip exporting client' +
|
|
853
|
+
' side metrics' +
|
|
854
|
+
err);
|
|
855
|
+
}
|
|
842
856
|
}
|
|
843
857
|
}
|
|
844
858
|
}
|
|
@@ -909,46 +923,65 @@ class Spanner extends service_1.GrpcService {
|
|
|
909
923
|
},
|
|
910
924
|
},
|
|
911
925
|
}));
|
|
912
|
-
//
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
926
|
+
// Extract a lightweight config reference containing only headers so error
|
|
927
|
+
// enrichment is decoupled from the caller's mutable config object.
|
|
928
|
+
const errorConfig = { headers: config?.headers };
|
|
929
|
+
// Wrap requestFn to inject the Spanner request ID (x-goog-spanner-request-id)
|
|
930
|
+
// into any error returned via callback, rejected promise, stream event, or
|
|
931
|
+
// synchronous exception.
|
|
932
|
+
//
|
|
933
|
+
// Because reqOpts and gaxOpts are already pre-bound to requestFn, wrappedRequestFn
|
|
934
|
+
// receives at most one argument: an optional callback.
|
|
935
|
+
const wrappedRequestFn = (callback) => {
|
|
936
|
+
// Callback mode: invoke requestFn with an intercepted callback to enrich
|
|
937
|
+
// the error parameter before delegating to the caller's callback.
|
|
938
|
+
if (typeof callback === 'function') {
|
|
939
|
+
try {
|
|
940
|
+
requestFn((...results) => {
|
|
941
|
+
if (results[0]) {
|
|
942
|
+
(0, request_id_header_1.injectRequestIDIntoError)(errorConfig, results[0]);
|
|
925
943
|
}
|
|
926
|
-
|
|
944
|
+
callback(...results);
|
|
927
945
|
});
|
|
928
|
-
return;
|
|
929
946
|
}
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
if (stream) {
|
|
934
|
-
stream.on('error', err => {
|
|
935
|
-
(0, request_id_header_1.injectRequestIDIntoError)(config, err);
|
|
936
|
-
});
|
|
937
|
-
}
|
|
938
|
-
const originallyPromise = res instanceof Promise;
|
|
939
|
-
if (!originallyPromise) {
|
|
940
|
-
return res;
|
|
941
|
-
}
|
|
942
|
-
return new Promise((resolve, reject) => {
|
|
943
|
-
requestFn(...args)
|
|
944
|
-
.then(resolve)
|
|
945
|
-
.catch(err => {
|
|
946
|
-
(0, request_id_header_1.injectRequestIDIntoError)(config, err);
|
|
947
|
-
reject(err);
|
|
948
|
-
});
|
|
949
|
-
});
|
|
947
|
+
catch (err) {
|
|
948
|
+
(0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
|
|
949
|
+
throw err;
|
|
950
950
|
}
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
// Non-callback mode: invoke requestFn() for Promise or Stream callers.
|
|
954
|
+
let res;
|
|
955
|
+
try {
|
|
956
|
+
res = requestFn();
|
|
957
|
+
}
|
|
958
|
+
catch (err) {
|
|
959
|
+
(0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
|
|
960
|
+
throw err;
|
|
961
|
+
}
|
|
962
|
+
// Handle Promise / Thenable return values (e.g. unary requests).
|
|
963
|
+
// Attach a rejection handler to inject the request ID into rejected errors.
|
|
964
|
+
// If the promise is cancellable (e.g. google-gax CancellablePromise), preserve
|
|
965
|
+
// its .cancel() method so callers can cancel the underlying operation.
|
|
966
|
+
if (res && typeof res.then === 'function') {
|
|
967
|
+
const chained = res.then(null, err => {
|
|
968
|
+
(0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
|
|
969
|
+
throw err;
|
|
970
|
+
});
|
|
971
|
+
if (typeof res.cancel === 'function') {
|
|
972
|
+
chained.cancel = res.cancel.bind(res);
|
|
973
|
+
}
|
|
974
|
+
return chained;
|
|
975
|
+
}
|
|
976
|
+
// Handle Stream return values (e.g. streaming reads or queries).
|
|
977
|
+
// Listen for 'error' events to enrich the emitted error with the request ID.
|
|
978
|
+
const stream = res;
|
|
979
|
+
if (stream && typeof stream.on === 'function') {
|
|
980
|
+
stream.on('error', err => {
|
|
981
|
+
(0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
|
|
982
|
+
});
|
|
951
983
|
}
|
|
984
|
+
return res;
|
|
952
985
|
};
|
|
953
986
|
callback(null, wrappedRequestFn);
|
|
954
987
|
});
|
|
@@ -969,7 +1002,8 @@ class Spanner extends service_1.GrpcService {
|
|
|
969
1002
|
let metricsTracer = null;
|
|
970
1003
|
if (this._metricsEnabled &&
|
|
971
1004
|
config.client === 'SpannerClient' &&
|
|
972
|
-
this.projectId_
|
|
1005
|
+
this.projectId_ &&
|
|
1006
|
+
this.projectId_ !== '{{projectId}}') {
|
|
973
1007
|
metricsTracer =
|
|
974
1008
|
metrics_tracer_factory_1.MetricsTracerFactory?.getInstance(this.projectId_)?.createMetricsTracer(config.method, config.reqOpts.database ?? config.reqOpts.session, config.headers['x-goog-spanner-request-id']) ?? null;
|
|
975
1009
|
}
|
|
@@ -1003,6 +1037,7 @@ class Spanner extends service_1.GrpcService {
|
|
|
1003
1037
|
.then(val => {
|
|
1004
1038
|
metricsTracer?.recordOperationCompletion();
|
|
1005
1039
|
resolve(val);
|
|
1040
|
+
return val;
|
|
1006
1041
|
})
|
|
1007
1042
|
.catch(error => {
|
|
1008
1043
|
metricsTracer?.recordOperationCompletion();
|
|
@@ -1034,7 +1069,8 @@ class Spanner extends service_1.GrpcService {
|
|
|
1034
1069
|
let metricsTracer = null;
|
|
1035
1070
|
if (this._metricsEnabled &&
|
|
1036
1071
|
config.client === 'SpannerClient' &&
|
|
1037
|
-
this.projectId_
|
|
1072
|
+
this.projectId_ &&
|
|
1073
|
+
this.projectId_ !== '{{projectId}}') {
|
|
1038
1074
|
metricsTracer =
|
|
1039
1075
|
metrics_tracer_factory_1.MetricsTracerFactory?.getInstance(this.projectId_)?.createMetricsTracer(config.method, config.reqOpts.session ?? config.reqOpts.database, config.headers['x-goog-spanner-request-id']) ?? null;
|
|
1040
1076
|
}
|
package/build/src/instrument.js
CHANGED
|
@@ -80,9 +80,12 @@ const CACHE_TTL_MS = 10000; // 10 seconds TTL
|
|
|
80
80
|
* @returns {boolean} True if global tracing is enabled.
|
|
81
81
|
*/
|
|
82
82
|
function isGlobalTracingEnabled() {
|
|
83
|
+
if (globalTracingEnabled === true) {
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
83
86
|
const now = Date.now();
|
|
84
87
|
if (globalTracingEnabled !== undefined &&
|
|
85
|
-
|
|
88
|
+
now - lastCheckTime < CACHE_TTL_MS) {
|
|
86
89
|
return globalTracingEnabled;
|
|
87
90
|
}
|
|
88
91
|
lastCheckTime = now;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ViewOptions } from '@opentelemetry/sdk-metrics';
|
|
2
2
|
export declare const SPANNER_METER_NAME = "spanner-nodejs";
|
|
3
3
|
export declare const CLIENT_METRICS_PREFIX = "spanner.googleapis.com/internal/client";
|
|
4
4
|
export declare const SPANNER_RESOURCE_TYPE = "spanner_instance_client";
|
|
5
5
|
export declare const TRACER_CLEANUP_THRESHOLD_MS: number;
|
|
6
6
|
export declare const TRACER_CLEANUP_INTERVAL_MS: number;
|
|
7
7
|
export declare const ATTR_CLOUD_REGION = "cloud.region";
|
|
8
|
+
export declare const ATTR_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone";
|
|
8
9
|
export declare const MIN_EXPORT_FREQUENCY_MS: number;
|
|
9
10
|
export declare const MONITORED_RES_LABEL_KEY_PROJECT = "project_id";
|
|
10
11
|
export declare const MONITORED_RES_LABEL_KEY_INSTANCE = "instance_id";
|
|
@@ -29,8 +30,8 @@ export declare const METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT = "afe_connectivit
|
|
|
29
30
|
export declare const METRIC_NAMES: Set<string>;
|
|
30
31
|
export declare const UNKNOWN_ATTRIBUTE = "unknown";
|
|
31
32
|
export declare const HISTOGRAM_BUCKET_BOUNDARIES: number[];
|
|
32
|
-
export declare const OPERATION_LATENCY_VIEW:
|
|
33
|
-
export declare const ATTEMPT_LATENCY_VIEW:
|
|
34
|
-
export declare const GFE_LATENCY_VIEW:
|
|
35
|
-
export declare const AFE_LATENCY_VIEW:
|
|
36
|
-
export declare const METRIC_VIEWS:
|
|
33
|
+
export declare const OPERATION_LATENCY_VIEW: ViewOptions;
|
|
34
|
+
export declare const ATTEMPT_LATENCY_VIEW: ViewOptions;
|
|
35
|
+
export declare const GFE_LATENCY_VIEW: ViewOptions;
|
|
36
|
+
export declare const AFE_LATENCY_VIEW: ViewOptions;
|
|
37
|
+
export declare const METRIC_VIEWS: ViewOptions[];
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.METRIC_VIEWS = exports.AFE_LATENCY_VIEW = exports.GFE_LATENCY_VIEW = exports.ATTEMPT_LATENCY_VIEW = exports.OPERATION_LATENCY_VIEW = exports.HISTOGRAM_BUCKET_BOUNDARIES = exports.UNKNOWN_ATTRIBUTE = exports.METRIC_NAMES = exports.METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT = exports.METRIC_NAME_AFE_LATENCIES = exports.METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT = exports.METRIC_NAME_GFE_LATENCIES = exports.METRIC_NAME_ATTEMPT_COUNT = exports.METRIC_NAME_OPERATION_COUNT = exports.METRIC_NAME_ATTEMPT_LATENCIES = exports.METRIC_NAME_OPERATION_LATENCIES = exports.METRIC_LABELS = exports.METRIC_LABEL_KEY_STATUS = exports.METRIC_LABEL_KEY_METHOD = exports.METRIC_LABEL_KEY_DATABASE = exports.METRIC_LABEL_KEY_CLIENT_NAME = exports.METRIC_LABEL_KEY_CLIENT_UID = exports.MONITORED_RESOURCE_LABELS = exports.MONITORED_RES_LABEL_KEY_CLIENT_HASH = exports.MONITORED_RES_LABEL_KEY_LOCATION = exports.MONITORED_RES_LABEL_KEY_INSTANCE_CONFIG = exports.MONITORED_RES_LABEL_KEY_INSTANCE = exports.MONITORED_RES_LABEL_KEY_PROJECT = exports.MIN_EXPORT_FREQUENCY_MS = exports.ATTR_CLOUD_REGION = exports.TRACER_CLEANUP_INTERVAL_MS = exports.TRACER_CLEANUP_THRESHOLD_MS = exports.SPANNER_RESOURCE_TYPE = exports.CLIENT_METRICS_PREFIX = exports.SPANNER_METER_NAME = void 0;
|
|
3
|
+
exports.METRIC_VIEWS = exports.AFE_LATENCY_VIEW = exports.GFE_LATENCY_VIEW = exports.ATTEMPT_LATENCY_VIEW = exports.OPERATION_LATENCY_VIEW = exports.HISTOGRAM_BUCKET_BOUNDARIES = exports.UNKNOWN_ATTRIBUTE = exports.METRIC_NAMES = exports.METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT = exports.METRIC_NAME_AFE_LATENCIES = exports.METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT = exports.METRIC_NAME_GFE_LATENCIES = exports.METRIC_NAME_ATTEMPT_COUNT = exports.METRIC_NAME_OPERATION_COUNT = exports.METRIC_NAME_ATTEMPT_LATENCIES = exports.METRIC_NAME_OPERATION_LATENCIES = exports.METRIC_LABELS = exports.METRIC_LABEL_KEY_STATUS = exports.METRIC_LABEL_KEY_METHOD = exports.METRIC_LABEL_KEY_DATABASE = exports.METRIC_LABEL_KEY_CLIENT_NAME = exports.METRIC_LABEL_KEY_CLIENT_UID = exports.MONITORED_RESOURCE_LABELS = exports.MONITORED_RES_LABEL_KEY_CLIENT_HASH = exports.MONITORED_RES_LABEL_KEY_LOCATION = exports.MONITORED_RES_LABEL_KEY_INSTANCE_CONFIG = exports.MONITORED_RES_LABEL_KEY_INSTANCE = exports.MONITORED_RES_LABEL_KEY_PROJECT = exports.MIN_EXPORT_FREQUENCY_MS = exports.ATTR_CLOUD_AVAILABILITY_ZONE = exports.ATTR_CLOUD_REGION = exports.TRACER_CLEANUP_INTERVAL_MS = exports.TRACER_CLEANUP_THRESHOLD_MS = exports.SPANNER_RESOURCE_TYPE = exports.CLIENT_METRICS_PREFIX = exports.SPANNER_METER_NAME = void 0;
|
|
4
4
|
// Copyright 2025 Google LLC
|
|
5
5
|
//
|
|
6
6
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
@@ -24,6 +24,7 @@ exports.TRACER_CLEANUP_INTERVAL_MS = 30 * 60 * 1000; // 30 Minutes
|
|
|
24
24
|
// OTel semantic conventions
|
|
25
25
|
// See https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv
|
|
26
26
|
exports.ATTR_CLOUD_REGION = 'cloud.region';
|
|
27
|
+
exports.ATTR_CLOUD_AVAILABILITY_ZONE = 'cloud.availability_zone';
|
|
27
28
|
// Minimum period that must past between metric exports
|
|
28
29
|
exports.MIN_EXPORT_FREQUENCY_MS = 30 * 1000;
|
|
29
30
|
// Monitored resource labels
|
|
@@ -81,22 +82,26 @@ exports.HISTOGRAM_BUCKET_BOUNDARIES = [
|
|
|
81
82
|
800000.0, 1600000.0, 3200000.0,
|
|
82
83
|
];
|
|
83
84
|
// Defined Views for metric aggregation
|
|
84
|
-
|
|
85
|
+
const HISTOGRAM_AGGREGATION = {
|
|
86
|
+
type: sdk_metrics_1.AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
|
|
87
|
+
options: { boundaries: exports.HISTOGRAM_BUCKET_BOUNDARIES },
|
|
88
|
+
};
|
|
89
|
+
exports.OPERATION_LATENCY_VIEW = {
|
|
85
90
|
instrumentName: exports.METRIC_NAME_OPERATION_LATENCIES,
|
|
86
|
-
aggregation:
|
|
87
|
-
}
|
|
88
|
-
exports.ATTEMPT_LATENCY_VIEW =
|
|
91
|
+
aggregation: HISTOGRAM_AGGREGATION,
|
|
92
|
+
};
|
|
93
|
+
exports.ATTEMPT_LATENCY_VIEW = {
|
|
89
94
|
instrumentName: exports.METRIC_NAME_ATTEMPT_LATENCIES,
|
|
90
|
-
aggregation:
|
|
91
|
-
}
|
|
92
|
-
exports.GFE_LATENCY_VIEW =
|
|
95
|
+
aggregation: HISTOGRAM_AGGREGATION,
|
|
96
|
+
};
|
|
97
|
+
exports.GFE_LATENCY_VIEW = {
|
|
93
98
|
instrumentName: exports.METRIC_NAME_GFE_LATENCIES,
|
|
94
|
-
aggregation:
|
|
95
|
-
}
|
|
96
|
-
exports.AFE_LATENCY_VIEW =
|
|
99
|
+
aggregation: HISTOGRAM_AGGREGATION,
|
|
100
|
+
};
|
|
101
|
+
exports.AFE_LATENCY_VIEW = {
|
|
97
102
|
instrumentName: exports.METRIC_NAME_AFE_LATENCIES,
|
|
98
|
-
aggregation:
|
|
99
|
-
}
|
|
103
|
+
aggregation: HISTOGRAM_AGGREGATION,
|
|
104
|
+
};
|
|
100
105
|
exports.METRIC_VIEWS = [
|
|
101
106
|
exports.OPERATION_LATENCY_VIEW,
|
|
102
107
|
exports.ATTEMPT_LATENCY_VIEW,
|
|
@@ -18,3 +18,17 @@ export declare enum ValueType {
|
|
|
18
18
|
DOUBLE = "DOUBLE",
|
|
19
19
|
DISTRIBUTION = "DISTRIBUTION"
|
|
20
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* A Google Cloud Monitoring monitored resource.
|
|
23
|
+
*
|
|
24
|
+
* Previously imported from `@google-cloud/opentelemetry-resource-util`, which is
|
|
25
|
+
* deprecated and scheduled for archival. The interface is a plain data shape, so
|
|
26
|
+
* it is declared locally instead.
|
|
27
|
+
* See https://cloud.google.com/monitoring/api/ref_v3/rest/v3/MonitoredResource
|
|
28
|
+
*/
|
|
29
|
+
export interface MonitoredResource {
|
|
30
|
+
type: string;
|
|
31
|
+
labels: {
|
|
32
|
+
[key: string]: string;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
@@ -41,25 +41,28 @@ const MetricInterceptor = (options, nextCall) => {
|
|
|
41
41
|
const requestId = metadata.get('x-goog-spanner-request-id')[0];
|
|
42
42
|
const metricsTracer = factory?.getCurrentTracer(requestId);
|
|
43
43
|
metricsTracer?.recordAttemptStart();
|
|
44
|
-
const
|
|
45
|
-
onReceiveMetadata: function (metadata
|
|
44
|
+
const interceptingListener = {
|
|
45
|
+
onReceiveMetadata: function (metadata) {
|
|
46
46
|
// Record GFE/AFE Metrics
|
|
47
47
|
// GFE/AFE latency if available,
|
|
48
48
|
// or else increase the GFE/AFE connectivity error count
|
|
49
49
|
if (metricsTracer) {
|
|
50
|
-
const
|
|
50
|
+
const serverTimingEntries = metadata.get('server-timing');
|
|
51
|
+
const serverTimingHeader = serverTimingEntries.length > 0
|
|
52
|
+
? String(serverTimingEntries[0])
|
|
53
|
+
: undefined;
|
|
51
54
|
const gfeTiming = metricsTracer?.extractGfeLatency(serverTimingHeader);
|
|
52
55
|
metricsTracer.gfeLatency = gfeTiming ?? null;
|
|
53
56
|
const afeTiming = metricsTracer?.extractAfeLatency(serverTimingHeader);
|
|
54
57
|
metricsTracer.afeLatency = afeTiming ?? null;
|
|
55
58
|
}
|
|
56
|
-
|
|
59
|
+
listener.onReceiveMetadata(metadata);
|
|
57
60
|
},
|
|
58
|
-
onReceiveMessage: function (message
|
|
59
|
-
|
|
61
|
+
onReceiveMessage: function (message) {
|
|
62
|
+
listener.onReceiveMessage(message);
|
|
60
63
|
},
|
|
61
|
-
onReceiveStatus: function (status
|
|
62
|
-
|
|
64
|
+
onReceiveStatus: function (status) {
|
|
65
|
+
listener.onReceiveStatus(status);
|
|
63
66
|
// Record attempt metric completion
|
|
64
67
|
metricsTracer?.recordAttemptCompletion(status.code);
|
|
65
68
|
if (metricsTracer?.gfeLatency) {
|
|
@@ -76,16 +79,7 @@ const MetricInterceptor = (options, nextCall) => {
|
|
|
76
79
|
}
|
|
77
80
|
},
|
|
78
81
|
};
|
|
79
|
-
next(metadata,
|
|
80
|
-
},
|
|
81
|
-
sendMessage: function (message, next) {
|
|
82
|
-
next(message);
|
|
83
|
-
},
|
|
84
|
-
halfClose: function (next) {
|
|
85
|
-
next();
|
|
86
|
-
},
|
|
87
|
-
cancel: function (next) {
|
|
88
|
-
next();
|
|
82
|
+
next(metadata, interceptingListener);
|
|
89
83
|
},
|
|
90
84
|
});
|
|
91
85
|
};
|
|
@@ -29,6 +29,8 @@ export declare class MetricsTracerFactory {
|
|
|
29
29
|
private _clientName;
|
|
30
30
|
private _clientUid;
|
|
31
31
|
private _location;
|
|
32
|
+
private _locationPromise;
|
|
33
|
+
private _metricReaders;
|
|
32
34
|
private _projectId;
|
|
33
35
|
private _currentOperationTracers;
|
|
34
36
|
private _currentOperationLastUpdatedMs;
|
|
@@ -52,6 +54,10 @@ export declare class MetricsTracerFactory {
|
|
|
52
54
|
/**
|
|
53
55
|
* Returns the MeterProvider, creating it and metric instruments if not already initialized.
|
|
54
56
|
* Client-wide attributes that are known at this time are cached to be provided to all MetricsTracers.
|
|
57
|
+
*
|
|
58
|
+
* If called again with readers when the existing MeterProvider has none, the provider is
|
|
59
|
+
* recreated with those readers. If readers are already attached, additional readers are ignored.
|
|
60
|
+
*
|
|
55
61
|
* @param readers Optional array of MetricReader instances to attach to the MeterProvider.
|
|
56
62
|
* @returns The OTEL MeterProvider instance.
|
|
57
63
|
*/
|
|
@@ -96,6 +102,14 @@ export declare class MetricsTracerFactory {
|
|
|
96
102
|
* Returns the Client Name.
|
|
97
103
|
*/
|
|
98
104
|
get clientName(): string;
|
|
105
|
+
/**
|
|
106
|
+
* Returns the detected client location.
|
|
107
|
+
*/
|
|
108
|
+
get location(): string;
|
|
109
|
+
/**
|
|
110
|
+
* Returns true if the MeterProvider is initialized with at least one MetricReader.
|
|
111
|
+
*/
|
|
112
|
+
hasMetricReaders(): boolean;
|
|
99
113
|
/**
|
|
100
114
|
* Creates a new MetricsTracer for a given resource name and method, and stores it for later retrieval.
|
|
101
115
|
* Returns null if metrics are disabled.
|
|
@@ -155,9 +169,11 @@ export declare class MetricsTracerFactory {
|
|
|
155
169
|
*/
|
|
156
170
|
private static _generateClientHash;
|
|
157
171
|
/**
|
|
158
|
-
* Gets the location (region) of the client,
|
|
159
|
-
* Uses
|
|
160
|
-
*
|
|
172
|
+
* Gets the location (region or zone) of the client, or defaults to "global".
|
|
173
|
+
* Uses the GCP resource detector to detect the location from the environment.
|
|
174
|
+
* Checks `cloud.region` first and falls back to `cloud.availability_zone`
|
|
175
|
+
* for zonal GKE clusters where `cloud.region` is not set.
|
|
176
|
+
* @returns The detected location string, or "global" if not found.
|
|
161
177
|
*/
|
|
162
178
|
private static _detectClientLocation;
|
|
163
179
|
private _cleanMetricsTracers;
|
|
@@ -20,7 +20,7 @@ const process = require("process");
|
|
|
20
20
|
const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
|
|
21
21
|
const api_1 = require("@opentelemetry/api");
|
|
22
22
|
const resources_1 = require("@opentelemetry/resources");
|
|
23
|
-
const
|
|
23
|
+
const resource_detector_gcp_1 = require("@opentelemetry/resource-detector-gcp");
|
|
24
24
|
const Constants = require("./constants");
|
|
25
25
|
const metrics_tracer_1 = require("./metrics-tracer");
|
|
26
26
|
const version = require('../../../package.json').version;
|
|
@@ -52,6 +52,8 @@ class MetricsTracerFactory {
|
|
|
52
52
|
_clientName;
|
|
53
53
|
_clientUid;
|
|
54
54
|
_location = 'global';
|
|
55
|
+
_locationPromise = null;
|
|
56
|
+
_metricReaders = [];
|
|
55
57
|
_projectId;
|
|
56
58
|
_currentOperationTracers = new Map();
|
|
57
59
|
_currentOperationLastUpdatedMs = new Map();
|
|
@@ -69,11 +71,17 @@ class MetricsTracerFactory {
|
|
|
69
71
|
this._clientName = `${Constants.SPANNER_METER_NAME}/${version}`;
|
|
70
72
|
// Only perform async call to retrieve location is metrics are enabled.
|
|
71
73
|
if (MetricsTracerFactory.enabled) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
+
this._locationPromise = MetricsTracerFactory._detectClientLocation()
|
|
75
|
+
.then(location => {
|
|
74
76
|
this._location = location.length > 0 ? location : 'global';
|
|
75
|
-
|
|
76
|
-
|
|
77
|
+
return this._location;
|
|
78
|
+
})
|
|
79
|
+
.catch(error => {
|
|
80
|
+
console.warn('Unable to detect location.', error);
|
|
81
|
+
return this._location;
|
|
82
|
+
})
|
|
83
|
+
.finally(() => {
|
|
84
|
+
this._locationPromise = null;
|
|
77
85
|
});
|
|
78
86
|
}
|
|
79
87
|
this._clientHash = MetricsTracerFactory._generateClientHash(this._clientUid);
|
|
@@ -103,23 +111,42 @@ class MetricsTracerFactory {
|
|
|
103
111
|
/**
|
|
104
112
|
* Returns the MeterProvider, creating it and metric instruments if not already initialized.
|
|
105
113
|
* Client-wide attributes that are known at this time are cached to be provided to all MetricsTracers.
|
|
114
|
+
*
|
|
115
|
+
* If called again with readers when the existing MeterProvider has none, the provider is
|
|
116
|
+
* recreated with those readers. If readers are already attached, additional readers are ignored.
|
|
117
|
+
*
|
|
106
118
|
* @param readers Optional array of MetricReader instances to attach to the MeterProvider.
|
|
107
119
|
* @returns The OTEL MeterProvider instance.
|
|
108
120
|
*/
|
|
109
121
|
getMeterProvider(readers = []) {
|
|
122
|
+
if (this._meterProvider !== null && readers.length > 0) {
|
|
123
|
+
if (this._metricReaders.length === 0) {
|
|
124
|
+
const staleMeterProvider = this._meterProvider;
|
|
125
|
+
this._meterProvider = null;
|
|
126
|
+
staleMeterProvider.shutdown().catch(error => {
|
|
127
|
+
console.warn('Unable to shut down the previous MeterProvider.', error);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
console.warn('MeterProvider is already initialized with metric readers. The ' +
|
|
132
|
+
'additional readers passed to getMeterProvider() are ignored.');
|
|
133
|
+
}
|
|
134
|
+
}
|
|
110
135
|
if (this._meterProvider === null) {
|
|
111
|
-
const resource =
|
|
136
|
+
const resource = (0, resources_1.resourceFromAttributes)({
|
|
112
137
|
[Constants.MONITORED_RES_LABEL_KEY_PROJECT]: this._projectId,
|
|
113
138
|
[Constants.MONITORED_RES_LABEL_KEY_CLIENT_HASH]: this._clientHash,
|
|
114
|
-
[Constants.MONITORED_RES_LABEL_KEY_LOCATION]: this._location,
|
|
139
|
+
[Constants.MONITORED_RES_LABEL_KEY_LOCATION]: this._locationPromise ?? this._location,
|
|
115
140
|
[Constants.MONITORED_RES_LABEL_KEY_INSTANCE]: 'unknown',
|
|
116
141
|
[Constants.MONITORED_RES_LABEL_KEY_INSTANCE_CONFIG]: 'unknown',
|
|
117
142
|
});
|
|
143
|
+
void resource.waitForAsyncAttributes?.();
|
|
118
144
|
this._meterProvider = new sdk_metrics_1.MeterProvider({
|
|
119
145
|
resource: resource,
|
|
120
146
|
readers: readers,
|
|
121
147
|
views: Constants.METRIC_VIEWS,
|
|
122
148
|
});
|
|
149
|
+
this._metricReaders = readers;
|
|
123
150
|
this._createMetricInstruments();
|
|
124
151
|
}
|
|
125
152
|
return this._meterProvider;
|
|
@@ -140,6 +167,7 @@ class MetricsTracerFactory {
|
|
|
140
167
|
await this._meterProvider.shutdown();
|
|
141
168
|
}
|
|
142
169
|
this._meterProvider = null;
|
|
170
|
+
this._metricReaders = [];
|
|
143
171
|
this._currentOperationTracers = new Map();
|
|
144
172
|
this._currentOperationLastUpdatedMs = new Map();
|
|
145
173
|
}
|
|
@@ -191,6 +219,18 @@ class MetricsTracerFactory {
|
|
|
191
219
|
get clientName() {
|
|
192
220
|
return this._clientName;
|
|
193
221
|
}
|
|
222
|
+
/**
|
|
223
|
+
* Returns the detected client location.
|
|
224
|
+
*/
|
|
225
|
+
get location() {
|
|
226
|
+
return this._location;
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Returns true if the MeterProvider is initialized with at least one MetricReader.
|
|
230
|
+
*/
|
|
231
|
+
hasMetricReaders() {
|
|
232
|
+
return this._metricReaders.length > 0;
|
|
233
|
+
}
|
|
194
234
|
/**
|
|
195
235
|
* Creates a new MetricsTracer for a given resource name and method, and stores it for later retrieval.
|
|
196
236
|
* Returns null if metrics are disabled.
|
|
@@ -350,20 +390,23 @@ class MetricsTracerFactory {
|
|
|
350
390
|
return shiftedValue.toString(16).padStart(6, '0');
|
|
351
391
|
}
|
|
352
392
|
/**
|
|
353
|
-
* Gets the location (region) of the client,
|
|
354
|
-
* Uses
|
|
355
|
-
*
|
|
393
|
+
* Gets the location (region or zone) of the client, or defaults to "global".
|
|
394
|
+
* Uses the GCP resource detector to detect the location from the environment.
|
|
395
|
+
* Checks `cloud.region` first and falls back to `cloud.availability_zone`
|
|
396
|
+
* for zonal GKE clusters where `cloud.region` is not set.
|
|
397
|
+
* @returns The detected location string, or "global" if not found.
|
|
356
398
|
*/
|
|
357
399
|
static async _detectClientLocation() {
|
|
358
400
|
const defaultRegion = 'global';
|
|
359
401
|
try {
|
|
360
402
|
const resource = await (0, resources_1.detectResources)({
|
|
361
|
-
detectors: [
|
|
403
|
+
detectors: [resource_detector_gcp_1.gcpDetector],
|
|
362
404
|
});
|
|
363
405
|
await resource?.waitForAsyncAttributes?.();
|
|
364
|
-
const
|
|
365
|
-
|
|
366
|
-
|
|
406
|
+
const location = resource.attributes[Constants.ATTR_CLOUD_REGION] ??
|
|
407
|
+
resource.attributes[Constants.ATTR_CLOUD_AVAILABILITY_ZONE];
|
|
408
|
+
if (typeof location === 'string' && location) {
|
|
409
|
+
return location;
|
|
367
410
|
}
|
|
368
411
|
}
|
|
369
412
|
catch (err) {
|
|
@@ -47,10 +47,13 @@ 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;
|
|
53
|
-
this._exportAsync(metrics)
|
|
54
|
+
this._exportAsync(metrics)
|
|
55
|
+
.then(resultCallback)
|
|
56
|
+
.catch(err => {
|
|
54
57
|
resultCallback({ code: core_1.ExportResultCode.FAILED, error: err });
|
|
55
58
|
});
|
|
56
59
|
}
|
|
@@ -64,6 +67,9 @@ class CloudMonitoringMetricsExporter {
|
|
|
64
67
|
* @param resourceMetrics Metrics to be sent to the Google Cloud Monitoring backend
|
|
65
68
|
*/
|
|
66
69
|
async _exportAsync(resourceMetrics) {
|
|
70
|
+
if (resourceMetrics?.resource?.asyncAttributesPending) {
|
|
71
|
+
await resourceMetrics.resource.waitForAsyncAttributes?.();
|
|
72
|
+
}
|
|
67
73
|
const timeSeriesList = (0, transform_1.transformResourceMetricToTimeSeriesArray)(resourceMetrics, this._projectId);
|
|
68
74
|
let failure = {
|
|
69
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
|
};
|