@google-cloud/spanner 7.21.0 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +2 -0
  2. package/build/protos/google/spanner/admin/database/v1/backup.proto +1 -1
  3. package/build/protos/google/spanner/admin/database/v1/backup_schedule.proto +1 -1
  4. package/build/protos/google/spanner/admin/database/v1/common.proto +1 -1
  5. package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +36 -1
  6. package/build/protos/google/spanner/admin/instance/v1/common.proto +1 -1
  7. package/build/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto +1 -1
  8. package/build/protos/google/spanner/executor/v1/cloud_executor.proto +1 -1
  9. package/build/protos/google/spanner/v1/change_stream.proto +451 -0
  10. package/build/protos/google/spanner/v1/commit_response.proto +10 -5
  11. package/build/protos/google/spanner/v1/keys.proto +1 -1
  12. package/build/protos/google/spanner/v1/mutation.proto +1 -1
  13. package/build/protos/google/spanner/v1/query_plan.proto +1 -1
  14. package/build/protos/google/spanner/v1/result_set.proto +55 -49
  15. package/build/protos/google/spanner/v1/spanner.proto +1 -1
  16. package/build/protos/google/spanner/v1/transaction.proto +41 -357
  17. package/build/protos/google/spanner/v1/type.proto +1 -1
  18. package/build/protos/protos.d.ts +1577 -194
  19. package/build/protos/protos.js +3977 -288
  20. package/build/protos/protos.json +325 -3
  21. package/build/src/backup.js +7 -0
  22. package/build/src/batch-transaction.d.ts +48 -29
  23. package/build/src/batch-transaction.js +15 -100
  24. package/build/src/codec.js +63 -47
  25. package/build/src/common-grpc/service-object.js +1 -0
  26. package/build/src/common-grpc/service.js +35 -18
  27. package/build/src/common.d.ts +1 -0
  28. package/build/src/common.js +9 -1
  29. package/build/src/database.d.ts +1 -0
  30. package/build/src/database.js +54 -42
  31. package/build/src/helper.d.ts +99 -0
  32. package/build/src/helper.js +178 -0
  33. package/build/src/index.d.ts +33 -0
  34. package/build/src/index.js +202 -21
  35. package/build/src/instance-config.d.ts +1 -1
  36. package/build/src/instance-config.js +4 -0
  37. package/build/src/instance.js +12 -6
  38. package/build/src/instrument.js +5 -6
  39. package/build/src/metrics/constants.d.ts +36 -0
  40. package/build/src/metrics/constants.js +106 -0
  41. package/build/src/metrics/external-types.d.ts +20 -0
  42. package/build/src/metrics/external-types.js +32 -0
  43. package/build/src/metrics/interceptor.d.ts +13 -0
  44. package/build/src/metrics/interceptor.js +87 -0
  45. package/build/src/metrics/metrics-tracer-factory.d.ts +165 -0
  46. package/build/src/metrics/metrics-tracer-factory.js +389 -0
  47. package/build/src/metrics/metrics-tracer.d.ts +204 -0
  48. package/build/src/metrics/metrics-tracer.js +371 -0
  49. package/build/src/metrics/spanner-metrics-exporter.d.ts +35 -0
  50. package/build/src/metrics/spanner-metrics-exporter.js +119 -0
  51. package/build/src/metrics/transform.d.ts +144 -0
  52. package/build/src/metrics/transform.js +272 -0
  53. package/build/src/multiplexed-session.js +7 -1
  54. package/build/src/partial-result-stream.js +18 -10
  55. package/build/src/request_id_header.js +1 -0
  56. package/build/src/session-factory.d.ts +34 -0
  57. package/build/src/session-factory.js +35 -2
  58. package/build/src/session-pool.js +24 -8
  59. package/build/src/session.d.ts +0 -1
  60. package/build/src/session.js +7 -2
  61. package/build/src/table.js +6 -3
  62. package/build/src/transaction-runner.d.ts +1 -0
  63. package/build/src/transaction-runner.js +18 -2
  64. package/build/src/transaction.d.ts +42 -1
  65. package/build/src/transaction.js +258 -94
  66. package/build/src/v1/database_admin_client.d.ts +37 -2
  67. package/build/src/v1/database_admin_client.js +718 -168
  68. package/build/src/v1/database_admin_client_config.json +4 -0
  69. package/build/src/v1/instance_admin_client.d.ts +122 -1
  70. package/build/src/v1/instance_admin_client.js +765 -146
  71. package/build/src/v1/spanner_client.d.ts +2 -1
  72. package/build/src/v1/spanner_client.js +391 -85
  73. package/build/src/v1/spanner_executor_proxy_client.d.ts +2 -1
  74. package/build/src/v1/spanner_executor_proxy_client.js +41 -19
  75. package/build/src/v1/spanner_proto_list.json +1 -0
  76. package/package.json +64 -58
@@ -18,20 +18,18 @@ Object.defineProperty(exports, "__esModule", { value: true });
18
18
  exports.PartitionedDml = exports.MutationGroup = exports.MutationSet = exports.Transaction = exports.Dml = exports.Snapshot = void 0;
19
19
  const precise_date_1 = require("@google-cloud/precise-date");
20
20
  const promisify_1 = require("@google-cloud/promisify");
21
- const arrify = require("arrify");
21
+ const helper_1 = require("./helper");
22
22
  const events_1 = require("events");
23
23
  const google_gax_1 = require("google-gax");
24
- const is = require("is");
25
24
  const stream_1 = require("stream");
26
25
  const codec_1 = require("./codec");
27
26
  const partial_result_stream_1 = require("./partial-result-stream");
28
- const instrument_1 = require("./instrument");
29
27
  const protos_1 = require("../protos/protos");
30
28
  const common_1 = require("./common");
31
29
  const protos_2 = require("../protos/protos");
32
30
  var IsolationLevel = protos_2.google.spanner.v1.TransactionOptions.IsolationLevel;
33
31
  var ReadLockMode = protos_2.google.spanner.v1.TransactionOptions.ReadWrite.ReadLockMode;
34
- const instrument_2 = require("./instrument");
32
+ const instrument_1 = require("./instrument");
35
33
  const request_id_header_1 = require("./request_id_header");
36
34
  const RETRY_INFO_TYPE = 'type.googleapis.com/google.rpc.retryinfo';
37
35
  const RETRY_INFO_BIN = 'google.rpc.retryinfo-bin';
@@ -90,6 +88,28 @@ const RETRY_INFO_BIN = 'google.rpc.retryinfo-bin';
90
88
  * ```
91
89
  */
92
90
  class Snapshot extends events_1.EventEmitter {
91
+ _options;
92
+ _seqno = 1;
93
+ _waitingRequests;
94
+ _inlineBeginStarted;
95
+ _useInRunner = false;
96
+ _latestPreCommitToken;
97
+ id;
98
+ multiplexedSessionPreviousTransactionId;
99
+ ended;
100
+ metadata;
101
+ readTimestamp;
102
+ readTimestampProto;
103
+ request;
104
+ requestStream;
105
+ session;
106
+ queryOptions;
107
+ commonHeaders_;
108
+ requestOptions;
109
+ _observabilityOptions;
110
+ _traceConfig;
111
+ _dbName;
112
+ _mutationKey;
93
113
  /**
94
114
  * The transaction ID.
95
115
  *
@@ -134,10 +154,7 @@ class Snapshot extends events_1.EventEmitter {
134
154
  * are specified for a query.
135
155
  */
136
156
  constructor(session, options, queryOptions) {
137
- var _a;
138
157
  super();
139
- this._seqno = 1;
140
- this._useInRunner = false;
141
158
  this.ended = false;
142
159
  this.session = session;
143
160
  this.queryOptions = Object.assign({}, queryOptions);
@@ -149,22 +166,134 @@ class Snapshot extends events_1.EventEmitter {
149
166
  this._waitingRequests = [];
150
167
  this._inlineBeginStarted = false;
151
168
  this._observabilityOptions = session._observabilityOptions;
152
- this.commonHeaders_ = (0, common_1.getCommonHeaders)(this._dbName, (_a = this._observabilityOptions) === null || _a === void 0 ? void 0 : _a.enableEndToEndTracing);
169
+ this.commonHeaders_ = (0, common_1.getCommonHeaders)(this._dbName, this._observabilityOptions?.enableEndToEndTracing);
153
170
  this._traceConfig = {
154
171
  opts: this._observabilityOptions,
155
172
  dbName: this._dbName,
156
173
  };
174
+ this._latestPreCommitToken = null;
175
+ this._mutationKey = null;
176
+ }
177
+ _updatePrecommitToken(resp) {
178
+ if (this._latestPreCommitToken === null ||
179
+ this._latestPreCommitToken === undefined ||
180
+ this._latestPreCommitToken.seqNum < resp.precommitToken.seqNum) {
181
+ this._latestPreCommitToken = resp.precommitToken;
182
+ }
183
+ }
184
+ /**
185
+ * Selects a single representative mutation from a list to be used as the
186
+ * transaction's `mutationKey`.
187
+ *
188
+ * This key is required by Spanner and is sent in the `BeginTransactionRequest`
189
+ * for read-write transactions that only contain mutations. The selection follows
190
+ * a two-tiered heuristic to choose the most significant mutation.
191
+ *
192
+ * The selection heuristic is as follows:
193
+ *
194
+ * 1. Priority of Operation Type: High-priority mutations (`delete`, `update`,
195
+ * `replace`, `insertOrUpdate`) are always chosen over low-priority
196
+ * (`insert`) mutations.
197
+ *
198
+ * 2. Selection Strategy:
199
+ * - If any high-priority mutations exist, one is chosen randomly from
200
+ * that group, ignoring the number of rows.
201
+ * - If only `insert` mutations exist, the one(s) with the largest number
202
+ * of rows are identified, and one is chosen randomly from that subset.
203
+ *
204
+ * @protected
205
+ * @param mutations The list of mutations from which to select the key.
206
+ */
207
+ _setMutationKey(mutations) {
208
+ // return if the list is empty
209
+ if (mutations.length === 0) {
210
+ return;
211
+ }
212
+ // maintain a set of high priority keys
213
+ const HIGH_PRIORITY_KEYS = new Set([
214
+ 'delete',
215
+ 'update',
216
+ 'replace',
217
+ 'insertOrUpdate',
218
+ ]);
219
+ // maintain a variable for low priority key
220
+ const LOW_PRIORITY_KEY = 'insert';
221
+ // Partition mutations into high and low priority groups.
222
+ const [highPriority, lowPriority] = mutations.reduce((acc, mutation) => {
223
+ const key = Object.keys(mutation)[0];
224
+ if (HIGH_PRIORITY_KEYS.has(key)) {
225
+ acc[0].push(mutation);
226
+ }
227
+ else if (key === LOW_PRIORITY_KEY) {
228
+ acc[1].push(mutation);
229
+ }
230
+ // return accumulated mutations list
231
+ return acc;
232
+ }, [[], []]);
233
+ // Apply the selection logic based on the rules.
234
+ if (highPriority.length > 0) {
235
+ // RULE 1: If high-priority keys exist, pick one randomly.
236
+ const randomIndex = Math.floor(Math.random() * highPriority.length);
237
+ this._mutationKey = highPriority[randomIndex];
238
+ }
239
+ else if (lowPriority.length > 0) {
240
+ // RULE 2: If only 'insert' key(s) exist, find the one with
241
+ // highest number of values
242
+ const { bestCandidates } = lowPriority.reduce((acc, mutation) => {
243
+ const size = mutation.insert?.values?.length || 0;
244
+ if (size > acc.maxSize) {
245
+ // New largest size found, start a new list
246
+ return { maxSize: size, bestCandidates: [mutation] };
247
+ }
248
+ if (size === acc.maxSize) {
249
+ // Same size as current max, add to list
250
+ acc.bestCandidates.push(mutation);
251
+ }
252
+ // return accumulated mutations list
253
+ return acc;
254
+ }, {
255
+ maxSize: -1,
256
+ bestCandidates: [],
257
+ });
258
+ // Pick randomly from the largest 'insert' mutation(s).
259
+ const randomIndex = Math.floor(Math.random() * bestCandidates.length);
260
+ this._mutationKey = bestCandidates[randomIndex];
261
+ }
262
+ else {
263
+ // No mutations to select from.
264
+ this._mutationKey = null;
265
+ }
266
+ }
267
+ /**
268
+ * Modifies transaction selector to include the multiplexed session previous
269
+ * transaction id.
270
+ * This is essential for operations that use an `inline begin`.
271
+ * @protected
272
+ * @param transaction The transaction selector object that will be mutated
273
+ * to include the multiplexed session previous transaction id.
274
+ */
275
+ _setPreviousTransactionId(transaction) {
276
+ transaction.begin.readWrite = Object.assign({}, transaction.begin.readWrite || {}, {
277
+ multiplexedSessionPreviousTransactionId: this.multiplexedSessionPreviousTransactionId,
278
+ });
157
279
  }
158
280
  begin(gaxOptionsOrCallback, cb) {
159
- var _a;
160
281
  const gaxOpts = typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {};
161
282
  const callback = typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb;
162
283
  const session = this.session.formattedName_;
163
284
  const options = this._options;
285
+ if (this.multiplexedSessionPreviousTransactionId &&
286
+ this.session.parent.isMuxEnabledForRW_) {
287
+ options.readWrite.multiplexedSessionPreviousTransactionId =
288
+ this.multiplexedSessionPreviousTransactionId;
289
+ }
164
290
  const reqOpts = {
165
291
  session,
166
292
  options,
167
293
  };
294
+ if (this._mutationKey) {
295
+ reqOpts.mutationKey = this._mutationKey;
296
+ }
168
297
  // Only hand crafted read-write transactions will be able to set a
169
298
  // transaction tag for the BeginTransaction RPC. Also, this.requestOptions
170
299
  // is only set in the constructor of Transaction, which is the constructor
@@ -178,8 +307,8 @@ class Snapshot extends events_1.EventEmitter {
178
307
  this._options.partitionedDml !== undefined)) {
179
308
  (0, common_1.addLeaderAwareRoutingHeader)(headers);
180
309
  }
181
- return (0, instrument_2.startTrace)('Snapshot.begin', {
182
- transactionTag: (_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag,
310
+ return (0, instrument_1.startTrace)('Snapshot.begin', {
311
+ transactionTag: this.requestOptions?.transactionTag,
183
312
  ...this._traceConfig,
184
313
  }, span => {
185
314
  span.addEvent('Begin Transaction');
@@ -191,10 +320,11 @@ class Snapshot extends events_1.EventEmitter {
191
320
  headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session),
192
321
  }, (err, resp) => {
193
322
  if (err) {
194
- (0, instrument_2.setSpanError)(span, err);
323
+ (0, instrument_1.setSpanError)(span, err);
195
324
  }
196
325
  else {
197
- this._update(resp);
326
+ this._updatePrecommitToken(resp);
327
+ this._update(resp, span);
198
328
  }
199
329
  span.end();
200
330
  callback(err, resp);
@@ -372,7 +502,6 @@ class Snapshot extends events_1.EventEmitter {
372
502
  * ```
373
503
  */
374
504
  createReadStream(table, request = {}) {
375
- var _a, _b, _c;
376
505
  const { gaxOptions, json, jsonOptions, maxResumeRetries, requestOptions, columnsMetadata, } = request;
377
506
  const keySet = Snapshot.encodeKeySet(request);
378
507
  const transaction = {};
@@ -385,6 +514,11 @@ class Snapshot extends events_1.EventEmitter {
385
514
  else {
386
515
  transaction.singleUse = this._options;
387
516
  }
517
+ if (!this.id &&
518
+ this._options.readWrite &&
519
+ this.session.parent.isMuxEnabledForRW_) {
520
+ this._setPreviousTransactionId(transaction);
521
+ }
388
522
  const directedReadOptions = this._getDirectedReadOptions(request.directedReadOptions);
389
523
  request = Object.assign({}, request);
390
524
  delete request.gaxOptions;
@@ -398,7 +532,7 @@ class Snapshot extends events_1.EventEmitter {
398
532
  delete request.columnsMetadata;
399
533
  const reqOpts = Object.assign(request, {
400
534
  session: this.session.formattedName_,
401
- requestOptions: this.configureTagOptions(typeof transaction.singleUse !== 'undefined', (_b = (_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag) !== null && _b !== void 0 ? _b : undefined, requestOptions),
535
+ requestOptions: this.configureTagOptions(typeof transaction.singleUse !== 'undefined', this.requestOptions?.transactionTag ?? undefined, requestOptions),
402
536
  directedReadOptions: directedReadOptions,
403
537
  transaction,
404
538
  table,
@@ -413,11 +547,10 @@ class Snapshot extends events_1.EventEmitter {
413
547
  const traceConfig = {
414
548
  ...this._traceConfig,
415
549
  tableName: table,
416
- transactionTag: (_c = this.requestOptions) === null || _c === void 0 ? void 0 : _c.transactionTag,
417
- requestTag: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.requestTag,
550
+ transactionTag: this.requestOptions?.transactionTag,
551
+ requestTag: requestOptions?.requestTag,
418
552
  };
419
- return (0, instrument_2.startTrace)('Snapshot.createReadStream', traceConfig, span => {
420
- var _a;
553
+ return (0, instrument_1.startTrace)('Snapshot.createReadStream', traceConfig, span => {
421
554
  let attempt = 0;
422
555
  const database = this.session.parent;
423
556
  const nthRequest = (0, request_id_header_1.nextNthRequest)(database);
@@ -449,42 +582,45 @@ class Snapshot extends events_1.EventEmitter {
449
582
  headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session, nthRequest, attempt),
450
583
  });
451
584
  };
452
- const resultStream = (_a = (0, partial_result_stream_1.partialResultStream)(this._wrapWithIdWaiter(makeRequest), {
585
+ const resultStream = (0, partial_result_stream_1.partialResultStream)(this._wrapWithIdWaiter(makeRequest), {
453
586
  json,
454
587
  jsonOptions,
455
588
  maxResumeRetries,
456
589
  columnsMetadata,
457
590
  gaxOptions,
458
- })) === null || _a === void 0 ? void 0 : _a.on('response', response => {
591
+ })
592
+ ?.on('response', response => {
593
+ this._updatePrecommitToken(response);
459
594
  if (response.metadata && response.metadata.transaction && !this.id) {
460
- this._update(response.metadata.transaction);
595
+ this._update(response.metadata.transaction, span);
461
596
  }
462
- }).on('error', err => {
463
- var _a;
464
- (0, instrument_2.setSpanError)(span, err);
597
+ })
598
+ .on('error', err => {
599
+ (0, instrument_1.setSpanError)(span, err);
465
600
  const wasAborted = isErrorAborted(err);
466
601
  if (!this.id && this._useInRunner && !wasAborted) {
467
602
  // TODO: resolve https://github.com/googleapis/nodejs-spanner/issues/2170
468
- this.begin();
603
+ void this.begin();
469
604
  }
470
605
  else {
471
606
  if (wasAborted) {
472
607
  span.addEvent('Stream broken. Not safe to retry', {
473
- 'transaction.id': (_a = this.id) === null || _a === void 0 ? void 0 : _a.toString(),
608
+ 'transaction.id': this.id?.toString(),
474
609
  });
475
610
  }
476
611
  }
477
612
  span.end();
478
- }).on('end', err => {
613
+ })
614
+ .on('end', err => {
479
615
  if (err) {
480
- (0, instrument_2.setSpanError)(span, err);
616
+ (0, instrument_1.setSpanError)(span, err);
481
617
  }
482
618
  span.end();
483
619
  });
484
620
  if (resultStream instanceof stream_1.Stream) {
485
621
  (0, stream_1.finished)(resultStream, err => {
486
622
  if (err) {
487
- (0, instrument_2.setSpanError)(span, err);
623
+ (0, instrument_1.setSpanError)(span, err);
488
624
  }
489
625
  span.end();
490
626
  });
@@ -556,14 +692,14 @@ class Snapshot extends events_1.EventEmitter {
556
692
  request = requestOrCallback;
557
693
  callback = cb;
558
694
  }
559
- return (0, instrument_2.startTrace)('Snapshot.read', {
695
+ return (0, instrument_1.startTrace)('Snapshot.read', {
560
696
  tableName: table,
561
697
  ...this._traceConfig,
562
698
  }, span => {
563
699
  this.createReadStream(table, request)
564
700
  .on('error', err => {
565
701
  const e = err;
566
- (0, instrument_2.setSpanError)(span, e);
702
+ (0, instrument_1.setSpanError)(span, e);
567
703
  span.end();
568
704
  callback(e, null);
569
705
  })
@@ -578,13 +714,13 @@ class Snapshot extends events_1.EventEmitter {
578
714
  const rows = [];
579
715
  let stats;
580
716
  let metadata;
581
- (0, instrument_2.startTrace)('Snapshot.run', {
717
+ (0, instrument_1.startTrace)('Snapshot.run', {
582
718
  ...query,
583
719
  ...this._traceConfig,
584
720
  }, span => {
585
721
  return this.runStream(query)
586
722
  .on('error', (err, rows, stats, metadata) => {
587
- (0, instrument_2.setSpanError)(span, err);
723
+ (0, instrument_1.setSpanError)(span, err);
588
724
  span.end();
589
725
  callback(err, rows, stats, metadata);
590
726
  })
@@ -592,7 +728,7 @@ class Snapshot extends events_1.EventEmitter {
592
728
  if (response.metadata) {
593
729
  metadata = response.metadata;
594
730
  if (metadata.transaction && !this.id) {
595
- this._update(metadata.transaction);
731
+ this._update(metadata.transaction, span);
596
732
  }
597
733
  }
598
734
  })
@@ -704,7 +840,6 @@ class Snapshot extends events_1.EventEmitter {
704
840
  * ```
705
841
  */
706
842
  runStream(query) {
707
- var _a;
708
843
  if (typeof query === 'string') {
709
844
  query = { sql: query };
710
845
  }
@@ -714,7 +849,6 @@ class Snapshot extends events_1.EventEmitter {
714
849
  let reqOpts;
715
850
  const directedReadOptions = this._getDirectedReadOptions(query.directedReadOptions);
716
851
  const sanitizeRequest = () => {
717
- var _a, _b;
718
852
  query = query;
719
853
  const { params, paramTypes } = Snapshot.encodeParams(query);
720
854
  const transaction = {};
@@ -727,6 +861,11 @@ class Snapshot extends events_1.EventEmitter {
727
861
  else {
728
862
  transaction.singleUse = this._options;
729
863
  }
864
+ if (!this.id &&
865
+ this._options.readWrite &&
866
+ this.session.parent.isMuxEnabledForRW_) {
867
+ this._setPreviousTransactionId(transaction);
868
+ }
730
869
  delete query.gaxOptions;
731
870
  delete query.json;
732
871
  delete query.jsonOptions;
@@ -738,7 +877,7 @@ class Snapshot extends events_1.EventEmitter {
738
877
  reqOpts = Object.assign(query, {
739
878
  session: this.session.formattedName_,
740
879
  seqno: this._seqno++,
741
- requestOptions: this.configureTagOptions(typeof transaction.singleUse !== 'undefined', (_b = (_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag) !== null && _b !== void 0 ? _b : undefined, requestOptions),
880
+ requestOptions: this.configureTagOptions(typeof transaction.singleUse !== 'undefined', this.requestOptions?.transactionTag ?? undefined, requestOptions),
742
881
  directedReadOptions: directedReadOptions,
743
882
  transaction,
744
883
  params,
@@ -752,12 +891,12 @@ class Snapshot extends events_1.EventEmitter {
752
891
  (0, common_1.addLeaderAwareRoutingHeader)(headers);
753
892
  }
754
893
  const traceConfig = {
755
- transactionTag: (_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag,
756
- requestTag: requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.requestTag,
894
+ transactionTag: this.requestOptions?.transactionTag,
895
+ requestTag: requestOptions?.requestTag,
757
896
  ...query,
758
897
  ...this._traceConfig,
759
898
  };
760
- return (0, instrument_2.startTrace)('Snapshot.runStream', traceConfig, span => {
899
+ return (0, instrument_1.startTrace)('Snapshot.runStream', traceConfig, span => {
761
900
  let attempt = 0;
762
901
  const database = this.session.parent;
763
902
  const nthRequest = (0, request_id_header_1.nextNthRequest)(database);
@@ -783,7 +922,7 @@ class Snapshot extends events_1.EventEmitter {
783
922
  }
784
923
  catch (e) {
785
924
  const errorStream = new stream_1.PassThrough();
786
- (0, instrument_2.setSpanErrorAndException)(span, e);
925
+ (0, instrument_1.setSpanErrorAndException)(span, e);
787
926
  span.end();
788
927
  setImmediate(() => errorStream.destroy(e));
789
928
  return errorStream;
@@ -805,23 +944,23 @@ class Snapshot extends events_1.EventEmitter {
805
944
  gaxOptions,
806
945
  })
807
946
  .on('response', response => {
947
+ this._updatePrecommitToken(response);
808
948
  if (response.metadata && response.metadata.transaction && !this.id) {
809
- this._update(response.metadata.transaction);
949
+ this._update(response.metadata.transaction, span);
810
950
  }
811
951
  })
812
952
  .on('error', err => {
813
- var _a;
814
- (0, instrument_2.setSpanError)(span, err);
953
+ (0, instrument_1.setSpanError)(span, err);
815
954
  const wasAborted = isErrorAborted(err);
816
955
  if (!this.id && this._useInRunner && !wasAborted) {
817
956
  span.addEvent('Stream broken. Safe to retry');
818
957
  // TODO: resolve https://github.com/googleapis/nodejs-spanner/issues/2170
819
- this.begin();
958
+ void this.begin();
820
959
  }
821
960
  else {
822
961
  if (wasAborted) {
823
962
  span.addEvent('Stream broken. Not safe to retry', {
824
- 'transaction.id': (_a = this.id) === null || _a === void 0 ? void 0 : _a.toString(),
963
+ 'transaction.id': this.id?.toString(),
825
964
  });
826
965
  }
827
966
  }
@@ -829,14 +968,14 @@ class Snapshot extends events_1.EventEmitter {
829
968
  })
830
969
  .on('end', err => {
831
970
  if (err) {
832
- (0, instrument_2.setSpanError)(span, err);
971
+ (0, instrument_1.setSpanError)(span, err);
833
972
  }
834
973
  span.end();
835
974
  });
836
975
  if (resultStream instanceof stream_1.Stream) {
837
976
  (0, stream_1.finished)(resultStream, err => {
838
977
  if (err) {
839
- (0, instrument_2.setSpanError)(span, err);
978
+ (0, instrument_1.setSpanError)(span, err);
840
979
  }
841
980
  span.end();
842
981
  });
@@ -866,10 +1005,10 @@ class Snapshot extends events_1.EventEmitter {
866
1005
  static encodeKeySet(request) {
867
1006
  const keySet = request.keySet || {};
868
1007
  if (request.keys) {
869
- keySet.keys = arrify(request.keys).map(codec_1.codec.convertToListValue);
1008
+ keySet.keys = (0, helper_1.toArray)(request.keys).map(codec_1.codec.convertToListValue);
870
1009
  }
871
1010
  if (request.ranges) {
872
- keySet.ranges = arrify(request.ranges).map(range => {
1011
+ keySet.ranges = (0, helper_1.toArray)(request.ranges).map(range => {
873
1012
  const encodedRange = {};
874
1013
  Object.keys(range).forEach(bound => {
875
1014
  encodedRange[bound] = codec_1.codec.convertToListValue(range[bound]);
@@ -877,7 +1016,7 @@ class Snapshot extends events_1.EventEmitter {
877
1016
  return encodedRange;
878
1017
  });
879
1018
  }
880
- if (is.empty(keySet)) {
1019
+ if ((0, helper_1.isEmpty)(keySet)) {
881
1020
  keySet.all = true;
882
1021
  }
883
1022
  return keySet;
@@ -908,7 +1047,7 @@ class Snapshot extends events_1.EventEmitter {
908
1047
  }
909
1048
  // If we didn't detect a convenience format, we'll just assume that
910
1049
  // they passed in a protobuf timestamp.
911
- if (is.empty(readOnly)) {
1050
+ if ((0, helper_1.isEmpty)(readOnly)) {
912
1051
  Object.assign(readOnly, options);
913
1052
  }
914
1053
  readOnly.returnReadTimestamp = returnReadTimestamp;
@@ -924,9 +1063,8 @@ class Snapshot extends events_1.EventEmitter {
924
1063
  * @returns {object}
925
1064
  */
926
1065
  static encodeParams(request) {
927
- var _a;
928
1066
  const typeMap = request.types || {};
929
- const params = { fields: ((_a = request.params) === null || _a === void 0 ? void 0 : _a.fields) || {} };
1067
+ const params = { fields: request.params?.fields || {} };
930
1068
  const paramTypes = request.paramTypes || {};
931
1069
  if (request.params && !request.params.fields) {
932
1070
  const fields = {};
@@ -939,7 +1077,7 @@ class Snapshot extends events_1.EventEmitter {
939
1077
  });
940
1078
  params.fields = fields;
941
1079
  }
942
- if (!is.empty(typeMap)) {
1080
+ if (!(0, helper_1.isEmpty)(typeMap)) {
943
1081
  Object.keys(typeMap).forEach(param => {
944
1082
  const type = typeMap[param];
945
1083
  paramTypes[param] = codec_1.codec.createTypeObject(type);
@@ -967,11 +1105,10 @@ class Snapshot extends events_1.EventEmitter {
967
1105
  *
968
1106
  * @param {spannerClient.spanner.v1.ITransaction} resp Response object.
969
1107
  */
970
- _update(resp) {
1108
+ _update(resp, span) {
971
1109
  const { id, readTimestamp } = resp;
972
1110
  this.id = id;
973
1111
  this.metadata = resp;
974
- const span = (0, instrument_1.getActiveOrNoopSpan)();
975
1112
  span.addEvent('Transaction Creation Done', { id: this.id.toString() });
976
1113
  if (readTimestamp) {
977
1114
  this.readTimestampProto = readTimestamp;
@@ -1011,7 +1148,7 @@ class Snapshot extends events_1.EventEmitter {
1011
1148
  _releaseWaitingRequests() {
1012
1149
  while (this._waitingRequests.length > 0) {
1013
1150
  const request = this._waitingRequests.shift();
1014
- request === null || request === void 0 ? void 0 : request();
1151
+ request?.();
1015
1152
  }
1016
1153
  }
1017
1154
  /**
@@ -1043,15 +1180,14 @@ exports.Snapshot = Snapshot;
1043
1180
  */
1044
1181
  class Dml extends Snapshot {
1045
1182
  runUpdate(query, callback) {
1046
- var _a, _b;
1047
1183
  if (typeof query === 'string') {
1048
1184
  query = { sql: query };
1049
1185
  }
1050
- return (0, instrument_2.startTrace)('Dml.runUpdate', {
1186
+ return (0, instrument_1.startTrace)('Dml.runUpdate', {
1051
1187
  ...query,
1052
1188
  ...this._traceConfig,
1053
- transactionTag: (_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag,
1054
- requestTag: (_b = query.requestOptions) === null || _b === void 0 ? void 0 : _b.requestTag,
1189
+ transactionTag: this.requestOptions?.transactionTag,
1190
+ requestTag: query.requestOptions?.requestTag,
1055
1191
  }, span => {
1056
1192
  this.run(query, (err, rows, stats) => {
1057
1193
  let rowCount = 0;
@@ -1059,7 +1195,7 @@ class Dml extends Snapshot {
1059
1195
  rowCount = Math.floor(stats[stats.rowCount]);
1060
1196
  }
1061
1197
  if (err) {
1062
- (0, instrument_2.setSpanError)(span, err);
1198
+ (0, instrument_1.setSpanError)(span, err);
1063
1199
  }
1064
1200
  span.end();
1065
1201
  callback(err, rowCount);
@@ -1120,6 +1256,10 @@ exports.Dml = Dml;
1120
1256
  * ```
1121
1257
  */
1122
1258
  class Transaction extends Dml {
1259
+ commitTimestamp;
1260
+ commitTimestampProto;
1261
+ _queuedMutations;
1262
+ _retryCommit;
1123
1263
  /**
1124
1264
  * Timestamp at which the transaction was committed. Will be populated once
1125
1265
  * {@link Transaction#commit} is called.
@@ -1166,9 +1306,9 @@ class Transaction extends Dml {
1166
1306
  this._options = { readWrite: options };
1167
1307
  this._options.isolationLevel = IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED;
1168
1308
  this.requestOptions = requestOptions;
1309
+ this._retryCommit = false;
1169
1310
  }
1170
1311
  batchUpdate(queries, optionsOrCallback, cb) {
1171
- var _a, _b, _c;
1172
1312
  const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
1173
1313
  const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
1174
1314
  const gaxOpts = 'gaxOptions' in options
@@ -1199,7 +1339,12 @@ class Transaction extends Dml {
1199
1339
  else {
1200
1340
  transaction.begin = this._options;
1201
1341
  }
1202
- const requestOptionsWithTag = this.configureTagOptions(false, (_b = (_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag) !== null && _b !== void 0 ? _b : undefined, options.requestOptions);
1342
+ if (!this.id &&
1343
+ this._options.readWrite &&
1344
+ this.session.parent.isMuxEnabledForRW_) {
1345
+ this._setPreviousTransactionId(transaction);
1346
+ }
1347
+ const requestOptionsWithTag = this.configureTagOptions(false, this.requestOptions?.transactionTag ?? undefined, options.requestOptions);
1203
1348
  const reqOpts = {
1204
1349
  session: this.session.formattedName_,
1205
1350
  requestOptions: requestOptionsWithTag,
@@ -1214,10 +1359,10 @@ class Transaction extends Dml {
1214
1359
  }
1215
1360
  const traceConfig = {
1216
1361
  ...this._traceConfig,
1217
- transactionTag: requestOptionsWithTag === null || requestOptionsWithTag === void 0 ? void 0 : requestOptionsWithTag.transactionTag,
1218
- requestTag: (_c = options === null || options === void 0 ? void 0 : options.requestOptions) === null || _c === void 0 ? void 0 : _c.requestTag,
1362
+ transactionTag: requestOptionsWithTag?.transactionTag,
1363
+ requestTag: options?.requestOptions?.requestTag,
1219
1364
  };
1220
- return (0, instrument_2.startTrace)('Transaction.batchUpdate', traceConfig, span => {
1365
+ return (0, instrument_1.startTrace)('Transaction.batchUpdate', traceConfig, span => {
1221
1366
  this.request({
1222
1367
  client: 'SpannerClient',
1223
1368
  method: 'executeBatchDml',
@@ -1225,20 +1370,20 @@ class Transaction extends Dml {
1225
1370
  gaxOpts,
1226
1371
  headers: headers,
1227
1372
  }, (err, resp) => {
1228
- var _a;
1229
1373
  let batchUpdateError;
1230
1374
  if (err) {
1231
1375
  const rowCounts = [];
1232
1376
  batchUpdateError = Object.assign(err, { rowCounts });
1233
- (0, instrument_2.setSpanError)(span, batchUpdateError);
1377
+ (0, instrument_1.setSpanError)(span, batchUpdateError);
1234
1378
  span.end();
1235
1379
  callback(batchUpdateError, rowCounts, resp);
1236
1380
  return;
1237
1381
  }
1382
+ this._updatePrecommitToken(resp);
1238
1383
  const { resultSets, status } = resp;
1239
1384
  for (const resultSet of resultSets) {
1240
- if (!this.id && ((_a = resultSet.metadata) === null || _a === void 0 ? void 0 : _a.transaction)) {
1241
- this._update(resultSet.metadata.transaction);
1385
+ if (!this.id && resultSet.metadata?.transaction) {
1386
+ this._update(resultSet.metadata.transaction, span);
1242
1387
  }
1243
1388
  }
1244
1389
  const rowCounts = resultSets.map(({ stats }) => {
@@ -1253,7 +1398,7 @@ class Transaction extends Dml {
1253
1398
  metadata: Transaction.extractKnownMetadata(status.details),
1254
1399
  rowCounts,
1255
1400
  });
1256
- (0, instrument_2.setSpanError)(span, batchUpdateError);
1401
+ (0, instrument_1.setSpanError)(span, batchUpdateError);
1257
1402
  }
1258
1403
  span.end();
1259
1404
  callback(batchUpdateError, rowCounts, resp);
@@ -1283,16 +1428,21 @@ class Transaction extends Dml {
1283
1428
  this._queuedMutations = mutation;
1284
1429
  }
1285
1430
  commit(optionsOrCallback, cb) {
1286
- var _a;
1287
1431
  const options = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
1288
1432
  const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
1289
1433
  const gaxOpts = 'gaxOptions' in options ? options.gaxOptions : options;
1290
1434
  const mutations = this._queuedMutations;
1291
1435
  const session = this.session.formattedName_;
1436
+ const precommitToken = this._latestPreCommitToken;
1292
1437
  const requestOptions = options.requestOptions;
1293
- const reqOpts = { mutations, session, requestOptions };
1294
- return (0, instrument_2.startTrace)('Transaction.commit', {
1295
- transactionTag: (_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag,
1438
+ const reqOpts = {
1439
+ mutations,
1440
+ session,
1441
+ requestOptions,
1442
+ precommitToken,
1443
+ };
1444
+ return (0, instrument_1.startTrace)('Transaction.commit', {
1445
+ transactionTag: this.requestOptions?.transactionTag,
1296
1446
  ...this._traceConfig,
1297
1447
  }, span => {
1298
1448
  if (this.id) {
@@ -1302,16 +1452,19 @@ class Transaction extends Dml {
1302
1452
  reqOpts.singleUseTransaction = this._options;
1303
1453
  }
1304
1454
  else {
1455
+ if (this.session.parent.isMuxEnabledForRW_) {
1456
+ this._setMutationKey(mutations);
1457
+ }
1305
1458
  this.begin().then(() => {
1306
1459
  this.commit(options, (err, resp) => {
1307
1460
  if (err) {
1308
- (0, instrument_2.setSpanError)(span, err);
1461
+ (0, instrument_1.setSpanError)(span, err);
1309
1462
  }
1310
1463
  span.end();
1311
1464
  callback(err, resp);
1312
1465
  });
1313
1466
  }, err => {
1314
- (0, instrument_2.setSpanError)(span, err);
1467
+ (0, instrument_1.setSpanError)(span, err);
1315
1468
  span.end();
1316
1469
  callback(err, null);
1317
1470
  });
@@ -1339,10 +1492,17 @@ class Transaction extends Dml {
1339
1492
  gaxOpts: gaxOpts,
1340
1493
  headers: (0, request_id_header_1.injectRequestIDIntoHeaders)(headers, this.session, (0, request_id_header_1.nextNthRequest)(database), 1),
1341
1494
  }, (err, resp) => {
1495
+ if (resp &&
1496
+ 'MultiplexedSessionRetry' in resp &&
1497
+ !this._retryCommit) {
1498
+ this._retryCommit = true;
1499
+ this._updatePrecommitToken(resp);
1500
+ return this.commit(options, callback);
1501
+ }
1342
1502
  this.end();
1343
1503
  if (err) {
1344
1504
  span.addEvent('Commit failed');
1345
- (0, instrument_2.setSpanError)(span, err);
1505
+ (0, instrument_1.setSpanError)(span, err);
1346
1506
  }
1347
1507
  else {
1348
1508
  span.addEvent('Commit Done');
@@ -1388,7 +1548,6 @@ class Transaction extends Dml {
1388
1548
  * @private
1389
1549
  */
1390
1550
  static decoratePossibleJsonMismatchError(err, mutations) {
1391
- var _a, _b;
1392
1551
  const errorMessage = /Invalid value for column (?<column>.+) in table (?<table>.+): Expected JSON./;
1393
1552
  const found = err.message && err.message.match(errorMessage);
1394
1553
  if (found && found.groups) {
@@ -1400,10 +1559,10 @@ class Transaction extends Dml {
1400
1559
  mutation.insertOrUpdate ||
1401
1560
  mutation.replace;
1402
1561
  if (write && write.table === table) {
1403
- const index = (_a = write.columns) === null || _a === void 0 ? void 0 : _a.indexOf(column);
1562
+ const index = write.columns?.indexOf(column);
1404
1563
  if (index && index > -1 && write.values) {
1405
1564
  for (const row of write.values) {
1406
- if (((_b = row.values) === null || _b === void 0 ? void 0 : _b.length) &&
1565
+ if (row.values?.length &&
1407
1566
  row.values.length > index &&
1408
1567
  row.values[index].listValue) {
1409
1568
  // If the value is an array, the client library also encoded it as
@@ -1582,7 +1741,7 @@ class Transaction extends Dml {
1582
1741
  rollback(gaxOptionsOrCallback, cb) {
1583
1742
  const gaxOpts = typeof gaxOptionsOrCallback === 'object' ? gaxOptionsOrCallback : {};
1584
1743
  const callback = typeof gaxOptionsOrCallback === 'function' ? gaxOptionsOrCallback : cb;
1585
- return (0, instrument_2.startTrace)('Transaction.rollback', this._traceConfig, span => {
1744
+ return (0, instrument_1.startTrace)('Transaction.rollback', this._traceConfig, span => {
1586
1745
  if (!this.id) {
1587
1746
  span.addEvent('Transaction ID is unknown, nothing to rollback.');
1588
1747
  span.end();
@@ -1607,7 +1766,7 @@ class Transaction extends Dml {
1607
1766
  headers: headers,
1608
1767
  }, (err) => {
1609
1768
  if (err) {
1610
- (0, instrument_2.setSpanError)(span, err);
1769
+ (0, instrument_1.setSpanError)(span, err);
1611
1770
  }
1612
1771
  span.end();
1613
1772
  this.end();
@@ -1751,21 +1910,21 @@ class Transaction extends Dml {
1751
1910
  /**
1752
1911
  * Set optimistic concurrency control for the transaction.
1753
1912
  */
1754
- if (options === null || options === void 0 ? void 0 : options.optimisticLock) {
1913
+ if (options?.optimisticLock) {
1755
1914
  this._options.readWrite.readLockMode = ReadLockMode.OPTIMISTIC;
1756
1915
  }
1757
1916
  /**
1758
1917
  * Set option excludeTxnFromChangeStreams=true to exclude read/write transactions
1759
1918
  * from being tracked in change streams.
1760
1919
  */
1761
- if (options === null || options === void 0 ? void 0 : options.excludeTxnFromChangeStreams) {
1920
+ if (options?.excludeTxnFromChangeStreams) {
1762
1921
  this._options.excludeTxnFromChangeStreams = true;
1763
1922
  }
1764
1923
  /**
1765
1924
  * Set isolation level .
1766
1925
  */
1767
- this._options.isolationLevel = (options === null || options === void 0 ? void 0 : options.isolationLevel)
1768
- ? options === null || options === void 0 ? void 0 : options.isolationLevel
1926
+ this._options.isolationLevel = options?.isolationLevel
1927
+ ? options?.isolationLevel
1769
1928
  : this._getSpanner().defaultTransactionOptions.isolationLevel;
1770
1929
  }
1771
1930
  }
@@ -1788,7 +1947,7 @@ exports.Transaction = Transaction;
1788
1947
  * @throws {GoogleError} - If a row does not contain the correct number of columns.
1789
1948
  */
1790
1949
  function buildMutation(method, table, keyVals) {
1791
- const rows = arrify(keyVals);
1950
+ const rows = (0, helper_1.toArray)(keyVals);
1792
1951
  const columns = Transaction.getUniqueKeys(rows);
1793
1952
  const values = rows.map((row, index) => {
1794
1953
  const keys = Object.keys(row);
@@ -1816,7 +1975,7 @@ function buildMutation(method, table, keyVals) {
1816
1975
  */
1817
1976
  function buildDeleteMutation(table, keys) {
1818
1977
  const keySet = {
1819
- keys: arrify(keys).map(codec_1.codec.convertToListValue),
1978
+ keys: (0, helper_1.toArray)(keys).map(codec_1.codec.convertToListValue),
1820
1979
  };
1821
1980
  const mutation = {
1822
1981
  delete: { table, keySet },
@@ -1857,6 +2016,10 @@ function buildDeleteMutation(table, keys) {
1857
2016
  * ```
1858
2017
  */
1859
2018
  class MutationSet {
2019
+ /**
2020
+ * An array to store the mutations.
2021
+ */
2022
+ _queuedMutations;
1860
2023
  /**
1861
2024
  * Creates a new Mutation object.
1862
2025
  */
@@ -1948,6 +2111,7 @@ exports.MutationSet = MutationSet;
1948
2111
  * ```
1949
2112
  */
1950
2113
  class MutationGroup {
2114
+ _proto;
1951
2115
  constructor() {
1952
2116
  this._proto =
1953
2117
  new protos_1.google.spanner.v1.BatchWriteRequest.MutationGroup();
@@ -2003,13 +2167,13 @@ class PartitionedDml extends Dml {
2003
2167
  this._options.excludeTxnFromChangeStreams = true;
2004
2168
  }
2005
2169
  runUpdate(query, callback) {
2006
- return (0, instrument_2.startTrace)('PartitionedDml.runUpdate', {
2170
+ return (0, instrument_1.startTrace)('PartitionedDml.runUpdate', {
2007
2171
  ...query,
2008
2172
  ...this._traceConfig,
2009
2173
  }, span => {
2010
2174
  super.runUpdate(query, (err, count) => {
2011
2175
  if (err) {
2012
- (0, instrument_2.setSpanError)(span, err);
2176
+ (0, instrument_1.setSpanError)(span, err);
2013
2177
  }
2014
2178
  this.end();
2015
2179
  span.end();