@google-cloud/spanner 9.0.0 → 9.1.1

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 +3 -16
  2. package/build/src/backup.js.map +1 -0
  3. package/build/src/batch-transaction.js +15 -12
  4. package/build/src/batch-transaction.js.map +1 -0
  5. package/build/src/codec.d.ts +6 -0
  6. package/build/src/codec.js +99 -34
  7. package/build/src/codec.js.map +1 -0
  8. package/build/src/common-grpc/service-object.js.map +1 -0
  9. package/build/src/common-grpc/service.js.map +1 -0
  10. package/build/src/common.d.ts +14 -0
  11. package/build/src/common.js +27 -1
  12. package/build/src/common.js.map +1 -0
  13. package/build/src/database.d.ts +31 -41
  14. package/build/src/database.js +122 -313
  15. package/build/src/database.js.map +1 -0
  16. package/build/src/helper.d.ts +12 -0
  17. package/build/src/helper.js +44 -0
  18. package/build/src/helper.js.map +1 -0
  19. package/build/src/index.d.ts +33 -8
  20. package/build/src/index.js +338 -134
  21. package/build/src/index.js.map +1 -0
  22. package/build/src/instance-config.js.map +1 -0
  23. package/build/src/instance.d.ts +15 -2
  24. package/build/src/instance.js +11 -2
  25. package/build/src/instance.js.map +1 -0
  26. package/build/src/instrument.d.ts +12 -1
  27. package/build/src/instrument.js +13 -0
  28. package/build/src/instrument.js.map +1 -0
  29. package/build/src/metrics/constants.d.ts +6 -0
  30. package/build/src/metrics/constants.js +6 -1
  31. package/build/src/metrics/constants.js.map +1 -0
  32. package/build/src/metrics/external-types.d.ts +9 -1
  33. package/build/src/metrics/external-types.js.map +1 -0
  34. package/build/src/metrics/interceptor.js +32 -28
  35. package/build/src/metrics/interceptor.js.map +1 -0
  36. package/build/src/metrics/metrics-tracer-factory.d.ts +24 -18
  37. package/build/src/metrics/metrics-tracer-factory.js +94 -77
  38. package/build/src/metrics/metrics-tracer-factory.js.map +1 -0
  39. package/build/src/metrics/metrics-tracer.d.ts +19 -6
  40. package/build/src/metrics/metrics-tracer.js +147 -55
  41. package/build/src/metrics/metrics-tracer.js.map +1 -0
  42. package/build/src/metrics/spanner-metrics-exporter.d.ts +49 -1
  43. package/build/src/metrics/spanner-metrics-exporter.js +207 -4
  44. package/build/src/metrics/spanner-metrics-exporter.js.map +1 -0
  45. package/build/src/metrics/transform.d.ts +2 -2
  46. package/build/src/metrics/transform.js +7 -7
  47. package/build/src/metrics/transform.js.map +1 -0
  48. package/build/src/multiplexed-session.d.ts +13 -2
  49. package/build/src/multiplexed-session.js +20 -4
  50. package/build/src/multiplexed-session.js.map +1 -0
  51. package/build/src/partial-result-stream.d.ts +26 -33
  52. package/build/src/partial-result-stream.js +263 -283
  53. package/build/src/partial-result-stream.js.map +1 -0
  54. package/build/src/protos.js.map +1 -0
  55. package/build/src/request-stream-coordinator.d.ts +88 -0
  56. package/build/src/request-stream-coordinator.js +229 -0
  57. package/build/src/request-stream-coordinator.js.map +1 -0
  58. package/build/src/request_id_header.d.ts +6 -4
  59. package/build/src/request_id_header.js +24 -24
  60. package/build/src/request_id_header.js.map +1 -0
  61. package/build/src/session-factory.d.ts +52 -63
  62. package/build/src/session-factory.js +41 -92
  63. package/build/src/session-factory.js.map +1 -0
  64. package/build/src/session-pool.d.ts +97 -227
  65. package/build/src/session-pool.js +74 -547
  66. package/build/src/session-pool.js.map +1 -0
  67. package/build/src/session.js +1 -1
  68. package/build/src/session.js.map +1 -0
  69. package/build/src/table.js.map +1 -0
  70. package/build/src/transaction-runner.js +1 -12
  71. package/build/src/transaction-runner.js.map +1 -0
  72. package/build/src/transaction.d.ts +5 -5
  73. package/build/src/transaction.js +72 -112
  74. package/build/src/transaction.js.map +1 -0
  75. package/build/src/v1/index.js.map +1 -0
  76. package/package.json +25 -27
@@ -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
  /**
@@ -95,17 +97,24 @@ function getUniverseDomain(options) {
95
97
  const universeDomainEnvVar = typeof process === 'object' && typeof process.env === 'object'
96
98
  ? process.env['GOOGLE_CLOUD_UNIVERSE_DOMAIN']
97
99
  : undefined;
98
- const universeDomain = options?.universeDomain ??
100
+ const rawUniverseDomain = options?.universeDomain ??
99
101
  options?.universe_domain ??
100
102
  universeDomainEnvVar ??
101
103
  'googleapis.com';
102
- // if the options.universe_domain/GOOGLE_CLOUD_UNIVERSE_DOMAIN env variable is set,
103
- // set its value to the Spanner `universeDomain` options
104
- // to match it with the universe from Auth Client
105
- if (!options?.universeDomain &&
106
- (options?.universe_domain || process.env.GOOGLE_CLOUD_UNIVERSE_DOMAIN)) {
104
+ const universeDomain = typeof rawUniverseDomain === 'string'
105
+ ? rawUniverseDomain.trim()
106
+ : rawUniverseDomain;
107
+ // Sync the trimmed universe domain onto options whenever configured explicitly
108
+ // (via universeDomain, universe_domain, or GOOGLE_CLOUD_UNIVERSE_DOMAIN) so
109
+ // Spanner, GAX clients, and GoogleAuth observe the same normalized value.
110
+ if (options?.universeDomain !== undefined ||
111
+ options?.universe_domain !== undefined ||
112
+ universeDomainEnvVar) {
107
113
  options.universeDomain = universeDomain;
108
114
  }
115
+ if (options?.universe_domain !== undefined) {
116
+ options.universe_domain = universeDomain;
117
+ }
109
118
  return universeDomain;
110
119
  }
111
120
  /**
@@ -164,10 +173,12 @@ class Spanner extends service_1.GrpcService {
164
173
  _observabilityOptions;
165
174
  sessionLabels;
166
175
  _universeDomain;
176
+ _metricsUniverseDomain;
177
+ _monitoringTargetKey;
167
178
  _isInSecureCredentials;
168
179
  _metricsEnabled = false;
169
- static _isAFEServerTimingEnabled;
170
180
  _nthClientId;
181
+ _pendingProjectIdCallbacks;
171
182
  /**
172
183
  * Placeholder used to auto populate a column with the commit timestamp.
173
184
  * This can only be used for timestamp columns that have set the option
@@ -182,23 +193,17 @@ class Spanner extends service_1.GrpcService {
182
193
  * Returns whether AFE (Application Frontend Extension) server timing is enabled.
183
194
  *
184
195
  * 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`.
196
+ * `SPANNER_DISABLE_AFE_SERVER_TIMING`. If the variable is explicitly set to
197
+ * the string `'true'` (case-insensitive), then AFE server timing is
198
+ * considered disabled, and this method returns `false`. For all other
199
+ * values (including if the variable is unset), the method returns `true`.
189
200
  *
190
201
  * @returns {boolean} `true` if AFE server timing is enabled; otherwise, `false`.
191
202
  */
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
- };
203
+ static isAFEServerTimingEnabled = common_1.isAFEServerTimingEnabled;
199
204
  /** Resets the cached value (use in tests if env changes). */
200
205
  static _resetAFEServerTimingForTest() {
201
- this._isAFEServerTimingEnabled = undefined;
206
+ (0, common_1.resetAFEServerTimingForTest)();
202
207
  }
203
208
  /**
204
209
  * Gets the configured Spanner emulator host from an environment variable.
@@ -265,9 +270,15 @@ class Spanner extends service_1.GrpcService {
265
270
  readLockMode: ReadLockMode.READ_LOCK_MODE_UNSPECIFIED,
266
271
  };
267
272
  delete options.defaultTransactionOptions;
268
- if (options?.universe_domain &&
269
- options?.universeDomain &&
270
- options?.universe_domain !== options?.universeDomain) {
273
+ const trimmedSnakeUniverse = typeof options?.universe_domain === 'string'
274
+ ? options.universe_domain.trim()
275
+ : options?.universe_domain;
276
+ const trimmedCamelUniverse = typeof options?.universeDomain === 'string'
277
+ ? options.universeDomain.trim()
278
+ : options?.universeDomain;
279
+ if (trimmedSnakeUniverse &&
280
+ trimmedCamelUniverse &&
281
+ trimmedSnakeUniverse !== trimmedCamelUniverse) {
271
282
  throw new Error('Please set either universe_domain or universeDomain, but not both.');
272
283
  }
273
284
  const emulatorHost = Spanner.getSpannerEmulatorHost();
@@ -298,7 +309,10 @@ class Spanner extends service_1.GrpcService {
298
309
  }
299
310
  this._isInSecureCredentials = options.sslCreds?._isSecure() === false;
300
311
  this.options = options;
301
- this.auth = new google_auth_library_1.GoogleAuth(this.options);
312
+ this.auth =
313
+ options.auth instanceof google_auth_library_1.GoogleAuth
314
+ ? options.auth
315
+ : new google_auth_library_1.GoogleAuth(this.options);
302
316
  this.clients_ = new Map();
303
317
  this.instances_ = new Map();
304
318
  this.instanceConfigs_ = new Map();
@@ -812,48 +826,114 @@ class Spanner extends service_1.GrpcService {
812
826
  * Setup the OpenTelemetry metrics capturing for service metrics to Google Cloud Monitoring.
813
827
  */
814
828
  configureMetrics_(disableBuiltInMetrics) {
815
- // Only enable metrics if not explicitly disabled and we are not using
816
- // insecure credentials.
829
+ // Only enable metrics if not explicitly disabled, using secure credentials,
830
+ // and not confined to a custom Spanner endpoint without an explicit monitoring host.
817
831
  const metricsExplicitlyDisabled = process.env.SPANNER_DISABLE_BUILTIN_METRICS === 'true' ||
818
832
  !!disableBuiltInMetrics;
833
+ const spannerOptions = this.options;
834
+ const hasCustomEndpoint = Boolean(spannerOptions.apiEndpoint ||
835
+ spannerOptions.servicePath ||
836
+ spannerOptions.port);
837
+ const monitoringHost = process.env.SPANNER_MONITORING_HOST?.trim() || undefined;
838
+ const disabledByCustomEndpoint = hasCustomEndpoint && !monitoringHost;
819
839
  this._metricsEnabled =
820
- !metricsExplicitlyDisabled && !this._isInSecureCredentials;
821
- metrics_tracer_factory_1.MetricsTracerFactory.enabled = this._metricsEnabled;
840
+ !metricsExplicitlyDisabled &&
841
+ !this._isInSecureCredentials &&
842
+ !disabledByCustomEndpoint;
843
+ // Only enable the process-wide flag when this client has metrics enabled;
844
+ // never clear it from a disabled client constructor because each Spanner
845
+ // instance checks its own `this._metricsEnabled` and clearing the global
846
+ // flag would break sibling clients with active metrics.
822
847
  if (this._metricsEnabled) {
823
- const initializeMetrics = (projectId) => {
824
- this.projectId_ = projectId;
825
- const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(projectId);
826
- if (factory && !factory.hasMetricReaders()) {
827
- api_1.context.with(api_1.ROOT_CONTEXT, () => {
828
- const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
829
- exporter: new spanner_metrics_exporter_1.CloudMonitoringMetricsExporter({ auth: this.auth }, projectId),
830
- exportIntervalMillis: 60000,
831
- });
832
- factory.getMeterProvider([periodicReader]);
833
- });
848
+ metrics_tracer_factory_1.MetricsTracerFactory.enabled = true;
849
+ }
850
+ if (!this._metricsEnabled) {
851
+ return;
852
+ }
853
+ // Validate universeDomain and SPANNER_MONITORING_HOST synchronously before
854
+ // any async getProjectId lookup so invalid configs fail closed at construction.
855
+ const exporterConfig = this._buildMetricsExporterConfig(monitoringHost);
856
+ this._metricsUniverseDomain = exporterConfig.universeDomain;
857
+ this._monitoringTargetKey = exporterConfig.monitoringTargetKey;
858
+ if (this.projectId_ && this.projectId_ !== '{{projectId}}') {
859
+ this._initializeMetricsForProject(this.projectId_, exporterConfig);
860
+ return;
861
+ }
862
+ try {
863
+ this.auth.getProjectId((err, projectId) => {
864
+ if (err || !projectId) {
865
+ this._metricsEnabled = false;
866
+ const errMsg = err
867
+ ? (err?.message ?? String(err))
868
+ : 'empty project ID';
869
+ console.error('Unable to get Project Id for client side metrics, will skip exporting client' +
870
+ ' side metrics: ' +
871
+ errMsg);
872
+ return;
834
873
  }
835
- };
836
- if (this.projectId_ && this.projectId_ !== '{{projectId}}') {
837
- initializeMetrics(this.projectId_);
874
+ this._initializeMetricsForProject(projectId, exporterConfig);
875
+ });
876
+ }
877
+ catch (err) {
878
+ this._metricsEnabled = false;
879
+ const errMsg = err?.message ?? String(err);
880
+ console.error('Unable to configure client side metrics, will skip exporting client' +
881
+ ' side metrics: ' +
882
+ errMsg);
883
+ }
884
+ }
885
+ /**
886
+ * Synchronously validates and builds the exporter configuration for built-in metrics.
887
+ *
888
+ * @param monitoringHost Optional trimmed `SPANNER_MONITORING_HOST` override.
889
+ * @returns Validated exporter options, pre-resolved client config, and normalized target key.
890
+ */
891
+ _buildMetricsExporterConfig(monitoringHost) {
892
+ const exporterOptions = {
893
+ auth: this.auth,
894
+ universeDomain: this._universeDomain,
895
+ // Explicitly pass apiEndpoint (even when undefined) so delayed async
896
+ // initialization cannot drift if SPANNER_MONITORING_HOST changes later.
897
+ apiEndpoint: monitoringHost,
898
+ };
899
+ const resolvedConfig = (0, spanner_metrics_exporter_1.resolveExporterConfig)(exporterOptions);
900
+ return {
901
+ exporterOptions,
902
+ resolvedConfig,
903
+ universeDomain: resolvedConfig.universeDomain,
904
+ monitoringTargetKey: resolvedConfig.monitoringEndpoint,
905
+ };
906
+ }
907
+ /**
908
+ * Attaches the Cloud Monitoring exporter to the `MetricsTracerFactory`
909
+ * scoped to the resolved `(universeDomain, monitoringTargetKey)`.
910
+ *
911
+ * @param projectId Resolved GCP project ID.
912
+ * @param config Validated exporter configuration and target key.
913
+ */
914
+ _initializeMetricsForProject(projectId, config) {
915
+ try {
916
+ const factory = metrics_tracer_factory_1.MetricsTracerFactory.getInstance(projectId, config.universeDomain, config.monitoringTargetKey);
917
+ if (!factory) {
918
+ return;
838
919
  }
839
- else {
840
- try {
841
- this.auth.getProjectId((err, projectId) => {
842
- if (err || !projectId) {
843
- console.error('Unable to get Project Id for client side metrics, will skip exporting client' +
844
- ' side metrics' +
845
- err);
846
- return;
847
- }
848
- initializeMetrics(projectId);
920
+ if (!factory.hasMetricReaders()) {
921
+ api_1.context.with(api_1.ROOT_CONTEXT, () => {
922
+ const periodicReader = new sdk_metrics_1.PeriodicExportingMetricReader({
923
+ exporter: new spanner_metrics_exporter_1.CloudMonitoringMetricsExporter(config.exporterOptions, projectId, config.resolvedConfig),
924
+ exportIntervalMillis: 60000,
849
925
  });
850
- }
851
- catch (err) {
852
- console.error('Unable to configure client side metrics, will skip exporting client' +
853
- ' side metrics' +
854
- err);
855
- }
926
+ factory.getMeterProvider([periodicReader]);
927
+ });
856
928
  }
929
+ this.projectId_ = projectId;
930
+ }
931
+ catch (err) {
932
+ this._metricsEnabled = false;
933
+ const errMsg = err?.message ?? String(err);
934
+ console.error('Unable to configure client side metrics, will skip exporting client' +
935
+ ' side metrics: ' +
936
+ errMsg);
857
937
  }
858
938
  }
859
939
  /**
@@ -865,40 +945,100 @@ class Spanner extends service_1.GrpcService {
865
945
  * @param {object} config Request config
866
946
  * @param {function} callback Callback function
867
947
  */
868
- prepareGapicRequest_(config, callback) {
869
- this.auth.getProjectId((err, projectId) => {
870
- if (err) {
871
- callback(err);
948
+ prepareGapicRequest_(config,
949
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
950
+ callback) {
951
+ if (this.projectId && this.projectIdReplaced_) {
952
+ this._prepareGapicRequestWithProjectId(config, this.projectId, callback);
953
+ return;
954
+ }
955
+ if (this._pendingProjectIdCallbacks) {
956
+ this._pendingProjectIdCallbacks.push((error, projectId) => {
957
+ if (error) {
958
+ callback(error);
959
+ return;
960
+ }
961
+ this._prepareGapicRequestWithProjectId(config, projectId, callback);
962
+ });
963
+ return;
964
+ }
965
+ this._pendingProjectIdCallbacks = [];
966
+ this.auth.getProjectId((error, projectId) => {
967
+ const pendingCallbacks = this._pendingProjectIdCallbacks || [];
968
+ this._pendingProjectIdCallbacks = undefined;
969
+ if (error) {
970
+ try {
971
+ callback(error);
972
+ }
973
+ finally {
974
+ for (const pendingCallback of pendingCallbacks) {
975
+ try {
976
+ pendingCallback(error);
977
+ }
978
+ catch {
979
+ // Prevent one failing user callback from stranding subsequent pending callers.
980
+ }
981
+ }
982
+ }
872
983
  return;
873
984
  }
874
- const clientName = config.client;
875
985
  try {
876
- if (!this.clients_.has(clientName)) {
877
- this.clients_.set(clientName, new v1[clientName](this.options));
986
+ this._prepareGapicRequestWithProjectId(config, projectId, callback);
987
+ }
988
+ finally {
989
+ for (const pendingCallback of pendingCallbacks) {
990
+ try {
991
+ pendingCallback(null, projectId);
992
+ }
993
+ catch {
994
+ // Prevent one failing user callback from stranding subsequent pending callers.
995
+ }
878
996
  }
879
997
  }
880
- catch (err) {
881
- callback(err, null);
998
+ });
999
+ }
1000
+ _prepareGapicRequestWithProjectId(config, projectId,
1001
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1002
+ callback) {
1003
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1004
+ let wrappedRequestFn;
1005
+ try {
1006
+ const clientName = config.client;
1007
+ if (!this.clients_.has(clientName)) {
1008
+ this.clients_.set(clientName, new v1[clientName](this.options));
882
1009
  }
883
1010
  const gaxClient = this.clients_.get(clientName);
884
- let reqOpts = extend(true, {}, config.reqOpts);
885
- reqOpts = (0, helper_1.replaceProjectIdToken)(reqOpts, projectId);
886
- // It would have been preferable to replace the projectId already in the
887
- // constructor of Spanner, but that is not possible as auth.getProjectId
888
- // is an async method. This is therefore the first place where we have
889
- // access to the value that should be used instead of the placeholder.
1011
+ let reqOpts = config.reqOpts;
1012
+ if (!this.projectIdReplaced_ || (0, helper_1.hasProjectIdToken)(reqOpts)) {
1013
+ reqOpts = extend(true, {}, config.reqOpts);
1014
+ reqOpts = (0, helper_1.replaceProjectIdToken)(reqOpts, projectId);
1015
+ }
890
1016
  if (!this.projectIdReplaced_) {
891
1017
  this.projectId = (0, helper_1.replaceProjectIdToken)(this.projectId, projectId);
892
1018
  this.projectFormattedName_ = (0, helper_1.replaceProjectIdToken)(this.projectFormattedName_, projectId);
1019
+ if (this.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER]?.includes('{{projectId}}')) {
1020
+ this.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER] = (0, helper_1.replaceProjectIdToken)(this.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER], projectId);
1021
+ }
893
1022
  this.instances_.forEach(instance => {
894
1023
  instance.formattedName_ = (0, helper_1.replaceProjectIdToken)(instance.formattedName_, projectId);
1024
+ if (instance.commonHeaders_?.[common_1.CLOUD_RESOURCE_HEADER]?.includes('{{projectId}}')) {
1025
+ instance.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER] =
1026
+ (0, helper_1.replaceProjectIdToken)(instance.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER], projectId);
1027
+ }
895
1028
  instance.databases_.forEach(database => {
896
1029
  database.formattedName_ = (0, helper_1.replaceProjectIdToken)(database.formattedName_, projectId);
1030
+ if (database.commonHeaders_?.[common_1.CLOUD_RESOURCE_HEADER]?.includes('{{projectId}}')) {
1031
+ database.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER] =
1032
+ (0, helper_1.replaceProjectIdToken)(database.commonHeaders_[common_1.CLOUD_RESOURCE_HEADER], projectId);
1033
+ }
897
1034
  });
898
1035
  });
899
1036
  this.projectIdReplaced_ = true;
900
1037
  }
901
- config.headers[common_1.CLOUD_RESOURCE_HEADER] = (0, helper_1.replaceProjectIdToken)(config.headers[common_1.CLOUD_RESOURCE_HEADER], projectId);
1038
+ config.headers = extend(true, {}, config.headers);
1039
+ if (config.headers[common_1.CLOUD_RESOURCE_HEADER]?.includes('{{projectId}}')) {
1040
+ config.headers[common_1.CLOUD_RESOURCE_HEADER] = (0, helper_1.replaceProjectIdToken)(config.headers[common_1.CLOUD_RESOURCE_HEADER], projectId);
1041
+ }
902
1042
  if ((0, instrument_1.isTracingEnabled)(this._observabilityOptions)) {
903
1043
  // Do context propagation
904
1044
  api_1.propagation.inject(api_1.context.active(), config.headers, {
@@ -909,20 +1049,34 @@ class Spanner extends service_1.GrpcService {
909
1049
  // Attach the x-goog-spanner-request-id to the currently active span.
910
1050
  (0, request_id_header_1.attributeXGoogSpannerRequestIdToActiveSpan)(config);
911
1051
  }
912
- const interceptors = [];
913
- if (this._metricsEnabled) {
914
- interceptors.push(interceptor_1.MetricInterceptor);
1052
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1053
+ const customInterceptors = config.gaxOpts?.otherArgs?.options?.interceptors ?? [];
1054
+ const shouldIntercept = this._metricsEnabled &&
1055
+ (config.client === 'SpannerClient' || config.metricsTracer);
1056
+ const interceptors = shouldIntercept
1057
+ ? [...customInterceptors, interceptor_1.MetricInterceptor]
1058
+ : customInterceptors;
1059
+ const headers = Object.assign({}, config.gaxOpts?.otherArgs?.headers, config.headers);
1060
+ const options = Object.assign({}, config.gaxOpts?.otherArgs?.options, {
1061
+ interceptors,
1062
+ metricsTracer: config.metricsTracer,
1063
+ });
1064
+ // Deep clone caller-owned properties to prevent downstream mutations
1065
+ // (e.g. gax mutating `retry.backoffSettings`), while attaching our
1066
+ // freshly merged otherArgs without redundantly deep-cloning them.
1067
+ let gaxOpts;
1068
+ if (config.gaxOpts) {
1069
+ const { otherArgs: callerOtherArgs, ...restGaxOpts } = config.gaxOpts;
1070
+ gaxOpts = extend(true, {}, restGaxOpts);
1071
+ gaxOpts.otherArgs = Object.assign({}, callerOtherArgs, {
1072
+ headers,
1073
+ options,
1074
+ });
1075
+ }
1076
+ else {
1077
+ gaxOpts = { otherArgs: { headers, options } };
915
1078
  }
916
- const requestFn = gaxClient[config.method].bind(gaxClient, reqOpts,
917
- // Add headers to `gaxOpts`
918
- extend(true, {}, config.gaxOpts, {
919
- otherArgs: {
920
- headers: config.headers,
921
- options: {
922
- interceptors: interceptors,
923
- },
924
- },
925
- }));
1079
+ const requestFn = gaxClient[config.method].bind(gaxClient, reqOpts, gaxOpts);
926
1080
  // Extract a lightweight config reference containing only headers so error
927
1081
  // enrichment is decoupled from the caller's mutable config object.
928
1082
  const errorConfig = { headers: config?.headers };
@@ -932,7 +1086,7 @@ class Spanner extends service_1.GrpcService {
932
1086
  //
933
1087
  // Because reqOpts and gaxOpts are already pre-bound to requestFn, wrappedRequestFn
934
1088
  // receives at most one argument: an optional callback.
935
- const wrappedRequestFn = (callback) => {
1089
+ wrappedRequestFn = (callback) => {
936
1090
  // Callback mode: invoke requestFn with an intercepted callback to enrich
937
1091
  // the error parameter before delegating to the caller's callback.
938
1092
  if (typeof callback === 'function') {
@@ -983,8 +1137,47 @@ class Spanner extends service_1.GrpcService {
983
1137
  }
984
1138
  return res;
985
1139
  };
986
- callback(null, wrappedRequestFn);
987
- });
1140
+ }
1141
+ catch (error) {
1142
+ callback(error, null);
1143
+ return;
1144
+ }
1145
+ callback(null, wrappedRequestFn);
1146
+ }
1147
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1148
+ _getResourceName(config) {
1149
+ const reqOpts = config?.reqOpts;
1150
+ if (reqOpts) {
1151
+ if (typeof reqOpts.database === 'string') {
1152
+ return reqOpts.database;
1153
+ }
1154
+ if (typeof reqOpts.session === 'string') {
1155
+ return reqOpts.session;
1156
+ }
1157
+ if (typeof reqOpts.name === 'string') {
1158
+ return reqOpts.name;
1159
+ }
1160
+ }
1161
+ const resourceHeader = config?.headers?.[common_1.CLOUD_RESOURCE_HEADER];
1162
+ if (typeof resourceHeader === 'string') {
1163
+ return resourceHeader;
1164
+ }
1165
+ return '';
1166
+ }
1167
+ _initMetricsTracer(
1168
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1169
+ config) {
1170
+ let metricsTracer = null;
1171
+ if (this._metricsEnabled &&
1172
+ config.client === 'SpannerClient' &&
1173
+ this.projectId_ &&
1174
+ this.projectId_ !== '{{projectId}}') {
1175
+ metricsTracer =
1176
+ metrics_tracer_factory_1.MetricsTracerFactory?.getInstance(this.projectId_, this._metricsUniverseDomain ?? this._universeDomain, this._monitoringTargetKey)?.createMetricsTracer(config.method, this._getResourceName(config), config.headers?.['x-goog-spanner-request-id']) ?? null;
1177
+ }
1178
+ metricsTracer?.recordOperationStart();
1179
+ config.metricsTracer = metricsTracer ?? undefined;
1180
+ return metricsTracer;
988
1181
  }
989
1182
  /**
990
1183
  * Funnel all API requests through this method to be sure we have a project
@@ -999,15 +1192,7 @@ class Spanner extends service_1.GrpcService {
999
1192
  */
1000
1193
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1001
1194
  request(config, callback) {
1002
- let metricsTracer = null;
1003
- if (this._metricsEnabled &&
1004
- config.client === 'SpannerClient' &&
1005
- this.projectId_ &&
1006
- this.projectId_ !== '{{projectId}}') {
1007
- metricsTracer =
1008
- 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;
1009
- }
1010
- metricsTracer?.recordOperationStart();
1195
+ const metricsTracer = this._initMetricsTracer(config);
1011
1196
  if (typeof callback === 'function') {
1012
1197
  this.prepareGapicRequest_(config, (err, requestFn) => {
1013
1198
  if (err) {
@@ -1015,11 +1200,38 @@ class Spanner extends service_1.GrpcService {
1015
1200
  metricsTracer?.recordOperationCompletion();
1016
1201
  }
1017
1202
  else {
1203
+ let callbackInvoked = false;
1204
+ let callbackThrew = false;
1205
+ let callbackError;
1018
1206
  const wrappedCallback = (...args) => {
1207
+ if (callbackInvoked) {
1208
+ return;
1209
+ }
1210
+ callbackInvoked = true;
1019
1211
  metricsTracer?.recordOperationCompletion();
1020
- callback(...args);
1212
+ try {
1213
+ callback(...args);
1214
+ }
1215
+ catch (error) {
1216
+ callbackThrew = true;
1217
+ callbackError = error;
1218
+ throw error;
1219
+ }
1021
1220
  };
1022
- requestFn(wrappedCallback);
1221
+ try {
1222
+ requestFn(wrappedCallback);
1223
+ }
1224
+ catch (error) {
1225
+ if (callbackThrew) {
1226
+ throw callbackError;
1227
+ }
1228
+ if (callbackInvoked) {
1229
+ return;
1230
+ }
1231
+ callbackInvoked = true;
1232
+ metricsTracer?.recordOperationCompletion();
1233
+ callback(error);
1234
+ }
1023
1235
  }
1024
1236
  });
1025
1237
  }
@@ -1031,22 +1243,29 @@ class Spanner extends service_1.GrpcService {
1031
1243
  reject(err);
1032
1244
  }
1033
1245
  else {
1034
- const result = requestFn();
1035
- if (result && typeof result.then === 'function') {
1036
- result
1037
- .then(val => {
1038
- metricsTracer?.recordOperationCompletion();
1039
- resolve(val);
1040
- return val;
1041
- })
1042
- .catch(error => {
1246
+ try {
1247
+ const result = requestFn();
1248
+ if (result && typeof result.then === 'function') {
1249
+ result
1250
+ .then(val => {
1251
+ metricsTracer?.recordOperationCompletion();
1252
+ resolve(val);
1253
+ return val;
1254
+ })
1255
+ .catch(error => {
1256
+ metricsTracer?.recordOperationCompletion();
1257
+ reject(error);
1258
+ return null;
1259
+ });
1260
+ }
1261
+ else {
1043
1262
  metricsTracer?.recordOperationCompletion();
1044
- reject(error);
1045
- });
1263
+ resolve(result);
1264
+ }
1046
1265
  }
1047
- else {
1266
+ catch (error) {
1048
1267
  metricsTracer?.recordOperationCompletion();
1049
- resolve(result);
1268
+ reject(error);
1050
1269
  }
1051
1270
  }
1052
1271
  });
@@ -1066,35 +1285,20 @@ class Spanner extends service_1.GrpcService {
1066
1285
  */
1067
1286
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1068
1287
  requestStream(config) {
1069
- let metricsTracer = null;
1070
- if (this._metricsEnabled &&
1071
- config.client === 'SpannerClient' &&
1072
- this.projectId_ &&
1073
- this.projectId_ !== '{{projectId}}') {
1074
- metricsTracer =
1075
- 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;
1076
- }
1077
- metricsTracer?.recordOperationStart();
1288
+ const metricsTracer = this._initMetricsTracer(config);
1078
1289
  const stream = streamEvents(through.obj());
1290
+ const coordinator = new request_stream_coordinator_1.RequestStreamCoordinator(stream, metricsTracer);
1291
+ coordinator.setup();
1079
1292
  stream.once('reading', () => {
1293
+ coordinator.startRequest();
1080
1294
  this.prepareGapicRequest_(config, (err, requestFn) => {
1081
1295
  if (err) {
1082
- stream.destroy(err);
1296
+ coordinator.handleRequestError(err);
1083
1297
  return;
1084
1298
  }
1085
- requestFn()
1086
- .on('error', err => {
1087
- stream.destroy(err);
1088
- })
1089
- .pipe(stream);
1299
+ coordinator.attachRequestFn(requestFn);
1090
1300
  });
1091
1301
  });
1092
- stream.on('finish', () => {
1093
- stream.destroy();
1094
- });
1095
- stream.on('close', () => {
1096
- metricsTracer?.recordOperationCompletion();
1097
- });
1098
1302
  return stream;
1099
1303
  }
1100
1304
  /**