@google-cloud/spanner 8.13.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +1 -16
  2. package/build/src/batch-transaction.js +15 -12
  3. package/build/src/codec.d.ts +18 -30
  4. package/build/src/codec.js +197 -79
  5. package/build/src/common.d.ts +14 -0
  6. package/build/src/common.js +28 -3
  7. package/build/src/database.d.ts +31 -41
  8. package/build/src/database.js +147 -315
  9. package/build/src/helper.d.ts +12 -0
  10. package/build/src/helper.js +44 -0
  11. package/build/src/index.d.ts +24 -8
  12. package/build/src/index.js +303 -147
  13. package/build/src/instance.d.ts +15 -2
  14. package/build/src/instance.js +11 -2
  15. package/build/src/instrument.d.ts +12 -1
  16. package/build/src/instrument.js +13 -0
  17. package/build/src/metrics/constants.d.ts +13 -6
  18. package/build/src/metrics/constants.js +24 -14
  19. package/build/src/metrics/external-types.d.ts +14 -0
  20. package/build/src/metrics/interceptor.js +39 -44
  21. package/build/src/metrics/metrics-tracer-factory.d.ts +25 -14
  22. package/build/src/metrics/metrics-tracer-factory.js +119 -78
  23. package/build/src/metrics/metrics-tracer.d.ts +19 -6
  24. package/build/src/metrics/metrics-tracer.js +147 -55
  25. package/build/src/metrics/spanner-metrics-exporter.js +4 -0
  26. package/build/src/metrics/transform.d.ts +3 -4
  27. package/build/src/metrics/transform.js +16 -10
  28. package/build/src/multiplexed-session.d.ts +26 -2
  29. package/build/src/multiplexed-session.js +39 -11
  30. package/build/src/partial-result-stream.d.ts +26 -33
  31. package/build/src/partial-result-stream.js +263 -283
  32. package/build/src/request-stream-coordinator.d.ts +88 -0
  33. package/build/src/request-stream-coordinator.js +229 -0
  34. package/build/src/request_id_header.d.ts +6 -4
  35. package/build/src/request_id_header.js +24 -24
  36. package/build/src/session-factory.d.ts +62 -60
  37. package/build/src/session-factory.js +46 -86
  38. package/build/src/session-pool.d.ts +97 -227
  39. package/build/src/session-pool.js +74 -547
  40. package/build/src/session.js +1 -1
  41. package/build/src/transaction-runner.js +1 -12
  42. package/build/src/transaction.d.ts +21 -5
  43. package/build/src/transaction.js +107 -136
  44. package/package.json +28 -37
@@ -16,6 +16,7 @@
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.Interval = exports.SpannerDate = exports.PGNumeric = exports.Numeric = exports.Struct = exports.Int = exports.Float = exports.Float32 = exports.protos = exports.v1 = exports.MutationSet = exports.MutationGroup = exports.Transaction = exports.Snapshot = exports.PartitionedDml = exports.Table = exports.SessionPool = exports.Session = exports.Backup = exports.Database = exports.InstanceConfig = exports.Instance = exports.Spanner = void 0;
19
+ /* eslint-disable import/namespace, promise/catch-or-return, promise/always-return */
19
20
  const service_1 = require("./common-grpc/service");
20
21
  const precise_date_1 = require("@google-cloud/precise-date");
21
22
  const helper_1 = require("./helper");
@@ -72,6 +73,7 @@ const sdk_metrics_1 = require("@opentelemetry/sdk-metrics");
72
73
  const interceptor_1 = require("./metrics/interceptor");
73
74
  const spanner_metrics_exporter_1 = require("./metrics/spanner-metrics-exporter");
74
75
  const metrics_tracer_factory_1 = require("./metrics/metrics-tracer-factory");
76
+ const request_stream_coordinator_1 = require("./request-stream-coordinator");
75
77
  // eslint-disable-next-line @typescript-eslint/no-var-requires
76
78
  const gcpApiConfig = require('./spanner_grpc_config.json');
77
79
  /**
@@ -166,8 +168,8 @@ class Spanner extends service_1.GrpcService {
166
168
  _universeDomain;
167
169
  _isInSecureCredentials;
168
170
  _metricsEnabled = false;
169
- static _isAFEServerTimingEnabled;
170
171
  _nthClientId;
172
+ _pendingProjectIdCallbacks;
171
173
  /**
172
174
  * Placeholder used to auto populate a column with the commit timestamp.
173
175
  * This can only be used for timestamp columns that have set the option
@@ -182,23 +184,17 @@ class Spanner extends service_1.GrpcService {
182
184
  * Returns whether AFE (Application Frontend Extension) server timing is enabled.
183
185
  *
184
186
  * This method checks the value of the environment variable
185
- * `SPANNER_DISABLE_AFE_SERVER_TIMING`. If the variable is explicitly set to the
186
- * string `'true'`, then AFE server timing is considered disabled, and this method
187
- * returns `false`. For all other values (including if the variable is unset),
188
- * the method returns `true`.
187
+ * `SPANNER_DISABLE_AFE_SERVER_TIMING`. If the variable is explicitly set to
188
+ * the string `'true'` (case-insensitive), then AFE server timing is
189
+ * considered disabled, and this method returns `false`. For all other
190
+ * values (including if the variable is unset), the method returns `true`.
189
191
  *
190
192
  * @returns {boolean} `true` if AFE server timing is enabled; otherwise, `false`.
191
193
  */
192
- static isAFEServerTimingEnabled = () => {
193
- if (this._isAFEServerTimingEnabled === undefined) {
194
- this._isAFEServerTimingEnabled =
195
- process.env['SPANNER_DISABLE_AFE_SERVER_TIMING'] !== 'true';
196
- }
197
- return this._isAFEServerTimingEnabled;
198
- };
194
+ static isAFEServerTimingEnabled = common_1.isAFEServerTimingEnabled;
199
195
  /** Resets the cached value (use in tests if env changes). */
200
196
  static _resetAFEServerTimingForTest() {
201
- this._isAFEServerTimingEnabled = undefined;
197
+ (0, common_1.resetAFEServerTimingForTest)();
202
198
  }
203
199
  /**
204
200
  * Gets the configured Spanner emulator host from an environment variable.
@@ -246,6 +242,8 @@ class Spanner extends service_1.GrpcService {
246
242
  scopes,
247
243
  // Add grpc keep alive setting
248
244
  'grpc.keepalive_time_ms': 120000,
245
+ // Disable Channelz by default to reduce per-RPC tracking and allocation overhead
246
+ 'grpc.enable_channelz': 0,
249
247
  // Enable grpc-gcp support
250
248
  'grpc.callInvocationTransformer': grpcGcp.gcpCallInvocationTransformer,
251
249
  'grpc.channelFactoryOverride': grpcGcp.gcpChannelFactoryOverride,
@@ -334,7 +332,7 @@ class Spanner extends service_1.GrpcService {
334
332
  getInstanceAdminClient() {
335
333
  const clientName = 'InstanceAdminClient';
336
334
  if (!this.clients_.has(clientName)) {
337
- this.clients_.set(clientName, new v1[clientName](this.options));
335
+ this.clients_.set(clientName, new v1.InstanceAdminClient(this.options));
338
336
  }
339
337
  return this.clients_.get(clientName);
340
338
  }
@@ -354,7 +352,7 @@ class Spanner extends service_1.GrpcService {
354
352
  getDatabaseAdminClient() {
355
353
  const clientName = 'DatabaseAdminClient';
356
354
  if (!this.clients_.has(clientName)) {
357
- this.clients_.set(clientName, new v1[clientName](this.options));
355
+ this.clients_.set(clientName, new v1.DatabaseAdminClient(this.options));
358
356
  }
359
357
  return this.clients_.get(clientName);
360
358
  }
@@ -391,11 +389,12 @@ class Spanner extends service_1.GrpcService {
391
389
  const res = performTeardown();
392
390
  if (callback) {
393
391
  // process.nextTick prevents Unhandled Promise Rejections if callback throws
394
- res.then(() => process.nextTick(() => callback(null)), err => process.nextTick(() => callback(err)));
395
- }
396
- else {
397
- return res;
392
+ res
393
+ .then(() => process.nextTick(() => callback(null)))
394
+ .catch(err => process.nextTick(() => callback(err)));
395
+ return;
398
396
  }
397
+ return res;
399
398
  }
400
399
  createInstance(name, config, callback) {
401
400
  if (!name) {
@@ -817,28 +816,39 @@ class Spanner extends service_1.GrpcService {
817
816
  !metricsExplicitlyDisabled && !this._isInSecureCredentials;
818
817
  metrics_tracer_factory_1.MetricsTracerFactory.enabled = this._metricsEnabled;
819
818
  if (this._metricsEnabled) {
820
- try {
821
- this.auth.getProjectId((err, projectId) => {
822
- if (err || !projectId) {
823
- console.error('Unable to get Project Id for client side metrics, will skip exporting client' +
824
- ' side metrics' +
825
- err);
826
- return;
827
- }
828
- this.projectId_ = projectId;
829
- const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(projectId);
830
- const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
831
- exporter: new spanner_metrics_exporter_1.CloudMonitoringMetricsExporter({ auth: this.auth }, projectId),
832
- exportIntervalMillis: 60000,
819
+ const initializeMetrics = (projectId) => {
820
+ this.projectId_ = projectId;
821
+ const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(projectId);
822
+ if (factory && !factory.hasMetricReaders()) {
823
+ api_1.context.with(api_1.ROOT_CONTEXT, () => {
824
+ const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
825
+ exporter: new spanner_metrics_exporter_1.CloudMonitoringMetricsExporter({ auth: this.auth }, projectId),
826
+ exportIntervalMillis: 60000,
827
+ });
828
+ factory.getMeterProvider([periodicReader]);
833
829
  });
834
- // Retrieve the MeterProvider to trigger construction
835
- factory.getMeterProvider([periodicReader]);
836
- });
830
+ }
831
+ };
832
+ if (this.projectId_ && this.projectId_ !== '{{projectId}}') {
833
+ initializeMetrics(this.projectId_);
837
834
  }
838
- catch (err) {
839
- console.error('Unable to configure client side metrics, will skip exporting client' +
840
- ' side metrics' +
841
- err);
835
+ else {
836
+ try {
837
+ this.auth.getProjectId((err, projectId) => {
838
+ if (err || !projectId) {
839
+ console.error('Unable to get Project Id for client side metrics, will skip exporting client' +
840
+ ' side metrics' +
841
+ err);
842
+ return;
843
+ }
844
+ initializeMetrics(projectId);
845
+ });
846
+ }
847
+ catch (err) {
848
+ console.error('Unable to configure client side metrics, will skip exporting client' +
849
+ ' side metrics' +
850
+ err);
851
+ }
842
852
  }
843
853
  }
844
854
  }
@@ -851,40 +861,100 @@ class Spanner extends service_1.GrpcService {
851
861
  * @param {object} config Request config
852
862
  * @param {function} callback Callback function
853
863
  */
854
- prepareGapicRequest_(config, callback) {
855
- this.auth.getProjectId((err, projectId) => {
856
- if (err) {
857
- callback(err);
864
+ prepareGapicRequest_(config,
865
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
866
+ callback) {
867
+ if (this.projectId && this.projectIdReplaced_) {
868
+ this._prepareGapicRequestWithProjectId(config, this.projectId, callback);
869
+ return;
870
+ }
871
+ if (this._pendingProjectIdCallbacks) {
872
+ this._pendingProjectIdCallbacks.push((error, projectId) => {
873
+ if (error) {
874
+ callback(error);
875
+ return;
876
+ }
877
+ this._prepareGapicRequestWithProjectId(config, projectId, callback);
878
+ });
879
+ return;
880
+ }
881
+ this._pendingProjectIdCallbacks = [];
882
+ this.auth.getProjectId((error, projectId) => {
883
+ const pendingCallbacks = this._pendingProjectIdCallbacks || [];
884
+ this._pendingProjectIdCallbacks = undefined;
885
+ if (error) {
886
+ try {
887
+ callback(error);
888
+ }
889
+ finally {
890
+ for (const pendingCallback of pendingCallbacks) {
891
+ try {
892
+ pendingCallback(error);
893
+ }
894
+ catch {
895
+ // Prevent one failing user callback from stranding subsequent pending callers.
896
+ }
897
+ }
898
+ }
858
899
  return;
859
900
  }
860
- const clientName = config.client;
861
901
  try {
862
- if (!this.clients_.has(clientName)) {
863
- this.clients_.set(clientName, new v1[clientName](this.options));
902
+ this._prepareGapicRequestWithProjectId(config, projectId, callback);
903
+ }
904
+ finally {
905
+ for (const pendingCallback of pendingCallbacks) {
906
+ try {
907
+ pendingCallback(null, projectId);
908
+ }
909
+ catch {
910
+ // Prevent one failing user callback from stranding subsequent pending callers.
911
+ }
864
912
  }
865
913
  }
866
- catch (err) {
867
- callback(err, null);
914
+ });
915
+ }
916
+ _prepareGapicRequestWithProjectId(config, projectId,
917
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
918
+ callback) {
919
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
920
+ let wrappedRequestFn;
921
+ try {
922
+ const clientName = config.client;
923
+ if (!this.clients_.has(clientName)) {
924
+ this.clients_.set(clientName, new v1[clientName](this.options));
868
925
  }
869
926
  const gaxClient = this.clients_.get(clientName);
870
- let reqOpts = extend(true, {}, config.reqOpts);
871
- reqOpts = (0, helper_1.replaceProjectIdToken)(reqOpts, projectId);
872
- // It would have been preferable to replace the projectId already in the
873
- // constructor of Spanner, but that is not possible as auth.getProjectId
874
- // is an async method. This is therefore the first place where we have
875
- // access to the value that should be used instead of the placeholder.
927
+ let reqOpts = config.reqOpts;
928
+ if (!this.projectIdReplaced_ || (0, helper_1.hasProjectIdToken)(reqOpts)) {
929
+ reqOpts = extend(true, {}, config.reqOpts);
930
+ reqOpts = (0, helper_1.replaceProjectIdToken)(reqOpts, projectId);
931
+ }
876
932
  if (!this.projectIdReplaced_) {
877
933
  this.projectId = (0, helper_1.replaceProjectIdToken)(this.projectId, projectId);
878
934
  this.projectFormattedName_ = (0, helper_1.replaceProjectIdToken)(this.projectFormattedName_, projectId);
935
+ if (this.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER]?.includes('{{projectId}}')) {
936
+ this.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER] = (0, helper_1.replaceProjectIdToken)(this.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER], projectId);
937
+ }
879
938
  this.instances_.forEach(instance => {
880
939
  instance.formattedName_ = (0, helper_1.replaceProjectIdToken)(instance.formattedName_, projectId);
940
+ if (instance.commonHeaders_?.[common_1.CLOUD_RESOURCE_HEADER]?.includes('{{projectId}}')) {
941
+ instance.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER] =
942
+ (0, helper_1.replaceProjectIdToken)(instance.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER], projectId);
943
+ }
881
944
  instance.databases_.forEach(database => {
882
945
  database.formattedName_ = (0, helper_1.replaceProjectIdToken)(database.formattedName_, projectId);
946
+ if (database.commonHeaders_?.[common_1.CLOUD_RESOURCE_HEADER]?.includes('{{projectId}}')) {
947
+ database.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER] =
948
+ (0, helper_1.replaceProjectIdToken)(database.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER], projectId);
949
+ }
883
950
  });
884
951
  });
885
952
  this.projectIdReplaced_ = true;
886
953
  }
887
- config.headers[common_1.CLOUD_RESOURCE_HEADER] = (0, helper_1.replaceProjectIdToken)(config.headers[common_1.CLOUD_RESOURCE_HEADER], projectId);
954
+ config.headers = extend(true, {}, config.headers);
955
+ if (config.headers[common_1.CLOUD_RESOURCE_HEADER]?.includes('{{projectId}}')) {
956
+ config.headers[common_1.CLOUD_RESOURCE_HEADER] = (0, helper_1.replaceProjectIdToken)(config.headers[common_1.CLOUD_RESOURCE_HEADER], projectId);
957
+ }
888
958
  if ((0, instrument_1.isTracingEnabled)(this._observabilityOptions)) {
889
959
  // Do context propagation
890
960
  api_1.propagation.inject(api_1.context.active(), config.headers, {
@@ -895,63 +965,135 @@ class Spanner extends service_1.GrpcService {
895
965
  // Attach the x-goog-spanner-request-id to the currently active span.
896
966
  (0, request_id_header_1.attributeXGoogSpannerRequestIdToActiveSpan)(config);
897
967
  }
898
- const interceptors = [];
899
- if (this._metricsEnabled) {
900
- interceptors.push(interceptor_1.MetricInterceptor);
968
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
969
+ const customInterceptors = config.gaxOpts?.otherArgs?.options?.interceptors ?? [];
970
+ const shouldIntercept = this._metricsEnabled &&
971
+ (config.client === 'SpannerClient' || config.metricsTracer);
972
+ const interceptors = shouldIntercept
973
+ ? [...customInterceptors, interceptor_1.MetricInterceptor]
974
+ : customInterceptors;
975
+ const headers = Object.assign({}, config.gaxOpts?.otherArgs?.headers, config.headers);
976
+ const options = Object.assign({}, config.gaxOpts?.otherArgs?.options, {
977
+ interceptors,
978
+ metricsTracer: config.metricsTracer,
979
+ });
980
+ // Deep clone caller-owned properties to prevent downstream mutations
981
+ // (e.g. gax mutating `retry.backoffSettings`), while attaching our
982
+ // freshly merged otherArgs without redundantly deep-cloning them.
983
+ let gaxOpts;
984
+ if (config.gaxOpts) {
985
+ const { otherArgs: callerOtherArgs, ...restGaxOpts } = config.gaxOpts;
986
+ gaxOpts = extend(true, {}, restGaxOpts);
987
+ gaxOpts.otherArgs = Object.assign({}, callerOtherArgs, {
988
+ headers,
989
+ options,
990
+ });
901
991
  }
902
- const requestFn = gaxClient[config.method].bind(gaxClient, reqOpts,
903
- // Add headers to `gaxOpts`
904
- extend(true, {}, config.gaxOpts, {
905
- otherArgs: {
906
- headers: config.headers,
907
- options: {
908
- interceptors: interceptors,
909
- },
910
- },
911
- }));
912
- // Wrap requestFn to inject the spanner request id into every returned error.
913
- const wrappedRequestFn = (...args) => {
914
- const hasCallback = args &&
915
- args.length > 0 &&
916
- typeof args[args.length - 1] === 'function';
917
- switch (hasCallback) {
918
- case true: {
919
- const cb = args[args.length - 1];
920
- const priorArgs = args.slice(0, args.length - 1);
921
- requestFn(...priorArgs, (...results) => {
922
- if (results && results.length > 0) {
923
- const err = results[0];
924
- (0, request_id_header_1.injectRequestIDIntoError)(config, err);
992
+ else {
993
+ gaxOpts = { otherArgs: { headers, options } };
994
+ }
995
+ const requestFn = gaxClient[config.method].bind(gaxClient, reqOpts, gaxOpts);
996
+ // Extract a lightweight config reference containing only headers so error
997
+ // enrichment is decoupled from the caller's mutable config object.
998
+ const errorConfig = { headers: config?.headers };
999
+ // Wrap requestFn to inject the Spanner request ID (x-goog-spanner-request-id)
1000
+ // into any error returned via callback, rejected promise, stream event, or
1001
+ // synchronous exception.
1002
+ //
1003
+ // Because reqOpts and gaxOpts are already pre-bound to requestFn, wrappedRequestFn
1004
+ // receives at most one argument: an optional callback.
1005
+ wrappedRequestFn = (callback) => {
1006
+ // Callback mode: invoke requestFn with an intercepted callback to enrich
1007
+ // the error parameter before delegating to the caller's callback.
1008
+ if (typeof callback === 'function') {
1009
+ try {
1010
+ requestFn((...results) => {
1011
+ if (results[0]) {
1012
+ (0, request_id_header_1.injectRequestIDIntoError)(errorConfig, results[0]);
925
1013
  }
926
- cb(...results);
1014
+ callback(...results);
927
1015
  });
928
- return;
929
1016
  }
930
- case false: {
931
- const res = requestFn(...args);
932
- const stream = res;
933
- if (stream) {
934
- stream.on('error', err => {
935
- (0, request_id_header_1.injectRequestIDIntoError)(config, err);
936
- });
937
- }
938
- const originallyPromise = res instanceof Promise;
939
- if (!originallyPromise) {
940
- return res;
941
- }
942
- return new Promise((resolve, reject) => {
943
- requestFn(...args)
944
- .then(resolve)
945
- .catch(err => {
946
- (0, request_id_header_1.injectRequestIDIntoError)(config, err);
947
- reject(err);
948
- });
949
- });
1017
+ catch (err) {
1018
+ (0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
1019
+ throw err;
950
1020
  }
1021
+ return;
1022
+ }
1023
+ // Non-callback mode: invoke requestFn() for Promise or Stream callers.
1024
+ let res;
1025
+ try {
1026
+ res = requestFn();
951
1027
  }
1028
+ catch (err) {
1029
+ (0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
1030
+ throw err;
1031
+ }
1032
+ // Handle Promise / Thenable return values (e.g. unary requests).
1033
+ // Attach a rejection handler to inject the request ID into rejected errors.
1034
+ // If the promise is cancellable (e.g. google-gax CancellablePromise), preserve
1035
+ // its .cancel() method so callers can cancel the underlying operation.
1036
+ if (res && typeof res.then === 'function') {
1037
+ const chained = res.then(null, err => {
1038
+ (0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
1039
+ throw err;
1040
+ });
1041
+ if (typeof res.cancel === 'function') {
1042
+ chained.cancel = res.cancel.bind(res);
1043
+ }
1044
+ return chained;
1045
+ }
1046
+ // Handle Stream return values (e.g. streaming reads or queries).
1047
+ // Listen for 'error' events to enrich the emitted error with the request ID.
1048
+ const stream = res;
1049
+ if (stream && typeof stream.on === 'function') {
1050
+ stream.on('error', err => {
1051
+ (0, request_id_header_1.injectRequestIDIntoError)(errorConfig, err);
1052
+ });
1053
+ }
1054
+ return res;
952
1055
  };
953
- callback(null, wrappedRequestFn);
954
- });
1056
+ }
1057
+ catch (error) {
1058
+ callback(error, null);
1059
+ return;
1060
+ }
1061
+ callback(null, wrappedRequestFn);
1062
+ }
1063
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1064
+ _getResourceName(config) {
1065
+ const reqOpts = config?.reqOpts;
1066
+ if (reqOpts) {
1067
+ if (typeof reqOpts.database === 'string') {
1068
+ return reqOpts.database;
1069
+ }
1070
+ if (typeof reqOpts.session === 'string') {
1071
+ return reqOpts.session;
1072
+ }
1073
+ if (typeof reqOpts.name === 'string') {
1074
+ return reqOpts.name;
1075
+ }
1076
+ }
1077
+ const resourceHeader = config?.headers?.[common_1.CLOUD_RESOURCE_HEADER];
1078
+ if (typeof resourceHeader === 'string') {
1079
+ return resourceHeader;
1080
+ }
1081
+ return '';
1082
+ }
1083
+ _initMetricsTracer(
1084
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1085
+ config) {
1086
+ let metricsTracer = null;
1087
+ if (this._metricsEnabled &&
1088
+ config.client === 'SpannerClient' &&
1089
+ this.projectId_ &&
1090
+ this.projectId_ !== '{{projectId}}') {
1091
+ metricsTracer =
1092
+ metrics_tracer_factory_1.MetricsTracerFactory?.getInstance(this.projectId_)?.createMetricsTracer(config.method, this._getResourceName(config), config.headers?.['x-goog-spanner-request-id']) ?? null;
1093
+ }
1094
+ metricsTracer?.recordOperationStart();
1095
+ config.metricsTracer = metricsTracer ?? undefined;
1096
+ return metricsTracer;
955
1097
  }
956
1098
  /**
957
1099
  * Funnel all API requests through this method to be sure we have a project
@@ -966,14 +1108,7 @@ class Spanner extends service_1.GrpcService {
966
1108
  */
967
1109
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
968
1110
  request(config, callback) {
969
- let metricsTracer = null;
970
- if (this._metricsEnabled &&
971
- config.client === 'SpannerClient' &&
972
- this.projectId_) {
973
- metricsTracer =
974
- metrics_tracer_factory_1.MetricsTracerFactory?.getInstance(this.projectId_)?.createMetricsTracer(config.method, config.reqOpts.database ?? config.reqOpts.session, config.headers['x-goog-spanner-request-id']) ?? null;
975
- }
976
- metricsTracer?.recordOperationStart();
1111
+ const metricsTracer = this._initMetricsTracer(config);
977
1112
  if (typeof callback === 'function') {
978
1113
  this.prepareGapicRequest_(config, (err, requestFn) => {
979
1114
  if (err) {
@@ -981,11 +1116,38 @@ class Spanner extends service_1.GrpcService {
981
1116
  metricsTracer?.recordOperationCompletion();
982
1117
  }
983
1118
  else {
1119
+ let callbackInvoked = false;
1120
+ let callbackThrew = false;
1121
+ let callbackError;
984
1122
  const wrappedCallback = (...args) => {
1123
+ if (callbackInvoked) {
1124
+ return;
1125
+ }
1126
+ callbackInvoked = true;
985
1127
  metricsTracer?.recordOperationCompletion();
986
- callback(...args);
1128
+ try {
1129
+ callback(...args);
1130
+ }
1131
+ catch (error) {
1132
+ callbackThrew = true;
1133
+ callbackError = error;
1134
+ throw error;
1135
+ }
987
1136
  };
988
- requestFn(wrappedCallback);
1137
+ try {
1138
+ requestFn(wrappedCallback);
1139
+ }
1140
+ catch (error) {
1141
+ if (callbackThrew) {
1142
+ throw callbackError;
1143
+ }
1144
+ if (callbackInvoked) {
1145
+ return;
1146
+ }
1147
+ callbackInvoked = true;
1148
+ metricsTracer?.recordOperationCompletion();
1149
+ callback(error);
1150
+ }
989
1151
  }
990
1152
  });
991
1153
  }
@@ -997,21 +1159,29 @@ class Spanner extends service_1.GrpcService {
997
1159
  reject(err);
998
1160
  }
999
1161
  else {
1000
- const result = requestFn();
1001
- if (result && typeof result.then === 'function') {
1002
- result
1003
- .then(val => {
1004
- metricsTracer?.recordOperationCompletion();
1005
- resolve(val);
1006
- })
1007
- .catch(error => {
1162
+ try {
1163
+ const result = requestFn();
1164
+ if (result && typeof result.then === 'function') {
1165
+ result
1166
+ .then(val => {
1167
+ metricsTracer?.recordOperationCompletion();
1168
+ resolve(val);
1169
+ return val;
1170
+ })
1171
+ .catch(error => {
1172
+ metricsTracer?.recordOperationCompletion();
1173
+ reject(error);
1174
+ return null;
1175
+ });
1176
+ }
1177
+ else {
1008
1178
  metricsTracer?.recordOperationCompletion();
1009
- reject(error);
1010
- });
1179
+ resolve(result);
1180
+ }
1011
1181
  }
1012
- else {
1182
+ catch (error) {
1013
1183
  metricsTracer?.recordOperationCompletion();
1014
- resolve(result);
1184
+ reject(error);
1015
1185
  }
1016
1186
  }
1017
1187
  });
@@ -1031,34 +1201,20 @@ class Spanner extends service_1.GrpcService {
1031
1201
  */
1032
1202
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1033
1203
  requestStream(config) {
1034
- let metricsTracer = null;
1035
- if (this._metricsEnabled &&
1036
- config.client === 'SpannerClient' &&
1037
- this.projectId_) {
1038
- metricsTracer =
1039
- metrics_tracer_factory_1.MetricsTracerFactory?.getInstance(this.projectId_)?.createMetricsTracer(config.method, config.reqOpts.session ?? config.reqOpts.database, config.headers['x-goog-spanner-request-id']) ?? null;
1040
- }
1041
- metricsTracer?.recordOperationStart();
1204
+ const metricsTracer = this._initMetricsTracer(config);
1042
1205
  const stream = streamEvents(through.obj());
1206
+ const coordinator = new request_stream_coordinator_1.RequestStreamCoordinator(stream, metricsTracer);
1207
+ coordinator.setup();
1043
1208
  stream.once('reading', () => {
1209
+ coordinator.startRequest();
1044
1210
  this.prepareGapicRequest_(config, (err, requestFn) => {
1045
1211
  if (err) {
1046
- stream.destroy(err);
1212
+ coordinator.handleRequestError(err);
1047
1213
  return;
1048
1214
  }
1049
- requestFn()
1050
- .on('error', err => {
1051
- stream.destroy(err);
1052
- })
1053
- .pipe(stream);
1215
+ coordinator.attachRequestFn(requestFn);
1054
1216
  });
1055
1217
  });
1056
- stream.on('finish', () => {
1057
- stream.destroy();
1058
- });
1059
- stream.on('close', () => {
1060
- metricsTracer?.recordOperationCompletion();
1061
- });
1062
1218
  return stream;
1063
1219
  }
1064
1220
  /**
@@ -47,7 +47,15 @@ export type GetBackupsResponse = PagedResponse<Backup, databaseAdmin.spanner.adm
47
47
  export type GetBackupOperationsResponse = PagedResponse<IOperation, databaseAdmin.spanner.admin.database.v1.IListBackupOperationsResponse>;
48
48
  export type GetDatabaseOperationsResponse = PagedResponse<IOperation, databaseAdmin.spanner.admin.database.v1.IListDatabaseOperationsResponse>;
49
49
  export interface CreateDatabaseOptions extends databaseAdmin.spanner.admin.database.v1.ICreateDatabaseRequest {
50
+ /**
51
+ * @deprecated Session pool options are deprecated and will be removed in a future release.
52
+ * Multiplexed sessions are now used for all operations by default.
53
+ */
50
54
  poolOptions?: SessionPoolOptions;
55
+ /**
56
+ * @deprecated Custom session pool constructors are deprecated and will be removed in a future release.
57
+ * Multiplexed sessions are now used for all operations by default.
58
+ */
51
59
  poolCtor?: SessionPool;
52
60
  schema?: string | string[];
53
61
  gaxOptions?: CallOptions;
@@ -331,8 +339,8 @@ declare class Instance extends common.GrpcServiceObject {
331
339
  * Config for the new database.
332
340
  *
333
341
  * @typedef {object} CreateDatabaseRequest
334
- * @property {SessionPoolOptions} [poolOptions]
335
- * @property {SessionPoolCtor} [poolCtor]
342
+ * @property {SessionPoolOptions} [poolOptions] **Deprecated**. Session pool options are deprecated and will be removed in a future release.
343
+ * @property {SessionPoolCtor} [poolCtor] **Deprecated**. Custom session pool constructors are deprecated and will be removed in a future release.
336
344
  */
337
345
  /**
338
346
  * @typedef {array} CreateDatabaseResponse
@@ -424,10 +432,15 @@ declare class Instance extends common.GrpcServiceObject {
424
432
  * @param {string} name The name of the instance.
425
433
  * @param {SessionPoolOptions|SessionPoolCtor} [poolOptions] Session pool
426
434
  * configuration options.
435
+ * **Deprecated**. Session pool options is deprecated and will be removed in a future release.
436
+ * Multiplexed sessions are now used for all operations by default, eliminating
437
+ * the need for session pooling.
427
438
  * @param {spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions} [queryOptions]
428
439
  * Default query options to use with the database. These options will be
429
440
  * overridden by any query options set in environment variables or that
430
441
  * are specified on a per-query basis.
442
+ * @param {string} [databaseRole] The database role to use for sessions on
443
+ * the database.
431
444
  * @return {Database} A Database object.
432
445
  *
433
446
  * @example