@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
@@ -233,7 +233,7 @@ class Session extends common.GrpcServiceObject {
233
233
  const reqOpts = {
234
234
  name: this.formattedName_,
235
235
  };
236
- const headers = this.commonHeaders_;
236
+ const headers = { ...this.commonHeaders_ };
237
237
  if (this._getSpanner().routeToLeaderEnabled) {
238
238
  (0, common_1.addLeaderAwareRoutingHeader)(headers);
239
239
  }
@@ -20,7 +20,6 @@ exports.isRetryableInternalError = isRetryableInternalError;
20
20
  const promisify_1 = require("@google-cloud/promisify");
21
21
  const google_gax_1 = require("google-gax");
22
22
  const through = require("through2");
23
- const session_pool_1 = require("./session-pool");
24
23
  const spanner_api_1 = require("@google-cloud/spanner-api");
25
24
  var google = spanner_api_1.protos.google;
26
25
  var IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel;
@@ -104,20 +103,13 @@ class Runner {
104
103
  const nanosInMs = Math.floor(retryDelay.nanos) / 1e6;
105
104
  return secondsInMs + nanosInMs;
106
105
  }
107
- // A 'Session not found' error without any specific retry info should not
108
- // cause any delay between retries.
109
- if ((0, session_pool_1.isSessionNotFoundError)(err)) {
110
- return 0;
111
- }
112
106
  // Max backoff should be 32 seconds.
113
107
  return (Math.pow(2, Math.min(this.attempts, 5)) * 1000 +
114
108
  Math.floor(Math.random() * 1000));
115
109
  }
116
110
  /** Returns whether the given error should cause a transaction retry. */
117
111
  shouldRetry(err) {
118
- return (RETRYABLE.includes(err.code) ||
119
- (0, session_pool_1.isSessionNotFoundError)(err) ||
120
- isRetryableInternalError(err));
112
+ return RETRYABLE.includes(err.code) || isRetryableInternalError(err);
121
113
  }
122
114
  /**
123
115
  * Retrieves a transaction to run against.
@@ -167,9 +159,6 @@ class Runner {
167
159
  finally {
168
160
  this.multiplexedSessionPreviousTransactionId = transaction.id;
169
161
  }
170
- // Note that if the error is a 'Session not found' error, it will be
171
- // thrown here. We do this to bubble this error up to the caller who is
172
- // responsible for retrying the transaction on a different session.
173
162
  if (!RETRYABLE.includes(lastError.code) &&
174
163
  !isRetryableInternalError(lastError)) {
175
164
  throw lastError;
@@ -304,6 +304,22 @@ export declare class Snapshot extends EventEmitter {
304
304
  * are specified for a query.
305
305
  */
306
306
  constructor(session: Session, options?: TimestampBounds, queryOptions?: IQueryOptions);
307
+ /**
308
+ * Binds the multiplexed session affinity key to the gax options of an
309
+ * outgoing request, so that all requests of this transaction are routed to
310
+ * the same gRPC channel.
311
+ *
312
+ * `config` is always a request descriptor that was freshly constructed by the
313
+ * caller for this one RPC (and {@link Spanner#prepareGapicRequest_} already
314
+ * modifies `config.headers` in place), so the affinity key is assigned
315
+ * directly instead of allocating a copy of the descriptor per request.
316
+ *
317
+ * @private
318
+ *
319
+ * @param {object} config The request configuration.
320
+ * @returns {object} The same request configuration.
321
+ */
322
+ private _applyAffinityGaxOpts;
307
323
  protected _updatePrecommitToken(resp: PrecommitTokenProvider): void;
308
324
  /**
309
325
  * Selects a single representative mutation from a list to be used as the
@@ -853,11 +869,11 @@ export declare class Snapshot extends EventEmitter {
853
869
  * @property {object} [gaxOptions] Request configuration options,
854
870
  * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions}
855
871
  * for more details.
856
- * @property {number} [maxResumeRetries] The maximum number of times that the
857
- * stream will retry to push data downstream, when the downstream indicates
858
- * that it is not ready for any more data. Increase this value if you
859
- * experience 'Stream is still not ready to receive data' errors as a
860
- * result of a slow writer in your receiving stream.
872
+ * @property {number} [maxResumeRetries] The maximum number of times that the
873
+ * query will retry on retryable errors (such as UNAVAILABLE). Only
874
+ * applicable to non-streaming queries executed via {@link Snapshot#run}.
875
+ * For streaming queries ({@link Snapshot#runStream}), this option is
876
+ * deprecated as backpressure is managed automatically.
861
877
  * @property {object} [directedReadOptions]
862
878
  * Indicates which replicas or regions should be used for non-transactional reads or queries.
863
879
  */
@@ -212,28 +212,10 @@ class Snapshot extends events_1.EventEmitter {
212
212
  },
213
213
  },
214
214
  };
215
- this.request = (config, callback) => {
216
- let gaxOpts;
217
- if (!config.gaxOpts || Object.keys(config.gaxOpts).length === 0) {
218
- gaxOpts = this._bindGaxOpts;
219
- }
220
- else {
221
- gaxOpts = injectGaxOpt(config.gaxOpts, 'affinityKey', this._affinityKey);
222
- }
223
- config = Object.assign({}, config, { gaxOpts });
224
- return session.request(config, callback);
225
- };
226
- this.requestStream = (config) => {
227
- let gaxOpts;
228
- if (!config.gaxOpts || Object.keys(config.gaxOpts).length === 0) {
229
- gaxOpts = this._bindGaxOpts;
230
- }
231
- else {
232
- gaxOpts = injectGaxOpt(config.gaxOpts, 'affinityKey', this._affinityKey);
233
- }
234
- config = Object.assign({}, config, { gaxOpts });
235
- return session.requestStream(config);
236
- };
215
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
216
+ this.request = (config, callback) => session.request(this._applyAffinityGaxOpts(config), callback);
217
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
218
+ this.requestStream = (config) => session.requestStream(this._applyAffinityGaxOpts(config));
237
219
  }
238
220
  else {
239
221
  this.request = session.request.bind(session);
@@ -253,6 +235,34 @@ class Snapshot extends events_1.EventEmitter {
253
235
  this._latestPreCommitToken = null;
254
236
  this._mutationKey = null;
255
237
  }
238
+ /**
239
+ * Binds the multiplexed session affinity key to the gax options of an
240
+ * outgoing request, so that all requests of this transaction are routed to
241
+ * the same gRPC channel.
242
+ *
243
+ * `config` is always a request descriptor that was freshly constructed by the
244
+ * caller for this one RPC (and {@link Spanner#prepareGapicRequest_} already
245
+ * modifies `config.headers` in place), so the affinity key is assigned
246
+ * directly instead of allocating a copy of the descriptor per request.
247
+ *
248
+ * @private
249
+ *
250
+ * @param {object} config The request configuration.
251
+ * @returns {object} The same request configuration.
252
+ */
253
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
254
+ _applyAffinityGaxOpts(config) {
255
+ if (!config) {
256
+ return config;
257
+ }
258
+ if (!config.gaxOpts || Object.keys(config.gaxOpts).length === 0) {
259
+ config.gaxOpts = this._bindGaxOpts;
260
+ }
261
+ else {
262
+ config.gaxOpts = injectGaxOpt(config.gaxOpts, 'affinityKey', this._affinityKey);
263
+ }
264
+ return config;
265
+ }
256
266
  _updatePrecommitToken(resp) {
257
267
  if (this._latestPreCommitToken === null ||
258
268
  this._latestPreCommitToken === undefined ||
@@ -362,8 +372,10 @@ class Snapshot extends events_1.EventEmitter {
362
372
  const callback = typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb;
363
373
  const session = this.session.formattedName_;
364
374
  const options = this._options;
365
- if (this.multiplexedSessionPreviousTransactionId &&
366
- this.session.parent.isMuxEnabledForRW_) {
375
+ if (this._options.readWrite) {
376
+ this._inlineBeginStarted = true;
377
+ }
378
+ if (this.multiplexedSessionPreviousTransactionId) {
367
379
  options.readWrite.multiplexedSessionPreviousTransactionId =
368
380
  this.multiplexedSessionPreviousTransactionId;
369
381
  }
@@ -381,12 +393,6 @@ class Snapshot extends events_1.EventEmitter {
381
393
  if (this.requestOptions) {
382
394
  reqOpts.requestOptions = this.requestOptions;
383
395
  }
384
- const headers = this.commonHeaders_;
385
- if (this._getSpanner().routeToLeaderEnabled &&
386
- (this._options.readWrite !== undefined ||
387
- this._options.partitionedDml !== undefined)) {
388
- (0, common_1.addLeaderAwareRoutingHeader)(headers);
389
- }
390
396
  return (0, instrument_1.startTrace)('Snapshot.begin', {
391
397
  transactionTag: this.requestOptions?.transactionTag,
392
398
  ...this._traceConfig,
@@ -397,10 +403,12 @@ class Snapshot extends events_1.EventEmitter {
397
403
  method: 'beginTransaction',
398
404
  reqOpts,
399
405
  gaxOpts,
400
- headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session),
406
+ headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(this.commonHeaders_, this.session),
401
407
  }, (err, resp) => {
402
408
  if (err) {
409
+ this._inlineBeginStarted = false;
403
410
  (0, instrument_1.setSpanError)(span, err);
411
+ this._releaseWaitingRequests(err);
404
412
  }
405
413
  else {
406
414
  this._updatePrecommitToken(resp);
@@ -582,7 +590,9 @@ class Snapshot extends events_1.EventEmitter {
582
590
  * ```
583
591
  */
584
592
  createReadStream(table, request = {}) {
585
- const { gaxOptions, json, jsonOptions, maxResumeRetries, requestOptions, columnsMetadata, } = request;
593
+ const { gaxOptions, json, jsonOptions, maxResumeRetries, requestOptions, columnsMetadata, keys: _omittedKeys, ranges: _omittedRanges, directedReadOptions: rawDirectedReadOptions, ...cleanRequest } = request;
594
+ void _omittedKeys;
595
+ void _omittedRanges;
586
596
  const keySet = Snapshot.encodeKeySet(request);
587
597
  const transaction = {};
588
598
  if (this.id) {
@@ -594,23 +604,11 @@ class Snapshot extends events_1.EventEmitter {
594
604
  else {
595
605
  transaction.singleUse = this._options;
596
606
  }
597
- if (!this.id &&
598
- this._options.readWrite &&
599
- this.session.parent.isMuxEnabledForRW_) {
607
+ if (!this.id && this._options.readWrite) {
600
608
  this._setPreviousTransactionId(transaction);
601
609
  }
602
- const directedReadOptions = this._getDirectedReadOptions(request.directedReadOptions);
603
- request = Object.assign({}, request);
604
- delete request.gaxOptions;
605
- delete request.json;
606
- delete request.jsonOptions;
607
- delete request.maxResumeRetries;
608
- delete request.keys;
609
- delete request.ranges;
610
- delete request.requestOptions;
611
- delete request.directedReadOptions;
612
- delete request.columnsMetadata;
613
- const reqOpts = Object.assign(request, {
610
+ const directedReadOptions = this._getDirectedReadOptions(rawDirectedReadOptions);
611
+ const reqOpts = Object.assign({}, cleanRequest, {
614
612
  session: this.session.formattedName_,
615
613
  requestOptions: this.configureTagOptions(typeof transaction.singleUse !== 'undefined', this.requestOptions?.transactionTag ?? undefined, requestOptions),
616
614
  directedReadOptions: directedReadOptions,
@@ -618,12 +616,6 @@ class Snapshot extends events_1.EventEmitter {
618
616
  table,
619
617
  keySet,
620
618
  });
621
- const headers = this.commonHeaders_;
622
- if (this._getSpanner().routeToLeaderEnabled &&
623
- (this._options.readWrite !== undefined ||
624
- this._options.partitionedDml !== undefined)) {
625
- (0, common_1.addLeaderAwareRoutingHeader)(headers);
626
- }
627
619
  const traceConfig = {
628
620
  ...this._traceConfig,
629
621
  tableName: table,
@@ -659,7 +651,7 @@ class Snapshot extends events_1.EventEmitter {
659
651
  method: 'streamingRead',
660
652
  reqOpts: Object.assign({}, reqOpts, { resumeToken }),
661
653
  gaxOpts: gaxOptions,
662
- headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session, nthRequest, attempt),
654
+ headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(this.commonHeaders_, this.session, nthRequest, attempt),
663
655
  });
664
656
  };
665
657
  const resultStream = (0, partial_result_stream_1.partialResultStream)(this._wrapWithIdWaiter(makeRequest), {
@@ -788,6 +780,8 @@ class Snapshot extends events_1.EventEmitter {
788
780
  return (0, instrument_1.startTrace)('Snapshot.read', {
789
781
  tableName: table,
790
782
  ...this._traceConfig,
783
+ transactionTag: this.requestOptions?.transactionTag,
784
+ requestTag: request?.requestOptions?.requestTag,
791
785
  }, span => {
792
786
  this.createReadStream(table, request)
793
787
  .on('error', err => {
@@ -821,8 +815,9 @@ class Snapshot extends events_1.EventEmitter {
821
815
  let stats;
822
816
  let metadata;
823
817
  (0, instrument_1.startTrace)('Snapshot.run', {
824
- ...query,
825
818
  ...this._traceConfig,
819
+ transactionTag: this.requestOptions?.transactionTag,
820
+ ...(0, instrument_1.getQueryTraceConfig)(query),
826
821
  }, span => {
827
822
  this.runStream(query)
828
823
  .on('error', err => {
@@ -880,9 +875,7 @@ class Snapshot extends events_1.EventEmitter {
880
875
  else {
881
876
  transaction.singleUse = this._options;
882
877
  }
883
- if (!this.id &&
884
- this._options.readWrite &&
885
- this.session.parent.isMuxEnabledForRW_) {
878
+ if (!this.id && this._options.readWrite) {
886
879
  this._setPreviousTransactionId(transaction);
887
880
  }
888
881
  formattedRequest = Object.assign({}, rawQuery, {
@@ -895,17 +888,10 @@ class Snapshot extends events_1.EventEmitter {
895
888
  paramTypes,
896
889
  });
897
890
  };
898
- const headers = Object.assign({}, this.commonHeaders_);
899
- if (this._getSpanner().routeToLeaderEnabled &&
900
- (this._options.readWrite !== undefined ||
901
- this._options.partitionedDml !== undefined)) {
902
- (0, common_1.addLeaderAwareRoutingHeader)(headers);
903
- }
904
891
  const traceConfig = {
905
- transactionTag: this.requestOptions?.transactionTag,
906
- requestTag: requestOptions?.requestTag,
907
- ...query,
908
892
  ...this._traceConfig,
893
+ transactionTag: this.requestOptions?.transactionTag,
894
+ ...(0, instrument_1.getQueryTraceConfig)(queryInput),
909
895
  };
910
896
  const executeWithSpans = (fn) => {
911
897
  const startRunSpan = options?.startRunSpan !== false;
@@ -973,7 +959,7 @@ class Snapshot extends events_1.EventEmitter {
973
959
  return errorStream;
974
960
  }
975
961
  }
976
- const injectedHeaders = (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session, nthRequest, attempt);
962
+ const injectedHeaders = (0, request_id_header_1.injectRequestIDIntoHeaders)(this.commonHeaders_, this.session, nthRequest, attempt);
977
963
  const requestId = injectedHeaders[request_id_header_1.X_GOOG_SPANNER_REQUEST_ID_HEADER];
978
964
  if (runSpan && requestId) {
979
965
  runSpan.setAttribute(request_id_header_1.X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR, requestId);
@@ -1162,11 +1148,11 @@ class Snapshot extends events_1.EventEmitter {
1162
1148
  * @property {object} [gaxOptions] Request configuration options,
1163
1149
  * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions}
1164
1150
  * for more details.
1165
- * @property {number} [maxResumeRetries] The maximum number of times that the
1166
- * stream will retry to push data downstream, when the downstream indicates
1167
- * that it is not ready for any more data. Increase this value if you
1168
- * experience 'Stream is still not ready to receive data' errors as a
1169
- * result of a slow writer in your receiving stream.
1151
+ * @property {number} [maxResumeRetries] The maximum number of times that the
1152
+ * query will retry on retryable errors (such as UNAVAILABLE). Only
1153
+ * applicable to non-streaming queries executed via {@link Snapshot#run}.
1154
+ * For streaming queries ({@link Snapshot#runStream}), this option is
1155
+ * deprecated as backpressure is managed automatically.
1170
1156
  * @property {object} [directedReadOptions]
1171
1157
  * Indicates which replicas or regions should be used for non-transactional reads or queries.
1172
1158
  */
@@ -1230,17 +1216,19 @@ class Snapshot extends events_1.EventEmitter {
1230
1216
  * ```
1231
1217
  */
1232
1218
  runStream(query) {
1233
- if (typeof query === 'string') {
1234
- query = { sql: query };
1235
- }
1236
- query = Object.assign({}, query);
1237
- query.queryOptions = Object.assign(Object.assign({}, this.queryOptions), query.queryOptions);
1238
- const { gaxOptions, json, jsonOptions, maxResumeRetries, requestOptions, columnsMetadata, } = query;
1219
+ const originalQuery = typeof query === 'string' ? { sql: query } : query;
1220
+ const queryOptions = Object.assign({}, this.queryOptions, originalQuery.queryOptions);
1221
+ const { gaxOptions, json, jsonOptions, maxResumeRetries, requestOptions, columnsMetadata, types: _omittedTypes, directedReadOptions: rawDirectedReadOptions, ...cleanQuery } = originalQuery;
1222
+ void _omittedTypes;
1239
1223
  let reqOpts;
1240
- const directedReadOptions = this._getDirectedReadOptions(query.directedReadOptions);
1224
+ const directedReadOptions = this._getDirectedReadOptions(rawDirectedReadOptions);
1225
+ const statementSeqno = this._seqno++;
1226
+ let encodedParams;
1241
1227
  const sanitizeRequest = () => {
1242
- query = query;
1243
- const { params, paramTypes } = Snapshot.encodeParams(query);
1228
+ if (!encodedParams) {
1229
+ encodedParams = Snapshot.encodeParams(originalQuery);
1230
+ }
1231
+ const { params, paramTypes } = encodedParams;
1244
1232
  const transaction = {};
1245
1233
  if (this.id) {
1246
1234
  transaction.id = this.id;
@@ -1251,22 +1239,13 @@ class Snapshot extends events_1.EventEmitter {
1251
1239
  else {
1252
1240
  transaction.singleUse = this._options;
1253
1241
  }
1254
- if (!this.id &&
1255
- this._options.readWrite &&
1256
- this.session.parent.isMuxEnabledForRW_) {
1242
+ if (!this.id && this._options.readWrite) {
1257
1243
  this._setPreviousTransactionId(transaction);
1258
1244
  }
1259
- delete query.gaxOptions;
1260
- delete query.json;
1261
- delete query.jsonOptions;
1262
- delete query.maxResumeRetries;
1263
- delete query.requestOptions;
1264
- delete query.types;
1265
- delete query.directedReadOptions;
1266
- delete query.columnsMetadata;
1267
- reqOpts = Object.assign(query, {
1245
+ reqOpts = Object.assign({}, cleanQuery, {
1268
1246
  session: this.session.formattedName_,
1269
- seqno: this._seqno++,
1247
+ seqno: statementSeqno,
1248
+ queryOptions,
1270
1249
  requestOptions: this.configureTagOptions(typeof transaction.singleUse !== 'undefined', this.requestOptions?.transactionTag ?? undefined, requestOptions),
1271
1250
  directedReadOptions: directedReadOptions,
1272
1251
  transaction,
@@ -1274,17 +1253,10 @@ class Snapshot extends events_1.EventEmitter {
1274
1253
  paramTypes,
1275
1254
  });
1276
1255
  };
1277
- const headers = this.commonHeaders_;
1278
- if (this._getSpanner().routeToLeaderEnabled &&
1279
- (this._options.readWrite !== undefined ||
1280
- this._options.partitionedDml !== undefined)) {
1281
- (0, common_1.addLeaderAwareRoutingHeader)(headers);
1282
- }
1283
1256
  const traceConfig = {
1284
- transactionTag: this.requestOptions?.transactionTag,
1285
- requestTag: requestOptions?.requestTag,
1286
- ...query,
1287
1257
  ...this._traceConfig,
1258
+ transactionTag: this.requestOptions?.transactionTag,
1259
+ ...(0, instrument_1.getQueryTraceConfig)(originalQuery),
1288
1260
  };
1289
1261
  return (0, instrument_1.startTrace)('Snapshot.runStream', traceConfig, span => {
1290
1262
  let attempt = 0;
@@ -1323,7 +1295,7 @@ class Snapshot extends events_1.EventEmitter {
1323
1295
  method: 'executeStreamingSql',
1324
1296
  reqOpts: Object.assign({}, reqOpts, { resumeToken }),
1325
1297
  gaxOpts: gaxOptions,
1326
- headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session, nthRequest, attempt),
1298
+ headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(this.commonHeaders_, this.session, nthRequest, attempt),
1327
1299
  });
1328
1300
  };
1329
1301
  const resultStream = (0, partial_result_stream_1.partialResultStream)(this._wrapWithIdWaiter(makeRequest), {
@@ -1379,9 +1351,9 @@ class Snapshot extends events_1.EventEmitter {
1379
1351
  */
1380
1352
  configureTagOptions(singleUse, transactionTag, requestOptions = {}) {
1381
1353
  if (!singleUse && transactionTag) {
1382
- requestOptions.transactionTag = transactionTag;
1354
+ return Object.assign({}, requestOptions, { transactionTag });
1383
1355
  }
1384
- return requestOptions;
1356
+ return Object.assign({}, requestOptions);
1385
1357
  }
1386
1358
  /**
1387
1359
  * Transforms convenience options `keys` and `ranges` into a KeySet object.
@@ -1393,7 +1365,7 @@ class Snapshot extends events_1.EventEmitter {
1393
1365
  * @returns {object}
1394
1366
  */
1395
1367
  static encodeKeySet(request) {
1396
- const keySet = request.keySet || {};
1368
+ const keySet = Object.assign({}, request.keySet);
1397
1369
  if (request.keys) {
1398
1370
  keySet.keys = (0, helper_1.toArray)(request.keys).map(codec_1.codec.convertToListValue);
1399
1371
  }
@@ -1453,15 +1425,24 @@ class Snapshot extends events_1.EventEmitter {
1453
1425
  * @returns {object}
1454
1426
  */
1455
1427
  static encodeParams(request) {
1456
- const typeMap = request.types || {};
1457
- const params = { fields: request.params?.fields || {} };
1458
- const paramTypes = request.paramTypes || {};
1428
+ if (!request.params && !request.types && !request.paramTypes) {
1429
+ return {
1430
+ params: { fields: {} },
1431
+ paramTypes: {},
1432
+ };
1433
+ }
1434
+ const isUuidUntyped = codec_1.codec.isUuidUntypedEnv();
1435
+ const typeMap = Object.assign({}, request.types);
1436
+ const params = {
1437
+ fields: Object.assign({}, request.params?.fields),
1438
+ };
1439
+ const paramTypes = Object.assign({}, request.paramTypes);
1459
1440
  if (request.params && !request.params.fields) {
1460
1441
  const fields = {};
1461
1442
  Object.keys(request.params).forEach(param => {
1462
1443
  const value = request.params[param];
1463
1444
  if (!typeMap[param]) {
1464
- typeMap[param] = codec_1.codec.getType(value);
1445
+ typeMap[param] = codec_1.codec.getType(value, isUuidUntyped);
1465
1446
  }
1466
1447
  fields[param] = codec_1.codec.encode(value);
1467
1448
  });
@@ -1470,7 +1451,7 @@ class Snapshot extends events_1.EventEmitter {
1470
1451
  if (!(0, helper_1.isEmpty)(typeMap)) {
1471
1452
  Object.keys(typeMap).forEach(param => {
1472
1453
  const type = typeMap[param];
1473
- if (process.env['SPANNER_ENABLE_UUID_AS_UNTYPED'] === 'true') {
1454
+ if (isUuidUntyped) {
1474
1455
  const typeObject = codec_1.codec.createTypeObject(type);
1475
1456
  if ((type.child &&
1476
1457
  typeObject.code === 'ARRAY' &&
@@ -1567,7 +1548,7 @@ class Snapshot extends events_1.EventEmitter {
1567
1548
  * @returns {Spanner}
1568
1549
  */
1569
1550
  _getSpanner() {
1570
- return this.session.parent.parent.parent;
1551
+ return this.session?.parent?.parent?.parent;
1571
1552
  }
1572
1553
  }
1573
1554
  exports.Snapshot = Snapshot;
@@ -1592,10 +1573,9 @@ class Dml extends Snapshot {
1592
1573
  query = { sql: query };
1593
1574
  }
1594
1575
  return (0, instrument_1.startTrace)('Dml.runUpdate', {
1595
- ...query,
1596
1576
  ...this._traceConfig,
1597
1577
  transactionTag: this.requestOptions?.transactionTag,
1598
- requestTag: query.requestOptions?.requestTag,
1578
+ ...(0, instrument_1.getQueryTraceConfig)(query),
1599
1579
  }, span => {
1600
1580
  this.run(query, (err, rows, stats) => {
1601
1581
  let rowCount = 0;
@@ -1715,6 +1695,9 @@ class Transaction extends Dml {
1715
1695
  this._options.isolationLevel = IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED;
1716
1696
  this.requestOptions = requestOptions;
1717
1697
  this._retryCommit = false;
1698
+ if (this._getSpanner()?.routeToLeaderEnabled) {
1699
+ (0, common_1.addLeaderAwareRoutingHeader)(this.commonHeaders_);
1700
+ }
1718
1701
  }
1719
1702
  batchUpdate(queries, optionsOrCallback, cb) {
1720
1703
  const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
@@ -1747,9 +1730,7 @@ class Transaction extends Dml {
1747
1730
  else {
1748
1731
  transaction.begin = this._options;
1749
1732
  }
1750
- if (!this.id &&
1751
- this._options.readWrite &&
1752
- this.session.parent.isMuxEnabledForRW_) {
1733
+ if (!this.id && this._options.readWrite) {
1753
1734
  this._setPreviousTransactionId(transaction);
1754
1735
  }
1755
1736
  const requestOptionsWithTag = this.configureTagOptions(false, this.requestOptions?.transactionTag ?? undefined, options.requestOptions);
@@ -1762,9 +1743,6 @@ class Transaction extends Dml {
1762
1743
  };
1763
1744
  const database = this.session.parent;
1764
1745
  const headers = (0, request_id_header_1.injectRequestIDIntoHeaders)(this.commonHeaders_, this.session, (0, request_id_header_1.nextNthRequest)(database), 1);
1765
- if (this._getSpanner().routeToLeaderEnabled) {
1766
- (0, common_1.addLeaderAwareRoutingHeader)(headers);
1767
- }
1768
1746
  const traceConfig = {
1769
1747
  ...this._traceConfig,
1770
1748
  transactionTag: requestOptionsWithTag?.transactionTag,
@@ -1860,9 +1838,7 @@ class Transaction extends Dml {
1860
1838
  reqOpts.singleUseTransaction = this._options;
1861
1839
  }
1862
1840
  else {
1863
- if (this.session.parent.isMuxEnabledForRW_) {
1864
- this._setMutationKey(mutations);
1865
- }
1841
+ this._setMutationKey(mutations);
1866
1842
  this.begin()
1867
1843
  .then(() => {
1868
1844
  this.commit(options, (err, resp) => {
@@ -1890,10 +1866,6 @@ class Transaction extends Dml {
1890
1866
  reqOpts.maxCommitDelay = options.maxCommitDelay;
1891
1867
  }
1892
1868
  reqOpts.requestOptions = Object.assign(requestOptions || {}, this.requestOptions);
1893
- const headers = this.commonHeaders_;
1894
- if (this._getSpanner().routeToLeaderEnabled) {
1895
- (0, common_1.addLeaderAwareRoutingHeader)(headers);
1896
- }
1897
1869
  span.addEvent('Starting Commit');
1898
1870
  const database = this.session.parent;
1899
1871
  if (this._affinityKey) {
@@ -1909,7 +1881,7 @@ class Transaction extends Dml {
1909
1881
  method: 'commit',
1910
1882
  reqOpts,
1911
1883
  gaxOpts,
1912
- headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session, (0, request_id_header_1.nextNthRequest)(database), 1),
1884
+ headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(this.commonHeaders_, this.session, (0, request_id_header_1.nextNthRequest)(database), 1),
1913
1885
  }, (err, resp) => {
1914
1886
  if (resp &&
1915
1887
  'MultiplexedSessionRetry' in resp &&
@@ -2193,10 +2165,6 @@ class Transaction extends Dml {
2193
2165
  session,
2194
2166
  transactionId,
2195
2167
  };
2196
- const headers = this.commonHeaders_;
2197
- if (this._getSpanner().routeToLeaderEnabled) {
2198
- (0, common_1.addLeaderAwareRoutingHeader)(headers);
2199
- }
2200
2168
  if (this._affinityKey) {
2201
2169
  if (!gaxOpts || Object.keys(gaxOpts).length === 0) {
2202
2170
  gaxOpts = this._unbindGaxOpts;
@@ -2210,7 +2178,7 @@ class Transaction extends Dml {
2210
2178
  method: 'rollback',
2211
2179
  reqOpts,
2212
2180
  gaxOpts,
2213
- headers: headers,
2181
+ headers: { ...this.commonHeaders_ },
2214
2182
  }, (err) => {
2215
2183
  if (err) {
2216
2184
  (0, instrument_1.setSpanError)(span, err);
@@ -2681,6 +2649,9 @@ class PartitionedDml extends Dml {
2681
2649
  constructor(session, options = {}) {
2682
2650
  super(session);
2683
2651
  this._options = { partitionedDml: options };
2652
+ if (this._getSpanner()?.routeToLeaderEnabled) {
2653
+ (0, common_1.addLeaderAwareRoutingHeader)(this.commonHeaders_);
2654
+ }
2684
2655
  }
2685
2656
  /**
2686
2657
  * Use option excludeTxnFromChangeStreams to exclude partitionedDml
@@ -2695,8 +2666,8 @@ class PartitionedDml extends Dml {
2695
2666
  }
2696
2667
  runUpdate(query, callback) {
2697
2668
  return (0, instrument_1.startTrace)('PartitionedDml.runUpdate', {
2698
- ...query,
2699
2669
  ...this._traceConfig,
2670
+ ...(0, instrument_1.getQueryTraceConfig)(query),
2700
2671
  }, span => {
2701
2672
  super.runUpdate(query, (err, count) => {
2702
2673
  if (err) {