@google-cloud/spanner 8.0.0 → 8.2.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 (54) hide show
  1. package/README.md +2 -0
  2. package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +35 -0
  3. package/build/protos/google/spanner/v1/change_stream.proto +451 -0
  4. package/build/protos/google/spanner/v1/commit_response.proto +9 -4
  5. package/build/protos/google/spanner/v1/transaction.proto +40 -356
  6. package/build/protos/protos.d.ts +2087 -4
  7. package/build/protos/protos.js +6191 -349
  8. package/build/protos/protos.json +556 -25
  9. package/build/src/batch-transaction.js +2 -2
  10. package/build/src/codec.js +20 -21
  11. package/build/src/common-grpc/service.js +10 -10
  12. package/build/src/common.d.ts +1 -0
  13. package/build/src/common.js +9 -1
  14. package/build/src/database.d.ts +3 -2
  15. package/build/src/database.js +16 -14
  16. package/build/src/helper.d.ts +90 -0
  17. package/build/src/helper.js +154 -0
  18. package/build/src/index.d.ts +36 -1
  19. package/build/src/index.js +179 -8
  20. package/build/src/instrument.js +3 -2
  21. package/build/src/metrics/constants.d.ts +36 -0
  22. package/build/src/metrics/constants.js +106 -0
  23. package/build/src/metrics/external-types.d.ts +20 -0
  24. package/build/src/metrics/external-types.js +32 -0
  25. package/build/src/metrics/interceptor.d.ts +13 -0
  26. package/build/src/metrics/interceptor.js +87 -0
  27. package/build/src/metrics/metrics-tracer-factory.d.ts +165 -0
  28. package/build/src/metrics/metrics-tracer-factory.js +389 -0
  29. package/build/src/metrics/metrics-tracer.d.ts +204 -0
  30. package/build/src/metrics/metrics-tracer.js +371 -0
  31. package/build/src/metrics/spanner-metrics-exporter.d.ts +35 -0
  32. package/build/src/metrics/spanner-metrics-exporter.js +119 -0
  33. package/build/src/metrics/transform.d.ts +144 -0
  34. package/build/src/metrics/transform.js +272 -0
  35. package/build/src/multiplexed-session.d.ts +1 -1
  36. package/build/src/multiplexed-session.js +2 -4
  37. package/build/src/partial-result-stream.js +9 -5
  38. package/build/src/session-factory.d.ts +34 -0
  39. package/build/src/session-factory.js +30 -0
  40. package/build/src/session-pool.js +1 -2
  41. package/build/src/table.d.ts +2 -0
  42. package/build/src/table.js +5 -0
  43. package/build/src/transaction-runner.d.ts +6 -0
  44. package/build/src/transaction-runner.js +8 -0
  45. package/build/src/transaction.d.ts +44 -1
  46. package/build/src/transaction.js +202 -49
  47. package/build/src/v1/database_admin_client.d.ts +34 -0
  48. package/build/src/v1/database_admin_client.js +167 -1
  49. package/build/src/v1/database_admin_client_config.json +4 -0
  50. package/build/src/v1/instance_admin_client.d.ts +120 -0
  51. package/build/src/v1/instance_admin_client.js +312 -13
  52. package/build/src/v1/spanner_client.js +108 -0
  53. package/build/src/v1/spanner_proto_list.json +1 -0
  54. package/package.json +15 -8
@@ -20,6 +20,21 @@ exports.isDefaultCredentialsNotSetError = isDefaultCredentialsNotSetError;
20
20
  exports.isProjectIdNotSetInEnvironmentError = isProjectIdNotSetInEnvironmentError;
21
21
  exports.isCreateSessionPermissionError = isCreateSessionPermissionError;
22
22
  exports.toArray = toArray;
23
+ exports.isDefined = isDefined;
24
+ exports.isNull = isNull;
25
+ exports.isUndefined = isUndefined;
26
+ exports.isEmpty = isEmpty;
27
+ exports.isObject = isObject;
28
+ exports.isString = isString;
29
+ exports.isArray = isArray;
30
+ exports.isDate = isDate;
31
+ exports.isBoolean = isBoolean;
32
+ exports.isNumber = isNumber;
33
+ exports.isInteger = isInteger;
34
+ exports.isActualNaN = isActualNaN;
35
+ exports.isDecimal = isDecimal;
36
+ exports.isInfinite = isInfinite;
37
+ exports.isError = isError;
23
38
  const google_gax_1 = require("google-gax");
24
39
  /**
25
40
  * Checks whether the given error is a 'Database not found' error.
@@ -92,4 +107,143 @@ function toArray(value) {
92
107
  }
93
108
  return [value];
94
109
  }
110
+ /**
111
+ * Checks if a value is defined.
112
+ * @param {*} value The value to check.
113
+ * @returns {Boolean} `true` if the value is NOT `undefined`, otherwise `false`.
114
+ */
115
+ function isDefined(value) {
116
+ return typeof value !== 'undefined';
117
+ }
118
+ /**
119
+ * Checks if a value is null.
120
+ * @param {*} value The value to check.
121
+ * @returns {Boolean} `true` if the value is null, otherwise `false`.
122
+ */
123
+ function isNull(value) {
124
+ return value === null;
125
+ }
126
+ /**
127
+ * Checks if a value is undefined.
128
+ * @param {*} value The value to check.
129
+ * @returns {Boolean} `true` if the value is `undefined`, otherwise `false`.
130
+ */
131
+ function isUndefined(value) {
132
+ return typeof value === 'undefined';
133
+ }
134
+ /**
135
+ * Checks if a value is empty.
136
+ * @param {*} value The value to check.
137
+ * @returns {Boolean} `true` if the value is empty, otherwise `false`.
138
+ */
139
+ function isEmpty(value) {
140
+ const type = Object.prototype.toString.call(value);
141
+ if (type === '[object Array]' ||
142
+ type === '[object Arguments]' ||
143
+ type === '[object String]') {
144
+ return value.length === 0;
145
+ }
146
+ if (type === '[object Object]') {
147
+ for (const key in value) {
148
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
149
+ return false;
150
+ }
151
+ }
152
+ return true;
153
+ }
154
+ return !value;
155
+ }
156
+ /**
157
+ * Checks if a value is a plain javascript object.
158
+ * @param {*} value The value to check.
159
+ * @returns {Boolean} `true` if the value is an object, otherwise `false`.
160
+ */
161
+ function isObject(value) {
162
+ return Object.prototype.toString.call(value) === '[object Object]';
163
+ }
164
+ /**
165
+ * Checks if a value is a string.
166
+ * @param {*} value The value to check.
167
+ * @returns {Boolean} `true` if the value is string, otherwise `false`.
168
+ */
169
+ function isString(value) {
170
+ return Object.prototype.toString.call(value) === '[object String]';
171
+ }
172
+ /**
173
+ * Checks if a value is an array.
174
+ * @param {*} value The value to check.
175
+ * @returns {Boolean} `true` if the value is an array, otherwise `false`.
176
+ */
177
+ function isArray(value) {
178
+ return Array.isArray(value);
179
+ }
180
+ /**
181
+ * Checks if a value is a Date object.
182
+ * @param {*} value The value to check.
183
+ * @returns {Boolean} `true` if the value is a `Date` object, otherwise `false`.
184
+ */
185
+ function isDate(value) {
186
+ return Object.prototype.toString.call(value) === '[object Date]';
187
+ }
188
+ /**
189
+ * Checks if a value is a boolean.
190
+ * @param {*} value The value to check.
191
+ * @returns {Boolean} `true` if the value is boolean, otherwise `false`.
192
+ */
193
+ function isBoolean(value) {
194
+ return Object.prototype.toString.call(value) === '[object Boolean]';
195
+ }
196
+ /**
197
+ * Checks if a value is a number.
198
+ * @param {*} value The value to check.
199
+ * @returns {Boolean} `true` if the value is a number, otherwise `false`.
200
+ */
201
+ function isNumber(value) {
202
+ return Object.prototype.toString.call(value) === '[object Number]';
203
+ }
204
+ /**
205
+ * Checks if a value is an integer.
206
+ * @param {*} value The value to check.
207
+ * @returns {Boolean} `true` if the value is an integer, otherwise `false`.
208
+ */
209
+ function isInteger(value) {
210
+ return Number.isInteger(value);
211
+ }
212
+ /**
213
+ * Checks if a value is `NaN`.
214
+ * @param {*} value The value to check.
215
+ * @returns {Boolean} `true` if the value is `NaN`, otherwise `false`.
216
+ */
217
+ function isActualNaN(value) {
218
+ return value !== value;
219
+ }
220
+ /**
221
+ * Checks if a value is a non-integer (decimal) number.
222
+ * @param {*} value The value to check.
223
+ * @returns {Boolean} `true` if the value is a decimal number, otherwise `false`.
224
+ */
225
+ function isDecimal(value) {
226
+ // A number is a decimal if it's a number but not an integer.
227
+ return (isNumber(value) &&
228
+ !isInfinite(value) &&
229
+ !isActualNaN(value) &&
230
+ value % 1 !== 0);
231
+ }
232
+ /**
233
+ * Checks if a value is `Infinity` or `-Infinity`.
234
+ * @param {*} value The value to check.
235
+ * @returns {Boolean} `true` if the value is infinite, otherwise `false`.
236
+ */
237
+ function isInfinite(value) {
238
+ return value === Infinity || value === -Infinity;
239
+ }
240
+ /**
241
+ * Checks if a value is an `Error` object.
242
+ * @param {*} value The value to check.
243
+ * @returns {Boolean} `true` if the value is an `Error` object, otherwise `false`.
244
+ */
245
+ function isError(value) {
246
+ return (value instanceof Error ||
247
+ Object.prototype.toString.call(value) === '[object Error]');
248
+ }
95
249
  //# sourceMappingURL=helper.js.map
@@ -54,6 +54,7 @@ export type GetInstanceConfigOperationsCallback = PagedCallback<IOperation, inst
54
54
  * Indicates which replicas or regions should be used for non-transactional reads or queries.
55
55
  * DirectedReadOptions won't be set for readWrite transactions"
56
56
  * @property {ObservabilityOptions} [observabilityOptions] Sets the observability options to be used for OpenTelemetry tracing
57
+ * @property {boolean} [disableBuiltInMetrics=True] If set to true, built-in metrics will be disabled.
57
58
  */
58
59
  export interface SpannerOptions extends GrpcClientOptions {
59
60
  apiEndpoint?: string;
@@ -62,9 +63,21 @@ export interface SpannerOptions extends GrpcClientOptions {
62
63
  sslCreds?: grpc.ChannelCredentials;
63
64
  routeToLeaderEnabled?: boolean;
64
65
  directedReadOptions?: google.spanner.v1.IDirectedReadOptions | null;
65
- defaultTransactionOptions?: Pick<RunTransactionOptions, 'isolationLevel'>;
66
+ defaultTransactionOptions?: Pick<RunTransactionOptions, 'isolationLevel' | 'readLockMode'>;
66
67
  observabilityOptions?: ObservabilityOptions;
68
+ disableBuiltInMetrics?: boolean;
67
69
  interceptors?: any[];
70
+ /**
71
+ * The Trusted Cloud Domain (TPC) DNS of the service used to make requests.
72
+ * Defaults to `googleapis.com`.
73
+ * We support both camelCase and snake_case for the universe domain.
74
+ * Customer may set any of these as both the options are same,
75
+ * they both points to universe endpoint.
76
+ * There is no preference for any of these option; however exception will be
77
+ * thrown if both are set to different values.
78
+ */
79
+ universe_domain?: string;
80
+ universeDomain?: string;
68
81
  }
69
82
  export interface RequestConfig {
70
83
  client: string;
@@ -172,6 +185,9 @@ declare class Spanner extends GrpcService {
172
185
  directedReadOptions: google.spanner.v1.IDirectedReadOptions | null;
173
186
  defaultTransactionOptions: RunTransactionOptions;
174
187
  _observabilityOptions: ObservabilityOptions | undefined;
188
+ private _universeDomain;
189
+ private _isInSecureCredentials;
190
+ private static _isAFEServerTimingEnabled;
175
191
  readonly _nthClientId: number;
176
192
  /**
177
193
  * Placeholder used to auto populate a column with the commit timestamp.
@@ -183,6 +199,20 @@ declare class Spanner extends GrpcService {
183
199
  static COMMIT_TIMESTAMP: string;
184
200
  static POSTGRESQL: google.spanner.admin.database.v1.DatabaseDialect;
185
201
  static GOOGLE_STANDARD_SQL: google.spanner.admin.database.v1.DatabaseDialect;
202
+ /**
203
+ * Returns whether AFE (Application Frontend Extension) server timing is enabled.
204
+ *
205
+ * This method checks the value of the environment variable
206
+ * `SPANNER_DISABLE_AFE_SERVER_TIMING`. If the variable is explicitly set to the
207
+ * string `'true'`, then AFE server timing is considered disabled, and this method
208
+ * returns `false`. For all other values (including if the variable is unset),
209
+ * the method returns `true`.
210
+ *
211
+ * @returns {boolean} `true` if AFE server timing is enabled; otherwise, `false`.
212
+ */
213
+ static isAFEServerTimingEnabled: () => boolean;
214
+ /** Resets the cached value (use in tests if env changes). */
215
+ static _resetAFEServerTimingForTest(): void;
186
216
  /**
187
217
  * Gets the configured Spanner emulator host from an environment variable.
188
218
  */
@@ -191,6 +221,7 @@ declare class Spanner extends GrpcService {
191
221
  port?: number;
192
222
  } | undefined;
193
223
  constructor(options?: SpannerOptions);
224
+ get universeDomain(): string;
194
225
  /**
195
226
  * Gets the InstanceAdminClient object.
196
227
  * The returned InstanceAdminClient object is a shared, managed instance and should not be manually closed.
@@ -816,6 +847,10 @@ declare class Spanner extends GrpcService {
816
847
  * ```
817
848
  */
818
849
  instanceConfig(name: string): InstanceConfig;
850
+ /**
851
+ * Setup the OpenTelemetry metrics capturing for service metrics to Google Cloud Monitoring.
852
+ */
853
+ configureMetrics_(disableBuiltInMetrics?: boolean): void;
819
854
  /**
820
855
  * Prepare a gapic request. This will cache the GAX client and replace
821
856
  * {{projectId}} placeholders, if necessary.
@@ -46,6 +46,7 @@ Object.defineProperty(exports, "InstanceConfig", { enumerable: true, get: functi
46
46
  const google_gax_1 = require("google-gax");
47
47
  const protos_1 = require("../protos/protos");
48
48
  var IsolationLevel = protos_1.google.spanner.v1.TransactionOptions.IsolationLevel;
49
+ var ReadLockMode = protos_1.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
49
50
  const common_1 = require("./common");
50
51
  const session_1 = require("./session");
51
52
  Object.defineProperty(exports, "Session", { enumerable: true, get: function () { return session_1.Session; } });
@@ -65,8 +66,46 @@ const v1 = require("./v1");
65
66
  exports.v1 = v1;
66
67
  const instrument_1 = require("./instrument");
67
68
  const request_id_header_1 = require("./request_id_header");
69
+ const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
70
+ const interceptor_1 = require("./metrics/interceptor");
71
+ const spanner_metrics_exporter_1 = require("./metrics/spanner-metrics-exporter");
72
+ const metrics_tracer_factory_1 = require("./metrics/metrics-tracer-factory");
68
73
  // eslint-disable-next-line @typescript-eslint/no-var-requires
69
74
  const gcpApiConfig = require('./spanner_grpc_config.json');
75
+ /**
76
+ * Retrieves the universe domain.
77
+ *
78
+ * This function checks for a universe domain in the following order:
79
+ * 1. The `universeDomain` property within the provided spanner options.
80
+ * 2. The `universe_domain` property within the provided spanner options.
81
+ * 3. The `GOOGLE_CLOUD_UNIVERSE_DOMAIN` environment variable.
82
+ * 4. If none of the above properties will be set, it will fallback to `googleapis.com`.
83
+ *
84
+ * For consistency with the Auth client, if the `universe_domain` option or the
85
+ * `GOOGLE_CLOUD_UNIVERSE_DOMAIN` env variable is used, this function will also set the
86
+ * `universeDomain` property within the provided `SpannerOptions` object. This ensures the
87
+ * Spanner client's universe domain aligns with the universe configured for authentication.
88
+ *
89
+ * @param {SpannerOptions} options - The Spanner client options.
90
+ * @returns {string} The universe domain.
91
+ */
92
+ function getUniverseDomain(options) {
93
+ const universeDomainEnvVar = typeof process === 'object' && typeof process.env === 'object'
94
+ ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']
95
+ : undefined;
96
+ const universeDomain = options?.universeDomain ??
97
+ options?.universe_domain ??
98
+ universeDomainEnvVar ??
99
+ 'googleapis.com';
100
+ // if the options.universe_domain/GOOGLE_CLOUD_UNIVERSE_DOMAIN env variable is set,
101
+ // set its value to the Spanner `universeDomain` options
102
+ // to match it with the universe from Auth Client
103
+ if (!options?.universeDomain &&
104
+ (options?.universe_domain || process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN)) {
105
+ options.universeDomain = universeDomain;
106
+ }
107
+ return universeDomain;
108
+ }
70
109
  /**
71
110
  * [Cloud Spanner](https://cloud.google.com/spanner) is a highly scalable,
72
111
  * transactional, managed, NewSQL database service. Cloud Spanner solves the
@@ -120,6 +159,9 @@ class Spanner extends service_1.GrpcService {
120
159
  directedReadOptions;
121
160
  defaultTransactionOptions;
122
161
  _observabilityOptions;
162
+ _universeDomain;
163
+ _isInSecureCredentials;
164
+ static _isAFEServerTimingEnabled;
123
165
  _nthClientId;
124
166
  /**
125
167
  * Placeholder used to auto populate a column with the commit timestamp.
@@ -131,6 +173,28 @@ class Spanner extends service_1.GrpcService {
131
173
  static COMMIT_TIMESTAMP = 'spanner.commit_timestamp()';
132
174
  static POSTGRESQL = protos_1.google.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL;
133
175
  static GOOGLE_STANDARD_SQL = protos_1.google.spanner.admin.database.v1.DatabaseDialect.GOOGLE_STANDARD_SQL;
176
+ /**
177
+ * Returns whether AFE (Application Frontend Extension) server timing is enabled.
178
+ *
179
+ * This method checks the value of the environment variable
180
+ * `SPANNER_DISABLE_AFE_SERVER_TIMING`. If the variable is explicitly set to the
181
+ * string `'true'`, then AFE server timing is considered disabled, and this method
182
+ * returns `false`. For all other values (including if the variable is unset),
183
+ * the method returns `true`.
184
+ *
185
+ * @returns {boolean} `true` if AFE server timing is enabled; otherwise, `false`.
186
+ */
187
+ static isAFEServerTimingEnabled = () => {
188
+ if (this._isAFEServerTimingEnabled === undefined) {
189
+ this._isAFEServerTimingEnabled =
190
+ process.env['SPANNER_DISABLE_AFE_SERVER_TIMING'] !== 'true';
191
+ }
192
+ return this._isAFEServerTimingEnabled;
193
+ };
194
+ /** Resets the cached value (use in tests if env changes). */
195
+ static _resetAFEServerTimingForTest() {
196
+ this._isAFEServerTimingEnabled = undefined;
197
+ }
134
198
  /**
135
199
  * Gets the configured Spanner emulator host from an environment variable.
136
200
  */
@@ -192,8 +256,14 @@ class Spanner extends service_1.GrpcService {
192
256
  ? options.defaultTransactionOptions
193
257
  : {
194
258
  isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED,
259
+ readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED,
195
260
  };
196
261
  delete options.defaultTransactionOptions;
262
+ if (options?.universe_domain &&
263
+ options?.universeDomain &&
264
+ options?.universe_domain !== options?.universeDomain) {
265
+ throw new Error('Please set either universe_domain or universeDomain, but not both.');
266
+ }
197
267
  const emulatorHost = Spanner.getSpannerEmulatorHost();
198
268
  if (emulatorHost &&
199
269
  emulatorHost.endpoint &&
@@ -202,11 +272,10 @@ class Spanner extends service_1.GrpcService {
202
272
  options.port = emulatorHost.port;
203
273
  options.sslCreds = google_gax_1.grpc.credentials.createInsecure();
204
274
  }
275
+ const universeEndpoint = getUniverseDomain(options);
276
+ const spannerUniverseEndpoint = 'spanner.' + universeEndpoint;
205
277
  const config = {
206
- baseUrl: options.apiEndpoint ||
207
- options.servicePath ||
208
- // TODO: for TPC, this needs to support universeDomain
209
- 'spanner.googleapis.com',
278
+ baseUrl: options.apiEndpoint || options.servicePath || spannerUniverseEndpoint,
210
279
  protosDir: path.resolve(__dirname, '../protos'),
211
280
  protoServices: {
212
281
  Operations: {
@@ -221,6 +290,7 @@ class Spanner extends service_1.GrpcService {
221
290
  if (options.routeToLeaderEnabled === false) {
222
291
  this.routeToLeaderEnabled = false;
223
292
  }
293
+ this._isInSecureCredentials = options.sslCreds?._isSecure() === false;
224
294
  this.options = options;
225
295
  this.auth = new google_auth_library_1.GoogleAuth(this.options);
226
296
  this.clients_ = new Map();
@@ -234,6 +304,11 @@ class Spanner extends service_1.GrpcService {
234
304
  this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.projectFormattedName_, this._observabilityOptions?.enableEndToEndTracing);
235
305
  (0, instrument_1.ensureInitialContextManagerSet)();
236
306
  this._nthClientId = (0, request_id_header_1.nextSpannerClientId)();
307
+ this._universeDomain = universeEndpoint;
308
+ this.configureMetrics_(options.disableBuiltInMetrics);
309
+ }
310
+ get universeDomain() {
311
+ return this._universeDomain;
237
312
  }
238
313
  /**
239
314
  * Gets the InstanceAdminClient object.
@@ -285,6 +360,9 @@ class Spanner extends service_1.GrpcService {
285
360
  }
286
361
  client.close();
287
362
  });
363
+ cleanup().catch(err => {
364
+ console.error('Error occured during cleanup: ', err);
365
+ });
288
366
  }
289
367
  createInstance(name, config, callback) {
290
368
  if (!name) {
@@ -679,6 +757,24 @@ class Spanner extends service_1.GrpcService {
679
757
  }
680
758
  return this.instanceConfigs_.get(key);
681
759
  }
760
+ /**
761
+ * Setup the OpenTelemetry metrics capturing for service metrics to Google Cloud Monitoring.
762
+ */
763
+ configureMetrics_(disableBuiltInMetrics) {
764
+ const metricsEnabled = process.env.SPANNER_DISABLE_BUILTIN_METRICS !== 'true' &&
765
+ !disableBuiltInMetrics &&
766
+ !this._isInSecureCredentials;
767
+ metrics_tracer_factory_1.MetricsTracerFactory.enabled = metricsEnabled;
768
+ if (metricsEnabled) {
769
+ const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(this.projectId);
770
+ const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
771
+ exporter: new spanner_metrics_exporter_1.CloudMonitoringMetricsExporter({ auth: this.auth }),
772
+ exportIntervalMillis: 60000,
773
+ });
774
+ // Retrieve the MeterProvider to trigger construction
775
+ factory.getMeterProvider([periodicReader]);
776
+ }
777
+ }
682
778
  /**
683
779
  * Prepare a gapic request. This will cache the GAX client and replace
684
780
  * {{projectId}} placeholders, if necessary.
@@ -695,8 +791,13 @@ class Spanner extends service_1.GrpcService {
695
791
  return;
696
792
  }
697
793
  const clientName = config.client;
698
- if (!this.clients_.has(clientName)) {
699
- this.clients_.set(clientName, new v1[clientName](this.options));
794
+ try {
795
+ if (!this.clients_.has(clientName)) {
796
+ this.clients_.set(clientName, new v1[clientName](this.options));
797
+ }
798
+ }
799
+ catch (err) {
800
+ callback(err, null);
700
801
  }
701
802
  const gaxClient = this.clients_.get(clientName);
702
803
  let reqOpts = extend(true, {}, config.reqOpts);
@@ -725,11 +826,18 @@ class Spanner extends service_1.GrpcService {
725
826
  });
726
827
  // Attach the x-goog-spanner-request-id to the currently active span.
727
828
  (0, request_id_header_1.attributeXGoogSpannerRequestIdToActiveSpan)(config);
829
+ const interceptors = [];
830
+ if (metrics_tracer_factory_1.MetricsTracerFactory.enabled) {
831
+ interceptors.push(interceptor_1.MetricInterceptor);
832
+ }
728
833
  const requestFn = gaxClient[config.method].bind(gaxClient, reqOpts,
729
834
  // Add headers to `gaxOpts`
730
835
  extend(true, {}, config.gaxOpts, {
731
836
  otherArgs: {
732
837
  headers: config.headers,
838
+ options: {
839
+ interceptors: interceptors,
840
+ },
733
841
  },
734
842
  }));
735
843
  // Wrap requestFn to inject the spanner request id into every returned error.
@@ -789,13 +897,24 @@ class Spanner extends service_1.GrpcService {
789
897
  */
790
898
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
791
899
  request(config, callback) {
900
+ let metricsTracer = null;
901
+ if (config.client === 'SpannerClient') {
902
+ metricsTracer =
903
+ metrics_tracer_factory_1.MetricsTracerFactory?.getInstance()?.createMetricsTracer(config.method, config.reqOpts.session ?? config.reqOpts.database, config.headers['x-goog-spanner-request-id']) ?? null;
904
+ }
905
+ metricsTracer?.recordOperationStart();
792
906
  if (typeof callback === 'function') {
793
907
  this.prepareGapicRequest_(config, (err, requestFn) => {
794
908
  if (err) {
795
909
  callback(err);
910
+ metricsTracer?.recordOperationCompletion();
796
911
  }
797
912
  else {
798
- requestFn(callback);
913
+ const wrappedCallback = (...args) => {
914
+ metricsTracer?.recordOperationCompletion();
915
+ callback(...args);
916
+ };
917
+ requestFn(wrappedCallback);
799
918
  }
800
919
  });
801
920
  }
@@ -803,10 +922,26 @@ class Spanner extends service_1.GrpcService {
803
922
  return new Promise((resolve, reject) => {
804
923
  this.prepareGapicRequest_(config, (err, requestFn) => {
805
924
  if (err) {
925
+ metricsTracer?.recordOperationCompletion();
806
926
  reject(err);
807
927
  }
808
928
  else {
809
- resolve(requestFn());
929
+ const result = requestFn();
930
+ if (result && typeof result.then === 'function') {
931
+ result
932
+ .then(val => {
933
+ metricsTracer?.recordOperationCompletion();
934
+ resolve(val);
935
+ })
936
+ .catch(error => {
937
+ metricsTracer?.recordOperationCompletion();
938
+ reject(error);
939
+ });
940
+ }
941
+ else {
942
+ metricsTracer?.recordOperationCompletion();
943
+ resolve(result);
944
+ }
810
945
  }
811
946
  });
812
947
  });
@@ -825,6 +960,12 @@ class Spanner extends service_1.GrpcService {
825
960
  */
826
961
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
827
962
  requestStream(config) {
963
+ let metricsTracer = null;
964
+ if (config.client === 'SpannerClient') {
965
+ metricsTracer =
966
+ metrics_tracer_factory_1.MetricsTracerFactory?.getInstance()?.createMetricsTracer(config.method, config.reqOpts.session ?? config.reqOpts.database, config.headers['x-goog-spanner-request-id']) ?? null;
967
+ }
968
+ metricsTracer?.recordOperationStart();
828
969
  const stream = streamEvents(through.obj());
829
970
  stream.once('reading', () => {
830
971
  this.prepareGapicRequest_(config, (err, requestFn) => {
@@ -839,6 +980,12 @@ class Spanner extends service_1.GrpcService {
839
980
  .pipe(stream);
840
981
  });
841
982
  });
983
+ stream.on('finish', () => {
984
+ stream.destroy();
985
+ });
986
+ stream.on('close', () => {
987
+ metricsTracer?.recordOperationCompletion();
988
+ });
842
989
  return stream;
843
990
  }
844
991
  /**
@@ -1104,6 +1251,30 @@ class Spanner extends service_1.GrpcService {
1104
1251
  }
1105
1252
  }
1106
1253
  exports.Spanner = Spanner;
1254
+ let cleanupCalled = false;
1255
+ const cleanup = async () => {
1256
+ if (cleanupCalled)
1257
+ return;
1258
+ cleanupCalled = true;
1259
+ await metrics_tracer_factory_1.MetricsTracerFactory.resetInstance();
1260
+ };
1261
+ // For signals (let process exit naturally)
1262
+ process.on('SIGINT', async () => {
1263
+ await cleanup();
1264
+ });
1265
+ process.on('SIGTERM', async () => {
1266
+ await cleanup();
1267
+ });
1268
+ // For natural exit (Node will NOT wait for async, so we must block the event loop)
1269
+ process.on('beforeExit', () => {
1270
+ const done = cleanup();
1271
+ if (done && typeof done.then === 'function') {
1272
+ // Handle promise rejection
1273
+ done.catch(err => {
1274
+ console.error('Cleanup error before exit:', err);
1275
+ });
1276
+ }
1277
+ });
1107
1278
  /*! Developer Documentation
1108
1279
  *
1109
1280
  * All async methods (except for streams) will return a Promise in the event
@@ -54,8 +54,9 @@ const { AsyncHooksContextManager, } = require('@opentelemetry/context-async-hook
54
54
  * associated in their respective hierarchies.
55
55
  */
56
56
  function ensureInitialContextManagerSet() {
57
- if (api_1.context.active() === api_1.ROOT_CONTEXT) {
58
- // If no active context was set previously, trace context propagation cannot
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
59
60
  // function correctly with async/await for OpenTelemetry
60
61
  // See {@link https://opentelemetry.io/docs/languages/js/context/#active-context}
61
62
  api_1.context.disable(); // Disable any prior contextManager.
@@ -0,0 +1,36 @@
1
+ import { View } from '@opentelemetry/sdk-metrics';
2
+ export declare const SPANNER_METER_NAME = "spanner-nodejs";
3
+ export declare const CLIENT_METRICS_PREFIX = "spanner.googleapis.com/internal/client";
4
+ export declare const SPANNER_RESOURCE_TYPE = "spanner_instance_client";
5
+ export declare const TRACER_CLEANUP_THRESHOLD_MS: number;
6
+ export declare const TRACER_CLEANUP_INTERVAL_MS: number;
7
+ export declare const ATTR_CLOUD_REGION = "cloud.region";
8
+ export declare const MIN_EXPORT_FREQUENCY_MS: number;
9
+ export declare const MONITORED_RES_LABEL_KEY_PROJECT = "project_id";
10
+ export declare const MONITORED_RES_LABEL_KEY_INSTANCE = "instance_id";
11
+ export declare const MONITORED_RES_LABEL_KEY_INSTANCE_CONFIG = "instance_config";
12
+ export declare const MONITORED_RES_LABEL_KEY_LOCATION = "location";
13
+ export declare const MONITORED_RES_LABEL_KEY_CLIENT_HASH = "client_hash";
14
+ export declare const MONITORED_RESOURCE_LABELS: Set<string>;
15
+ export declare const METRIC_LABEL_KEY_CLIENT_UID = "client_uid";
16
+ export declare const METRIC_LABEL_KEY_CLIENT_NAME = "client_name";
17
+ export declare const METRIC_LABEL_KEY_DATABASE = "database";
18
+ export declare const METRIC_LABEL_KEY_METHOD = "method";
19
+ export declare const METRIC_LABEL_KEY_STATUS = "status";
20
+ export declare const METRIC_LABELS: Set<string>;
21
+ export declare const METRIC_NAME_OPERATION_LATENCIES = "operation_latencies";
22
+ export declare const METRIC_NAME_ATTEMPT_LATENCIES = "attempt_latencies";
23
+ export declare const METRIC_NAME_OPERATION_COUNT = "operation_count";
24
+ export declare const METRIC_NAME_ATTEMPT_COUNT = "attempt_count";
25
+ export declare const METRIC_NAME_GFE_LATENCIES = "gfe_latencies";
26
+ export declare const METRIC_NAME_GFE_CONNECTIVITY_ERROR_COUNT = "gfe_connectivity_error_count";
27
+ export declare const METRIC_NAME_AFE_LATENCIES = "afe_latencies";
28
+ export declare const METRIC_NAME_AFE_CONNECTIVITY_ERROR_COUNT = "afe_connectivity_error_count";
29
+ export declare const METRIC_NAMES: Set<string>;
30
+ export declare const UNKNOWN_ATTRIBUTE = "unknown";
31
+ export declare const HISTOGRAM_BUCKET_BOUNDARIES: number[];
32
+ export declare const OPERATION_LATENCY_VIEW: View;
33
+ export declare const ATTEMPT_LATENCY_VIEW: View;
34
+ export declare const GFE_LATENCY_VIEW: View;
35
+ export declare const AFE_LATENCY_VIEW: View;
36
+ export declare const METRIC_VIEWS: View[];