@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
@@ -27,7 +27,6 @@ const backup_1 = require("./backup");
27
27
  const batch_transaction_1 = require("./batch-transaction");
28
28
  const session_factory_1 = require("./session-factory");
29
29
  const session_1 = require("./session");
30
- const session_pool_1 = require("./session-pool");
31
30
  const table_1 = require("./table");
32
31
  const transaction_1 = require("./transaction");
33
32
  const transaction_runner_1 = require("./transaction-runner");
@@ -43,10 +42,15 @@ const request_id_header_1 = require("./request_id_header");
43
42
  * @class
44
43
  *
45
44
  * @param {string} name Name of the database.
46
- * @param {SessionPoolOptions|SessionPoolInterface} options Session pool
47
- * configuration options or custom pool interface.
48
- * @param {google.spanner.v1.ExecuteSqlRequest.IQueryOptions} queryOptions
45
+ * @param {SessionPoolOptions|SessionPoolInterface} [poolOptions] Session pool
46
+ * configuration options.
47
+ * **Deprecated**. Session pool options is deprecated and will be removed in a future release.
48
+ * Multiplexed sessions are now used for all operations by default, eliminating
49
+ * the need for session pooling.
50
+ * @param {google.spanner.v1.ExecuteSqlRequest.IQueryOptions} [queryOptions]
49
51
  * The default query options to use for queries on the database.
52
+ * @param {string} [databaseRole] The database role to use for sessions on
53
+ * the database.
50
54
  *
51
55
  * @example
52
56
  * ```
@@ -62,7 +66,6 @@ class Database extends common.GrpcServiceObject {
62
66
  pool_;
63
67
  sessionFactory_;
64
68
  queryOptions_;
65
- isMuxEnabledForRW_;
66
69
  commonHeaders_;
67
70
  request;
68
71
  databaseRole;
@@ -71,7 +74,26 @@ class Database extends common.GrpcServiceObject {
71
74
  _observabilityOptions; // TODO: exmaine if we can remove it
72
75
  _traceConfig;
73
76
  _nthRequest;
74
- _clientId;
77
+ _clientIdValue = 1;
78
+ get _clientId() {
79
+ return this._clientIdValue;
80
+ }
81
+ set _clientId(value) {
82
+ this._clientIdValue = value ?? 1;
83
+ this._updateRequestIdPrefix();
84
+ }
85
+ _channelIdValue = 1;
86
+ get _channelId() {
87
+ return this._channelIdValue;
88
+ }
89
+ set _channelId(value) {
90
+ this._channelIdValue = value ?? 1;
91
+ this._updateRequestIdPrefix();
92
+ }
93
+ _updateRequestIdPrefix() {
94
+ this._requestIdPrefix = (0, request_id_header_1.getRequestIdPrefix)(this._clientIdValue, this._channelIdValue);
95
+ }
96
+ _requestIdPrefix = (0, request_id_header_1.getRequestIdPrefix)(1, 1);
75
97
  constructor(instance, name, poolOptions, queryOptions, databaseRole) {
76
98
  const methods = {
77
99
  /**
@@ -124,40 +146,7 @@ class Database extends common.GrpcServiceObject {
124
146
  id: name,
125
147
  methods,
126
148
  createMethod: (_, options, callback) => {
127
- const pool = this.pool_;
128
- if (pool._pending > 0) {
129
- // If there are BatchCreateSessions requests pending, then we should
130
- // wait until these have finished before we try to create the database.
131
- // Otherwise the results of these requests might be propagated to
132
- // client requests that are submitted after the database has been
133
- // created. If the pending requests have not finished within 10 seconds,
134
- // they will be ignored and the database creation will proceed.
135
- let timeout;
136
- const promises = [
137
- new Promise(resolve => (timeout = setTimeout(resolve, 10000))),
138
- new Promise(resolve => {
139
- pool
140
- .on('available', () => {
141
- if (pool._pending === 0) {
142
- clearTimeout(timeout);
143
- resolve();
144
- }
145
- })
146
- .on('createError', () => {
147
- if (pool._pending === 0) {
148
- clearTimeout(timeout);
149
- resolve();
150
- }
151
- });
152
- }),
153
- ];
154
- Promise.race(promises)
155
- .then(() => instance.createDatabase(formattedName_, options, callback))
156
- .catch(() => { });
157
- }
158
- else {
159
- return instance.createDatabase(formattedName_, options, callback);
160
- }
149
+ return instance.createDatabase(formattedName_, options, callback);
161
150
  },
162
151
  });
163
152
  this.formattedName_ = formattedName_;
@@ -172,12 +161,11 @@ class Database extends common.GrpcServiceObject {
172
161
  };
173
162
  this.request = instance.request;
174
163
  this._nthRequest = (0, request_id_header_1.newAtomicCounter)(0);
175
- if (this.parent && this.parent.parent) {
176
- this._clientId = this.parent.parent._nthClientId;
177
- }
178
- else {
179
- this._clientId = instance._nthClientId;
180
- }
164
+ const spanner = instance.parent;
165
+ this._clientId =
166
+ spanner?._nthClientId ??
167
+ instance._nthClientId ??
168
+ 1;
181
169
  this._observabilityOptions = instance._observabilityOptions;
182
170
  this.commonHeaders_ = {
183
171
  ...instance.commonHeaders_,
@@ -187,12 +175,6 @@ class Database extends common.GrpcServiceObject {
187
175
  this.requestStream = instance.requestStream;
188
176
  this.sessionFactory_ = new session_factory_1.SessionFactory(this, name, poolOptions);
189
177
  this.pool_ = this.sessionFactory_.getPool();
190
- this.isMuxEnabledForRW_ = this.sessionFactory_.isMultiplexedEnabledForRW();
191
- const sessionPoolInstance = this.pool_;
192
- if (sessionPoolInstance) {
193
- sessionPoolInstance._observabilityOptions =
194
- instance._observabilityOptions;
195
- }
196
178
  this.queryOptions_ = Object.assign(Object.assign({}, queryOptions), Database.getEnvironmentQueryOptions());
197
179
  }
198
180
  _nextNthRequest() {
@@ -240,11 +222,10 @@ class Database extends common.GrpcServiceObject {
240
222
  sessionTemplate: { labels: labels, creatorRole: databaseRole },
241
223
  sessionCount: count,
242
224
  };
243
- const headers = this.commonHeaders_;
225
+ const allHeaders = this._metadataWithRequestId(this._nextNthRequest(), 1, this.commonHeaders_);
244
226
  if (this._getSpanner().routeToLeaderEnabled) {
245
- (0, common_1.addLeaderAwareRoutingHeader)(headers);
227
+ (0, common_1.addLeaderAwareRoutingHeader)(allHeaders);
246
228
  }
247
- const allHeaders = this._metadataWithRequestId(this._nextNthRequest(), 1, headers);
248
229
  (0, instrument_1.startTrace)('Database.batchCreateSessions', this._traceConfig, span => {
249
230
  this.request({
250
231
  client: 'SpannerClient',
@@ -271,14 +252,9 @@ class Database extends common.GrpcServiceObject {
271
252
  });
272
253
  }
273
254
  _metadataWithRequestId(nthRequest, attempt, priorMetadata) {
274
- if (!priorMetadata) {
275
- priorMetadata = {};
276
- }
277
- const withReqId = {
278
- ...priorMetadata,
279
- };
280
- withReqId[request_id_header_1.X_GOOG_SPANNER_REQUEST_ID_HEADER] = (0, request_id_header_1.craftRequestId)(this._clientId || 1, 1, // TODO: Properly infer the channelId
281
- nthRequest, attempt);
255
+ const withReqId = priorMetadata ? { ...priorMetadata } : {};
256
+ withReqId[request_id_header_1.X_GOOG_SPANNER_REQUEST_ID_HEADER] =
257
+ `${this._requestIdPrefix}${nthRequest ?? 1}.${attempt ?? 1}`;
282
258
  return withReqId;
283
259
  }
284
260
  /**
@@ -317,10 +293,16 @@ class Database extends common.GrpcServiceObject {
317
293
  return transaction;
318
294
  }
319
295
  close(callback) {
320
- const key = this.id.split('/').pop();
321
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
322
- this.parent.databases_.delete(key);
323
- this.pool_.close(callback);
296
+ this.sessionFactory_?.close?.();
297
+ const databases = this.parent.databases_;
298
+ for (const [key, database] of databases) {
299
+ if (database === this) {
300
+ databases.delete(key);
301
+ }
302
+ }
303
+ if (callback) {
304
+ process.nextTick(callback);
305
+ }
324
306
  }
325
307
  createBatchTransaction(optionsOrCallback, cb) {
326
308
  const callback = typeof optionsOrCallback === 'function'
@@ -338,15 +320,9 @@ class Database extends common.GrpcServiceObject {
338
320
  return;
339
321
  }
340
322
  const transaction = this.batchTransaction({ session: session }, options);
341
- this._releaseOnEnd(session, transaction, span);
342
323
  transaction.begin((err, resp) => {
343
324
  if (err) {
344
325
  (0, instrument_1.setSpanError)(span, err);
345
- if ((0, session_pool_1.isSessionNotFoundError)(err)) {
346
- span.addEvent('No session available', {
347
- 'session.id': session?.id,
348
- });
349
- }
350
326
  span.end();
351
327
  callback(err, null, resp);
352
328
  return;
@@ -413,30 +389,6 @@ class Database extends common.GrpcServiceObject {
413
389
  callback(null, table, operation, resp);
414
390
  });
415
391
  }
416
- /**
417
- * Decorates transaction so that when end() is called it will return the session
418
- * back into the pool.
419
- *
420
- * @private
421
- *
422
- * @param {Session} session The session to release.
423
- * @param {Transaction} transaction The transaction to observe.
424
- * @returns {Transaction}
425
- */
426
- _releaseOnEnd(session, transaction, span) {
427
- transaction.once('end', () => {
428
- try {
429
- this.sessionFactory_.release(session);
430
- }
431
- catch (e) {
432
- (0, instrument_1.setSpanErrorAndException)(span, e);
433
- this.emit('error', e);
434
- }
435
- finally {
436
- span.end();
437
- }
438
- });
439
- }
440
392
  delete(optionsOrCallback, cb) {
441
393
  const gaxOpts = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
442
394
  const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
@@ -738,30 +690,16 @@ class Database extends common.GrpcServiceObject {
738
690
  return;
739
691
  }
740
692
  const snapshot = session.snapshot(options, this.queryOptions_);
693
+ span.addEvent('Using Session', { 'session.id': session?.id });
741
694
  snapshot.begin(err => {
742
695
  if (err) {
743
696
  (0, instrument_1.setSpanError)(span, err);
744
- if ((0, session_pool_1.isSessionNotFoundError)(err) &&
745
- !this.sessionFactory_.isMultiplexedEnabled()) {
746
- span.addEvent('No session available', {
747
- 'session.id': session?.id,
748
- });
749
- session.lastError = err;
750
- this.sessionFactory_.release(session);
751
- span.end();
752
- this.getSnapshot(options, callback);
753
- }
754
- else {
755
- span.addEvent('Using Session', { 'session.id': session?.id });
756
- this.sessionFactory_.release(session);
757
- span.end();
758
- callback(err);
759
- }
697
+ span.end();
698
+ callback(err);
760
699
  return;
761
700
  }
762
- this._releaseOnEnd(session, snapshot, span);
763
701
  span.end();
764
- callback(err, snapshot);
702
+ callback(null, snapshot);
765
703
  });
766
704
  });
767
705
  });
@@ -777,21 +715,22 @@ class Database extends common.GrpcServiceObject {
777
715
  ...this._traceConfig,
778
716
  transactionTag: options.requestOptions?.transactionTag,
779
717
  }, span => {
780
- this.sessionFactory_.getSessionForReadWrite((err, session, transaction) => {
781
- if (!err) {
782
- if (options.requestOptions) {
783
- transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
784
- }
785
- transaction?.setReadWriteTransactionOptions(options);
786
- span.addEvent('Using Session', { 'session.id': session?.id });
787
- transaction._observabilityOptions = this._observabilityOptions;
788
- this._releaseOnEnd(session, transaction, span);
789
- }
790
- else {
718
+ this.sessionFactory_.getSession((err, session, transaction) => {
719
+ if (err) {
791
720
  (0, instrument_1.setSpanError)(span, err);
721
+ span.end();
722
+ cb(err);
723
+ return;
792
724
  }
725
+ const activeTransaction = transaction ?? session.transaction(this.queryOptions_);
726
+ if (options.requestOptions) {
727
+ activeTransaction.requestOptions = Object.assign(activeTransaction.requestOptions || {}, options.requestOptions);
728
+ }
729
+ activeTransaction?.setReadWriteTransactionOptions(options);
730
+ span.addEvent('Using Session', { 'session.id': session?.id });
731
+ activeTransaction._observabilityOptions = this._observabilityOptions;
793
732
  span.end();
794
- cb(err, transaction);
733
+ cb(null, activeTransaction);
795
734
  });
796
735
  });
797
736
  }
@@ -844,7 +783,7 @@ class Database extends common.GrpcServiceObject {
844
783
  }
845
784
  makePooledRequest_(config, callback) {
846
785
  const sessionFactory_ = this.sessionFactory_;
847
- sessionFactory_.getSessionForReadWrite((err, session) => {
786
+ const onSession = (err, session) => {
848
787
  if (err) {
849
788
  callback(err, null);
850
789
  return;
@@ -853,10 +792,15 @@ class Database extends common.GrpcServiceObject {
853
792
  span.addEvent('Using Session', { 'session.id': session?.id });
854
793
  config.reqOpts.session = session.formattedName_;
855
794
  this.request(config, (err, ...args) => {
856
- sessionFactory_.release(session);
857
795
  callback(err, ...args);
858
796
  });
859
- });
797
+ };
798
+ const session = sessionFactory_.getSessionSync?.();
799
+ if (session) {
800
+ onSession(null, session);
801
+ return;
802
+ }
803
+ sessionFactory_.getSession(onSession);
860
804
  }
861
805
  /**
862
806
  * Make an API request as a stream, first assuring an active session is used.
@@ -871,11 +815,11 @@ class Database extends common.GrpcServiceObject {
871
815
  const self = this;
872
816
  const sessionFactory_ = this.sessionFactory_;
873
817
  let requestStream;
874
- let session;
818
+ let aborted = false;
875
819
  const waitForSessionStream = streamEvents(through.obj());
876
820
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
877
821
  waitForSessionStream.abort = () => {
878
- releaseSession();
822
+ aborted = true;
879
823
  if (requestStream) {
880
824
  requestStream.cancel();
881
825
  }
@@ -883,29 +827,21 @@ class Database extends common.GrpcServiceObject {
883
827
  function destroyStream(err) {
884
828
  waitForSessionStream.destroy(err);
885
829
  }
886
- function releaseSession() {
887
- if (session) {
888
- sessionFactory_.release(session);
889
- session = null;
890
- }
891
- }
892
830
  waitForSessionStream.on('reading', () => {
893
- sessionFactory_.getSession((err, session_) => {
831
+ sessionFactory_.getSession((err, session) => {
832
+ if (aborted) {
833
+ return;
834
+ }
894
835
  const span = (0, instrument_1.getActiveOrNoopSpan)();
895
836
  if (err) {
896
837
  (0, instrument_1.setSpanError)(span, err);
897
838
  destroyStream(err);
898
839
  return;
899
840
  }
900
- span.addEvent('Using Session', { 'session.id': session_?.id });
901
- session = session_;
841
+ span.addEvent('Using Session', { 'session.id': session?.id });
902
842
  config.reqOpts.session = session.formattedName_;
903
843
  requestStream = self.requestStream(config);
904
- requestStream
905
- .on('error', releaseSession)
906
- .on('error', destroyStream)
907
- .on('end', releaseSession)
908
- .pipe(waitForSessionStream);
844
+ requestStream.on('error', destroyStream).pipe(waitForSessionStream);
909
845
  });
910
846
  });
911
847
  return waitForSessionStream;
@@ -948,8 +884,7 @@ class Database extends common.GrpcServiceObject {
948
884
  const options = typeof optionsOrCallback === 'object'
949
885
  ? optionsOrCallback
950
886
  : {};
951
- if (this.runStream !== Database.prototype.runStream ||
952
- !this.sessionFactory_.isMultiplexedEnabled()) {
887
+ if (this.runStream !== Database.prototype.runStream) {
953
888
  this._runLegacy(query, options, callback);
954
889
  return;
955
890
  }
@@ -957,8 +892,8 @@ class Database extends common.GrpcServiceObject {
957
892
  }
958
893
  /**
959
894
  * Always runs the query through the full streaming pipeline (Database.prototype.runStream).
960
- * Used when runStream has been overridden on Database, or when multiplexed
961
- * sessions are disabled (requiring standard session pool checkout and session-not-found retries).
895
+ * Used when runStream has been overridden on Database to preserve backward compatibility
896
+ * with custom stream implementations.
962
897
  *
963
898
  * @private
964
899
  */
@@ -967,8 +902,8 @@ class Database extends common.GrpcServiceObject {
967
902
  let stats;
968
903
  let metadata;
969
904
  (0, instrument_1.startTrace)('Database.run', {
970
- ...query,
971
905
  ...this._traceConfig,
906
+ ...(0, instrument_1.getQueryTraceConfig)(query),
972
907
  }, span => {
973
908
  this.runStream(query, options)
974
909
  .on('error', err => {
@@ -1002,8 +937,8 @@ class Database extends common.GrpcServiceObject {
1002
937
  */
1003
938
  _run(query, options, callback) {
1004
939
  const traceConfig = {
1005
- ...query,
1006
940
  ...this._traceConfig,
941
+ ...(0, instrument_1.getQueryTraceConfig)(query),
1007
942
  };
1008
943
  (0, instrument_1.startTrace)('Database.run', traceConfig, runSpan => {
1009
944
  (0, instrument_1.startTrace)('Database.runStream', traceConfig, streamSpan => {
@@ -1013,7 +948,7 @@ class Database extends common.GrpcServiceObject {
1013
948
  }
1014
949
  /**
1015
950
  * Acquires a session and executes the query on a snapshot, managing span
1016
- * lifetimes and session release.
951
+ * lifetimes.
1017
952
  *
1018
953
  * @private
1019
954
  */
@@ -1034,30 +969,35 @@ class Database extends common.GrpcServiceObject {
1034
969
  runSpan.end();
1035
970
  callback(error, rows, stats, metadata);
1036
971
  };
1037
- this.sessionFactory_.getSession((error, session) => {
972
+ const onSession = (error, session) => {
1038
973
  if (error) {
1039
974
  complete(error);
1040
975
  return;
1041
976
  }
1042
977
  streamSpan.addEvent('Using Session', { 'session.id': session?.id });
1043
- snapshot = session.snapshot(options, this.queryOptions_);
1044
- this._runOnSnapshot(snapshot, session, query, complete);
1045
- });
978
+ try {
979
+ snapshot = session.snapshot(options, this.queryOptions_);
980
+ this._runOnSnapshot(snapshot, query, complete);
981
+ }
982
+ catch (syncError) {
983
+ // Defer error delivery via nextTick so callback callers never experience
984
+ // synchronous callback execution (Zalgo) when getSessionSync() returns synchronously.
985
+ process.nextTick(() => complete(syncError));
986
+ }
987
+ };
988
+ const session = this.sessionFactory_.getSessionSync?.();
989
+ if (session) {
990
+ onSession(null, session);
991
+ return;
992
+ }
993
+ this.sessionFactory_.getSession(onSession);
1046
994
  }
1047
995
  /**
1048
- * Executes the query on the snapshot and binds session release to snapshot end.
996
+ * Executes the query on the snapshot.
1049
997
  *
1050
998
  * @private
1051
999
  */
1052
- _runOnSnapshot(snapshot, session, query, callback) {
1053
- snapshot.once('end', () => {
1054
- try {
1055
- this.sessionFactory_.release(session);
1056
- }
1057
- catch (releaseError) {
1058
- this.emit('error', releaseError);
1059
- }
1060
- });
1000
+ _runOnSnapshot(snapshot, query, callback) {
1061
1001
  const snapshotWithRun = snapshot;
1062
1002
  try {
1063
1003
  if (typeof snapshotWithRun._run === 'function' &&
@@ -1071,17 +1011,17 @@ class Database extends common.GrpcServiceObject {
1071
1011
  }
1072
1012
  }
1073
1013
  catch (syncError) {
1074
- callback(syncError);
1014
+ // Defer error delivery via nextTick so callback callers never experience
1015
+ // synchronous callback execution (Zalgo) when getSessionSync() returns synchronously.
1016
+ process.nextTick(() => callback(syncError));
1075
1017
  }
1076
1018
  }
1077
1019
  runPartitionedUpdate(query, callback) {
1078
1020
  return (0, instrument_1.startTrace)('Database.runPartitionedUpdate', {
1079
- ...query,
1080
1021
  ...this._traceConfig,
1081
- requestTag: query?.requestOptions
1082
- ?.requestTag,
1022
+ ...(0, instrument_1.getQueryTraceConfig)(query),
1083
1023
  }, span => {
1084
- this.sessionFactory_.getSessionForPartitionedOps((err, session) => {
1024
+ this.sessionFactory_.getSession((err, session) => {
1085
1025
  if (err) {
1086
1026
  (0, instrument_1.setSpanError)(span, err);
1087
1027
  span.end();
@@ -1105,21 +1045,18 @@ class Database extends common.GrpcServiceObject {
1105
1045
  }
1106
1046
  transaction.begin(err => {
1107
1047
  if (err) {
1108
- this.sessionFactory_.release(session);
1109
1048
  callback(err, 0);
1110
1049
  return;
1111
1050
  }
1112
1051
  transaction.runUpdate(query, async (err, updateCount) => {
1113
1052
  if (err) {
1114
1053
  if (err.code !== google_gax_1.grpc.status.ABORTED) {
1115
- this.sessionFactory_.release(session);
1116
1054
  callback(err, 0);
1117
1055
  return;
1118
1056
  }
1119
1057
  void this._runPartitionedUpdate(session, query, callback);
1120
1058
  }
1121
1059
  else {
1122
- this.sessionFactory_.release(session);
1123
1060
  callback(null, updateCount);
1124
1061
  return;
1125
1062
  }
@@ -1254,9 +1191,8 @@ class Database extends common.GrpcServiceObject {
1254
1191
  runStream(query, options) {
1255
1192
  const proxyStream = through.obj();
1256
1193
  return (0, instrument_1.startTrace)('Database.runStream', {
1257
- ...query,
1258
1194
  ...this._traceConfig,
1259
- requestTag: query?.requestOptions?.requestTag,
1195
+ ...(0, instrument_1.getQueryTraceConfig)(query),
1260
1196
  }, span => {
1261
1197
  this.sessionFactory_.getSession((err, session) => {
1262
1198
  if (err) {
@@ -1267,42 +1203,15 @@ class Database extends common.GrpcServiceObject {
1267
1203
  }
1268
1204
  span.addEvent('Using Session', { 'session.id': session?.id });
1269
1205
  const snapshot = session.snapshot(options, this.queryOptions_);
1270
- this._releaseOnEnd(session, snapshot, span);
1271
- let dataReceived = false;
1272
- let dataStream = snapshot.runStream(query);
1206
+ const dataStream = snapshot.runStream(query);
1273
1207
  const endListener = () => {
1274
1208
  snapshot.end();
1275
1209
  };
1276
1210
  dataStream
1277
- .once('data', () => (dataReceived = true))
1278
1211
  .once('error', err => {
1279
1212
  (0, instrument_1.setSpanError)(span, err);
1280
- if (!dataReceived &&
1281
- (0, session_pool_1.isSessionNotFoundError)(err) &&
1282
- !this.sessionFactory_.isMultiplexedEnabled()) {
1283
- // If it is a 'Session not found' error and we have not yet received
1284
- // any data, we can safely retry the query on a new session.
1285
- // Register the error on the session so the pool can discard it.
1286
- if (session) {
1287
- session.lastError = err;
1288
- }
1289
- span.addEvent('No session available', {
1290
- 'session.id': session?.id,
1291
- });
1292
- // Remove the current data stream from the end user stream.
1293
- dataStream.unpipe(proxyStream);
1294
- dataStream.removeListener('end', endListener);
1295
- dataStream.end();
1296
- snapshot.end();
1297
- span.end();
1298
- // Create a new data stream and add it to the end user stream.
1299
- dataStream = this.runStream(query, options);
1300
- dataStream.pipe(proxyStream);
1301
- }
1302
- else {
1303
- proxyStream.destroy(err);
1304
- snapshot.end();
1305
- }
1213
+ proxyStream.destroy(err);
1214
+ snapshot.end();
1306
1215
  })
1307
1216
  .on('stats', stats => proxyStream.emit('stats', stats))
1308
1217
  .on('response', response => proxyStream.emit('response', response))
@@ -1331,57 +1240,33 @@ class Database extends common.GrpcServiceObject {
1331
1240
  }, span => this._runTransaction(span, options, runFn));
1332
1241
  }
1333
1242
  _runTransaction(span, options, runFn) {
1334
- this.sessionFactory_.getSessionForReadWrite((err, session, transaction) => {
1243
+ this.sessionFactory_.getSession((err, session, transaction) => {
1335
1244
  if (err) {
1336
1245
  (0, instrument_1.setSpanError)(span, err);
1337
- if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1338
- span.addEvent('No session available', {
1339
- 'session.id': session?.id,
1340
- });
1341
- span.end();
1342
- this.runTransaction(options, runFn);
1343
- return;
1344
- }
1345
1246
  span.end();
1346
1247
  runFn(err);
1347
1248
  return;
1348
1249
  }
1349
- this._executeTransactionRunner(session, transaction, span, options, runFn);
1250
+ span.addEvent('Using Session', { 'session.id': session?.id });
1251
+ const activeTransaction = transaction ?? session.transaction(this.queryOptions_);
1252
+ this._executeTransactionRunner(session, activeTransaction, span, options, runFn);
1350
1253
  });
1351
1254
  }
1352
1255
  _executeTransactionRunner(session, transaction, span, options, runFn) {
1353
1256
  transaction._observabilityOptions = this._observabilityOptions;
1354
1257
  transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1355
1258
  transaction.setReadWriteTransactionOptions(options);
1356
- const release = () => {
1357
- this.sessionFactory_.release(session);
1358
- span.end();
1359
- };
1360
1259
  const runner = new transaction_runner_1.TransactionRunner(session, transaction, runFn, options);
1361
1260
  runner
1362
1261
  .run()
1363
1262
  .then(() => {
1364
- release();
1365
- return null;
1366
- }, err => {
1367
- (0, instrument_1.setSpanError)(span, err);
1368
- if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1369
- span.addEvent('No session available', {
1370
- 'session.id': session.id,
1371
- });
1372
- release();
1373
- this.runTransaction(options, runFn);
1374
- }
1375
- else {
1376
- setImmediate(runFn, err);
1377
- release();
1378
- }
1263
+ span.end();
1379
1264
  return null;
1380
1265
  })
1381
1266
  .catch(err => {
1382
- (0, instrument_1.setSpanErrorAndException)(span, err);
1267
+ (0, instrument_1.setSpanError)(span, err);
1268
+ setImmediate(runFn, err);
1383
1269
  span.end();
1384
- this.emit('error', err);
1385
1270
  });
1386
1271
  }
1387
1272
  /**
@@ -1409,9 +1294,8 @@ class Database extends common.GrpcServiceObject {
1409
1294
  *
1410
1295
  * **NOTE:** In the event that you encounter an error while reading/writing,
1411
1296
  * if you decide to forgo calling {@link Transaction#commit} or
1412
- * {@link Transaction#rollback}, then you need to call
1413
- * {@link Transaction#end} to release the underlying {@link Session} object.
1414
- * **Failure to do could result in a Session leak.**
1297
+ * {@link Transaction#rollback}, then you should call
1298
+ * {@link Transaction#end} to end the transaction.
1415
1299
  *
1416
1300
  * For a more complete listing of functionality available to a Transaction, see
1417
1301
  * the {@link Transaction} API documentation. For a general overview of
@@ -1451,45 +1335,28 @@ class Database extends common.GrpcServiceObject {
1451
1335
  ? optionsOrRunFn
1452
1336
  : {};
1453
1337
  let sessionId = '';
1454
- const getSession = this.sessionFactory_.getSessionForReadWrite.bind(this.sessionFactory_);
1338
+ const getSession = this.sessionFactory_.getSession.bind(this.sessionFactory_);
1455
1339
  return (0, instrument_1.startTrace)('Database.runTransactionAsync', {
1456
1340
  ...this._traceConfig,
1457
1341
  transactionTag: options?.requestOptions?.transactionTag,
1458
1342
  }, async (span) => {
1459
- // Loop to retry 'Session not found' errors.
1460
- // (and yes, we like while (true) more than for (;;) here)
1461
- // eslint-disable-next-line no-constant-condition
1462
- while (true) {
1463
- try {
1464
- const [session, transaction] = await (0, promisify_1.promisify)(getSession)();
1465
- transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1466
- transaction.setReadWriteTransactionOptions(options);
1467
- sessionId = session?.id;
1468
- span.addEvent('Using Session', { 'session.id': sessionId });
1469
- const runner = new transaction_runner_1.AsyncTransactionRunner(session, transaction, runFn, options);
1470
- try {
1471
- return await runner.run();
1472
- }
1473
- catch (e) {
1474
- (0, instrument_1.setSpanErrorAndException)(span, e);
1475
- throw e;
1476
- }
1477
- finally {
1478
- span.end();
1479
- this.sessionFactory_.release(session);
1480
- }
1481
- }
1482
- catch (e) {
1483
- if ((0, session_pool_1.isSessionNotFoundError)(e)) {
1484
- span.addEvent('No session available', {
1485
- 'session.id': sessionId,
1486
- });
1487
- }
1488
- else {
1489
- span.end();
1490
- throw e;
1491
- }
1492
- }
1343
+ try {
1344
+ const session = this.sessionFactory_.getSessionSync?.() ??
1345
+ (await (0, promisify_1.promisify)(getSession)())[0];
1346
+ const activeTransaction = session.transaction(this.queryOptions_);
1347
+ activeTransaction.requestOptions = Object.assign(activeTransaction.requestOptions || {}, options.requestOptions);
1348
+ activeTransaction.setReadWriteTransactionOptions(options);
1349
+ sessionId = session?.id;
1350
+ span.addEvent('Using Session', { 'session.id': sessionId });
1351
+ const runner = new transaction_runner_1.AsyncTransactionRunner(session, activeTransaction, runFn, options);
1352
+ return await runner.run();
1353
+ }
1354
+ catch (e) {
1355
+ (0, instrument_1.setSpanErrorAndException)(span, e);
1356
+ throw e;
1357
+ }
1358
+ finally {
1359
+ span.end();
1493
1360
  }
1494
1361
  });
1495
1362
  }
@@ -1557,7 +1424,7 @@ class Database extends common.GrpcServiceObject {
1557
1424
  ...this._traceConfig,
1558
1425
  transactionTag: options?.requestOptions?.transactionTag,
1559
1426
  }, span => {
1560
- this.sessionFactory_.getSessionForReadWrite((err, session) => {
1427
+ this.sessionFactory_.getSession((err, session) => {
1561
1428
  if (err) {
1562
1429
  proxyStream.destroy(err);
1563
1430
  (0, instrument_1.setSpanError)(span, err);
@@ -1572,8 +1439,7 @@ class Database extends common.GrpcServiceObject {
1572
1439
  requestOptions: options?.requestOptions,
1573
1440
  excludeTxnFromChangeStream: options?.excludeTxnFromChangeStreams,
1574
1441
  });
1575
- let dataReceived = false;
1576
- let dataStream = this.requestStream({
1442
+ const dataStream = this.requestStream({
1577
1443
  client: 'SpannerClient',
1578
1444
  method: 'batchWrite',
1579
1445
  reqOpts,
@@ -1581,36 +1447,13 @@ class Database extends common.GrpcServiceObject {
1581
1447
  headers: this.commonHeaders_,
1582
1448
  });
1583
1449
  dataStream
1584
- .once('data', () => (dataReceived = true))
1585
1450
  .once('error', err => {
1586
1451
  (0, instrument_1.setSpanError)(span, err);
1587
- if (!dataReceived &&
1588
- (0, session_pool_1.isSessionNotFoundError)(err)) {
1589
- // If there's a 'Session not found' error and we have not yet received
1590
- // any data, we can safely retry the writes on a new session.
1591
- // Register the error on the session so the pool can discard it.
1592
- if (session) {
1593
- session.lastError = err;
1594
- }
1595
- span.addEvent('No session available', {
1596
- 'session.id': session?.id,
1597
- });
1598
- // Remove the current data stream from the end user stream.
1599
- dataStream.unpipe(proxyStream);
1600
- dataStream.end();
1601
- span.end();
1602
- // Create a new stream and add it to the end user stream.
1603
- dataStream = this.batchWriteAtLeastOnce(mutationGroups, options);
1604
- dataStream.pipe(proxyStream);
1605
- }
1606
- else {
1607
- span.end();
1608
- proxyStream.destroy(err);
1609
- }
1452
+ span.end();
1453
+ proxyStream.destroy(err);
1610
1454
  })
1611
1455
  .once('end', () => {
1612
1456
  span.end();
1613
- this.sessionFactory_.release(session);
1614
1457
  })
1615
1458
  .pipe(proxyStream);
1616
1459
  });
@@ -1626,16 +1469,6 @@ class Database extends common.GrpcServiceObject {
1626
1469
  : {};
1627
1470
  return (0, instrument_1.startTrace)('Database.writeAtLeastOnce', this._traceConfig, span => {
1628
1471
  this.sessionFactory_.getSession((err, session, transaction) => {
1629
- if (err &&
1630
- (0, session_pool_1.isSessionNotFoundError)(err) &&
1631
- !this.sessionFactory_.isMultiplexedEnabled()) {
1632
- span.addEvent('No session available', {
1633
- 'session.id': session?.id,
1634
- });
1635
- span.end();
1636
- this.writeAtLeastOnce(mutations, options, cb);
1637
- return;
1638
- }
1639
1472
  if (err) {
1640
1473
  (0, instrument_1.setSpanError)(span, err);
1641
1474
  span.end();
@@ -1651,7 +1484,6 @@ class Database extends common.GrpcServiceObject {
1651
1484
  cb(error);
1652
1485
  return;
1653
1486
  }
1654
- this._releaseOnEnd(session, activeTransaction, span);
1655
1487
  try {
1656
1488
  activeTransaction.setReadWriteTransactionOptions(options);
1657
1489
  activeTransaction.setQueuedMutations(mutations.proto());