@google-cloud/spanner 9.0.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.
Files changed (40) hide show
  1. package/README.md +1 -16
  2. package/build/src/batch-transaction.js +15 -12
  3. package/build/src/codec.d.ts +6 -0
  4. package/build/src/codec.js +99 -34
  5. package/build/src/common.d.ts +14 -0
  6. package/build/src/common.js +27 -1
  7. package/build/src/database.d.ts +31 -41
  8. package/build/src/database.js +122 -313
  9. package/build/src/helper.d.ts +12 -0
  10. package/build/src/helper.js +44 -0
  11. package/build/src/index.d.ts +16 -8
  12. package/build/src/index.js +210 -90
  13. package/build/src/instance.d.ts +15 -2
  14. package/build/src/instance.js +11 -2
  15. package/build/src/instrument.d.ts +12 -1
  16. package/build/src/instrument.js +13 -0
  17. package/build/src/metrics/constants.d.ts +6 -0
  18. package/build/src/metrics/constants.js +6 -1
  19. package/build/src/metrics/interceptor.js +32 -28
  20. package/build/src/metrics/metrics-tracer-factory.d.ts +6 -11
  21. package/build/src/metrics/metrics-tracer-factory.js +62 -64
  22. package/build/src/metrics/metrics-tracer.d.ts +19 -6
  23. package/build/src/metrics/metrics-tracer.js +147 -55
  24. package/build/src/multiplexed-session.d.ts +13 -2
  25. package/build/src/multiplexed-session.js +20 -4
  26. package/build/src/partial-result-stream.d.ts +26 -33
  27. package/build/src/partial-result-stream.js +263 -283
  28. package/build/src/request-stream-coordinator.d.ts +88 -0
  29. package/build/src/request-stream-coordinator.js +229 -0
  30. package/build/src/request_id_header.d.ts +6 -4
  31. package/build/src/request_id_header.js +24 -24
  32. package/build/src/session-factory.d.ts +52 -63
  33. package/build/src/session-factory.js +41 -92
  34. package/build/src/session-pool.d.ts +97 -227
  35. package/build/src/session-pool.js +74 -547
  36. package/build/src/session.js +1 -1
  37. package/build/src/transaction-runner.js +1 -12
  38. package/build/src/transaction.d.ts +5 -5
  39. package/build/src/transaction.js +72 -112
  40. package/package.json +9 -10
@@ -47,7 +47,15 @@ export type GetBackupsResponse = PagedResponse<Backup, databaseAdmin.spanner.adm
47
47
  export type GetBackupOperationsResponse = PagedResponse<IOperation, databaseAdmin.spanner.admin.database.v1.IListBackupOperationsResponse>;
48
48
  export type GetDatabaseOperationsResponse = PagedResponse<IOperation, databaseAdmin.spanner.admin.database.v1.IListDatabaseOperationsResponse>;
49
49
  export interface CreateDatabaseOptions extends databaseAdmin.spanner.admin.database.v1.ICreateDatabaseRequest {
50
+ /**
51
+ * @deprecated Session pool options are deprecated and will be removed in a future release.
52
+ * Multiplexed sessions are now used for all operations by default.
53
+ */
50
54
  poolOptions?: SessionPoolOptions;
55
+ /**
56
+ * @deprecated Custom session pool constructors are deprecated and will be removed in a future release.
57
+ * Multiplexed sessions are now used for all operations by default.
58
+ */
51
59
  poolCtor?: SessionPool;
52
60
  schema?: string | string[];
53
61
  gaxOptions?: CallOptions;
@@ -331,8 +339,8 @@ declare class Instance extends common.GrpcServiceObject {
331
339
  * Config for the new database.
332
340
  *
333
341
  * @typedef {object} CreateDatabaseRequest
334
- * @property {SessionPoolOptions} [poolOptions]
335
- * @property {SessionPoolCtor} [poolCtor]
342
+ * @property {SessionPoolOptions} [poolOptions] **Deprecated**. Session pool options are deprecated and will be removed in a future release.
343
+ * @property {SessionPoolCtor} [poolCtor] **Deprecated**. Custom session pool constructors are deprecated and will be removed in a future release.
336
344
  */
337
345
  /**
338
346
  * @typedef {array} CreateDatabaseResponse
@@ -424,10 +432,15 @@ declare class Instance extends common.GrpcServiceObject {
424
432
  * @param {string} name The name of the instance.
425
433
  * @param {SessionPoolOptions|SessionPoolCtor} [poolOptions] Session pool
426
434
  * configuration options.
435
+ * **Deprecated**. Session pool options is deprecated and will be removed in a future release.
436
+ * Multiplexed sessions are now used for all operations by default, eliminating
437
+ * the need for session pooling.
427
438
  * @param {spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions} [queryOptions]
428
439
  * Default query options to use with the database. These options will be
429
440
  * overridden by any query options set in environment variables or that
430
441
  * are specified on a per-query basis.
442
+ * @param {string} [databaseRole] The database role to use for sessions on
443
+ * the database.
431
444
  * @return {Database} A Database object.
432
445
  *
433
446
  * @example
@@ -505,10 +505,15 @@ class Instance extends common.GrpcServiceObject {
505
505
  * @param {string} name The name of the instance.
506
506
  * @param {SessionPoolOptions|SessionPoolCtor} [poolOptions] Session pool
507
507
  * configuration options.
508
+ * **Deprecated**. Session pool options is deprecated and will be removed in a future release.
509
+ * Multiplexed sessions are now used for all operations by default, eliminating
510
+ * the need for session pooling.
508
511
  * @param {spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions} [queryOptions]
509
512
  * Default query options to use with the database. These options will be
510
513
  * overridden by any query options set in environment variables or that
511
514
  * are specified on a per-query basis.
515
+ * @param {string} [databaseRole] The database role to use for sessions on
516
+ * the database.
512
517
  * @return {Database} A Database object.
513
518
  *
514
519
  * @example
@@ -524,8 +529,8 @@ class Instance extends common.GrpcServiceObject {
524
529
  if (!name) {
525
530
  throw new google_gax_1.GoogleError('A name is required to access a Database object.');
526
531
  }
527
- // Only add an additional key for SessionPoolOptions and QueryOptions if an
528
- // options object with at least one value was passed in.
532
+ // Only add an additional key for SessionPoolOptions, QueryOptions, and databaseRole
533
+ // if provided.
529
534
  let optionsKey = poolOptions && Object.keys(poolOptions).length > 0
530
535
  ? '/' + JSON.stringify(Object.entries(poolOptions).sort())
531
536
  : '';
@@ -533,6 +538,9 @@ class Instance extends common.GrpcServiceObject {
533
538
  optionsKey =
534
539
  optionsKey + '/' + JSON.stringify(Object.entries(queryOptions).sort());
535
540
  }
541
+ if (databaseRole) {
542
+ optionsKey = optionsKey + '/' + databaseRole;
543
+ }
536
544
  const key = name.split('/').pop() + optionsKey;
537
545
  if (!this.databases_.has(key)) {
538
546
  const db = new database_1.Database(this, name, poolOptions, queryOptions, databaseRole);
@@ -569,6 +577,7 @@ class Instance extends common.GrpcServiceObject {
569
577
  }
570
578
  callback(err, resp);
571
579
  });
580
+ return null;
572
581
  });
573
582
  }
574
583
  exists(optionsOrCallback, cb) {
@@ -43,8 +43,19 @@ interface traceConfig {
43
43
  requestTag?: string | null;
44
44
  opts?: ObservabilityOptions;
45
45
  }
46
+ interface QueryWithRequestOptions {
47
+ sql?: string | SQLStatement;
48
+ requestOptions?: {
49
+ requestTag?: string | null;
50
+ transactionTag?: string | null;
51
+ } | null;
52
+ }
53
+ declare function getQueryTraceConfig(query?: string | QueryWithRequestOptions | null): {
54
+ sql?: string | SQLStatement;
55
+ requestTag?: string | null;
56
+ };
46
57
  declare const SPAN_NAMESPACE_PREFIX = "CloudSpanner";
47
- export { SPAN_NAMESPACE_PREFIX, traceConfig };
58
+ export { SPAN_NAMESPACE_PREFIX, traceConfig, QueryWithRequestOptions, getQueryTraceConfig, };
48
59
  declare function ensureInitialContextManagerSet(): void;
49
60
  export { ensureInitialContextManagerSet };
50
61
  /**
@@ -17,6 +17,7 @@
17
17
  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
+ exports.getQueryTraceConfig = getQueryTraceConfig;
20
21
  exports.ensureInitialContextManagerSet = ensureInitialContextManagerSet;
21
22
  exports.isTracingEnabled = isTracingEnabled;
22
23
  exports._resetTracingEnabledForTest = _resetTracingEnabledForTest;
@@ -45,6 +46,18 @@ function getTracer(tracerProvider) {
45
46
  // Otherwise use the global tracer.
46
47
  return api_1.trace.getTracer(TRACER_NAME, TRACER_VERSION);
47
48
  }
49
+ function getQueryTraceConfig(query) {
50
+ if (typeof query === 'string') {
51
+ return { sql: query };
52
+ }
53
+ if (query && typeof query === 'object') {
54
+ return {
55
+ sql: query.sql,
56
+ requestTag: query.requestOptions?.requestTag,
57
+ };
58
+ }
59
+ return {};
60
+ }
48
61
  const SPAN_NAMESPACE_PREFIX = 'CloudSpanner'; // TODO: discuss & standardize this prefix.
49
62
  exports.SPAN_NAMESPACE_PREFIX = SPAN_NAMESPACE_PREFIX;
50
63
  const { AsyncHooksContextManager, } = require('@opentelemetry/context-async-hooks');
@@ -2,7 +2,13 @@ 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
+ /**
6
+ * @deprecated No longer used after eliminating the background tracer cleanup timer.
7
+ */
5
8
  export declare const TRACER_CLEANUP_THRESHOLD_MS: number;
9
+ /**
10
+ * @deprecated No longer used after eliminating the background tracer cleanup timer.
11
+ */
6
12
  export declare const TRACER_CLEANUP_INTERVAL_MS: number;
7
13
  export declare const ATTR_CLOUD_REGION = "cloud.region";
8
14
  export declare const ATTR_CLOUD_AVAILABILITY_ZONE = "cloud.availability_zone";
@@ -18,8 +18,13 @@ const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
18
18
  exports.SPANNER_METER_NAME = 'spanner-nodejs';
19
19
  exports.CLIENT_METRICS_PREFIX = 'spanner.googleapis.com/internal/client';
20
20
  exports.SPANNER_RESOURCE_TYPE = 'spanner_instance_client';
21
- // Maximum time to keep MetricsTracers before considering them stale, and stop tracking them.
21
+ /**
22
+ * @deprecated No longer used after eliminating the background tracer cleanup timer.
23
+ */
22
24
  exports.TRACER_CLEANUP_THRESHOLD_MS = 60 * 60 * 1000; // 60 minutes
25
+ /**
26
+ * @deprecated No longer used after eliminating the background tracer cleanup timer.
27
+ */
23
28
  exports.TRACER_CLEANUP_INTERVAL_MS = 30 * 60 * 1000; // 30 Minutes
24
29
  // OTel semantic conventions
25
30
  // See https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv
@@ -15,7 +15,7 @@
15
15
  Object.defineProperty(exports, "__esModule", { value: true });
16
16
  exports.MetricInterceptor = void 0;
17
17
  const google_gax_1 = require("google-gax");
18
- const metrics_tracer_factory_1 = require("./metrics-tracer-factory");
18
+ const common_1 = require("../common");
19
19
  /**
20
20
  * Interceptor for recording metrics on gRPC calls.
21
21
  *
@@ -30,17 +30,11 @@ const metrics_tracer_factory_1 = require("./metrics-tracer-factory");
30
30
  const MetricInterceptor = (options, nextCall) => {
31
31
  return new google_gax_1.grpc.InterceptingCall(nextCall(options), {
32
32
  start: function (metadata, listener, next) {
33
- // Record attempt metric on request start
34
- const resourcePrefix = metadata.get('google-cloud-resource-prefix')[0];
35
- const match = resourcePrefix?.match(/^projects\/([^/]+)\//);
36
- const projectId = match ? match[1] : undefined;
37
- let factory;
38
- if (projectId) {
39
- factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(projectId);
40
- }
41
- const requestId = metadata.get('x-goog-spanner-request-id')[0];
42
- const metricsTracer = factory?.getCurrentTracer(requestId);
33
+ // Record attempt metric on request start.
34
+ // The tracer is carried directly on the call options.
35
+ const metricsTracer = options?.metricsTracer ?? null;
43
36
  metricsTracer?.recordAttemptStart();
37
+ const afeServerTimingEnabled = (0, common_1.isAFEServerTimingEnabled)();
44
38
  const interceptingListener = {
45
39
  onReceiveMetadata: function (metadata) {
46
40
  // Record GFE/AFE Metrics
@@ -51,10 +45,12 @@ const MetricInterceptor = (options, nextCall) => {
51
45
  const serverTimingHeader = serverTimingEntries.length > 0
52
46
  ? String(serverTimingEntries[0])
53
47
  : undefined;
54
- const gfeTiming = metricsTracer?.extractGfeLatency(serverTimingHeader);
48
+ const gfeTiming = metricsTracer.extractGfeLatency(serverTimingHeader);
55
49
  metricsTracer.gfeLatency = gfeTiming ?? null;
56
- const afeTiming = metricsTracer?.extractAfeLatency(serverTimingHeader);
57
- metricsTracer.afeLatency = afeTiming ?? null;
50
+ if (afeServerTimingEnabled) {
51
+ const afeTiming = metricsTracer.extractAfeLatency(serverTimingHeader);
52
+ metricsTracer.afeLatency = afeTiming ?? null;
53
+ }
58
54
  }
59
55
  listener.onReceiveMetadata(metadata);
60
56
  },
@@ -62,21 +58,29 @@ const MetricInterceptor = (options, nextCall) => {
62
58
  listener.onReceiveMessage(message);
63
59
  },
64
60
  onReceiveStatus: function (status) {
65
- listener.onReceiveStatus(status);
66
- // Record attempt metric completion
67
- metricsTracer?.recordAttemptCompletion(status.code);
68
- if (metricsTracer?.gfeLatency) {
69
- metricsTracer?.recordGfeLatency(status.code);
70
- }
71
- else {
72
- metricsTracer?.recordGfeConnectivityErrorCount(status.code);
73
- }
74
- if (metricsTracer?.afeLatency) {
75
- metricsTracer?.recordAfeLatency(status.code);
76
- }
77
- else {
78
- metricsTracer?.recordAfeConnectivityErrorCount(status.code);
61
+ if (metricsTracer) {
62
+ // Record attempt metric completion before notifying downstream listener
63
+ metricsTracer.recordAttemptCompletion(status?.code);
64
+ if (typeof metricsTracer.gfeLatency === 'number' &&
65
+ Number.isFinite(metricsTracer.gfeLatency) &&
66
+ metricsTracer.gfeLatency >= 0) {
67
+ metricsTracer.recordGfeLatency(status?.code);
68
+ }
69
+ else {
70
+ metricsTracer.recordGfeConnectivityErrorCount(status?.code);
71
+ }
72
+ if (afeServerTimingEnabled) {
73
+ if (typeof metricsTracer.afeLatency === 'number' &&
74
+ Number.isFinite(metricsTracer.afeLatency) &&
75
+ metricsTracer.afeLatency >= 0) {
76
+ metricsTracer.recordAfeLatency(status?.code);
77
+ }
78
+ else {
79
+ metricsTracer.recordAfeConnectivityErrorCount(status?.code);
80
+ }
81
+ }
79
82
  }
83
+ listener.onReceiveStatus(status);
80
84
  },
81
85
  };
82
86
  next(metadata, interceptingListener);
@@ -32,9 +32,7 @@ export declare class MetricsTracerFactory {
32
32
  private _locationPromise;
33
33
  private _metricReaders;
34
34
  private _projectId;
35
- private _currentOperationTracers;
36
- private _currentOperationLastUpdatedMs;
37
- private _intervalTracerCleanup;
35
+ private _attributesCache;
38
36
  static enabled: boolean;
39
37
  /**
40
38
  * Private constructor to enforce singleton pattern.
@@ -50,7 +48,7 @@ export declare class MetricsTracerFactory {
50
48
  * @param projectId Optional GCP project ID for the factory instantiation. Does nothing for subsequent calls.
51
49
  * @returns The singleton MetricsTracerFactory instance or null if disabled.
52
50
  */
53
- static getInstance(projectId: string): MetricsTracerFactory | null;
51
+ static getInstance(projectId?: string): MetricsTracerFactory | null;
54
52
  /**
55
53
  * Returns the MeterProvider, creating it and metric instruments if not already initialized.
56
54
  * Client-wide attributes that are known at this time are cached to be provided to all MetricsTracers.
@@ -117,7 +115,7 @@ export declare class MetricsTracerFactory {
117
115
  * @param method The gRPC method name.
118
116
  * @returns A new MetricsTracer instance or null if metrics are disabled.
119
117
  */
120
- createMetricsTracer(method: string, formattedName: string, requestId: string): MetricsTracer | null;
118
+ createMetricsTracer(method: string, formattedName: string, requestId?: string): MetricsTracer | null;
121
119
  /**
122
120
  * Takes a formatted name and parses the project, instance, and database.
123
121
  * @param formattedName The formatted resource name (e.g., full database path).
@@ -130,16 +128,14 @@ export declare class MetricsTracerFactory {
130
128
  };
131
129
  /**
132
130
  * Retrieves the current MetricsTracer for a given request id.
133
- * Returns null if no tracer exists for the request.
134
- * Does not implicitly create MetricsTracers as that should be done
135
- * explicitly using the createMetricsTracer function.
136
- * request id is expected to be as set in the gRPC metadata.
131
+ * @deprecated MetricsTracer is carried directly on the call context.
137
132
  * @param requestId The request id of the gRPC call set under 'x-goog-spanner-request-id'.
138
- * @returns The MetricsTracer instance or null if not found.
133
+ * @returns null.
139
134
  */
140
135
  getCurrentTracer(requestId: string): MetricsTracer | null;
141
136
  /**
142
137
  * Removes the MetricsTracer associated with the given request id.
138
+ * @deprecated MetricsTracer is carried directly on the call context.
143
139
  * @param requestId The request id of the gRPC call set under 'x-goog-spanner-request-id'.
144
140
  */
145
141
  clearCurrentTracer(requestId: string): void;
@@ -176,5 +172,4 @@ export declare class MetricsTracerFactory {
176
172
  * @returns The detected location string, or "global" if not found.
177
173
  */
178
174
  private static _detectClientLocation;
179
- private _cleanMetricsTracers;
180
175
  }
@@ -18,7 +18,6 @@ const crypto = require("crypto");
18
18
  const os = require("os");
19
19
  const process = require("process");
20
20
  const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
21
- const api_1 = require("@opentelemetry/api");
22
21
  const resources_1 = require("@opentelemetry/resources");
23
22
  const resource_detector_gcp_1 = require("@opentelemetry/resource-detector-gcp");
24
23
  const Constants = require("./constants");
@@ -55,9 +54,7 @@ class MetricsTracerFactory {
55
54
  _locationPromise = null;
56
55
  _metricReaders = [];
57
56
  _projectId;
58
- _currentOperationTracers = new Map();
59
- _currentOperationLastUpdatedMs = new Map();
60
- _intervalTracerCleanup;
57
+ _attributesCache = new Map();
61
58
  static enabled = true;
62
59
  /**
63
60
  * Private constructor to enforce singleton pattern.
@@ -69,7 +66,7 @@ class MetricsTracerFactory {
69
66
  this._projectId = projectId;
70
67
  this._clientUid = MetricsTracerFactory._generateClientUId();
71
68
  this._clientName = `${Constants.SPANNER_METER_NAME}/${version}`;
72
- // Only perform async call to retrieve location is metrics are enabled.
69
+ // Only perform async call to retrieve location if metrics are enabled.
73
70
  if (MetricsTracerFactory.enabled) {
74
71
  this._locationPromise = MetricsTracerFactory._detectClientLocation()
75
72
  .then(location => {
@@ -85,11 +82,6 @@ class MetricsTracerFactory {
85
82
  });
86
83
  }
87
84
  this._clientHash = MetricsTracerFactory._generateClientHash(this._clientUid);
88
- // Start the Tracer cleanup task at an interval
89
- this._intervalTracerCleanup = api_1.context.with(api_1.ROOT_CONTEXT, () => setInterval(this._cleanMetricsTracers.bind(this), Constants.TRACER_CLEANUP_INTERVAL_MS));
90
- // unref the interval to prevent it from blocking app termination
91
- // in the event loop
92
- this._intervalTracerCleanup.unref();
93
85
  }
94
86
  /**
95
87
  * Returns the singleton instance of MetricsTracerFactory.
@@ -104,7 +96,10 @@ class MetricsTracerFactory {
104
96
  }
105
97
  // Create a singleton instance, enabling/disabling metrics can only be done on the initial call
106
98
  if (MetricsTracerFactory._instance === null) {
107
- MetricsTracerFactory._instance = new MetricsTracerFactory(projectId);
99
+ MetricsTracerFactory._instance = new MetricsTracerFactory(projectId || '');
100
+ }
101
+ else if (projectId && !MetricsTracerFactory._instance._projectId) {
102
+ MetricsTracerFactory._instance._projectId = projectId;
108
103
  }
109
104
  return MetricsTracerFactory._instance;
110
105
  }
@@ -155,7 +150,6 @@ class MetricsTracerFactory {
155
150
  * Resets the singleton instance of the MetricsTracerFactory.
156
151
  */
157
152
  static async resetInstance() {
158
- clearInterval(MetricsTracerFactory._instance?._intervalTracerCleanup);
159
153
  await MetricsTracerFactory._instance?.resetMeterProvider();
160
154
  MetricsTracerFactory._instance = null;
161
155
  }
@@ -168,8 +162,7 @@ class MetricsTracerFactory {
168
162
  }
169
163
  this._meterProvider = null;
170
164
  this._metricReaders = [];
171
- this._currentOperationTracers = new Map();
172
- this._currentOperationLastUpdatedMs = new Map();
165
+ this._attributesCache = new Map();
173
166
  }
174
167
  /**
175
168
  * Returns the attempt latency histogram instrument.
@@ -242,15 +235,14 @@ class MetricsTracerFactory {
242
235
  if (!MetricsTracerFactory.enabled) {
243
236
  return null;
244
237
  }
245
- const operationRequest = this._extractOperationRequest(requestId);
246
- if (this._currentOperationTracers.has(operationRequest)) {
247
- return this._currentOperationTracers.get(operationRequest);
248
- }
249
238
  const { instance, database } = this.getInstanceAttributes(formattedName);
250
- const tracer = new metrics_tracer_1.MetricsTracer(this._instrumentAttemptCounter, this._instrumentAttemptLatency, this._instrumentOperationCounter, this._instrumentOperationLatency, this._instrumentGfeConnectivityErrorCount, this._instrumentGfeLatency, this._instrumentAfeConnectivityErrorCount, this._instrumentAfeLatency, MetricsTracerFactory.enabled, database, instance, this._projectId, method, operationRequest);
251
- this._currentOperationTracers.set(operationRequest, tracer);
252
- this._currentOperationLastUpdatedMs.set(operationRequest, Date.now());
253
- return tracer;
239
+ const cacheKey = `${instance}/${database}/${method}`;
240
+ let attributesCache = this._attributesCache.get(cacheKey);
241
+ if (!attributesCache) {
242
+ attributesCache = new Map();
243
+ this._attributesCache.set(cacheKey, attributesCache);
244
+ }
245
+ return new metrics_tracer_1.MetricsTracer(this._instrumentAttemptCounter, this._instrumentAttemptLatency, this._instrumentOperationCounter, this._instrumentOperationLatency, this._instrumentGfeConnectivityErrorCount, this._instrumentGfeLatency, this._instrumentAfeConnectivityErrorCount, this._instrumentAfeLatency, MetricsTracerFactory.enabled, database, instance, this._projectId, method, requestId, attributesCache);
254
246
  }
255
247
  /**
256
248
  * Takes a formatted name and parses the project, instance, and database.
@@ -265,54 +257,71 @@ class MetricsTracerFactory {
265
257
  database: Constants.UNKNOWN_ATTRIBUTE,
266
258
  };
267
259
  }
268
- const regex = /projects\/(?<projectId>[^/]+)\/instances\/(?<instanceId>[^/]+)(?:\/databases\/(?<databaseId>[^/]+))?/;
269
- const match = formattedName.match(regex);
270
- const project = match?.groups?.projectId || Constants.UNKNOWN_ATTRIBUTE;
271
- const instance = match?.groups?.instanceId || Constants.UNKNOWN_ATTRIBUTE;
272
- const database = match?.groups?.databaseId || Constants.UNKNOWN_ATTRIBUTE;
260
+ const parts = formattedName.split('/');
261
+ const startIndex = parts[0] === '' ? 1 : 0;
262
+ if (parts.length < startIndex + 4 ||
263
+ parts[startIndex] !== 'projects' ||
264
+ parts[startIndex + 2] !== 'instances' ||
265
+ !parts[startIndex + 1] ||
266
+ !parts[startIndex + 3]) {
267
+ return {
268
+ project: Constants.UNKNOWN_ATTRIBUTE,
269
+ instance: Constants.UNKNOWN_ATTRIBUTE,
270
+ database: Constants.UNKNOWN_ATTRIBUTE,
271
+ };
272
+ }
273
+ const project = parts[startIndex + 1];
274
+ const instance = parts[startIndex + 3];
275
+ let database = Constants.UNKNOWN_ATTRIBUTE;
276
+ if (parts.length >= startIndex + 6 &&
277
+ parts[startIndex + 4] === 'databases' &&
278
+ parts[startIndex + 5]) {
279
+ database = parts[startIndex + 5];
280
+ }
273
281
  return { project: project, instance: instance, database: database };
274
282
  }
275
283
  /**
276
284
  * Retrieves the current MetricsTracer for a given request id.
277
- * Returns null if no tracer exists for the request.
278
- * Does not implicitly create MetricsTracers as that should be done
279
- * explicitly using the createMetricsTracer function.
280
- * request id is expected to be as set in the gRPC metadata.
285
+ * @deprecated MetricsTracer is carried directly on the call context.
281
286
  * @param requestId The request id of the gRPC call set under 'x-goog-spanner-request-id'.
282
- * @returns The MetricsTracer instance or null if not found.
287
+ * @returns null.
283
288
  */
289
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
284
290
  getCurrentTracer(requestId) {
285
- const operationRequest = this._extractOperationRequest(requestId);
286
- if (!this._currentOperationTracers.has(operationRequest)) {
287
- // Attempting to retrieve tracer that doesn't exist.
288
- return null;
289
- }
290
- this._currentOperationLastUpdatedMs.set(operationRequest, Date.now());
291
- return this._currentOperationTracers.get(operationRequest) ?? null;
291
+ return null;
292
292
  }
293
293
  /**
294
294
  * Removes the MetricsTracer associated with the given request id.
295
+ * @deprecated MetricsTracer is carried directly on the call context.
295
296
  * @param requestId The request id of the gRPC call set under 'x-goog-spanner-request-id'.
296
297
  */
297
- clearCurrentTracer(requestId) {
298
- const operationRequest = this._extractOperationRequest(requestId) || requestId;
299
- if (!this._currentOperationTracers.has(operationRequest)) {
300
- return;
301
- }
302
- this._currentOperationTracers.delete(operationRequest);
303
- this._currentOperationLastUpdatedMs.delete(operationRequest);
304
- }
298
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
299
+ clearCurrentTracer(requestId) { }
300
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
305
301
  _extractOperationRequest(requestId) {
306
- if (!requestId) {
302
+ if (!requestId || typeof requestId !== 'string') {
307
303
  return '';
308
304
  }
309
- const regex = /^(\d+\.[a-z0-9]+\.\d+\.\d+\.\d+)\.\d+$/i;
310
- const match = requestId.match(regex);
311
- if (!match) {
305
+ let dotCount = 0;
306
+ let fifthDotIndex = -1;
307
+ for (let index = 0; index < requestId.length; index++) {
308
+ if (requestId.charCodeAt(index) === 46 /* '.' */) {
309
+ dotCount++;
310
+ if (dotCount === 5) {
311
+ fifthDotIndex = index;
312
+ }
313
+ }
314
+ }
315
+ if (dotCount !== 5 || fifthDotIndex === requestId.length - 1) {
312
316
  return '';
313
317
  }
314
- const request = match[1];
315
- return request;
318
+ for (let index = fifthDotIndex + 1; index < requestId.length; index++) {
319
+ const code = requestId.charCodeAt(index);
320
+ if (code < 48 || code > 57) {
321
+ return '';
322
+ }
323
+ }
324
+ return requestId.slice(0, fifthDotIndex);
316
325
  }
317
326
  /**
318
327
  * Creates and initializes all metric instruments (counters and histograms) for the MeterProvider.
@@ -414,17 +423,6 @@ class MetricsTracerFactory {
414
423
  }
415
424
  return defaultRegion;
416
425
  }
417
- _cleanMetricsTracers() {
418
- if (this._currentOperationLastUpdatedMs.size === 0) {
419
- return;
420
- }
421
- for (const [operationTracer, lastUpdated,] of this._currentOperationLastUpdatedMs.entries()) {
422
- if (Date.now() - lastUpdated >= Constants.TRACER_CLEANUP_THRESHOLD_MS) {
423
- this._currentOperationTracers.delete(operationTracer);
424
- this._currentOperationLastUpdatedMs.delete(operationTracer);
425
- }
426
- }
427
- }
428
426
  }
429
427
  exports.MetricsTracerFactory = MetricsTracerFactory;
430
428
  //# sourceMappingURL=metrics-tracer-factory.js.map
@@ -81,7 +81,7 @@ export declare class MetricsTracer {
81
81
  private _instance;
82
82
  private _projectId;
83
83
  private _methodName;
84
- private _request;
84
+ private _request?;
85
85
  /**
86
86
  * The current MetricOperationTracer instance tracking the ongoing operation.
87
87
  */
@@ -90,6 +90,11 @@ export declare class MetricsTracer {
90
90
  * Stores client and resource attributes for labeling metrics.
91
91
  */
92
92
  private _clientAttributes;
93
+ /**
94
+ * Cached OTel attribute objects keyed by status name, avoiding repeated
95
+ * object allocations on every metric recording call.
96
+ */
97
+ private _attributesByStatus;
93
98
  gfeLatency: number | null;
94
99
  afeLatency: number | null;
95
100
  /**
@@ -105,7 +110,7 @@ export declare class MetricsTracer {
105
110
  * @param _instrumentAfeLatency Histogram for AFE latency metrics.
106
111
  * @param enabled Whether metrics recording is enabled.
107
112
  */
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);
113
+ 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 | undefined, attributesCache?: Map<string, Record<string, string>>);
109
114
  /**
110
115
  * Returns the difference in milliseconds between two times.
111
116
  * @param start The start time.
@@ -172,8 +177,16 @@ export declare class MetricsTracer {
172
177
  */
173
178
  extractAfeLatency(header: string): number | null;
174
179
  /**
175
- * Records the provided GFE latency.
176
- * @param latency The GFE latency in milliseconds.
180
+ * Returns a cached set of OTEL attributes for the given status, avoiding
181
+ * repeated object cloning on every metric record/add call.
182
+ *
183
+ * @param status Optional status code (as numeric Status enum or status name string).
184
+ * @returns The cached attributes object.
185
+ */
186
+ private _getAttributesForStatus;
187
+ /**
188
+ * Records the GFE latency for this attempt.
189
+ * @param statusCode The gRPC status code of the attempt.
177
190
  */
178
191
  recordGfeLatency(statusCode: Status): void;
179
192
  /**
@@ -185,8 +198,8 @@ export declare class MetricsTracer {
185
198
  */
186
199
  recordAfeConnectivityErrorCount(statusCode: Status): void;
187
200
  /**
188
- * Records the provided AFE latency.
189
- * @param latency The AFE latency in milliseconds.
201
+ * Records the AFE latency for this attempt.
202
+ * @param statusCode The gRPC status code of the attempt.
190
203
  */
191
204
  recordAfeLatency(statusCode: Status): void;
192
205
  /**