@google-cloud/spanner 7.14.0 → 7.16.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.
@@ -30,8 +30,10 @@ const session_pool_1 = require("./session-pool");
30
30
  const table_1 = require("./table");
31
31
  const transaction_runner_1 = require("./transaction-runner");
32
32
  const common_1 = require("./common");
33
+ const stream_1 = require("stream");
33
34
  const arrify = require("arrify");
34
35
  const snakeCase = require("lodash.snakecase");
36
+ const instrument_1 = require("./instrument");
35
37
  /**
36
38
  * Create a Database object to interact with a Cloud Spanner database.
37
39
  *
@@ -142,15 +144,26 @@ class Database extends common.GrpcServiceObject {
142
144
  typeof poolOptions === 'function'
143
145
  ? new poolOptions(this, null)
144
146
  : new session_pool_1.SessionPool(this, poolOptions);
147
+ const sessionPoolInstance = this.pool_;
148
+ if (sessionPoolInstance) {
149
+ sessionPoolInstance._observabilityOptions =
150
+ instance._observabilityOptions;
151
+ }
145
152
  if (typeof poolOptions === 'object') {
146
153
  this.databaseRole = poolOptions.databaseRole || null;
147
154
  }
148
155
  this.formattedName_ = formattedName_;
149
156
  this.instance = instance;
157
+ this._observabilityOptions = instance._observabilityOptions;
158
+ this._traceConfig = {
159
+ opts: this._observabilityOptions,
160
+ dbName: this.formattedName_,
161
+ };
150
162
  this.resourceHeader_ = {
151
163
  [common_1.CLOUD_RESOURCE_HEADER]: this.formattedName_,
152
164
  };
153
165
  this.request = instance.request;
166
+ this._observabilityOptions = instance._observabilityOptions;
154
167
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
155
168
  this.requestStream = instance.requestStream;
156
169
  this.pool_.on('error', this.emit.bind(this, 'error'));
@@ -203,23 +216,29 @@ class Database extends common.GrpcServiceObject {
203
216
  if (this._getSpanner().routeToLeaderEnabled) {
204
217
  (0, common_1.addLeaderAwareRoutingHeader)(headers);
205
218
  }
206
- this.request({
207
- client: 'SpannerClient',
208
- method: 'batchCreateSessions',
209
- reqOpts,
210
- gaxOpts: options.gaxOptions,
211
- headers: headers,
212
- }, (err, resp) => {
213
- if (err) {
214
- callback(err, null, resp);
215
- return;
216
- }
217
- const sessions = (resp.session || []).map(metadata => {
218
- const session = this.session(metadata.name);
219
- session.metadata = metadata;
220
- return session;
219
+ (0, instrument_1.startTrace)('Database.batchCreateSessions', this._traceConfig, span => {
220
+ this.request({
221
+ client: 'SpannerClient',
222
+ method: 'batchCreateSessions',
223
+ reqOpts,
224
+ gaxOpts: options.gaxOptions,
225
+ headers: headers,
226
+ }, (err, resp) => {
227
+ if (err) {
228
+ (0, instrument_1.setSpanError)(span, err);
229
+ span.end();
230
+ callback(err, null, resp);
231
+ return;
232
+ }
233
+ const sessions = (resp.session || []).map(metadata => {
234
+ const session = this.session(metadata.name);
235
+ session._observabilityOptions = this._traceConfig.opts;
236
+ session.metadata = metadata;
237
+ return session;
238
+ });
239
+ span.end();
240
+ callback(null, sessions, resp);
221
241
  });
222
- callback(null, sessions, resp);
223
242
  });
224
243
  }
225
244
  /**
@@ -253,6 +272,7 @@ class Database extends common.GrpcServiceObject {
253
272
  const id = identifier.transaction;
254
273
  const transaction = new batch_transaction_1.BatchTransaction(session, options);
255
274
  transaction.id = id;
275
+ transaction._observabilityOptions = this._traceConfig.opts;
256
276
  transaction.readTimestamp = identifier.timestamp;
257
277
  return transaction;
258
278
  }
@@ -269,19 +289,32 @@ class Database extends common.GrpcServiceObject {
269
289
  const options = typeof optionsOrCallback === 'object'
270
290
  ? optionsOrCallback
271
291
  : {};
272
- this.pool_.getSession((err, session) => {
273
- if (err) {
274
- callback(err, null, undefined);
275
- return;
276
- }
277
- const transaction = this.batchTransaction({ session: session }, options);
278
- this._releaseOnEnd(session, transaction);
279
- transaction.begin((err, resp) => {
292
+ return (0, instrument_1.startTrace)('Database.createBatchTransaction', this._traceConfig, span => {
293
+ this.pool_.getSession((err, session) => {
280
294
  if (err) {
281
- callback(err, null, resp);
295
+ (0, instrument_1.setSpanError)(span, err);
296
+ span.end();
297
+ callback(err, null, undefined);
282
298
  return;
283
299
  }
284
- callback(null, transaction, resp);
300
+ const transaction = this.batchTransaction({ session: session }, options);
301
+ this._releaseOnEnd(session, transaction, span);
302
+ transaction.begin((err, resp) => {
303
+ if (err) {
304
+ (0, instrument_1.setSpanError)(span, err);
305
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
306
+ span.addEvent('No session available', {
307
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
308
+ });
309
+ }
310
+ span.end();
311
+ callback(err, null, resp);
312
+ return;
313
+ }
314
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
315
+ span.end();
316
+ callback(null, transaction, resp);
317
+ });
285
318
  });
286
319
  });
287
320
  }
@@ -297,6 +330,9 @@ class Database extends common.GrpcServiceObject {
297
330
  if (options.labels) {
298
331
  reqOpts.session.labels = options.labels;
299
332
  }
333
+ if (options.multiplexed) {
334
+ reqOpts.session.multiplexed = options.multiplexed;
335
+ }
300
336
  reqOpts.session.creatorRole =
301
337
  options.databaseRole || this.databaseRole || null;
302
338
  const headers = this.resourceHeader_;
@@ -329,6 +365,7 @@ class Database extends common.GrpcServiceObject {
329
365
  }
330
366
  const tableName = schema.match(/CREATE TABLE `*([^\s`(]+)/)[1];
331
367
  const table = this.table(tableName);
368
+ table._observabilityOptions = this._traceConfig.opts;
332
369
  callback(null, table, operation, resp);
333
370
  });
334
371
  }
@@ -342,14 +379,18 @@ class Database extends common.GrpcServiceObject {
342
379
  * @param {Transaction} transaction The transaction to observe.
343
380
  * @returns {Transaction}
344
381
  */
345
- _releaseOnEnd(session, transaction) {
382
+ _releaseOnEnd(session, transaction, span) {
346
383
  transaction.once('end', () => {
347
384
  try {
348
385
  this.pool_.release(session);
349
386
  }
350
387
  catch (e) {
388
+ (0, instrument_1.setSpanErrorAndException)(span, e);
351
389
  this.emit('error', e);
352
390
  }
391
+ finally {
392
+ span.end();
393
+ }
353
394
  });
354
395
  }
355
396
  delete(optionsOrCallback, cb) {
@@ -526,25 +567,32 @@ class Database extends common.GrpcServiceObject {
526
567
  delete gaxOpts.pageSize;
527
568
  delete gaxOpts.pageToken;
528
569
  }
529
- this.request({
530
- client: 'SpannerClient',
531
- method: 'listSessions',
532
- reqOpts,
533
- gaxOpts,
534
- headers: this.resourceHeader_,
535
- }, (err, sessions, nextPageRequest, ...args) => {
536
- let sessionInstances = null;
537
- if (sessions) {
538
- sessionInstances = sessions.map(metadata => {
539
- const session = self.session(metadata.name);
540
- session.metadata = metadata;
541
- return session;
542
- });
543
- }
544
- const nextQuery = nextPageRequest
545
- ? extend({}, options, nextPageRequest)
546
- : null;
547
- callback(err, sessionInstances, nextQuery, ...args);
570
+ return (0, instrument_1.startTrace)('Database.getSessions', this._traceConfig, span => {
571
+ this.request({
572
+ client: 'SpannerClient',
573
+ method: 'listSessions',
574
+ reqOpts,
575
+ gaxOpts,
576
+ headers: this.resourceHeader_,
577
+ }, (err, sessions, nextPageRequest, ...args) => {
578
+ if (err) {
579
+ (0, instrument_1.setSpanError)(span, err);
580
+ }
581
+ let sessionInstances = null;
582
+ if (sessions) {
583
+ sessionInstances = sessions.map(metadata => {
584
+ const session = self.session(metadata.name);
585
+ session.metadata = metadata;
586
+ session._observabilityOptions = this._traceConfig.opts;
587
+ return session;
588
+ });
589
+ }
590
+ span.end();
591
+ const nextQuery = nextPageRequest
592
+ ? extend({}, options, nextPageRequest)
593
+ : null;
594
+ callback(err, sessionInstances, nextQuery, ...args);
595
+ });
548
596
  });
549
597
  }
550
598
  /**
@@ -618,27 +666,39 @@ class Database extends common.GrpcServiceObject {
618
666
  const options = typeof optionsOrCallback === 'object'
619
667
  ? optionsOrCallback
620
668
  : {};
621
- this.pool_.getSession((err, session) => {
622
- if (err) {
623
- callback(err);
624
- return;
625
- }
626
- const snapshot = session.snapshot(options, this.queryOptions_);
627
- snapshot.begin(err => {
669
+ return (0, instrument_1.startTrace)('Database.getSnapshot', this._traceConfig, span => {
670
+ this.pool_.getSession((err, session) => {
628
671
  if (err) {
629
- if ((0, session_pool_1.isSessionNotFoundError)(err)) {
630
- session.lastError = err;
631
- this.pool_.release(session);
632
- this.getSnapshot(options, callback);
633
- }
634
- else {
635
- this.pool_.release(session);
636
- callback(err);
637
- }
672
+ (0, instrument_1.setSpanError)(span, err);
673
+ span.end();
674
+ callback(err);
638
675
  return;
639
676
  }
640
- this._releaseOnEnd(session, snapshot);
641
- callback(err, snapshot);
677
+ const snapshot = session.snapshot(options, this.queryOptions_);
678
+ snapshot.begin(err => {
679
+ if (err) {
680
+ (0, instrument_1.setSpanError)(span, err);
681
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
682
+ span.addEvent('No session available', {
683
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
684
+ });
685
+ session.lastError = err;
686
+ this.pool_.release(session);
687
+ span.end();
688
+ this.getSnapshot(options, callback);
689
+ }
690
+ else {
691
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
692
+ this.pool_.release(session);
693
+ span.end();
694
+ callback(err);
695
+ }
696
+ return;
697
+ }
698
+ this._releaseOnEnd(session, snapshot, span);
699
+ span.end();
700
+ callback(err, snapshot);
701
+ });
642
702
  });
643
703
  });
644
704
  }
@@ -649,20 +709,34 @@ class Database extends common.GrpcServiceObject {
649
709
  const options = typeof optionsOrCallback === 'object' && optionsOrCallback
650
710
  ? optionsOrCallback
651
711
  : {};
652
- this.pool_.getSession((err, session, transaction) => {
653
- if (options.requestOptions) {
654
- transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
655
- }
656
- if (options.optimisticLock) {
657
- transaction.useOptimisticLock();
658
- }
659
- if (options.excludeTxnFromChangeStreams) {
660
- transaction.excludeTxnFromChangeStreams();
661
- }
662
- if (!err) {
663
- this._releaseOnEnd(session, transaction);
664
- }
665
- cb(err, transaction);
712
+ return (0, instrument_1.startTrace)('Database.getTransaction', this._traceConfig, span => {
713
+ this.pool_.getSession((err, session, transaction) => {
714
+ if (options.requestOptions) {
715
+ transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
716
+ }
717
+ if (options.optimisticLock) {
718
+ transaction.useOptimisticLock();
719
+ }
720
+ if (options.excludeTxnFromChangeStreams) {
721
+ transaction.excludeTxnFromChangeStreams();
722
+ }
723
+ if (!err) {
724
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
725
+ transaction._observabilityOptions = this._observabilityOptions;
726
+ this._releaseOnEnd(session, transaction, span);
727
+ }
728
+ else if ((0, session_pool_1.isSessionNotFoundError)(err)) {
729
+ span.addEvent('No session available', {
730
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
731
+ });
732
+ (0, instrument_1.setSpanError)(span, err);
733
+ }
734
+ else {
735
+ (0, instrument_1.setSpanError)(span, err);
736
+ }
737
+ span.end();
738
+ cb(err, transaction);
739
+ });
666
740
  });
667
741
  }
668
742
  async getOperations(optionsOrCallback) {
@@ -716,6 +790,8 @@ class Database extends common.GrpcServiceObject {
716
790
  callback(err, null);
717
791
  return;
718
792
  }
793
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
794
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
719
795
  config.reqOpts.session = session.formattedName_;
720
796
  this.request(config, (err, ...args) => {
721
797
  pool.release(session);
@@ -756,10 +832,17 @@ class Database extends common.GrpcServiceObject {
756
832
  }
757
833
  waitForSessionStream.on('reading', () => {
758
834
  pool.getSession((err, session_) => {
835
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
759
836
  if (err) {
837
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
838
+ span.addEvent('No session available', {
839
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
840
+ });
841
+ }
760
842
  destroyStream(err);
761
843
  return;
762
844
  }
845
+ span.addEvent('Using Session', { 'session.id': session_ === null || session_ === void 0 ? void 0 : session_.id });
763
846
  session = session_;
764
847
  config.reqOpts.session = session.formattedName_;
765
848
  requestStream = self.requestStream(config);
@@ -813,28 +896,53 @@ class Database extends common.GrpcServiceObject {
813
896
  const options = typeof optionsOrCallback === 'object'
814
897
  ? optionsOrCallback
815
898
  : {};
816
- this.runStream(query, options)
817
- .on('error', callback)
818
- .on('response', response => {
819
- if (response.metadata) {
820
- metadata = response.metadata;
821
- }
822
- })
823
- .on('stats', _stats => (stats = _stats))
824
- .on('data', row => {
825
- rows.push(row);
826
- })
827
- .on('end', () => {
828
- callback(null, rows, stats, metadata);
899
+ const traceConfig = {
900
+ sql: query,
901
+ ...this._traceConfig,
902
+ };
903
+ return (0, instrument_1.startTrace)('Database.run', traceConfig, span => {
904
+ this.runStream(query, options)
905
+ .on('error', err => {
906
+ (0, instrument_1.setSpanError)(span, err);
907
+ span.end();
908
+ callback(err, rows, stats, metadata);
909
+ })
910
+ .on('response', response => {
911
+ if (response.metadata) {
912
+ metadata = response.metadata;
913
+ }
914
+ })
915
+ .on('stats', _stats => (stats = _stats))
916
+ .on('data', row => {
917
+ rows.push(row);
918
+ })
919
+ .on('end', () => {
920
+ span.end();
921
+ callback(null, rows, stats, metadata);
922
+ });
829
923
  });
830
924
  }
831
925
  runPartitionedUpdate(query, callback) {
832
- this.pool_.getSession((err, session) => {
833
- if (err) {
834
- callback(err, 0);
835
- return;
836
- }
837
- this._runPartitionedUpdate(session, query, callback);
926
+ const traceConfig = {
927
+ sql: query,
928
+ ...this._traceConfig,
929
+ };
930
+ return (0, instrument_1.startTrace)('Database.runPartitionedUpdate', traceConfig, span => {
931
+ this.pool_.getSession((err, session) => {
932
+ if (err) {
933
+ (0, instrument_1.setSpanError)(span, err);
934
+ span.end();
935
+ callback(err, 0);
936
+ return;
937
+ }
938
+ this._runPartitionedUpdate(session, query, (err, count) => {
939
+ if (err) {
940
+ (0, instrument_1.setSpanError)(span, err);
941
+ }
942
+ span.end();
943
+ callback(err, count);
944
+ });
945
+ });
838
946
  });
839
947
  }
840
948
  _runPartitionedUpdate(session, query, callback) {
@@ -992,47 +1100,69 @@ class Database extends common.GrpcServiceObject {
992
1100
  */
993
1101
  runStream(query, options) {
994
1102
  const proxyStream = through.obj();
995
- this.pool_.getSession((err, session) => {
996
- if (err) {
997
- proxyStream.destroy(err);
998
- return;
999
- }
1000
- const snapshot = session.snapshot(options, this.queryOptions_);
1001
- this._releaseOnEnd(session, snapshot);
1002
- let dataReceived = false;
1003
- let dataStream = snapshot.runStream(query);
1004
- const endListener = () => snapshot.end();
1005
- dataStream
1006
- .once('data', () => (dataReceived = true))
1007
- .once('error', err => {
1008
- if (!dataReceived &&
1009
- (0, session_pool_1.isSessionNotFoundError)(err)) {
1010
- // If it is a 'Session not found' error and we have not yet received
1011
- // any data, we can safely retry the query on a new session.
1012
- // Register the error on the session so the pool can discard it.
1013
- if (session) {
1014
- session.lastError = err;
1015
- }
1016
- // Remove the current data stream from the end user stream.
1017
- dataStream.unpipe(proxyStream);
1018
- dataStream.removeListener('end', endListener);
1019
- dataStream.end();
1020
- snapshot.end();
1021
- // Create a new data stream and add it to the end user stream.
1022
- dataStream = this.runStream(query, options);
1023
- dataStream.pipe(proxyStream);
1024
- }
1025
- else {
1103
+ const traceConfig = {
1104
+ sql: query,
1105
+ ...this._traceConfig,
1106
+ };
1107
+ return (0, instrument_1.startTrace)('Database.runStream', traceConfig, span => {
1108
+ this.pool_.getSession((err, session) => {
1109
+ if (err) {
1110
+ (0, instrument_1.setSpanError)(span, err);
1026
1111
  proxyStream.destroy(err);
1112
+ span.end();
1113
+ return;
1114
+ }
1115
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
1116
+ const snapshot = session.snapshot(options, this.queryOptions_);
1117
+ this._releaseOnEnd(session, snapshot, span);
1118
+ let dataReceived = false;
1119
+ let dataStream = snapshot.runStream(query);
1120
+ const endListener = () => {
1027
1121
  snapshot.end();
1122
+ };
1123
+ dataStream
1124
+ .once('data', () => (dataReceived = true))
1125
+ .once('error', err => {
1126
+ (0, instrument_1.setSpanError)(span, err);
1127
+ if (!dataReceived &&
1128
+ (0, session_pool_1.isSessionNotFoundError)(err)) {
1129
+ // If it is a 'Session not found' error and we have not yet received
1130
+ // any data, we can safely retry the query on a new session.
1131
+ // Register the error on the session so the pool can discard it.
1132
+ if (session) {
1133
+ session.lastError = err;
1134
+ }
1135
+ span.addEvent('No session available', {
1136
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
1137
+ });
1138
+ // Remove the current data stream from the end user stream.
1139
+ dataStream.unpipe(proxyStream);
1140
+ dataStream.removeListener('end', endListener);
1141
+ dataStream.end();
1142
+ snapshot.end();
1143
+ span.end();
1144
+ // Create a new data stream and add it to the end user stream.
1145
+ dataStream = this.runStream(query, options);
1146
+ dataStream.pipe(proxyStream);
1147
+ }
1148
+ else {
1149
+ proxyStream.destroy(err);
1150
+ snapshot.end();
1151
+ }
1152
+ })
1153
+ .on('stats', stats => proxyStream.emit('stats', stats))
1154
+ .on('response', response => proxyStream.emit('response', response))
1155
+ .once('end', endListener)
1156
+ .pipe(proxyStream);
1157
+ });
1158
+ (0, stream_1.finished)(proxyStream, err => {
1159
+ if (err) {
1160
+ (0, instrument_1.setSpanError)(span, err);
1028
1161
  }
1029
- })
1030
- .on('stats', stats => proxyStream.emit('stats', stats))
1031
- .on('response', response => proxyStream.emit('response', response))
1032
- .once('end', endListener)
1033
- .pipe(proxyStream);
1162
+ span.end();
1163
+ });
1164
+ return proxyStream;
1034
1165
  });
1035
- return proxyStream;
1036
1166
  }
1037
1167
  runTransaction(optionsOrRunFn, fn) {
1038
1168
  const runFn = typeof optionsOrRunFn === 'function'
@@ -1041,32 +1171,50 @@ class Database extends common.GrpcServiceObject {
1041
1171
  const options = typeof optionsOrRunFn === 'object' && optionsOrRunFn
1042
1172
  ? optionsOrRunFn
1043
1173
  : {};
1044
- this.pool_.getSession((err, session, transaction) => {
1045
- if (err && (0, session_pool_1.isSessionNotFoundError)(err)) {
1046
- this.runTransaction(options, runFn);
1047
- return;
1048
- }
1049
- if (err) {
1050
- runFn(err);
1051
- return;
1052
- }
1053
- if (options.optimisticLock) {
1054
- transaction.useOptimisticLock();
1055
- }
1056
- if (options.excludeTxnFromChangeStreams) {
1057
- transaction.excludeTxnFromChangeStreams();
1058
- }
1059
- const release = this.pool_.release.bind(this.pool_, session);
1060
- const runner = new transaction_runner_1.TransactionRunner(session, transaction, runFn, options);
1061
- runner.run().then(release, err => {
1062
- if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1063
- release();
1174
+ (0, instrument_1.startTrace)('Database.runTransaction', this._traceConfig, span => {
1175
+ this.pool_.getSession((err, session, transaction) => {
1176
+ if (err) {
1177
+ (0, instrument_1.setSpanError)(span, err);
1178
+ }
1179
+ if (err && (0, session_pool_1.isSessionNotFoundError)(err)) {
1180
+ span.addEvent('No session available', {
1181
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
1182
+ });
1183
+ span.end();
1064
1184
  this.runTransaction(options, runFn);
1185
+ return;
1065
1186
  }
1066
- else {
1067
- setImmediate(runFn, err);
1068
- release();
1187
+ if (err) {
1188
+ span.end();
1189
+ runFn(err);
1190
+ return;
1191
+ }
1192
+ transaction._observabilityOptions = this._observabilityOptions;
1193
+ if (options.optimisticLock) {
1194
+ transaction.useOptimisticLock();
1069
1195
  }
1196
+ if (options.excludeTxnFromChangeStreams) {
1197
+ transaction.excludeTxnFromChangeStreams();
1198
+ }
1199
+ const release = () => {
1200
+ this.pool_.release(session);
1201
+ span.end();
1202
+ };
1203
+ const runner = new transaction_runner_1.TransactionRunner(session, transaction, runFn, options);
1204
+ runner.run().then(release, err => {
1205
+ (0, instrument_1.setSpanError)(span, err);
1206
+ if ((0, session_pool_1.isSessionNotFoundError)(err)) {
1207
+ span.addEvent('No session available', {
1208
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
1209
+ });
1210
+ release();
1211
+ this.runTransaction(options, runFn);
1212
+ }
1213
+ else {
1214
+ setImmediate(runFn, err);
1215
+ release();
1216
+ }
1217
+ });
1070
1218
  });
1071
1219
  });
1072
1220
  }
@@ -1136,34 +1284,48 @@ class Database extends common.GrpcServiceObject {
1136
1284
  const options = typeof optionsOrRunFn === 'object'
1137
1285
  ? optionsOrRunFn
1138
1286
  : {};
1287
+ let sessionId = '';
1139
1288
  const getSession = this.pool_.getSession.bind(this.pool_);
1140
- // Loop to retry 'Session not found' errors.
1141
- // (and yes, we like while (true) more than for (;;) here)
1142
- // eslint-disable-next-line no-constant-condition
1143
- while (true) {
1144
- try {
1145
- const [session, transaction] = await (0, promisify_1.promisify)(getSession)();
1146
- transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1147
- if (options.optimisticLock) {
1148
- transaction.useOptimisticLock();
1149
- }
1150
- if (options.excludeTxnFromChangeStreams) {
1151
- transaction.excludeTxnFromChangeStreams();
1152
- }
1153
- const runner = new transaction_runner_1.AsyncTransactionRunner(session, transaction, runFn, options);
1289
+ return (0, instrument_1.startTrace)('Database.runTransactionAsync', this._traceConfig, async (span) => {
1290
+ // Loop to retry 'Session not found' errors.
1291
+ // (and yes, we like while (true) more than for (;;) here)
1292
+ // eslint-disable-next-line no-constant-condition
1293
+ while (true) {
1154
1294
  try {
1155
- return await runner.run();
1156
- }
1157
- finally {
1158
- this.pool_.release(session);
1295
+ const [session, transaction] = await (0, promisify_1.promisify)(getSession)();
1296
+ transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1297
+ if (options.optimisticLock) {
1298
+ transaction.useOptimisticLock();
1299
+ }
1300
+ if (options.excludeTxnFromChangeStreams) {
1301
+ transaction.excludeTxnFromChangeStreams();
1302
+ }
1303
+ sessionId = session === null || session === void 0 ? void 0 : session.id;
1304
+ span.addEvent('Using Session', { 'session.id': sessionId });
1305
+ const runner = new transaction_runner_1.AsyncTransactionRunner(session, transaction, runFn, options);
1306
+ try {
1307
+ return await runner.run();
1308
+ }
1309
+ catch (e) {
1310
+ (0, instrument_1.setSpanErrorAndException)(span, e);
1311
+ throw e;
1312
+ }
1313
+ finally {
1314
+ span.end();
1315
+ this.pool_.release(session);
1316
+ }
1159
1317
  }
1160
- }
1161
- catch (e) {
1162
- if (!(0, session_pool_1.isSessionNotFoundError)(e)) {
1163
- throw e;
1318
+ catch (e) {
1319
+ if (!(0, session_pool_1.isSessionNotFoundError)(e)) {
1320
+ span.addEvent('No session available', {
1321
+ 'session.id': sessionId,
1322
+ });
1323
+ span.end();
1324
+ throw e;
1325
+ }
1164
1326
  }
1165
1327
  }
1166
- }
1328
+ });
1167
1329
  }
1168
1330
  /**
1169
1331
  * Write a batch of mutations to Spanner.
@@ -1225,52 +1387,66 @@ class Database extends common.GrpcServiceObject {
1225
1387
  */
1226
1388
  batchWriteAtLeastOnce(mutationGroups, options) {
1227
1389
  const proxyStream = through.obj();
1228
- this.pool_.getSession((err, session) => {
1229
- if (err) {
1230
- proxyStream.destroy(err);
1231
- return;
1232
- }
1233
- const gaxOpts = extend(true, {}, options === null || options === void 0 ? void 0 : options.gaxOptions);
1234
- const reqOpts = Object.assign({}, {
1235
- session: session.formattedName_,
1236
- mutationGroups: mutationGroups.map(mg => mg.proto()),
1237
- requestOptions: options === null || options === void 0 ? void 0 : options.requestOptions,
1238
- excludeTxnFromChangeStream: options === null || options === void 0 ? void 0 : options.excludeTxnFromChangeStreams,
1239
- });
1240
- let dataReceived = false;
1241
- let dataStream = this.requestStream({
1242
- client: 'SpannerClient',
1243
- method: 'batchWrite',
1244
- reqOpts,
1245
- gaxOpts,
1246
- headers: this.resourceHeader_,
1247
- });
1248
- dataStream
1249
- .once('data', () => (dataReceived = true))
1250
- .once('error', err => {
1251
- if (!dataReceived &&
1252
- (0, session_pool_1.isSessionNotFoundError)(err)) {
1253
- // If there's a 'Session not found' error and we have not yet received
1254
- // any data, we can safely retry the writes on a new session.
1255
- // Register the error on the session so the pool can discard it.
1256
- if (session) {
1257
- session.lastError = err;
1258
- }
1259
- // Remove the current data stream from the end user stream.
1260
- dataStream.unpipe(proxyStream);
1261
- dataStream.end();
1262
- // Create a new stream and add it to the end user stream.
1263
- dataStream = this.batchWriteAtLeastOnce(mutationGroups, options);
1264
- dataStream.pipe(proxyStream);
1265
- }
1266
- else {
1390
+ return (0, instrument_1.startTrace)('Database.batchWriteAtLeastOnce', this._traceConfig, span => {
1391
+ this.pool_.getSession((err, session) => {
1392
+ if (err) {
1267
1393
  proxyStream.destroy(err);
1394
+ (0, instrument_1.setSpanError)(span, err);
1395
+ span.end();
1396
+ return;
1268
1397
  }
1269
- })
1270
- .once('end', () => this.pool_.release(session))
1271
- .pipe(proxyStream);
1398
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
1399
+ const gaxOpts = extend(true, {}, options === null || options === void 0 ? void 0 : options.gaxOptions);
1400
+ const reqOpts = Object.assign({}, {
1401
+ session: session.formattedName_,
1402
+ mutationGroups: mutationGroups.map(mg => mg.proto()),
1403
+ requestOptions: options === null || options === void 0 ? void 0 : options.requestOptions,
1404
+ excludeTxnFromChangeStream: options === null || options === void 0 ? void 0 : options.excludeTxnFromChangeStreams,
1405
+ });
1406
+ let dataReceived = false;
1407
+ let dataStream = this.requestStream({
1408
+ client: 'SpannerClient',
1409
+ method: 'batchWrite',
1410
+ reqOpts,
1411
+ gaxOpts,
1412
+ headers: this.resourceHeader_,
1413
+ });
1414
+ dataStream
1415
+ .once('data', () => (dataReceived = true))
1416
+ .once('error', err => {
1417
+ (0, instrument_1.setSpanError)(span, err);
1418
+ if (!dataReceived &&
1419
+ (0, session_pool_1.isSessionNotFoundError)(err)) {
1420
+ // If there's a 'Session not found' error and we have not yet received
1421
+ // any data, we can safely retry the writes on a new session.
1422
+ // Register the error on the session so the pool can discard it.
1423
+ if (session) {
1424
+ session.lastError = err;
1425
+ }
1426
+ span.addEvent('No session available', {
1427
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
1428
+ });
1429
+ // Remove the current data stream from the end user stream.
1430
+ dataStream.unpipe(proxyStream);
1431
+ dataStream.end();
1432
+ span.end();
1433
+ // Create a new stream and add it to the end user stream.
1434
+ dataStream = this.batchWriteAtLeastOnce(mutationGroups, options);
1435
+ dataStream.pipe(proxyStream);
1436
+ }
1437
+ else {
1438
+ span.end();
1439
+ proxyStream.destroy(err);
1440
+ }
1441
+ })
1442
+ .once('end', () => {
1443
+ span.end();
1444
+ this.pool_.release(session);
1445
+ })
1446
+ .pipe(proxyStream);
1447
+ });
1448
+ return proxyStream;
1272
1449
  });
1273
- return proxyStream;
1274
1450
  }
1275
1451
  writeAtLeastOnce(mutations, optionsOrCallback, callback) {
1276
1452
  const cb = typeof optionsOrCallback === 'function'
@@ -1279,18 +1455,40 @@ class Database extends common.GrpcServiceObject {
1279
1455
  const options = typeof optionsOrCallback === 'object' && optionsOrCallback
1280
1456
  ? optionsOrCallback
1281
1457
  : {};
1282
- this.pool_.getSession((err, session, transaction) => {
1283
- if (err && (0, session_pool_1.isSessionNotFoundError)(err)) {
1284
- this.writeAtLeastOnce(mutations, options, cb);
1285
- return;
1286
- }
1287
- if (err) {
1288
- cb(err);
1289
- return;
1290
- }
1291
- this._releaseOnEnd(session, transaction);
1292
- transaction === null || transaction === void 0 ? void 0 : transaction.setQueuedMutations(mutations.proto());
1293
- return transaction === null || transaction === void 0 ? void 0 : transaction.commit(options, cb);
1458
+ return (0, instrument_1.startTrace)('Database.writeAtLeastOnce', this._traceConfig, span => {
1459
+ this.pool_.getSession((err, session, transaction) => {
1460
+ if (err && (0, session_pool_1.isSessionNotFoundError)(err)) {
1461
+ span.addEvent('No session available', {
1462
+ 'session.id': session === null || session === void 0 ? void 0 : session.id,
1463
+ });
1464
+ span.end();
1465
+ this.writeAtLeastOnce(mutations, options, cb);
1466
+ return;
1467
+ }
1468
+ if (err) {
1469
+ (0, instrument_1.setSpanError)(span, err);
1470
+ span.end();
1471
+ cb(err);
1472
+ return;
1473
+ }
1474
+ span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
1475
+ this._releaseOnEnd(session, transaction, span);
1476
+ try {
1477
+ transaction === null || transaction === void 0 ? void 0 : transaction.setQueuedMutations(mutations.proto());
1478
+ return transaction === null || transaction === void 0 ? void 0 : transaction.commit(options, (err, resp) => {
1479
+ if (err) {
1480
+ (0, instrument_1.setSpanError)(span, err);
1481
+ }
1482
+ span.end();
1483
+ cb(err, resp);
1484
+ });
1485
+ }
1486
+ catch (e) {
1487
+ (0, instrument_1.setSpanErrorAndException)(span, e);
1488
+ span.end();
1489
+ throw e;
1490
+ }
1491
+ });
1294
1492
  });
1295
1493
  }
1296
1494
  /**