@google-cloud/spanner 8.7.0 → 8.8.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.
@@ -178,7 +178,10 @@ class Database extends common.GrpcServiceObject {
178
178
  this._clientId = instance._nthClientId;
179
179
  }
180
180
  this._observabilityOptions = instance._observabilityOptions;
181
- this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.formattedName_, this._observabilityOptions?.enableEndToEndTracing);
181
+ this.commonHeaders_ = {
182
+ ...instance.commonHeaders_,
183
+ [common_1.CLOUD_RESOURCE_HEADER]: this.formattedName_,
184
+ };
182
185
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
183
186
  this.requestStream = instance.requestStream;
184
187
  this.sessionFactory_ = new session_factory_1.SessionFactory(this, name, poolOptions);
@@ -142,3 +142,19 @@ export declare function isInfinite(value: any): boolean;
142
142
  * @returns {Boolean} `true` if the value is an `Error` object, otherwise `false`.
143
143
  */
144
144
  export declare function isError(value: any): boolean;
145
+ /**
146
+ * Checks if a value is a UUID.
147
+ * @param {*} value The value to check.
148
+ * @returns {Boolean} `true` if the value is a UUID, otherwise `false`.
149
+ */
150
+ export declare function isUuid(value: any): boolean;
151
+ /**
152
+ * Populate the `{{projectId}}` placeholder.
153
+ *
154
+ * @throws {Error} If a projectId is required, but one is not provided.
155
+ *
156
+ * @param {*} - Any input value that may contain a placeholder. Arrays and objects will be looped.
157
+ * @param {string} projectId - A projectId. If not provided
158
+ * @return {*} - The original argument with all placeholders populated.
159
+ */
160
+ export declare function replaceProjectIdToken(value: any, projectId: string): any;
@@ -35,7 +35,10 @@ exports.isActualNaN = isActualNaN;
35
35
  exports.isDecimal = isDecimal;
36
36
  exports.isInfinite = isInfinite;
37
37
  exports.isError = isError;
38
+ exports.isUuid = isUuid;
39
+ exports.replaceProjectIdToken = replaceProjectIdToken;
38
40
  const google_gax_1 = require("google-gax");
41
+ const stream_1 = require("stream");
39
42
  /**
40
43
  * Checks whether the given error is a 'Database not found' error.
41
44
  * @param {Error} error The error to check.
@@ -246,4 +249,90 @@ function isError(value) {
246
249
  return (value instanceof Error ||
247
250
  Object.prototype.toString.call(value) === '[object Error]');
248
251
  }
252
+ const UUID_REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
253
+ /**
254
+ * Checks if a value is a UUID.
255
+ * @param {*} value The value to check.
256
+ * @returns {Boolean} `true` if the value is a UUID, otherwise `false`.
257
+ */
258
+ function isUuid(value) {
259
+ return typeof value === 'string' && UUID_REGEX.test(value);
260
+ }
261
+ const PROJECT_ID_TOKEN = '{{projectId}}';
262
+ const PROJECT_ID_TOKEN_REGEX = /{{projectId}}/g;
263
+ // Whitelisted request properties that contain, or lead to, resource name strings with project ID placeholders.
264
+ const KEYS_TO_SCAN = new Set([
265
+ 'database',
266
+ 'session',
267
+ 'name',
268
+ 'parent',
269
+ 'instance',
270
+ 'resource',
271
+ 'backup',
272
+ 'instanceConfig',
273
+ 'baseConfig',
274
+ 'kmsKeyName',
275
+ // Intermediate object keys that must be traversed to reach the above leaves
276
+ 'config',
277
+ 'encryptionConfig',
278
+ ]);
279
+ /**
280
+ * Populate the `{{projectId}}` placeholder.
281
+ *
282
+ * @throws {Error} If a projectId is required, but one is not provided.
283
+ *
284
+ * @param {*} - Any input value that may contain a placeholder. Arrays and objects will be looped.
285
+ * @param {string} projectId - A projectId. If not provided
286
+ * @return {*} - The original argument with all placeholders populated.
287
+ */
288
+ function replaceProjectIdToken(value, projectId) {
289
+ if (typeof value === 'string') {
290
+ if (value.includes(PROJECT_ID_TOKEN)) {
291
+ if (!projectId || projectId === PROJECT_ID_TOKEN) {
292
+ throw new MissingProjectIdError();
293
+ }
294
+ return value.replace(PROJECT_ID_TOKEN_REGEX, projectId);
295
+ }
296
+ return value;
297
+ }
298
+ if (value === null || typeof value !== 'object') {
299
+ return value;
300
+ }
301
+ if (Array.isArray(value)) {
302
+ for (let i = 0; i < value.length; i++) {
303
+ const original = value[i];
304
+ const processed = replaceProjectIdToken(original, projectId);
305
+ if (processed !== original) {
306
+ value[i] = processed;
307
+ }
308
+ }
309
+ return value;
310
+ }
311
+ if (value instanceof Buffer || value instanceof stream_1.Stream || isDate(value)) {
312
+ return value;
313
+ }
314
+ for (const key in value) {
315
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
316
+ if (!KEYS_TO_SCAN.has(key)) {
317
+ continue;
318
+ }
319
+ const original = value[key];
320
+ const processed = replaceProjectIdToken(original, projectId);
321
+ if (processed !== original) {
322
+ value[key] = processed;
323
+ }
324
+ }
325
+ }
326
+ return value;
327
+ }
328
+ /**
329
+ * Custom error type for missing project ID errors.
330
+ */
331
+ class MissingProjectIdError extends Error {
332
+ constructor() {
333
+ super(`Sorry, we cannot connect to Cloud Services without a project
334
+ ID. You may specify one with an environment variable named
335
+ "GOOGLE_CLOUD_PROJECT".`.replace(/ +/g, ' '));
336
+ }
337
+ }
249
338
  //# sourceMappingURL=helper.js.map
@@ -194,6 +194,7 @@ declare class Spanner extends GrpcService {
194
194
  } | null;
195
195
  private _universeDomain;
196
196
  private _isInSecureCredentials;
197
+ private _metricsEnabled;
197
198
  private static _isAFEServerTimingEnabled;
198
199
  readonly _nthClientId: number;
199
200
  /**
@@ -18,7 +18,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.Interval = exports.SpannerDate = exports.PGNumeric = exports.Numeric = exports.Struct = exports.Int = exports.Float = exports.Float32 = exports.protos = exports.v1 = exports.MutationSet = exports.MutationGroup = exports.Transaction = exports.Snapshot = exports.PartitionedDml = exports.Table = exports.SessionPool = exports.Session = exports.Backup = exports.Database = exports.InstanceConfig = exports.Instance = exports.Spanner = void 0;
19
19
  const service_1 = require("./common-grpc/service");
20
20
  const precise_date_1 = require("@google-cloud/precise-date");
21
- const projectify_1 = require("@google-cloud/projectify");
21
+ const helper_1 = require("./helper");
22
22
  const promisify_1 = require("@google-cloud/promisify");
23
23
  const extend = require("extend");
24
24
  const google_auth_library_1 = require("google-auth-library");
@@ -163,6 +163,7 @@ class Spanner extends service_1.GrpcService {
163
163
  sessionLabels;
164
164
  _universeDomain;
165
165
  _isInSecureCredentials;
166
+ _metricsEnabled = false;
166
167
  static _isAFEServerTimingEnabled;
167
168
  _nthClientId;
168
169
  /**
@@ -302,9 +303,11 @@ class Spanner extends service_1.GrpcService {
302
303
  this.directedReadOptions = directedReadOptions;
303
304
  this.defaultTransactionOptions = defaultTransactionOptions;
304
305
  this._observabilityOptions = options.observabilityOptions;
306
+ if ((0, instrument_1.isTracingEnabled)(this._observabilityOptions)) {
307
+ (0, instrument_1.ensureInitialContextManagerSet)();
308
+ }
305
309
  this.sessionLabels = options.sessionLabels || null;
306
310
  this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.projectFormattedName_, this._observabilityOptions?.enableEndToEndTracing);
307
- (0, instrument_1.ensureInitialContextManagerSet)();
308
311
  this._nthClientId = (0, request_id_header_1.nextSpannerClientId)();
309
312
  this._universeDomain = universeEndpoint;
310
313
  this.projectId_ = options.projectId;
@@ -766,10 +769,12 @@ class Spanner extends service_1.GrpcService {
766
769
  configureMetrics_(disableBuiltInMetrics) {
767
770
  // Only enable metrics if not explicitly disabled and we are not using
768
771
  // insecure credentials.
769
- const metricsEnabled = process.env.SPANNER_DISABLE_BUILTIN_METRICS !== 'true' &&
770
- !disableBuiltInMetrics &&
771
- !this._isInSecureCredentials;
772
- if (metricsEnabled) {
772
+ const metricsExplicitlyDisabled = process.env.SPANNER_DISABLE_BUILTIN_METRICS === 'true' ||
773
+ !!disableBuiltInMetrics;
774
+ this._metricsEnabled =
775
+ !metricsExplicitlyDisabled && !this._isInSecureCredentials;
776
+ metrics_tracer_factory_1.MetricsTracerFactory.enabled = this._metricsEnabled;
777
+ if (this._metricsEnabled) {
773
778
  try {
774
779
  this.auth.getProjectId((err, projectId) => {
775
780
  if (err || !projectId) {
@@ -778,7 +783,6 @@ class Spanner extends service_1.GrpcService {
778
783
  err);
779
784
  return;
780
785
  }
781
- metrics_tracer_factory_1.MetricsTracerFactory.enabled = metricsEnabled;
782
786
  this.projectId_ = projectId;
783
787
  const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(projectId);
784
788
  const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
@@ -822,33 +826,35 @@ class Spanner extends service_1.GrpcService {
822
826
  }
823
827
  const gaxClient = this.clients_.get(clientName);
824
828
  let reqOpts = extend(true, {}, config.reqOpts);
825
- reqOpts = (0, projectify_1.replaceProjectIdToken)(reqOpts, projectId);
829
+ reqOpts = (0, helper_1.replaceProjectIdToken)(reqOpts, projectId);
826
830
  // It would have been preferable to replace the projectId already in the
827
831
  // constructor of Spanner, but that is not possible as auth.getProjectId
828
832
  // is an async method. This is therefore the first place where we have
829
833
  // access to the value that should be used instead of the placeholder.
830
834
  if (!this.projectIdReplaced_) {
831
- this.projectId = (0, projectify_1.replaceProjectIdToken)(this.projectId, projectId);
832
- this.projectFormattedName_ = (0, projectify_1.replaceProjectIdToken)(this.projectFormattedName_, projectId);
835
+ this.projectId = (0, helper_1.replaceProjectIdToken)(this.projectId, projectId);
836
+ this.projectFormattedName_ = (0, helper_1.replaceProjectIdToken)(this.projectFormattedName_, projectId);
833
837
  this.instances_.forEach(instance => {
834
- instance.formattedName_ = (0, projectify_1.replaceProjectIdToken)(instance.formattedName_, projectId);
838
+ instance.formattedName_ = (0, helper_1.replaceProjectIdToken)(instance.formattedName_, projectId);
835
839
  instance.databases_.forEach(database => {
836
- database.formattedName_ = (0, projectify_1.replaceProjectIdToken)(database.formattedName_, projectId);
840
+ database.formattedName_ = (0, helper_1.replaceProjectIdToken)(database.formattedName_, projectId);
837
841
  });
838
842
  });
839
843
  this.projectIdReplaced_ = true;
840
844
  }
841
- config.headers[common_1.CLOUD_RESOURCE_HEADER] = (0, projectify_1.replaceProjectIdToken)(config.headers[common_1.CLOUD_RESOURCE_HEADER], projectId);
842
- // Do context propagation
843
- api_1.propagation.inject(api_1.context.active(), config.headers, {
844
- set: (carrier, key, value) => {
845
- carrier[key] = value; // Set the span context (trace and span ID)
846
- },
847
- });
848
- // Attach the x-goog-spanner-request-id to the currently active span.
849
- (0, request_id_header_1.attributeXGoogSpannerRequestIdToActiveSpan)(config);
845
+ config.headers[common_1.CLOUD_RESOURCE_HEADER] = (0, helper_1.replaceProjectIdToken)(config.headers[common_1.CLOUD_RESOURCE_HEADER], projectId);
846
+ if ((0, instrument_1.isTracingEnabled)(this._observabilityOptions)) {
847
+ // Do context propagation
848
+ api_1.propagation.inject(api_1.context.active(), config.headers, {
849
+ set: (carrier, key, value) => {
850
+ carrier[key] = value; // Set the span context (trace and span ID)
851
+ },
852
+ });
853
+ // Attach the x-goog-spanner-request-id to the currently active span.
854
+ (0, request_id_header_1.attributeXGoogSpannerRequestIdToActiveSpan)(config);
855
+ }
850
856
  const interceptors = [];
851
- if (metrics_tracer_factory_1.MetricsTracerFactory.enabled) {
857
+ if (this._metricsEnabled) {
852
858
  interceptors.push(interceptor_1.MetricInterceptor);
853
859
  }
854
860
  const requestFn = gaxClient[config.method].bind(gaxClient, reqOpts,
@@ -919,7 +925,9 @@ class Spanner extends service_1.GrpcService {
919
925
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
920
926
  request(config, callback) {
921
927
  let metricsTracer = null;
922
- if (config.client === 'SpannerClient' && this.projectId_) {
928
+ if (this._metricsEnabled &&
929
+ config.client === 'SpannerClient' &&
930
+ this.projectId_) {
923
931
  metricsTracer =
924
932
  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;
925
933
  }
@@ -982,7 +990,9 @@ class Spanner extends service_1.GrpcService {
982
990
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
983
991
  requestStream(config) {
984
992
  let metricsTracer = null;
985
- if (config.client === 'SpannerClient' && this.projectId_) {
993
+ if (this._metricsEnabled &&
994
+ config.client === 'SpannerClient' &&
995
+ this.projectId_) {
986
996
  metricsTracer =
987
997
  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;
988
998
  }
@@ -122,7 +122,10 @@ class Instance extends common.GrpcServiceObject {
122
122
  this.requestStream = spanner.requestStream.bind(spanner);
123
123
  this.databases_ = new Map();
124
124
  this._observabilityOptions = spanner._observabilityOptions;
125
- this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.formattedName_, this._observabilityOptions?.enableEndToEndTracing);
125
+ this.commonHeaders_ = {
126
+ ...spanner.commonHeaders_,
127
+ [common_1.CLOUD_RESOURCE_HEADER]: this.formattedName_,
128
+ };
126
129
  }
127
130
  /**
128
131
  * Get a reference to a Backup object.
@@ -47,6 +47,16 @@ declare const SPAN_NAMESPACE_PREFIX = "CloudSpanner";
47
47
  export { SPAN_NAMESPACE_PREFIX, traceConfig };
48
48
  declare function ensureInitialContextManagerSet(): void;
49
49
  export { ensureInitialContextManagerSet };
50
+ /**
51
+ * isTracingEnabled returns true if tracing is enabled for the given options
52
+ * or globally.
53
+ *
54
+ * @param {ObservabilityOptions} [opts] The observability options.
55
+ * @returns {boolean} True if tracing is enabled.
56
+ */
57
+ export declare function isTracingEnabled(opts?: ObservabilityOptions): boolean;
58
+ /** Only exported for resetting state in unit tests. */
59
+ export declare function _resetTracingEnabledForTest(): void;
50
60
  /**
51
61
  * startTrace begins an active span in the current active context
52
62
  * and passes it back to the set callback function. Each span will
@@ -18,6 +18,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.SPAN_NAMESPACE_PREFIX = exports.TRACER_VERSION = exports.TRACER_NAME = void 0;
19
19
  exports.getTracer = getTracer;
20
20
  exports.ensureInitialContextManagerSet = ensureInitialContextManagerSet;
21
+ exports.isTracingEnabled = isTracingEnabled;
22
+ exports._resetTracingEnabledForTest = _resetTracingEnabledForTest;
21
23
  exports.startTrace = startTrace;
22
24
  exports.setSpanError = setSpanError;
23
25
  exports.setSpanErrorAndException = setSpanErrorAndException;
@@ -46,25 +48,81 @@ function getTracer(tracerProvider) {
46
48
  const SPAN_NAMESPACE_PREFIX = 'CloudSpanner'; // TODO: discuss & standardize this prefix.
47
49
  exports.SPAN_NAMESPACE_PREFIX = SPAN_NAMESPACE_PREFIX;
48
50
  const { AsyncHooksContextManager, } = require('@opentelemetry/context-async-hooks');
51
+ let contextManagerInstallAttempted = false;
49
52
  /*
50
- * This function ensures that async/await works correctly by
51
- * checking if context.active() returns an invalid/unset context
52
- * and if so, sets a global AsyncHooksContextManager otherwise
53
- * spans resulting from async/await invocations won't be correctly
54
- * associated in their respective hierarchies.
53
+ * If no global ContextManager is registered, install an AsyncHooksContextManager
54
+ * so that async/await trace context propagation works for apps that haven't
55
+ * configured OpenTelemetry themselves. If the host app has already installed a
56
+ * ContextManager, leave it alone — tearing down a working manager breaks the
57
+ * host's baggage and span parentage on the next gRPC call.
58
+ *
59
+ * setGlobalContextManager() returns false when a manager is already registered,
60
+ * which is the documented signal that we shouldn't replace it. The
61
+ * `contextManagerInstallAttempted` latch makes the call idempotent so we don't
62
+ * allocate a new AsyncHooksContextManager on each Spanner client construction.
55
63
  */
56
64
  function ensureInitialContextManagerSet() {
57
- if (!api_1.context['_contextManager'] || api_1.context.active() === api_1.ROOT_CONTEXT) {
58
- // If no context manager is currently set, or if the active context is the ROOT_CONTEXT,
59
- // trace context propagation cannot
60
- // function correctly with async/await for OpenTelemetry
61
- // See {@link https://opentelemetry.io/docs/languages/js/context/#active-context}
62
- api_1.context.disable(); // Disable any prior contextManager.
63
- const contextManager = new AsyncHooksContextManager();
65
+ if (contextManagerInstallAttempted)
66
+ return;
67
+ contextManagerInstallAttempted = true;
68
+ const contextManager = new AsyncHooksContextManager();
69
+ if (api_1.context.setGlobalContextManager(contextManager)) {
64
70
  contextManager.enable();
65
- api_1.context.setGlobalContextManager(contextManager);
66
71
  }
67
72
  }
73
+ let globalTracingEnabled = undefined;
74
+ let lastCheckTime = 0;
75
+ const CACHE_TTL_MS = 10000; // 10 seconds TTL
76
+ /**
77
+ * isGlobalTracingEnabled returns true if tracing is enabled globally,
78
+ * respecting cached status and active recording spans.
79
+ *
80
+ * @returns {boolean} True if global tracing is enabled.
81
+ */
82
+ function isGlobalTracingEnabled() {
83
+ const now = Date.now();
84
+ if (globalTracingEnabled !== undefined &&
85
+ (globalTracingEnabled || now - lastCheckTime < CACHE_TTL_MS)) {
86
+ return globalTracingEnabled;
87
+ }
88
+ lastCheckTime = now;
89
+ const globalProvider = api_1.trace.getTracerProvider();
90
+ if (globalProvider) {
91
+ let delegate = globalProvider;
92
+ if (typeof globalProvider.getDelegate === 'function') {
93
+ delegate = globalProvider.getDelegate();
94
+ }
95
+ if (delegate) {
96
+ const name = delegate.constructor.name;
97
+ // Exclude the dummy NoopTracerProvider and uninitialized ProxyTracerProvider
98
+ if (name !== 'NoopTracerProvider' && name !== 'ProxyTracerProvider') {
99
+ globalTracingEnabled = true;
100
+ ensureInitialContextManagerSet();
101
+ return true;
102
+ }
103
+ }
104
+ }
105
+ globalTracingEnabled = false;
106
+ return false;
107
+ }
108
+ /**
109
+ * isTracingEnabled returns true if tracing is enabled for the given options
110
+ * or globally.
111
+ *
112
+ * @param {ObservabilityOptions} [opts] The observability options.
113
+ * @returns {boolean} True if tracing is enabled.
114
+ */
115
+ function isTracingEnabled(opts) {
116
+ if (opts?.tracerProvider) {
117
+ return true;
118
+ }
119
+ return isGlobalTracingEnabled();
120
+ }
121
+ /** Only exported for resetting state in unit tests. */
122
+ function _resetTracingEnabledForTest() {
123
+ globalTracingEnabled = undefined;
124
+ lastCheckTime = 0;
125
+ }
68
126
  /**
69
127
  * startTrace begins an active span in the current active context
70
128
  * and passes it back to the set callback function. Each span will
@@ -74,6 +132,9 @@ function ensureInitialContextManagerSet() {
74
132
  * @returns {Span} The created span.
75
133
  */
76
134
  function startTrace(spanNameSuffix, config, cb) {
135
+ if (!isTracingEnabled(config?.opts)) {
136
+ return cb(new noopSpan());
137
+ }
77
138
  if (!config) {
78
139
  config = {};
79
140
  }
@@ -59,7 +59,7 @@ export declare class MetricsTracerFactory {
59
59
  /**
60
60
  * Resets the singleton instance of the MetricsTracerFactory.
61
61
  */
62
- static resetInstance(projectId?: string): Promise<void>;
62
+ static resetInstance(): Promise<void>;
63
63
  /**
64
64
  * Resets the MeterProvider.
65
65
  */
@@ -17,8 +17,8 @@ exports.MetricsTracerFactory = void 0;
17
17
  const crypto = require("crypto");
18
18
  const os = require("os");
19
19
  const process = require("process");
20
- const uuid_1 = require("uuid");
21
20
  const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
21
+ const api_1 = require("@opentelemetry/api");
22
22
  const resources_1 = require("@opentelemetry/resources");
23
23
  const opentelemetry_resource_util_1 = require("@google-cloud/opentelemetry-resource-util");
24
24
  const Constants = require("./constants");
@@ -78,7 +78,7 @@ class MetricsTracerFactory {
78
78
  }
79
79
  this._clientHash = MetricsTracerFactory._generateClientHash(this._clientUid);
80
80
  // Start the Tracer cleanup task at an interval
81
- this._intervalTracerCleanup = setInterval(this._cleanMetricsTracers.bind(this), Constants.TRACER_CLEANUP_INTERVAL_MS);
81
+ this._intervalTracerCleanup = api_1.context.with(api_1.ROOT_CONTEXT, () => setInterval(this._cleanMetricsTracers.bind(this), Constants.TRACER_CLEANUP_INTERVAL_MS));
82
82
  // unref the interval to prevent it from blocking app termination
83
83
  // in the event loop
84
84
  this._intervalTracerCleanup.unref();
@@ -127,7 +127,7 @@ class MetricsTracerFactory {
127
127
  /**
128
128
  * Resets the singleton instance of the MetricsTracerFactory.
129
129
  */
130
- static async resetInstance(projectId) {
130
+ static async resetInstance() {
131
131
  clearInterval(MetricsTracerFactory._instance?._intervalTracerCleanup);
132
132
  await MetricsTracerFactory._instance?.resetMeterProvider();
133
133
  MetricsTracerFactory._instance = null;
@@ -255,7 +255,7 @@ class MetricsTracerFactory {
255
255
  * @param requestId The request id of the gRPC call set under 'x-goog-spanner-request-id'.
256
256
  */
257
257
  clearCurrentTracer(requestId) {
258
- const operationRequest = this._extractOperationRequest(requestId);
258
+ const operationRequest = this._extractOperationRequest(requestId) || requestId;
259
259
  if (!this._currentOperationTracers.has(operationRequest)) {
260
260
  return;
261
261
  }
@@ -313,7 +313,7 @@ class MetricsTracerFactory {
313
313
  * @returns A unique string identifier for the client.
314
314
  */
315
315
  static _generateClientUId() {
316
- const identifier = (0, uuid_1.v4)();
316
+ const identifier = crypto.randomUUID();
317
317
  const pid = process.pid.toString();
318
318
  let hostname = 'localhost';
319
319
  try {
@@ -14,7 +14,7 @@ declare class MetricAttemptTracer {
14
14
  /**
15
15
  * Returns the start time of the attempt.
16
16
  */
17
- get startTime(): Date;
17
+ get startTime(): number;
18
18
  }
19
19
  /**
20
20
  * MetricOperationTracer tracks the lifecycle and metadata of a single gRPC spanner operation,
@@ -50,7 +50,7 @@ declare class MetricOperationTracer {
50
50
  /**
51
51
  * Returns the start time of the operation.
52
52
  */
53
- get startTime(): Date;
53
+ get startTime(): number;
54
54
  /**
55
55
  * Increments the attempt count and creates a new MetricAttemptTracer
56
56
  * for tracking the next attempt within this operation.
@@ -107,7 +107,7 @@ export declare class MetricsTracer {
107
107
  */
108
108
  constructor(_instrumentAttemptCounter: Counter | null, _instrumentAttemptLatency: Histogram | null, _instrumentOperationCounter: Counter | null, _instrumentOperationLatency: Histogram | null, _instrumentGfeConnectivityErrorCount: Counter | null, _instrumentGfeLatency: Histogram | null, _instrumentAfeConnectivityErrorCount: Counter | null, _instrumentAfeLatency: Histogram | null, enabled: boolean, _database: string, _instance: string, _projectId: string, _methodName: string, _request: string);
109
109
  /**
110
- * Returns the difference in milliseconds between two Date objects.
110
+ * Returns the difference in milliseconds between two times.
111
111
  * @param start The start time.
112
112
  * @param end The end time.
113
113
  * @returns The time difference in milliseconds.
@@ -29,7 +29,7 @@ class MetricAttemptTracer {
29
29
  _startTime;
30
30
  status;
31
31
  constructor() {
32
- this._startTime = new Date(Date.now());
32
+ this._startTime = performance.now();
33
33
  this.status = grpc_js_1.status[grpc_js_1.status.UNKNOWN];
34
34
  }
35
35
  /**
@@ -63,7 +63,7 @@ class MetricOperationTracer {
63
63
  _currentAttempt;
64
64
  constructor() {
65
65
  this._attemptCount = 0;
66
- this._startTime = new Date(Date.now());
66
+ this._startTime = performance.now();
67
67
  this._currentAttempt = null;
68
68
  }
69
69
  /**
@@ -167,13 +167,13 @@ class MetricsTracer {
167
167
  this._clientAttributes[constants_1.MONITORED_RES_LABEL_KEY_INSTANCE] = _instance;
168
168
  }
169
169
  /**
170
- * Returns the difference in milliseconds between two Date objects.
170
+ * Returns the difference in milliseconds between two times.
171
171
  * @param start The start time.
172
172
  * @param end The end time.
173
173
  * @returns The time difference in milliseconds.
174
174
  */
175
175
  _getMillisecondTimeDifference(start, end) {
176
- return end.valueOf() - start.valueOf();
176
+ return end - start;
177
177
  }
178
178
  /**
179
179
  * Gets the current client and resource attributes for metrics.
@@ -224,7 +224,7 @@ class MetricsTracer {
224
224
  return;
225
225
  this.currentOperation.currentAttempt.status = grpc_js_1.status[statusCode];
226
226
  const attemptAttributes = this._createAttemptOtelAttributes();
227
- const endTime = new Date(Date.now());
227
+ const endTime = performance.now();
228
228
  const attemptLatencyMilliseconds = this._getMillisecondTimeDifference(this.currentOperation.currentAttempt.startTime, endTime);
229
229
  this.instrumentAttemptLatency?.record(attemptLatencyMilliseconds, attemptAttributes);
230
230
  this.instrumentAttemptCounter?.add(1, attemptAttributes);
@@ -247,7 +247,7 @@ class MetricsTracer {
247
247
  recordOperationCompletion() {
248
248
  if (!this.enabled || !this.currentOperation)
249
249
  return;
250
- const endTime = new Date(Date.now());
250
+ const endTime = performance.now();
251
251
  const operationAttributes = this._createOperationOtelAttributes();
252
252
  const operationLatencyMilliseconds = this._getMillisecondTimeDifference(this.currentOperation.startTime, endTime);
253
253
  this.instrumentOperationCounter?.add(1, operationAttributes);
@@ -17,6 +17,7 @@
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.MultiplexedSession = void 0;
19
19
  const events_1 = require("events");
20
+ const api_1 = require("@opentelemetry/api");
20
21
  const instrument_1 = require("./instrument");
21
22
  /**
22
23
  * Class used to manage connections to Spanner using multiplexed session.
@@ -83,22 +84,24 @@ class MultiplexedSession extends events_1.EventEmitter {
83
84
  opts: this._observabilityOptions,
84
85
  dbName: this.database.formattedName_,
85
86
  };
86
- return (0, instrument_1.startTrace)('MultiplexedSession.createSession', traceConfig, async (span) => {
87
- span.addEvent('Requesting a multiplexed session');
88
- try {
89
- const [createSessionResponse] = await this.database.createSession({
90
- multiplexed: true,
91
- });
92
- this._multiplexedSession = createSessionResponse;
93
- span.addEvent('Created a multiplexed session');
94
- }
95
- catch (e) {
96
- (0, instrument_1.setSpanError)(span, e);
97
- throw e;
98
- }
99
- finally {
100
- span.end();
101
- }
87
+ return api_1.context.with(api_1.ROOT_CONTEXT, () => {
88
+ return (0, instrument_1.startTrace)('MultiplexedSession.createSession', traceConfig, async (span) => {
89
+ span.addEvent('Requesting a multiplexed session');
90
+ try {
91
+ const [createSessionResponse] = await this.database.createSession({
92
+ multiplexed: true,
93
+ });
94
+ this._multiplexedSession = createSessionResponse;
95
+ span.addEvent('Created a multiplexed session');
96
+ }
97
+ catch (e) {
98
+ (0, instrument_1.setSpanError)(span, e);
99
+ throw e;
100
+ }
101
+ finally {
102
+ span.end();
103
+ }
104
+ });
102
105
  });
103
106
  };
104
107
  // Assign the running task to the shared promise variable, and ensure
@@ -132,9 +135,9 @@ class MultiplexedSession extends events_1.EventEmitter {
132
135
  clearInterval(this._refreshHandle);
133
136
  }
134
137
  const refreshRate = this.refreshRate * 24 * 60 * 60000;
135
- this._refreshHandle = setInterval(async () => {
136
- await this._createSession().catch(() => { });
137
- }, refreshRate);
138
+ this._refreshHandle = api_1.context.with(api_1.ROOT_CONTEXT, () => setInterval(() => {
139
+ this._createSession().catch(() => { });
140
+ }, refreshRate));
138
141
  // Unreference the timer so it does not prevent the Node.js process from exiting.
139
142
  // If the application has finished all other work, this background timer shouldn't
140
143
  // force the process to stay open.
@@ -158,6 +158,7 @@ interface ResultEvents {
158
158
  export declare class PartialResultStream extends Transform implements ResultEvents {
159
159
  private _destroyed;
160
160
  private _fields;
161
+ private _decoders;
161
162
  private _options;
162
163
  private _pendingValue?;
163
164
  private _pendingValueForResume?;
@@ -199,6 +200,16 @@ export declare class PartialResultStream extends Transform implements ResultEven
199
200
  * @param {*} value The complete value.
200
201
  */
201
202
  private _addValue;
203
+ /**
204
+ * Directly creates a plain JSON object from row cell values, bypassing
205
+ * Struct, Row, and WrappedNumber class wrappers when possible.
206
+ *
207
+ * @private
208
+ *
209
+ * @param {Value[]} values The raw cell values for the current row.
210
+ * @returns {Json} The plain JavaScript object representing the row.
211
+ */
212
+ private _createJsonRow;
202
213
  /**
203
214
  * Converts an array of values into a row.
204
215
  *