@google-cloud/spanner 7.21.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 (76) hide show
  1. package/README.md +2 -0
  2. package/build/protos/google/spanner/admin/database/v1/backup.proto +1 -1
  3. package/build/protos/google/spanner/admin/database/v1/backup_schedule.proto +1 -1
  4. package/build/protos/google/spanner/admin/database/v1/common.proto +1 -1
  5. package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +36 -1
  6. package/build/protos/google/spanner/admin/instance/v1/common.proto +1 -1
  7. package/build/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto +1 -1
  8. package/build/protos/google/spanner/executor/v1/cloud_executor.proto +1 -1
  9. package/build/protos/google/spanner/v1/change_stream.proto +451 -0
  10. package/build/protos/google/spanner/v1/commit_response.proto +10 -5
  11. package/build/protos/google/spanner/v1/keys.proto +1 -1
  12. package/build/protos/google/spanner/v1/mutation.proto +1 -1
  13. package/build/protos/google/spanner/v1/query_plan.proto +1 -1
  14. package/build/protos/google/spanner/v1/result_set.proto +55 -49
  15. package/build/protos/google/spanner/v1/spanner.proto +1 -1
  16. package/build/protos/google/spanner/v1/transaction.proto +41 -357
  17. package/build/protos/google/spanner/v1/type.proto +1 -1
  18. package/build/protos/protos.d.ts +1577 -194
  19. package/build/protos/protos.js +3977 -288
  20. package/build/protos/protos.json +325 -3
  21. package/build/src/backup.js +7 -0
  22. package/build/src/batch-transaction.d.ts +48 -29
  23. package/build/src/batch-transaction.js +15 -100
  24. package/build/src/codec.js +63 -47
  25. package/build/src/common-grpc/service-object.js +1 -0
  26. package/build/src/common-grpc/service.js +35 -18
  27. package/build/src/common.d.ts +1 -0
  28. package/build/src/common.js +9 -1
  29. package/build/src/database.d.ts +1 -0
  30. package/build/src/database.js +54 -42
  31. package/build/src/helper.d.ts +99 -0
  32. package/build/src/helper.js +178 -0
  33. package/build/src/index.d.ts +33 -0
  34. package/build/src/index.js +202 -21
  35. package/build/src/instance-config.d.ts +1 -1
  36. package/build/src/instance-config.js +4 -0
  37. package/build/src/instance.js +12 -6
  38. package/build/src/instrument.js +5 -6
  39. package/build/src/metrics/constants.d.ts +36 -0
  40. package/build/src/metrics/constants.js +106 -0
  41. package/build/src/metrics/external-types.d.ts +20 -0
  42. package/build/src/metrics/external-types.js +32 -0
  43. package/build/src/metrics/interceptor.d.ts +13 -0
  44. package/build/src/metrics/interceptor.js +87 -0
  45. package/build/src/metrics/metrics-tracer-factory.d.ts +165 -0
  46. package/build/src/metrics/metrics-tracer-factory.js +389 -0
  47. package/build/src/metrics/metrics-tracer.d.ts +204 -0
  48. package/build/src/metrics/metrics-tracer.js +371 -0
  49. package/build/src/metrics/spanner-metrics-exporter.d.ts +35 -0
  50. package/build/src/metrics/spanner-metrics-exporter.js +119 -0
  51. package/build/src/metrics/transform.d.ts +144 -0
  52. package/build/src/metrics/transform.js +272 -0
  53. package/build/src/multiplexed-session.js +7 -1
  54. package/build/src/partial-result-stream.js +18 -10
  55. package/build/src/request_id_header.js +1 -0
  56. package/build/src/session-factory.d.ts +34 -0
  57. package/build/src/session-factory.js +35 -2
  58. package/build/src/session-pool.js +24 -8
  59. package/build/src/session.d.ts +0 -1
  60. package/build/src/session.js +7 -2
  61. package/build/src/table.js +6 -3
  62. package/build/src/transaction-runner.d.ts +1 -0
  63. package/build/src/transaction-runner.js +18 -2
  64. package/build/src/transaction.d.ts +42 -1
  65. package/build/src/transaction.js +258 -94
  66. package/build/src/v1/database_admin_client.d.ts +37 -2
  67. package/build/src/v1/database_admin_client.js +718 -168
  68. package/build/src/v1/database_admin_client_config.json +4 -0
  69. package/build/src/v1/instance_admin_client.d.ts +122 -1
  70. package/build/src/v1/instance_admin_client.js +765 -146
  71. package/build/src/v1/spanner_client.d.ts +2 -1
  72. package/build/src/v1/spanner_client.js +391 -85
  73. package/build/src/v1/spanner_executor_proxy_client.d.ts +2 -1
  74. package/build/src/v1/spanner_executor_proxy_client.js +41 -19
  75. package/build/src/v1/spanner_proto_list.json +1 -0
  76. package/package.json +64 -58
@@ -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
@@ -108,6 +146,54 @@ const gcpApiConfig = require('./spanner_grpc_config.json');
108
146
  * @param {ClientConfig} [options] Configuration options.
109
147
  */
110
148
  class Spanner extends service_1.GrpcService {
149
+ options;
150
+ auth;
151
+ clients_;
152
+ instances_;
153
+ instanceConfigs_;
154
+ projectIdReplaced_;
155
+ projectFormattedName_;
156
+ commonHeaders_;
157
+ routeToLeaderEnabled = true;
158
+ directedReadOptions;
159
+ defaultTransactionOptions;
160
+ _observabilityOptions;
161
+ _universeDomain;
162
+ _isEmulatorEnabled;
163
+ static _isAFEServerTimingEnabled;
164
+ _nthClientId;
165
+ /**
166
+ * Placeholder used to auto populate a column with the commit timestamp.
167
+ * This can only be used for timestamp columns that have set the option
168
+ * "(allow_commit_timestamp=true)" in the schema.
169
+ *
170
+ * @type {string}
171
+ */
172
+ static COMMIT_TIMESTAMP = 'spanner.commit_timestamp()';
173
+ static POSTGRESQL = protos_1.google.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL;
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
+ }
111
197
  /**
112
198
  * Gets the configured Spanner emulator host from an environment variable.
113
199
  */
@@ -135,7 +221,6 @@ class Spanner extends service_1.GrpcService {
135
221
  return undefined;
136
222
  }
137
223
  constructor(options) {
138
- var _a;
139
224
  const scopes = [];
140
225
  const clientClasses = [
141
226
  v1.DatabaseAdminClient,
@@ -172,19 +257,25 @@ class Spanner extends service_1.GrpcService {
172
257
  isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED,
173
258
  };
174
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;
175
266
  const emulatorHost = Spanner.getSpannerEmulatorHost();
176
267
  if (emulatorHost &&
177
268
  emulatorHost.endpoint &&
178
269
  emulatorHost.endpoint.length > 0) {
270
+ isEmulatorEnabled = true;
179
271
  options.servicePath = emulatorHost.endpoint;
180
272
  options.port = emulatorHost.port;
181
273
  options.sslCreds = google_gax_1.grpc.credentials.createInsecure();
182
274
  }
275
+ const universeEndpoint = getUniverseDomain(options);
276
+ const spannerUniverseEndpoint = 'spanner.' + universeEndpoint;
183
277
  const config = {
184
- baseUrl: options.apiEndpoint ||
185
- options.servicePath ||
186
- // TODO: for TPC, this needs to support universeDomain
187
- 'spanner.googleapis.com',
278
+ baseUrl: options.apiEndpoint || options.servicePath || spannerUniverseEndpoint,
188
279
  protosDir: path.resolve(__dirname, '../protos'),
189
280
  protoServices: {
190
281
  Operations: {
@@ -196,10 +287,10 @@ class Spanner extends service_1.GrpcService {
196
287
  packageJson: require('../../package.json'),
197
288
  };
198
289
  super(config, options);
199
- this.routeToLeaderEnabled = true;
200
290
  if (options.routeToLeaderEnabled === false) {
201
291
  this.routeToLeaderEnabled = false;
202
292
  }
293
+ this._isEmulatorEnabled = isEmulatorEnabled;
203
294
  this.options = options;
204
295
  this.auth = new google_auth_library_1.GoogleAuth(this.options);
205
296
  this.clients_ = new Map();
@@ -210,9 +301,14 @@ class Spanner extends service_1.GrpcService {
210
301
  this.directedReadOptions = directedReadOptions;
211
302
  this.defaultTransactionOptions = defaultTransactionOptions;
212
303
  this._observabilityOptions = options.observabilityOptions;
213
- this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.projectFormattedName_, (_a = this._observabilityOptions) === null || _a === void 0 ? void 0 : _a.enableEndToEndTracing);
304
+ this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.projectFormattedName_, this._observabilityOptions?.enableEndToEndTracing);
214
305
  (0, instrument_1.ensureInitialContextManagerSet)();
215
306
  this._nthClientId = (0, request_id_header_1.nextSpannerClientId)();
307
+ this._universeDomain = universeEndpoint;
308
+ this.configureMetrics_();
309
+ }
310
+ get universeDomain() {
311
+ return this._universeDomain;
216
312
  }
217
313
  /**
218
314
  * Gets the InstanceAdminClient object.
@@ -264,6 +360,9 @@ class Spanner extends service_1.GrpcService {
264
360
  }
265
361
  client.close();
266
362
  });
363
+ cleanup().catch(err => {
364
+ console.error('Error occured during cleanup: ', err);
365
+ });
267
366
  }
268
367
  createInstance(name, config, callback) {
269
368
  if (!name) {
@@ -658,6 +757,23 @@ class Spanner extends service_1.GrpcService {
658
757
  }
659
758
  return this.instanceConfigs_.get(key);
660
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
+ }
661
777
  /**
662
778
  * Prepare a gapic request. This will cache the GAX client and replace
663
779
  * {{projectId}} placeholders, if necessary.
@@ -674,8 +790,13 @@ class Spanner extends service_1.GrpcService {
674
790
  return;
675
791
  }
676
792
  const clientName = config.client;
677
- if (!this.clients_.has(clientName)) {
678
- 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);
679
800
  }
680
801
  const gaxClient = this.clients_.get(clientName);
681
802
  let reqOpts = extend(true, {}, config.reqOpts);
@@ -704,11 +825,18 @@ class Spanner extends service_1.GrpcService {
704
825
  });
705
826
  // Attach the x-goog-spanner-request-id to the currently active span.
706
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
+ }
707
832
  const requestFn = gaxClient[config.method].bind(gaxClient, reqOpts,
708
833
  // Add headers to `gaxOpts`
709
834
  extend(true, {}, config.gaxOpts, {
710
835
  otherArgs: {
711
836
  headers: config.headers,
837
+ options: {
838
+ interceptors: interceptors,
839
+ },
712
840
  },
713
841
  }));
714
842
  // Wrap requestFn to inject the spanner request id into every returned error.
@@ -768,13 +896,24 @@ class Spanner extends service_1.GrpcService {
768
896
  */
769
897
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
770
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();
771
905
  if (typeof callback === 'function') {
772
906
  this.prepareGapicRequest_(config, (err, requestFn) => {
773
907
  if (err) {
774
908
  callback(err);
909
+ metricsTracer?.recordOperationCompletion();
775
910
  }
776
911
  else {
777
- requestFn(callback);
912
+ const wrappedCallback = (...args) => {
913
+ metricsTracer?.recordOperationCompletion();
914
+ callback(...args);
915
+ };
916
+ requestFn(wrappedCallback);
778
917
  }
779
918
  });
780
919
  }
@@ -782,10 +921,26 @@ class Spanner extends service_1.GrpcService {
782
921
  return new Promise((resolve, reject) => {
783
922
  this.prepareGapicRequest_(config, (err, requestFn) => {
784
923
  if (err) {
924
+ metricsTracer?.recordOperationCompletion();
785
925
  reject(err);
786
926
  }
787
927
  else {
788
- 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
+ }
789
944
  }
790
945
  });
791
946
  });
@@ -804,6 +959,12 @@ class Spanner extends service_1.GrpcService {
804
959
  */
805
960
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
806
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();
807
968
  const stream = streamEvents(through.obj());
808
969
  stream.once('reading', () => {
809
970
  this.prepareGapicRequest_(config, (err, requestFn) => {
@@ -818,6 +979,12 @@ class Spanner extends service_1.GrpcService {
818
979
  .pipe(stream);
819
980
  });
820
981
  });
982
+ stream.on('finish', () => {
983
+ stream.destroy();
984
+ });
985
+ stream.on('close', () => {
986
+ metricsTracer?.recordOperationCompletion();
987
+ });
821
988
  return stream;
822
989
  }
823
990
  /**
@@ -1083,16 +1250,30 @@ class Spanner extends service_1.GrpcService {
1083
1250
  }
1084
1251
  }
1085
1252
  exports.Spanner = Spanner;
1086
- /**
1087
- * Placeholder used to auto populate a column with the commit timestamp.
1088
- * This can only be used for timestamp columns that have set the option
1089
- * "(allow_commit_timestamp=true)" in the schema.
1090
- *
1091
- * @type {string}
1092
- */
1093
- Spanner.COMMIT_TIMESTAMP = 'spanner.commit_timestamp()';
1094
- Spanner.POSTGRESQL = protos_1.google.spanner.admin.database.v1.DatabaseDialect.POSTGRESQL;
1095
- Spanner.GOOGLE_STANDARD_SQL = protos_1.google.spanner.admin.database.v1.DatabaseDialect.GOOGLE_STANDARD_SQL;
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
+ });
1096
1277
  /*! Developer Documentation
1097
1278
  *
1098
1279
  * All async methods (except for streams) will return a Promise in the event
@@ -14,7 +14,7 @@
14
14
  */
15
15
  declare const common: any;
16
16
  import { google as instanceAdmin } from '../protos/protos';
17
- import { Operation as GaxOperation } from 'google-gax/build/src/longRunningCalls/longrunning';
17
+ import { Operation as GaxOperation } from 'google-gax';
18
18
  import { LongRunningCallback, RequestCallback, ResourceCallback, NormalCallback } from './common';
19
19
  import { GetInstanceConfigCallback, GetInstanceConfigOptions, GetInstanceConfigResponse, RequestConfig, Spanner } from './index';
20
20
  import { CallOptions } from 'google-gax';
@@ -41,6 +41,10 @@ const extend = require("extend");
41
41
  * ```
42
42
  */
43
43
  class InstanceConfig extends common.GrpcServiceObject {
44
+ formattedName_;
45
+ request;
46
+ metadata;
47
+ resourceHeader_;
44
48
  constructor(spanner, name) {
45
49
  const formattedName_ = InstanceConfig.formatName_(spanner.projectId, name);
46
50
  const methods = {
@@ -16,7 +16,7 @@
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.Instance = void 0;
19
- const arrify = require("arrify");
19
+ const helper_1 = require("./helper");
20
20
  // eslint-disable-next-line @typescript-eslint/no-var-requires
21
21
  const common = require('./common-grpc/service-object');
22
22
  const promisify_1 = require("@google-cloud/promisify");
@@ -46,8 +46,14 @@ const protos_1 = require("../protos/protos");
46
46
  * ```
47
47
  */
48
48
  class Instance extends common.GrpcServiceObject {
49
+ formattedName_;
50
+ request;
51
+ requestStream;
52
+ databases_;
53
+ metadata;
54
+ commonHeaders_;
55
+ _observabilityOptions;
49
56
  constructor(spanner, name) {
50
- var _a;
51
57
  const formattedName_ = Instance.formatName_(spanner.projectId, name);
52
58
  const methods = {
53
59
  /**
@@ -116,7 +122,7 @@ class Instance extends common.GrpcServiceObject {
116
122
  this.requestStream = spanner.requestStream.bind(spanner);
117
123
  this.databases_ = new Map();
118
124
  this._observabilityOptions = spanner._observabilityOptions;
119
- this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.formattedName_, (_a = this._observabilityOptions) === null || _a === void 0 ? void 0 : _a.enableEndToEndTracing);
125
+ this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.formattedName_, this._observabilityOptions?.enableEndToEndTracing);
120
126
  }
121
127
  /**
122
128
  * Get a reference to a Backup object.
@@ -456,7 +462,7 @@ class Instance extends common.GrpcServiceObject {
456
462
  delete reqOpts.poolCtor;
457
463
  delete reqOpts.gaxOptions;
458
464
  if (reqOpts.schema) {
459
- reqOpts.extraStatements = arrify(reqOpts.schema);
465
+ reqOpts.extraStatements = (0, helper_1.toArray)(reqOpts.schema);
460
466
  delete reqOpts.schema;
461
467
  }
462
468
  this.request({
@@ -529,7 +535,7 @@ class Instance extends common.GrpcServiceObject {
529
535
  const reqOpts = {
530
536
  name: this.formattedName_,
531
537
  };
532
- Promise.all(Array.from(this.databases_.values()).map(database => {
538
+ void Promise.all(Array.from(this.databases_.values()).map(database => {
533
539
  return database.close();
534
540
  }))
535
541
  .catch(() => { })
@@ -715,7 +721,7 @@ class Instance extends common.GrpcServiceObject {
715
721
  };
716
722
  if (options.fieldNames) {
717
723
  reqOpts['fieldMask'] = {
718
- paths: arrify(options['fieldNames']).map(snakeCase),
724
+ paths: (0, helper_1.toArray)(options['fieldNames']).map(snakeCase),
719
725
  };
720
726
  }
721
727
  return this.request({
@@ -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.
@@ -73,12 +74,10 @@ function ensureInitialContextManagerSet() {
73
74
  * @returns {Span} The created span.
74
75
  */
75
76
  function startTrace(spanNameSuffix, config, cb) {
76
- var _a;
77
77
  if (!config) {
78
78
  config = {};
79
79
  }
80
- return getTracer((_a = config.opts) === null || _a === void 0 ? void 0 : _a.tracerProvider).startActiveSpan(SPAN_NAMESPACE_PREFIX + '.' + spanNameSuffix, { kind: api_1.SpanKind.CLIENT }, span => {
81
- var _a;
80
+ return getTracer(config.opts?.tracerProvider).startActiveSpan(SPAN_NAMESPACE_PREFIX + '.' + spanNameSuffix, { kind: api_1.SpanKind.CLIENT }, span => {
82
81
  span.setAttribute(semantic_conventions_1.ATTR_OTEL_SCOPE_NAME, TRACER_NAME);
83
82
  span.setAttribute(semantic_conventions_1.ATTR_OTEL_SCOPE_VERSION, TRACER_VERSION);
84
83
  span.setAttribute('gcp.client.service', 'spanner');
@@ -96,7 +95,7 @@ function startTrace(spanNameSuffix, config, cb) {
96
95
  if (config.transactionTag) {
97
96
  span.setAttribute('transaction.tag', config.transactionTag);
98
97
  }
99
- const allowExtendedTracing = optedInPII || ((_a = config.opts) === null || _a === void 0 ? void 0 : _a.enableExtendedTracing);
98
+ const allowExtendedTracing = optedInPII || config.opts?.enableExtendedTracing;
100
99
  if (config.sql && allowExtendedTracing) {
101
100
  const sql = config.sql;
102
101
  if (typeof sql === 'string') {
@@ -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[];