@google-cloud/spanner 8.0.0 → 8.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 (50) 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 +1521 -0
  7. package/build/protos/protos.js +3906 -0
  8. package/build/protos/protos.json +317 -1
  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 +1 -0
  15. package/build/src/database.js +2 -0
  16. package/build/src/helper.d.ts +90 -0
  17. package/build/src/helper.js +154 -0
  18. package/build/src/index.d.ts +33 -0
  19. package/build/src/index.js +178 -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/partial-result-stream.js +9 -5
  36. package/build/src/session-factory.d.ts +34 -0
  37. package/build/src/session-factory.js +30 -0
  38. package/build/src/session-pool.js +1 -2
  39. package/build/src/transaction-runner.d.ts +1 -0
  40. package/build/src/transaction-runner.js +6 -0
  41. package/build/src/transaction.d.ts +42 -1
  42. package/build/src/transaction.js +192 -42
  43. package/build/src/v1/database_admin_client.d.ts +34 -0
  44. package/build/src/v1/database_admin_client.js +167 -1
  45. package/build/src/v1/database_admin_client_config.json +4 -0
  46. package/build/src/v1/instance_admin_client.d.ts +120 -0
  47. package/build/src/v1/instance_admin_client.js +312 -13
  48. package/build/src/v1/spanner_client.js +108 -0
  49. package/build/src/v1/spanner_proto_list.json +1 -0
  50. package/package.json +12 -5
@@ -52,3 +52,93 @@ export declare function isCreateSessionPermissionError(error: grpc.ServiceError
52
52
  * @returns An array containing the value, or an empty array.
53
53
  */
54
54
  export declare function toArray(value: any): any[];
55
+ /**
56
+ * Checks if a value is defined.
57
+ * @param {*} value The value to check.
58
+ * @returns {Boolean} `true` if the value is NOT `undefined`, otherwise `false`.
59
+ */
60
+ export declare function isDefined(value: any): boolean;
61
+ /**
62
+ * Checks if a value is null.
63
+ * @param {*} value The value to check.
64
+ * @returns {Boolean} `true` if the value is null, otherwise `false`.
65
+ */
66
+ export declare function isNull(value: any): boolean;
67
+ /**
68
+ * Checks if a value is undefined.
69
+ * @param {*} value The value to check.
70
+ * @returns {Boolean} `true` if the value is `undefined`, otherwise `false`.
71
+ */
72
+ export declare function isUndefined(value: any): boolean;
73
+ /**
74
+ * Checks if a value is empty.
75
+ * @param {*} value The value to check.
76
+ * @returns {Boolean} `true` if the value is empty, otherwise `false`.
77
+ */
78
+ export declare function isEmpty(value: any): boolean;
79
+ /**
80
+ * Checks if a value is a plain javascript object.
81
+ * @param {*} value The value to check.
82
+ * @returns {Boolean} `true` if the value is an object, otherwise `false`.
83
+ */
84
+ export declare function isObject(value: any): boolean;
85
+ /**
86
+ * Checks if a value is a string.
87
+ * @param {*} value The value to check.
88
+ * @returns {Boolean} `true` if the value is string, otherwise `false`.
89
+ */
90
+ export declare function isString(value: any): boolean;
91
+ /**
92
+ * Checks if a value is an array.
93
+ * @param {*} value The value to check.
94
+ * @returns {Boolean} `true` if the value is an array, otherwise `false`.
95
+ */
96
+ export declare function isArray(value: any): boolean;
97
+ /**
98
+ * Checks if a value is a Date object.
99
+ * @param {*} value The value to check.
100
+ * @returns {Boolean} `true` if the value is a `Date` object, otherwise `false`.
101
+ */
102
+ export declare function isDate(value: any): boolean;
103
+ /**
104
+ * Checks if a value is a boolean.
105
+ * @param {*} value The value to check.
106
+ * @returns {Boolean} `true` if the value is boolean, otherwise `false`.
107
+ */
108
+ export declare function isBoolean(value: any): boolean;
109
+ /**
110
+ * Checks if a value is a number.
111
+ * @param {*} value The value to check.
112
+ * @returns {Boolean} `true` if the value is a number, otherwise `false`.
113
+ */
114
+ export declare function isNumber(value: any): boolean;
115
+ /**
116
+ * Checks if a value is an integer.
117
+ * @param {*} value The value to check.
118
+ * @returns {Boolean} `true` if the value is an integer, otherwise `false`.
119
+ */
120
+ export declare function isInteger(value: any): boolean;
121
+ /**
122
+ * Checks if a value is `NaN`.
123
+ * @param {*} value The value to check.
124
+ * @returns {Boolean} `true` if the value is `NaN`, otherwise `false`.
125
+ */
126
+ export declare function isActualNaN(value: any): boolean;
127
+ /**
128
+ * Checks if a value is a non-integer (decimal) number.
129
+ * @param {*} value The value to check.
130
+ * @returns {Boolean} `true` if the value is a decimal number, otherwise `false`.
131
+ */
132
+ export declare function isDecimal(value: any): boolean;
133
+ /**
134
+ * Checks if a value is `Infinity` or `-Infinity`.
135
+ * @param {*} value The value to check.
136
+ * @returns {Boolean} `true` if the value is infinite, otherwise `false`.
137
+ */
138
+ export declare function isInfinite(value: any): boolean;
139
+ /**
140
+ * Checks if a value is an `Error` object.
141
+ * @param {*} value The value to check.
142
+ * @returns {Boolean} `true` if the value is an `Error` object, otherwise `false`.
143
+ */
144
+ export declare function isError(value: any): boolean;
@@ -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
@@ -65,6 +65,17 @@ export interface SpannerOptions extends GrpcClientOptions {
65
65
  defaultTransactionOptions?: Pick<RunTransactionOptions, 'isolationLevel'>;
66
66
  observabilityOptions?: ObservabilityOptions;
67
67
  interceptors?: any[];
68
+ /**
69
+ * The Trusted Cloud Domain (TPC) DNS of the service used to make requests.
70
+ * Defaults to `googleapis.com`.
71
+ * We support both camelCase and snake_case for the universe domain.
72
+ * Customer may set any of these as both the options are same,
73
+ * they both points to universe endpoint.
74
+ * There is no preference for any of these option; however exception will be
75
+ * thrown if both are set to different values.
76
+ */
77
+ universe_domain?: string;
78
+ universeDomain?: string;
68
79
  }
69
80
  export interface RequestConfig {
70
81
  client: string;
@@ -172,6 +183,9 @@ declare class Spanner extends GrpcService {
172
183
  directedReadOptions: google.spanner.v1.IDirectedReadOptions | null;
173
184
  defaultTransactionOptions: RunTransactionOptions;
174
185
  _observabilityOptions: ObservabilityOptions | undefined;
186
+ private _universeDomain;
187
+ private _isEmulatorEnabled;
188
+ private static _isAFEServerTimingEnabled;
175
189
  readonly _nthClientId: number;
176
190
  /**
177
191
  * Placeholder used to auto populate a column with the commit timestamp.
@@ -183,6 +197,20 @@ declare class Spanner extends GrpcService {
183
197
  static COMMIT_TIMESTAMP: string;
184
198
  static POSTGRESQL: google.spanner.admin.database.v1.DatabaseDialect;
185
199
  static GOOGLE_STANDARD_SQL: google.spanner.admin.database.v1.DatabaseDialect;
200
+ /**
201
+ * Returns whether AFE (Application Frontend Extension) server timing is enabled.
202
+ *
203
+ * This method checks the value of the environment variable
204
+ * `SPANNER_DISABLE_AFE_SERVER_TIMING`. If the variable is explicitly set to the
205
+ * string `'true'`, then AFE server timing is considered disabled, and this method
206
+ * returns `false`. For all other values (including if the variable is unset),
207
+ * the method returns `true`.
208
+ *
209
+ * @returns {boolean} `true` if AFE server timing is enabled; otherwise, `false`.
210
+ */
211
+ static isAFEServerTimingEnabled: () => boolean;
212
+ /** Resets the cached value (use in tests if env changes). */
213
+ static _resetAFEServerTimingForTest(): void;
186
214
  /**
187
215
  * Gets the configured Spanner emulator host from an environment variable.
188
216
  */
@@ -191,6 +219,7 @@ declare class Spanner extends GrpcService {
191
219
  port?: number;
192
220
  } | undefined;
193
221
  constructor(options?: SpannerOptions);
222
+ get universeDomain(): string;
194
223
  /**
195
224
  * Gets the InstanceAdminClient object.
196
225
  * The returned InstanceAdminClient object is a shared, managed instance and should not be manually closed.
@@ -816,6 +845,10 @@ declare class Spanner extends GrpcService {
816
845
  * ```
817
846
  */
818
847
  instanceConfig(name: string): InstanceConfig;
848
+ /**
849
+ * Setup the OpenTelemetry metrics capturing for service metrics to Google Cloud Monitoring.
850
+ */
851
+ configureMetrics_(): void;
819
852
  /**
820
853
  * Prepare a gapic request. This will cache the GAX client and replace
821
854
  * {{projectId}} placeholders, if necessary.
@@ -65,8 +65,46 @@ const v1 = require("./v1");
65
65
  exports.v1 = v1;
66
66
  const instrument_1 = require("./instrument");
67
67
  const request_id_header_1 = require("./request_id_header");
68
+ const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
69
+ const interceptor_1 = require("./metrics/interceptor");
70
+ const spanner_metrics_exporter_1 = require("./metrics/spanner-metrics-exporter");
71
+ const metrics_tracer_factory_1 = require("./metrics/metrics-tracer-factory");
68
72
  // eslint-disable-next-line @typescript-eslint/no-var-requires
69
73
  const gcpApiConfig = require('./spanner_grpc_config.json');
74
+ /**
75
+ * Retrieves the universe domain.
76
+ *
77
+ * This function checks for a universe domain in the following order:
78
+ * 1. The `universeDomain` property within the provided spanner options.
79
+ * 2. The `universe_domain` property within the provided spanner options.
80
+ * 3. The `GOOGLE_CLOUD_UNIVERSE_DOMAIN` environment variable.
81
+ * 4. If none of the above properties will be set, it will fallback to `googleapis.com`.
82
+ *
83
+ * For consistency with the Auth client, if the `universe_domain` option or the
84
+ * `GOOGLE_CLOUD_UNIVERSE_DOMAIN` env variable is used, this function will also set the
85
+ * `universeDomain` property within the provided `SpannerOptions` object. This ensures the
86
+ * Spanner client's universe domain aligns with the universe configured for authentication.
87
+ *
88
+ * @param {SpannerOptions} options - The Spanner client options.
89
+ * @returns {string} The universe domain.
90
+ */
91
+ function getUniverseDomain(options) {
92
+ const universeDomainEnvVar = typeof process === 'object' && typeof process.env === 'object'
93
+ ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']
94
+ : undefined;
95
+ const universeDomain = options?.universeDomain ??
96
+ options?.universe_domain ??
97
+ universeDomainEnvVar ??
98
+ 'googleapis.com';
99
+ // if the options.universe_domain/GOOGLE_CLOUD_UNIVERSE_DOMAIN env variable is set,
100
+ // set its value to the Spanner `universeDomain` options
101
+ // to match it with the universe from Auth Client
102
+ if (!options?.universeDomain &&
103
+ (options?.universe_domain || process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN)) {
104
+ options.universeDomain = universeDomain;
105
+ }
106
+ return universeDomain;
107
+ }
70
108
  /**
71
109
  * [Cloud Spanner](https://cloud.google.com/spanner) is a highly scalable,
72
110
  * transactional, managed, NewSQL database service. Cloud Spanner solves the
@@ -120,6 +158,9 @@ class Spanner extends service_1.GrpcService {
120
158
  directedReadOptions;
121
159
  defaultTransactionOptions;
122
160
  _observabilityOptions;
161
+ _universeDomain;
162
+ _isEmulatorEnabled;
163
+ static _isAFEServerTimingEnabled;
123
164
  _nthClientId;
124
165
  /**
125
166
  * Placeholder used to auto populate a column with the commit timestamp.
@@ -131,6 +172,28 @@ class Spanner extends service_1.GrpcService {
131
172
  static COMMIT_TIMESTAMP = 'spanner.commit_timestamp()';
132
173
  static POSTGRESQL = protos_1.google.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL;
133
174
  static GOOGLE_STANDARD_SQL = protos_1.google.spanner.admin.database.v1.DatabaseDialect.GOOGLE_STANDARD_SQL;
175
+ /**
176
+ * Returns whether AFE (Application Frontend Extension) server timing is enabled.
177
+ *
178
+ * This method checks the value of the environment variable
179
+ * `SPANNER_DISABLE_AFE_SERVER_TIMING`. If the variable is explicitly set to the
180
+ * string `'true'`, then AFE server timing is considered disabled, and this method
181
+ * returns `false`. For all other values (including if the variable is unset),
182
+ * the method returns `true`.
183
+ *
184
+ * @returns {boolean} `true` if AFE server timing is enabled; otherwise, `false`.
185
+ */
186
+ static isAFEServerTimingEnabled = () => {
187
+ if (this._isAFEServerTimingEnabled === undefined) {
188
+ this._isAFEServerTimingEnabled =
189
+ process.env['SPANNER_DISABLE_AFE_SERVER_TIMING'] !== 'true';
190
+ }
191
+ return this._isAFEServerTimingEnabled;
192
+ };
193
+ /** Resets the cached value (use in tests if env changes). */
194
+ static _resetAFEServerTimingForTest() {
195
+ this._isAFEServerTimingEnabled = undefined;
196
+ }
134
197
  /**
135
198
  * Gets the configured Spanner emulator host from an environment variable.
136
199
  */
@@ -194,19 +257,25 @@ class Spanner extends service_1.GrpcService {
194
257
  isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED,
195
258
  };
196
259
  delete options.defaultTransactionOptions;
260
+ if (options?.universe_domain &&
261
+ options?.universeDomain &&
262
+ options?.universe_domain !== options?.universeDomain) {
263
+ throw new Error('Please set either universe_domain or universeDomain, but not both.');
264
+ }
265
+ let isEmulatorEnabled = false;
197
266
  const emulatorHost = Spanner.getSpannerEmulatorHost();
198
267
  if (emulatorHost &&
199
268
  emulatorHost.endpoint &&
200
269
  emulatorHost.endpoint.length > 0) {
270
+ isEmulatorEnabled = true;
201
271
  options.servicePath = emulatorHost.endpoint;
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._isEmulatorEnabled = isEmulatorEnabled;
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_();
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,23 @@ 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_() {
764
+ const metricsEnabled = process.env.SPANNER_DISABLE_BUILTIN_METRICS !== 'true' &&
765
+ !this._isEmulatorEnabled;
766
+ metrics_tracer_factory_1.MetricsTracerFactory.enabled = metricsEnabled;
767
+ if (metricsEnabled) {
768
+ const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(this.projectId);
769
+ const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
770
+ exporter: new spanner_metrics_exporter_1.CloudMonitoringMetricsExporter({ auth: this.auth }),
771
+ exportIntervalMillis: 60000,
772
+ });
773
+ // Retrieve the MeterProvider to trigger construction
774
+ factory.getMeterProvider([periodicReader]);
775
+ }
776
+ }
682
777
  /**
683
778
  * Prepare a gapic request. This will cache the GAX client and replace
684
779
  * {{projectId}} placeholders, if necessary.
@@ -695,8 +790,13 @@ class Spanner extends service_1.GrpcService {
695
790
  return;
696
791
  }
697
792
  const clientName = config.client;
698
- if (!this.clients_.has(clientName)) {
699
- this.clients_.set(clientName, new v1[clientName](this.options));
793
+ try {
794
+ if (!this.clients_.has(clientName)) {
795
+ this.clients_.set(clientName, new v1[clientName](this.options));
796
+ }
797
+ }
798
+ catch (err) {
799
+ callback(err, null);
700
800
  }
701
801
  const gaxClient = this.clients_.get(clientName);
702
802
  let reqOpts = extend(true, {}, config.reqOpts);
@@ -725,11 +825,18 @@ class Spanner extends service_1.GrpcService {
725
825
  });
726
826
  // Attach the x-goog-spanner-request-id to the currently active span.
727
827
  (0, request_id_header_1.attributeXGoogSpannerRequestIdToActiveSpan)(config);
828
+ const interceptors = [];
829
+ if (metrics_tracer_factory_1.MetricsTracerFactory.enabled) {
830
+ interceptors.push(interceptor_1.MetricInterceptor);
831
+ }
728
832
  const requestFn = gaxClient[config.method].bind(gaxClient, reqOpts,
729
833
  // Add headers to `gaxOpts`
730
834
  extend(true, {}, config.gaxOpts, {
731
835
  otherArgs: {
732
836
  headers: config.headers,
837
+ options: {
838
+ interceptors: interceptors,
839
+ },
733
840
  },
734
841
  }));
735
842
  // Wrap requestFn to inject the spanner request id into every returned error.
@@ -789,13 +896,24 @@ class Spanner extends service_1.GrpcService {
789
896
  */
790
897
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
791
898
  request(config, callback) {
899
+ let metricsTracer = null;
900
+ if (config.client === 'SpannerClient') {
901
+ metricsTracer =
902
+ metrics_tracer_factory_1.MetricsTracerFactory?.getInstance()?.createMetricsTracer(config.method, config.reqOpts.session ?? config.reqOpts.database, config.headers['x-goog-spanner-request-id']) ?? null;
903
+ }
904
+ metricsTracer?.recordOperationStart();
792
905
  if (typeof callback === 'function') {
793
906
  this.prepareGapicRequest_(config, (err, requestFn) => {
794
907
  if (err) {
795
908
  callback(err);
909
+ metricsTracer?.recordOperationCompletion();
796
910
  }
797
911
  else {
798
- requestFn(callback);
912
+ const wrappedCallback = (...args) => {
913
+ metricsTracer?.recordOperationCompletion();
914
+ callback(...args);
915
+ };
916
+ requestFn(wrappedCallback);
799
917
  }
800
918
  });
801
919
  }
@@ -803,10 +921,26 @@ class Spanner extends service_1.GrpcService {
803
921
  return new Promise((resolve, reject) => {
804
922
  this.prepareGapicRequest_(config, (err, requestFn) => {
805
923
  if (err) {
924
+ metricsTracer?.recordOperationCompletion();
806
925
  reject(err);
807
926
  }
808
927
  else {
809
- resolve(requestFn());
928
+ const result = requestFn();
929
+ if (result && typeof result.then === 'function') {
930
+ result
931
+ .then(val => {
932
+ metricsTracer?.recordOperationCompletion();
933
+ resolve(val);
934
+ })
935
+ .catch(error => {
936
+ metricsTracer?.recordOperationCompletion();
937
+ reject(error);
938
+ });
939
+ }
940
+ else {
941
+ metricsTracer?.recordOperationCompletion();
942
+ resolve(result);
943
+ }
810
944
  }
811
945
  });
812
946
  });
@@ -825,6 +959,12 @@ class Spanner extends service_1.GrpcService {
825
959
  */
826
960
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
827
961
  requestStream(config) {
962
+ let metricsTracer = null;
963
+ if (config.client === 'SpannerClient') {
964
+ metricsTracer =
965
+ metrics_tracer_factory_1.MetricsTracerFactory?.getInstance()?.createMetricsTracer(config.method, config.reqOpts.session ?? config.reqOpts.database, config.headers['x-goog-spanner-request-id']) ?? null;
966
+ }
967
+ metricsTracer?.recordOperationStart();
828
968
  const stream = streamEvents(through.obj());
829
969
  stream.once('reading', () => {
830
970
  this.prepareGapicRequest_(config, (err, requestFn) => {
@@ -839,6 +979,12 @@ class Spanner extends service_1.GrpcService {
839
979
  .pipe(stream);
840
980
  });
841
981
  });
982
+ stream.on('finish', () => {
983
+ stream.destroy();
984
+ });
985
+ stream.on('close', () => {
986
+ metricsTracer?.recordOperationCompletion();
987
+ });
842
988
  return stream;
843
989
  }
844
990
  /**
@@ -1104,6 +1250,30 @@ class Spanner extends service_1.GrpcService {
1104
1250
  }
1105
1251
  }
1106
1252
  exports.Spanner = Spanner;
1253
+ let cleanupCalled = false;
1254
+ const cleanup = async () => {
1255
+ if (cleanupCalled)
1256
+ return;
1257
+ cleanupCalled = true;
1258
+ await metrics_tracer_factory_1.MetricsTracerFactory.resetInstance();
1259
+ };
1260
+ // For signals (let process exit naturally)
1261
+ process.on('SIGINT', async () => {
1262
+ await cleanup();
1263
+ });
1264
+ process.on('SIGTERM', async () => {
1265
+ await cleanup();
1266
+ });
1267
+ // For natural exit (Node will NOT wait for async, so we must block the event loop)
1268
+ process.on('beforeExit', () => {
1269
+ const done = cleanup();
1270
+ if (done && typeof done.then === 'function') {
1271
+ // Handle promise rejection
1272
+ done.catch(err => {
1273
+ console.error('Cleanup error before exit:', err);
1274
+ });
1275
+ }
1276
+ });
1107
1277
  /*! Developer Documentation
1108
1278
  *
1109
1279
  * 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[];