@google-cloud/spanner 9.0.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 (40) hide show
  1. package/README.md +1 -16
  2. package/build/src/batch-transaction.js +15 -12
  3. package/build/src/codec.d.ts +6 -0
  4. package/build/src/codec.js +99 -34
  5. package/build/src/common.d.ts +14 -0
  6. package/build/src/common.js +27 -1
  7. package/build/src/database.d.ts +31 -41
  8. package/build/src/database.js +122 -313
  9. package/build/src/helper.d.ts +12 -0
  10. package/build/src/helper.js +44 -0
  11. package/build/src/index.d.ts +16 -8
  12. package/build/src/index.js +210 -90
  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 +6 -0
  18. package/build/src/metrics/constants.js +6 -1
  19. package/build/src/metrics/interceptor.js +32 -28
  20. package/build/src/metrics/metrics-tracer-factory.d.ts +6 -11
  21. package/build/src/metrics/metrics-tracer-factory.js +62 -64
  22. package/build/src/metrics/metrics-tracer.d.ts +19 -6
  23. package/build/src/metrics/metrics-tracer.js +147 -55
  24. package/build/src/multiplexed-session.d.ts +13 -2
  25. package/build/src/multiplexed-session.js +20 -4
  26. package/build/src/partial-result-stream.d.ts +26 -33
  27. package/build/src/partial-result-stream.js +263 -283
  28. package/build/src/request-stream-coordinator.d.ts +88 -0
  29. package/build/src/request-stream-coordinator.js +229 -0
  30. package/build/src/request_id_header.d.ts +6 -4
  31. package/build/src/request_id_header.js +24 -24
  32. package/build/src/session-factory.d.ts +52 -63
  33. package/build/src/session-factory.js +41 -92
  34. package/build/src/session-pool.d.ts +97 -227
  35. package/build/src/session-pool.js +74 -547
  36. package/build/src/session.js +1 -1
  37. package/build/src/transaction-runner.js +1 -12
  38. package/build/src/transaction.d.ts +5 -5
  39. package/build/src/transaction.js +72 -112
  40. package/package.json +9 -10
@@ -15,30 +15,35 @@
15
15
  import { grpc } from 'google-gax';
16
16
  /**
17
17
  * Checks whether the given error is a 'Database not found' error.
18
+ * @deprecated Session pool is deprecated and will be removed in a future release.
18
19
  * @param {Error} error The error to check.
19
20
  * @return {boolean} True if the error is a 'Database not found' error, and otherwise false.
20
21
  */
21
22
  export declare function isDatabaseNotFoundError(error: grpc.ServiceError | undefined): boolean;
22
23
  /**
23
24
  * Checks whether the given error is an 'Instance not found' error.
25
+ * @deprecated Session pool is deprecated and will be removed in a future release.
24
26
  * @param {Error} error The error to check.
25
27
  * @return {boolean} True if the error is an 'Instance not found' error, and otherwise false.
26
28
  */
27
29
  export declare function isInstanceNotFoundError(error: grpc.ServiceError | undefined): boolean;
28
30
  /**
29
31
  * Checks whether the given error is a 'Could not load the default credentials' error.
32
+ * @deprecated Session pool is deprecated and will be removed in a future release.
30
33
  * @param {Error} error The error to check.
31
34
  * @return {boolean} True if the error is a 'Could not load the default credentials' error, and otherwise false.
32
35
  */
33
36
  export declare function isDefaultCredentialsNotSetError(error: grpc.ServiceError | undefined): boolean;
34
37
  /**
35
38
  * Checks whether the given error is an 'Unable to detect a Project Id in the current environment' error.
39
+ * @deprecated Session pool is deprecated and will be removed in a future release.
36
40
  * @param {Error} error The error to check.
37
41
  * @return {boolean} True if the error is an 'Unable to detect a Project Id in the current environment' error, and otherwise false.
38
42
  */
39
43
  export declare function isProjectIdNotSetInEnvironmentError(error: grpc.ServiceError | undefined): boolean;
40
44
  /**
41
45
  * Checks whether the given error is a 'Create session permission' error.
46
+ * @deprecated Session pool is deprecated and will be removed in a future release.
42
47
  * @param {Error} error The error to check.
43
48
  * @return {boolean} True if the error is a 'Create session permission' error, and otherwise false.
44
49
  */
@@ -158,3 +163,10 @@ export declare function isUuid(value: any): boolean;
158
163
  * @return {*} - The original argument with all placeholders populated.
159
164
  */
160
165
  export declare function replaceProjectIdToken(value: any, projectId: string): any;
166
+ /**
167
+ * Checks whether an input value contains the `{{projectId}}` placeholder.
168
+ *
169
+ * @param {*} value - The value to inspect.
170
+ * @return {boolean} - `true` if any placeholder is found, otherwise `false`.
171
+ */
172
+ export declare function hasProjectIdToken(value: any): boolean;
@@ -37,10 +37,12 @@ exports.isInfinite = isInfinite;
37
37
  exports.isError = isError;
38
38
  exports.isUuid = isUuid;
39
39
  exports.replaceProjectIdToken = replaceProjectIdToken;
40
+ exports.hasProjectIdToken = hasProjectIdToken;
40
41
  const google_gax_1 = require("google-gax");
41
42
  const stream_1 = require("stream");
42
43
  /**
43
44
  * Checks whether the given error is a 'Database not found' error.
45
+ * @deprecated Session pool is deprecated and will be removed in a future release.
44
46
  * @param {Error} error The error to check.
45
47
  * @return {boolean} True if the error is a 'Database not found' error, and otherwise false.
46
48
  */
@@ -51,6 +53,7 @@ function isDatabaseNotFoundError(error) {
51
53
  }
52
54
  /**
53
55
  * Checks whether the given error is an 'Instance not found' error.
56
+ * @deprecated Session pool is deprecated and will be removed in a future release.
54
57
  * @param {Error} error The error to check.
55
58
  * @return {boolean} True if the error is an 'Instance not found' error, and otherwise false.
56
59
  */
@@ -61,6 +64,7 @@ function isInstanceNotFoundError(error) {
61
64
  }
62
65
  /**
63
66
  * Checks whether the given error is a 'Could not load the default credentials' error.
67
+ * @deprecated Session pool is deprecated and will be removed in a future release.
64
68
  * @param {Error} error The error to check.
65
69
  * @return {boolean} True if the error is a 'Could not load the default credentials' error, and otherwise false.
66
70
  */
@@ -70,6 +74,7 @@ function isDefaultCredentialsNotSetError(error) {
70
74
  }
71
75
  /**
72
76
  * Checks whether the given error is an 'Unable to detect a Project Id in the current environment' error.
77
+ * @deprecated Session pool is deprecated and will be removed in a future release.
73
78
  * @param {Error} error The error to check.
74
79
  * @return {boolean} True if the error is an 'Unable to detect a Project Id in the current environment' error, and otherwise false.
75
80
  */
@@ -79,6 +84,7 @@ function isProjectIdNotSetInEnvironmentError(error) {
79
84
  }
80
85
  /**
81
86
  * Checks whether the given error is a 'Create session permission' error.
87
+ * @deprecated Session pool is deprecated and will be removed in a future release.
82
88
  * @param {Error} error The error to check.
83
89
  * @return {boolean} True if the error is a 'Create session permission' error, and otherwise false.
84
90
  */
@@ -325,6 +331,44 @@ function replaceProjectIdToken(value, projectId) {
325
331
  }
326
332
  return value;
327
333
  }
334
+ /**
335
+ * Checks whether an input value contains the `{{projectId}}` placeholder.
336
+ *
337
+ * @param {*} value - The value to inspect.
338
+ * @return {boolean} - `true` if any placeholder is found, otherwise `false`.
339
+ */
340
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
341
+ function hasProjectIdToken(value) {
342
+ if (typeof value === 'string') {
343
+ return value.includes(PROJECT_ID_TOKEN);
344
+ }
345
+ if (value === null ||
346
+ typeof value !== 'object' ||
347
+ value instanceof Buffer ||
348
+ value instanceof stream_1.Stream ||
349
+ isDate(value)) {
350
+ return false;
351
+ }
352
+ if (Array.isArray(value)) {
353
+ for (let i = 0; i < value.length; i++) {
354
+ if (hasProjectIdToken(value[i])) {
355
+ return true;
356
+ }
357
+ }
358
+ return false;
359
+ }
360
+ for (const key in value) {
361
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
362
+ if (!KEYS_TO_SCAN.has(key)) {
363
+ continue;
364
+ }
365
+ if (hasProjectIdToken(value[key])) {
366
+ return true;
367
+ }
368
+ }
369
+ }
370
+ return false;
371
+ }
328
372
  /**
329
373
  * Custom error type for missing project ID errors.
330
374
  */
@@ -26,13 +26,14 @@ import { grpc, GrpcClientOptions, CallOptions } from 'google-gax';
26
26
  import { protos } from '@google-cloud/spanner-api';
27
27
  import google = protos.google;
28
28
  import instanceAdmin = protos.google;
29
- import { PagedOptions, PagedResponse, PagedCallback, PagedOptionsWithFilter, NormalCallback } from './common';
29
+ import { PagedOptions, PagedResponse, PagedCallback, PagedOptionsWithFilter, NormalCallback, isAFEServerTimingEnabled } from './common';
30
30
  import { Session } from './session';
31
31
  import { SessionPool } from './session-pool';
32
32
  import { Table } from './table';
33
33
  import { MutationGroup, MutationSet, PartitionedDml, Snapshot, Transaction } from './transaction';
34
34
  import * as v1 from './v1';
35
35
  import { ObservabilityOptions } from './instrument';
36
+ import { MetricsTracer } from './metrics/metrics-tracer';
36
37
  export type IOperation = instanceAdmin.longrunning.IOperation;
37
38
  export type GetInstancesOptions = PagedOptionsWithFilter;
38
39
  export type GetInstancesResponse = PagedResponse<Instance, instanceAdmin.spanner.admin.instance.v1.IListInstancesResponse>;
@@ -100,6 +101,7 @@ export interface RequestConfig {
100
101
  headers: {
101
102
  [k: string]: string;
102
103
  };
104
+ metricsTracer?: MetricsTracer;
103
105
  }
104
106
  export interface CreateInstanceRequest {
105
107
  config?: string;
@@ -205,8 +207,8 @@ declare class Spanner extends GrpcService {
205
207
  private _universeDomain;
206
208
  private _isInSecureCredentials;
207
209
  private _metricsEnabled;
208
- private static _isAFEServerTimingEnabled;
209
210
  readonly _nthClientId: number;
211
+ private _pendingProjectIdCallbacks?;
210
212
  /**
211
213
  * Placeholder used to auto populate a column with the commit timestamp.
212
214
  * This can only be used for timestamp columns that have set the option
@@ -221,14 +223,14 @@ declare class Spanner extends GrpcService {
221
223
  * Returns whether AFE (Application Frontend Extension) server timing is enabled.
222
224
  *
223
225
  * This method checks the value of the environment variable
224
- * `SPANNER_DISABLE_AFE_SERVER_TIMING`. If the variable is explicitly set to the
225
- * string `'true'`, then AFE server timing is considered disabled, and this method
226
- * returns `false`. For all other values (including if the variable is unset),
227
- * the method returns `true`.
226
+ * `SPANNER_DISABLE_AFE_SERVER_TIMING`. If the variable is explicitly set to
227
+ * the string `'true'` (case-insensitive), then AFE server timing is
228
+ * considered disabled, and this method returns `false`. For all other
229
+ * values (including if the variable is unset), the method returns `true`.
228
230
  *
229
231
  * @returns {boolean} `true` if AFE server timing is enabled; otherwise, `false`.
230
232
  */
231
- static isAFEServerTimingEnabled: () => boolean;
233
+ static isAFEServerTimingEnabled: typeof isAFEServerTimingEnabled;
232
234
  /** Resets the cached value (use in tests if env changes). */
233
235
  static _resetAFEServerTimingForTest(): void;
234
236
  /**
@@ -879,7 +881,10 @@ declare class Spanner extends GrpcService {
879
881
  * @param {object} config Request config
880
882
  * @param {function} callback Callback function
881
883
  */
882
- prepareGapicRequest_(config: any, callback: any): void;
884
+ prepareGapicRequest_(config: RequestConfig, callback: (err: Error | null, requestFn?: any) => void): void;
885
+ private _prepareGapicRequestWithProjectId;
886
+ private _getResourceName;
887
+ private _initMetricsTracer;
883
888
  /**
884
889
  * Funnel all API requests through this method to be sure we have a project
885
890
  * ID.
@@ -1195,6 +1200,9 @@ export { Session };
1195
1200
  /**
1196
1201
  * {@link SessionPool} class.
1197
1202
  *
1203
+ * @deprecated Session pool is deprecated and will be removed in a future release.
1204
+ * Multiplexed sessions are now used for all operations by default, eliminating
1205
+ * the need for session pooling.
1198
1206
  * @name Spanner.SessionPool
1199
1207
  * @see SessionPool
1200
1208
  * @type {Constructor}
@@ -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.
@@ -865,40 +861,100 @@ class Spanner extends service_1.GrpcService {
865
861
  * @param {object} config Request config
866
862
  * @param {function} callback Callback function
867
863
  */
868
- prepareGapicRequest_(config, callback) {
869
- this.auth.getProjectId((err, projectId) => {
870
- if (err) {
871
- 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
+ }
872
899
  return;
873
900
  }
874
- const clientName = config.client;
875
901
  try {
876
- if (!this.clients_.has(clientName)) {
877
- 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
+ }
878
912
  }
879
913
  }
880
- catch (err) {
881
- 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));
882
925
  }
883
926
  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.
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
+ }
890
932
  if (!this.projectIdReplaced_) {
891
933
  this.projectId = (0, helper_1.replaceProjectIdToken)(this.projectId, projectId);
892
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
+ }
893
938
  this.instances_.forEach(instance => {
894
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
+ }
895
944
  instance.databases_.forEach(database => {
896
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
+ }
897
950
  });
898
951
  });
899
952
  this.projectIdReplaced_ = true;
900
953
  }
901
- 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
+ }
902
958
  if ((0, instrument_1.isTracingEnabled)(this._observabilityOptions)) {
903
959
  // Do context propagation
904
960
  api_1.propagation.inject(api_1.context.active(), config.headers, {
@@ -909,20 +965,34 @@ class Spanner extends service_1.GrpcService {
909
965
  // Attach the x-goog-spanner-request-id to the currently active span.
910
966
  (0, request_id_header_1.attributeXGoogSpannerRequestIdToActiveSpan)(config);
911
967
  }
912
- const interceptors = [];
913
- if (this._metricsEnabled) {
914
- 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
+ });
915
991
  }
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
- }));
992
+ else {
993
+ gaxOpts = { otherArgs: { headers, options } };
994
+ }
995
+ const requestFn = gaxClient[config.method].bind(gaxClient, reqOpts, gaxOpts);
926
996
  // Extract a lightweight config reference containing only headers so error
927
997
  // enrichment is decoupled from the caller's mutable config object.
928
998
  const errorConfig = { headers: config?.headers };
@@ -932,7 +1002,7 @@ class Spanner extends service_1.GrpcService {
932
1002
  //
933
1003
  // Because reqOpts and gaxOpts are already pre-bound to requestFn, wrappedRequestFn
934
1004
  // receives at most one argument: an optional callback.
935
- const wrappedRequestFn = (callback) => {
1005
+ wrappedRequestFn = (callback) => {
936
1006
  // Callback mode: invoke requestFn with an intercepted callback to enrich
937
1007
  // the error parameter before delegating to the caller's callback.
938
1008
  if (typeof callback === 'function') {
@@ -983,8 +1053,47 @@ class Spanner extends service_1.GrpcService {
983
1053
  }
984
1054
  return res;
985
1055
  };
986
- callback(null, wrappedRequestFn);
987
- });
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;
988
1097
  }
989
1098
  /**
990
1099
  * Funnel all API requests through this method to be sure we have a project
@@ -999,15 +1108,7 @@ class Spanner extends service_1.GrpcService {
999
1108
  */
1000
1109
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1001
1110
  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();
1111
+ const metricsTracer = this._initMetricsTracer(config);
1011
1112
  if (typeof callback === 'function') {
1012
1113
  this.prepareGapicRequest_(config, (err, requestFn) => {
1013
1114
  if (err) {
@@ -1015,11 +1116,38 @@ class Spanner extends service_1.GrpcService {
1015
1116
  metricsTracer?.recordOperationCompletion();
1016
1117
  }
1017
1118
  else {
1119
+ let callbackInvoked = false;
1120
+ let callbackThrew = false;
1121
+ let callbackError;
1018
1122
  const wrappedCallback = (...args) => {
1123
+ if (callbackInvoked) {
1124
+ return;
1125
+ }
1126
+ callbackInvoked = true;
1019
1127
  metricsTracer?.recordOperationCompletion();
1020
- callback(...args);
1128
+ try {
1129
+ callback(...args);
1130
+ }
1131
+ catch (error) {
1132
+ callbackThrew = true;
1133
+ callbackError = error;
1134
+ throw error;
1135
+ }
1021
1136
  };
1022
- 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
+ }
1023
1151
  }
1024
1152
  });
1025
1153
  }
@@ -1031,22 +1159,29 @@ class Spanner extends service_1.GrpcService {
1031
1159
  reject(err);
1032
1160
  }
1033
1161
  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 => {
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 {
1043
1178
  metricsTracer?.recordOperationCompletion();
1044
- reject(error);
1045
- });
1179
+ resolve(result);
1180
+ }
1046
1181
  }
1047
- else {
1182
+ catch (error) {
1048
1183
  metricsTracer?.recordOperationCompletion();
1049
- resolve(result);
1184
+ reject(error);
1050
1185
  }
1051
1186
  }
1052
1187
  });
@@ -1066,35 +1201,20 @@ class Spanner extends service_1.GrpcService {
1066
1201
  */
1067
1202
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1068
1203
  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();
1204
+ const metricsTracer = this._initMetricsTracer(config);
1078
1205
  const stream = streamEvents(through.obj());
1206
+ const coordinator = new request_stream_coordinator_1.RequestStreamCoordinator(stream, metricsTracer);
1207
+ coordinator.setup();
1079
1208
  stream.once('reading', () => {
1209
+ coordinator.startRequest();
1080
1210
  this.prepareGapicRequest_(config, (err, requestFn) => {
1081
1211
  if (err) {
1082
- stream.destroy(err);
1212
+ coordinator.handleRequestError(err);
1083
1213
  return;
1084
1214
  }
1085
- requestFn()
1086
- .on('error', err => {
1087
- stream.destroy(err);
1088
- })
1089
- .pipe(stream);
1215
+ coordinator.attachRequestFn(requestFn);
1090
1216
  });
1091
1217
  });
1092
- stream.on('finish', () => {
1093
- stream.destroy();
1094
- });
1095
- stream.on('close', () => {
1096
- metricsTracer?.recordOperationCompletion();
1097
- });
1098
1218
  return stream;
1099
1219
  }
1100
1220
  /**