@google-cloud/spanner 7.19.1 → 7.21.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.
@@ -20,6 +20,7 @@ import { CallOptions, Operation as GaxOperation } from 'google-gax';
20
20
  import { BatchTransaction, TransactionIdentifier } from './batch-transaction';
21
21
  import { SessionFactoryInterface } from './session-factory';
22
22
  import { google as databaseAdmin, google, google as spannerClient } from '../protos/protos';
23
+ import IsolationLevel = google.spanner.v1.TransactionOptions.IsolationLevel;
23
24
  import { GetDatabaseOperationsOptions, GetDatabaseOperationsResponse, Instance, GetDatabaseOperationsCallback } from './instance';
24
25
  import { PartialResultStream } from './partial-result-stream';
25
26
  import { Session } from './session';
@@ -148,6 +149,9 @@ export interface RestoreOptions {
148
149
  encryptionConfig?: databaseAdmin.spanner.admin.database.v1.IRestoreDatabaseEncryptionConfig;
149
150
  gaxOptions?: CallOptions;
150
151
  }
152
+ export interface WriteAtLeastOnceOptions extends CallOptions {
153
+ isolationLevel?: IsolationLevel;
154
+ }
151
155
  /**
152
156
  * Create a Database object to interact with a Cloud Spanner database.
153
157
  *
@@ -184,7 +188,10 @@ declare class Database extends common.GrpcServiceObject {
184
188
  databaseDialect?: EnumKey<typeof databaseAdmin.spanner.admin.database.v1.DatabaseDialect> | null;
185
189
  _observabilityOptions?: ObservabilityOptions;
186
190
  private _traceConfig;
191
+ private _nthRequest;
192
+ _clientId: number;
187
193
  constructor(instance: Instance, name: string, poolOptions?: SessionPoolConstructor | SessionPoolOptions, queryOptions?: spannerClient.spanner.v1.ExecuteSqlRequest.IQueryOptions);
194
+ _nextNthRequest(): number;
188
195
  /**
189
196
  * @typedef {array} SetDatabaseMetadataResponse
190
197
  * @property {object} 0 The {@link Database} metadata.
@@ -313,6 +320,11 @@ declare class Database extends common.GrpcServiceObject {
313
320
  */
314
321
  batchCreateSessions(options: number | BatchCreateSessionsOptions): Promise<BatchCreateSessionsResponse>;
315
322
  batchCreateSessions(options: number | BatchCreateSessionsOptions, callback: BatchCreateSessionsCallback): void;
323
+ _metadataWithRequestId(nthRequest: number, attempt: number, priorMetadata?: {
324
+ [k: string]: string;
325
+ }): {
326
+ [k: string]: string;
327
+ };
316
328
  /**
317
329
  * Get a reference to a {@link BatchTransaction} object.
318
330
  *
@@ -1896,9 +1908,9 @@ declare class Database extends common.GrpcServiceObject {
1896
1908
  * ```
1897
1909
  */
1898
1910
  writeAtLeastOnce(mutations: MutationSet): Promise<CommitResponse>;
1899
- writeAtLeastOnce(mutations: MutationSet, options: CallOptions): Promise<CommitResponse>;
1911
+ writeAtLeastOnce(mutations: MutationSet, options: WriteAtLeastOnceOptions): Promise<CommitResponse>;
1900
1912
  writeAtLeastOnce(mutations: MutationSet, callback: CommitCallback): void;
1901
- writeAtLeastOnce(mutations: MutationSet, options: CallOptions, callback: CommitCallback): void;
1913
+ writeAtLeastOnce(mutations: MutationSet, options: WriteAtLeastOnceOptions, callback: CommitCallback): void;
1902
1914
  /**
1903
1915
  * Create a Session object.
1904
1916
  *
@@ -35,6 +35,7 @@ const stream_1 = require("stream");
35
35
  const arrify = require("arrify");
36
36
  const snakeCase = require("lodash.snakecase");
37
37
  const instrument_1 = require("./instrument");
38
+ const request_id_header_1 = require("./request_id_header");
38
39
  /**
39
40
  * Create a Database object to interact with a Cloud Spanner database.
40
41
  *
@@ -154,6 +155,13 @@ class Database extends common.GrpcServiceObject {
154
155
  dbName: this.formattedName_,
155
156
  };
156
157
  this.request = instance.request;
158
+ this._nthRequest = (0, request_id_header_1.newAtomicCounter)(0);
159
+ if (this.parent && this.parent.parent) {
160
+ this._clientId = this.parent.parent._nthClientId;
161
+ }
162
+ else {
163
+ this._clientId = instance._nthClientId;
164
+ }
157
165
  this._observabilityOptions = instance._observabilityOptions;
158
166
  this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.formattedName_, (_a = this._observabilityOptions) === null || _a === void 0 ? void 0 : _a.enableEndToEndTracing);
159
167
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -167,6 +175,9 @@ class Database extends common.GrpcServiceObject {
167
175
  }
168
176
  this.queryOptions_ = Object.assign(Object.assign({}, queryOptions), Database.getEnvironmentQueryOptions());
169
177
  }
178
+ _nextNthRequest() {
179
+ return this._nthRequest.increment();
180
+ }
170
181
  setMetadata(metadata, optionsOrCallback, cb) {
171
182
  const gaxOpts = typeof optionsOrCallback === 'object' ? optionsOrCallback : {};
172
183
  const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : cb;
@@ -213,13 +224,14 @@ class Database extends common.GrpcServiceObject {
213
224
  if (this._getSpanner().routeToLeaderEnabled) {
214
225
  (0, common_1.addLeaderAwareRoutingHeader)(headers);
215
226
  }
227
+ const allHeaders = this._metadataWithRequestId(this._nextNthRequest(), 1, headers);
216
228
  (0, instrument_1.startTrace)('Database.batchCreateSessions', this._traceConfig, span => {
217
229
  this.request({
218
230
  client: 'SpannerClient',
219
231
  method: 'batchCreateSessions',
220
232
  reqOpts,
221
233
  gaxOpts: options.gaxOptions,
222
- headers: headers,
234
+ headers: allHeaders,
223
235
  }, (err, resp) => {
224
236
  if (err) {
225
237
  (0, instrument_1.setSpanError)(span, err);
@@ -238,6 +250,17 @@ class Database extends common.GrpcServiceObject {
238
250
  });
239
251
  });
240
252
  }
253
+ _metadataWithRequestId(nthRequest, attempt, priorMetadata) {
254
+ if (!priorMetadata) {
255
+ priorMetadata = {};
256
+ }
257
+ const withReqId = {
258
+ ...priorMetadata,
259
+ };
260
+ 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
261
+ nthRequest, attempt);
262
+ return withReqId;
263
+ }
241
264
  /**
242
265
  * Get a reference to a {@link BatchTransaction} object.
243
266
  *
@@ -330,7 +353,7 @@ class Database extends common.GrpcServiceObject {
330
353
  reqOpts.session.labels = options.labels || this.labels || null;
331
354
  reqOpts.session.creatorRole =
332
355
  options.databaseRole || this.databaseRole || null;
333
- const headers = this.commonHeaders_;
356
+ const headers = this._metadataWithRequestId(this._nextNthRequest(), 1, this.commonHeaders_);
334
357
  if (this._getSpanner().routeToLeaderEnabled) {
335
358
  (0, common_1.addLeaderAwareRoutingHeader)(headers);
336
359
  }
@@ -568,13 +591,14 @@ class Database extends common.GrpcServiceObject {
568
591
  delete gaxOpts.pageSize;
569
592
  delete gaxOpts.pageToken;
570
593
  }
594
+ const headers = this._metadataWithRequestId(this._nextNthRequest(), 1, this.commonHeaders_);
571
595
  return (0, instrument_1.startTrace)('Database.getSessions', this._traceConfig, span => {
572
596
  this.request({
573
597
  client: 'SpannerClient',
574
598
  method: 'listSessions',
575
599
  reqOpts,
576
600
  gaxOpts,
577
- headers: this.commonHeaders_,
601
+ headers: headers,
578
602
  }, (err, sessions, nextPageRequest, ...args) => {
579
603
  if (err) {
580
604
  (0, instrument_1.setSpanError)(span, err);
@@ -717,24 +741,23 @@ class Database extends common.GrpcServiceObject {
717
741
  });
718
742
  }
719
743
  getTransaction(optionsOrCallback, callback) {
744
+ var _a;
720
745
  const cb = typeof optionsOrCallback === 'function'
721
746
  ? optionsOrCallback
722
747
  : callback;
723
748
  const options = typeof optionsOrCallback === 'object' && optionsOrCallback
724
749
  ? optionsOrCallback
725
750
  : {};
726
- return (0, instrument_1.startTrace)('Database.getTransaction', this._traceConfig, span => {
751
+ return (0, instrument_1.startTrace)('Database.getTransaction', {
752
+ ...this._traceConfig,
753
+ transactionTag: (_a = options.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag,
754
+ }, span => {
727
755
  this.pool_.getSession((err, session, transaction) => {
728
- if (options.requestOptions) {
729
- transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
730
- }
731
- if (options.optimisticLock) {
732
- transaction.useOptimisticLock();
733
- }
734
- if (options.excludeTxnFromChangeStreams) {
735
- transaction.excludeTxnFromChangeStreams();
736
- }
737
756
  if (!err) {
757
+ if (options.requestOptions) {
758
+ transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
759
+ }
760
+ transaction === null || transaction === void 0 ? void 0 : transaction.setReadWriteTransactionOptions(options);
738
761
  span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
739
762
  transaction._observabilityOptions = this._observabilityOptions;
740
763
  this._releaseOnEnd(session, transaction, span);
@@ -900,11 +923,10 @@ class Database extends common.GrpcServiceObject {
900
923
  const options = typeof optionsOrCallback === 'object'
901
924
  ? optionsOrCallback
902
925
  : {};
903
- const traceConfig = {
904
- sql: query,
926
+ return (0, instrument_1.startTrace)('Database.run', {
927
+ ...query,
905
928
  ...this._traceConfig,
906
- };
907
- return (0, instrument_1.startTrace)('Database.run', traceConfig, span => {
929
+ }, span => {
908
930
  this.runStream(query, options)
909
931
  .on('error', err => {
910
932
  (0, instrument_1.setSpanError)(span, err);
@@ -927,12 +949,13 @@ class Database extends common.GrpcServiceObject {
927
949
  });
928
950
  }
929
951
  runPartitionedUpdate(query, callback) {
930
- const traceConfig = {
931
- sql: query,
952
+ var _a;
953
+ return (0, instrument_1.startTrace)('Database.runPartitionedUpdate', {
954
+ ...query,
932
955
  ...this._traceConfig,
933
- };
934
- return (0, instrument_1.startTrace)('Database.runPartitionedUpdate', traceConfig, span => {
935
- this.pool_.getSession((err, session) => {
956
+ requestTag: (_a = query === null || query === void 0 ? void 0 : query.requestOptions) === null || _a === void 0 ? void 0 : _a.requestTag,
957
+ }, span => {
958
+ this.sessionFactory_.getSessionForPartitionedOps((err, session) => {
936
959
  if (err) {
937
960
  (0, instrument_1.setSpanError)(span, err);
938
961
  span.end();
@@ -956,21 +979,21 @@ class Database extends common.GrpcServiceObject {
956
979
  }
957
980
  transaction.begin(err => {
958
981
  if (err) {
959
- this.pool_.release(session);
982
+ this.sessionFactory_.release(session);
960
983
  callback(err, 0);
961
984
  return;
962
985
  }
963
986
  transaction.runUpdate(query, (err, updateCount) => {
964
987
  if (err) {
965
988
  if (err.code !== google_gax_1.grpc.status.ABORTED) {
966
- this.pool_.release(session);
989
+ this.sessionFactory_.release(session);
967
990
  callback(err, 0);
968
991
  return;
969
992
  }
970
993
  this._runPartitionedUpdate(session, query, callback);
971
994
  }
972
995
  else {
973
- this.pool_.release(session);
996
+ this.sessionFactory_.release(session);
974
997
  callback(null, updateCount);
975
998
  return;
976
999
  }
@@ -1103,12 +1126,13 @@ class Database extends common.GrpcServiceObject {
1103
1126
  * ```
1104
1127
  */
1105
1128
  runStream(query, options) {
1129
+ var _a;
1106
1130
  const proxyStream = through.obj();
1107
- const traceConfig = {
1108
- sql: query,
1131
+ return (0, instrument_1.startTrace)('Database.runStream', {
1132
+ ...query,
1109
1133
  ...this._traceConfig,
1110
- };
1111
- return (0, instrument_1.startTrace)('Database.runStream', traceConfig, span => {
1134
+ requestTag: (_a = query === null || query === void 0 ? void 0 : query.requestOptions) === null || _a === void 0 ? void 0 : _a.requestTag,
1135
+ }, span => {
1112
1136
  this.sessionFactory_.getSession((err, session) => {
1113
1137
  if (err) {
1114
1138
  (0, instrument_1.setSpanError)(span, err);
@@ -1170,13 +1194,17 @@ class Database extends common.GrpcServiceObject {
1170
1194
  });
1171
1195
  }
1172
1196
  runTransaction(optionsOrRunFn, fn) {
1197
+ var _a;
1173
1198
  const runFn = typeof optionsOrRunFn === 'function'
1174
1199
  ? optionsOrRunFn
1175
1200
  : fn;
1176
1201
  const options = typeof optionsOrRunFn === 'object' && optionsOrRunFn
1177
1202
  ? optionsOrRunFn
1178
1203
  : {};
1179
- (0, instrument_1.startTrace)('Database.runTransaction', this._traceConfig, span => {
1204
+ (0, instrument_1.startTrace)('Database.runTransaction', {
1205
+ ...this._traceConfig,
1206
+ transactionTag: (_a = options.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag,
1207
+ }, span => {
1180
1208
  this.pool_.getSession((err, session, transaction) => {
1181
1209
  if (err) {
1182
1210
  (0, instrument_1.setSpanError)(span, err);
@@ -1195,12 +1223,8 @@ class Database extends common.GrpcServiceObject {
1195
1223
  return;
1196
1224
  }
1197
1225
  transaction._observabilityOptions = this._observabilityOptions;
1198
- if (options.optimisticLock) {
1199
- transaction.useOptimisticLock();
1200
- }
1201
- if (options.excludeTxnFromChangeStreams) {
1202
- transaction.excludeTxnFromChangeStreams();
1203
- }
1226
+ transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1227
+ transaction.setReadWriteTransactionOptions(options);
1204
1228
  const release = () => {
1205
1229
  this.pool_.release(session);
1206
1230
  span.end();
@@ -1283,6 +1307,7 @@ class Database extends common.GrpcServiceObject {
1283
1307
  * ```
1284
1308
  */
1285
1309
  async runTransactionAsync(optionsOrRunFn, fn) {
1310
+ var _a;
1286
1311
  const runFn = typeof optionsOrRunFn === 'function'
1287
1312
  ? optionsOrRunFn
1288
1313
  : fn;
@@ -1291,7 +1316,10 @@ class Database extends common.GrpcServiceObject {
1291
1316
  : {};
1292
1317
  let sessionId = '';
1293
1318
  const getSession = this.pool_.getSession.bind(this.pool_);
1294
- return (0, instrument_1.startTrace)('Database.runTransactionAsync', this._traceConfig, async (span) => {
1319
+ return (0, instrument_1.startTrace)('Database.runTransactionAsync', {
1320
+ ...this._traceConfig,
1321
+ transactionTag: (_a = options === null || options === void 0 ? void 0 : options.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag,
1322
+ }, async (span) => {
1295
1323
  // Loop to retry 'Session not found' errors.
1296
1324
  // (and yes, we like while (true) more than for (;;) here)
1297
1325
  // eslint-disable-next-line no-constant-condition
@@ -1299,12 +1327,7 @@ class Database extends common.GrpcServiceObject {
1299
1327
  try {
1300
1328
  const [session, transaction] = await (0, promisify_1.promisify)(getSession)();
1301
1329
  transaction.requestOptions = Object.assign(transaction.requestOptions || {}, options.requestOptions);
1302
- if (options.optimisticLock) {
1303
- transaction.useOptimisticLock();
1304
- }
1305
- if (options.excludeTxnFromChangeStreams) {
1306
- transaction.excludeTxnFromChangeStreams();
1307
- }
1330
+ transaction.setReadWriteTransactionOptions(options);
1308
1331
  sessionId = session === null || session === void 0 ? void 0 : session.id;
1309
1332
  span.addEvent('Using Session', { 'session.id': sessionId });
1310
1333
  const runner = new transaction_runner_1.AsyncTransactionRunner(session, transaction, runFn, options);
@@ -1393,8 +1416,12 @@ class Database extends common.GrpcServiceObject {
1393
1416
  * ```
1394
1417
  */
1395
1418
  batchWriteAtLeastOnce(mutationGroups, options) {
1419
+ var _a;
1396
1420
  const proxyStream = through.obj();
1397
- return (0, instrument_1.startTrace)('Database.batchWriteAtLeastOnce', this._traceConfig, span => {
1421
+ return (0, instrument_1.startTrace)('Database.batchWriteAtLeastOnce', {
1422
+ ...this._traceConfig,
1423
+ transactionTag: (_a = options === null || options === void 0 ? void 0 : options.requestOptions) === null || _a === void 0 ? void 0 : _a.transactionTag,
1424
+ }, span => {
1398
1425
  this.pool_.getSession((err, session) => {
1399
1426
  if (err) {
1400
1427
  proxyStream.destroy(err);
@@ -1483,6 +1510,7 @@ class Database extends common.GrpcServiceObject {
1483
1510
  span.addEvent('Using Session', { 'session.id': session === null || session === void 0 ? void 0 : session.id });
1484
1511
  this._releaseOnEnd(session, transaction, span);
1485
1512
  try {
1513
+ transaction.setReadWriteTransactionOptions(options);
1486
1514
  transaction === null || transaction === void 0 ? void 0 : transaction.setQueuedMutations(mutations.proto());
1487
1515
  return transaction === null || transaction === void 0 ? void 0 : transaction.commit(options, (err, resp) => {
1488
1516
  if (err) {
@@ -17,7 +17,7 @@ import { GrpcService } from './common-grpc/service';
17
17
  import { PreciseDate } from '@google-cloud/precise-date';
18
18
  import { GoogleAuth, GoogleAuthOptions } from 'google-auth-library';
19
19
  import { common as p } from 'protobufjs';
20
- import { Float32, Float, Int, Numeric, PGNumeric, PGJsonb, SpannerDate, Struct, ProtoMessage, ProtoEnum, IProtoMessageParams, IProtoEnumParams } from './codec';
20
+ import { Float32, Float, Int, Numeric, PGNumeric, PGJsonb, SpannerDate, Interval, Struct, ProtoMessage, ProtoEnum, IProtoMessageParams, IProtoEnumParams } from './codec';
21
21
  import { Backup } from './backup';
22
22
  import { Database } from './database';
23
23
  import { Instance, CreateInstanceCallback, CreateInstanceResponse } from './instance';
@@ -62,7 +62,9 @@ export interface SpannerOptions extends GrpcClientOptions {
62
62
  sslCreds?: grpc.ChannelCredentials;
63
63
  routeToLeaderEnabled?: boolean;
64
64
  directedReadOptions?: google.spanner.v1.IDirectedReadOptions | null;
65
+ defaultTransactionOptions?: Pick<RunTransactionOptions, 'isolationLevel'>;
65
66
  observabilityOptions?: ObservabilityOptions;
67
+ interceptors?: any[];
66
68
  }
67
69
  export interface RequestConfig {
68
70
  client: string;
@@ -168,7 +170,9 @@ declare class Spanner extends GrpcService {
168
170
  };
169
171
  routeToLeaderEnabled: boolean;
170
172
  directedReadOptions: google.spanner.v1.IDirectedReadOptions | null;
173
+ defaultTransactionOptions: RunTransactionOptions;
171
174
  _observabilityOptions: ObservabilityOptions | undefined;
175
+ readonly _nthClientId: number;
172
176
  /**
173
177
  * Placeholder used to auto populate a column with the commit timestamp.
174
178
  * This can only be used for timestamp columns that have set the option
@@ -971,6 +975,21 @@ declare class Spanner extends GrpcService {
971
975
  * ```
972
976
  */
973
977
  static pgJsonb(value: any): PGJsonb;
978
+ /**
979
+ * Helper function to get a Cloud Spanner Interval object.
980
+ *
981
+ * @param {number} months The months part of Interval as number.
982
+ * @param {number} days The days part of Interval as number.
983
+ * @param {bigint} nanoseconds The nanoseconds part of Interval as bigint.
984
+ * @returns {Interval}
985
+ *
986
+ * @example
987
+ * ```
988
+ * const {Spanner} = require('@google-cloud/spanner');
989
+ * const interval = Spanner.Interval(10, 20, BigInt(30));
990
+ * ```
991
+ */
992
+ static interval(months: number, days: number, nanoseconds: bigint): Interval;
974
993
  /**
975
994
  * @typedef IProtoMessageParams
976
995
  * @property {object} value Proto Message value as serialized-buffer or message object.
@@ -1186,10 +1205,11 @@ export { MutationSet };
1186
1205
  */
1187
1206
  import * as protos from '../protos/protos';
1188
1207
  import IInstanceConfig = instanceAdmin.spanner.admin.instance.v1.IInstanceConfig;
1208
+ import { RunTransactionOptions } from './transaction-runner';
1189
1209
  export { v1, protos };
1190
1210
  declare const _default: {
1191
1211
  Spanner: typeof Spanner;
1192
1212
  };
1193
1213
  export default _default;
1194
- export { Float32, Float, Int, Struct, Numeric, PGNumeric, SpannerDate };
1214
+ export { Float32, Float, Int, Struct, Numeric, PGNumeric, SpannerDate, Interval };
1195
1215
  export { ObservabilityOptions };
@@ -15,7 +15,7 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.SpannerDate = exports.PGNumeric = exports.Numeric = exports.Struct = exports.Int = exports.Float = exports.Float32 = exports.protos = exports.v1 = exports.MutationSet = exports.MutationGroup = exports.Transaction = exports.Snapshot = exports.PartitionedDml = exports.Table = exports.SessionPool = exports.Session = exports.Backup = exports.Database = exports.InstanceConfig = exports.Instance = exports.Spanner = void 0;
18
+ exports.Interval = exports.SpannerDate = exports.PGNumeric = exports.Numeric = exports.Struct = exports.Int = exports.Float = exports.Float32 = exports.protos = exports.v1 = exports.MutationSet = exports.MutationGroup = exports.Transaction = exports.Snapshot = exports.PartitionedDml = exports.Table = exports.SessionPool = exports.Session = exports.Backup = exports.Database = exports.InstanceConfig = exports.Instance = exports.Spanner = void 0;
19
19
  const service_1 = require("./common-grpc/service");
20
20
  const precise_date_1 = require("@google-cloud/precise-date");
21
21
  const projectify_1 = require("@google-cloud/projectify");
@@ -32,6 +32,7 @@ Object.defineProperty(exports, "Int", { enumerable: true, get: function () { ret
32
32
  Object.defineProperty(exports, "Numeric", { enumerable: true, get: function () { return codec_1.Numeric; } });
33
33
  Object.defineProperty(exports, "PGNumeric", { enumerable: true, get: function () { return codec_1.PGNumeric; } });
34
34
  Object.defineProperty(exports, "SpannerDate", { enumerable: true, get: function () { return codec_1.SpannerDate; } });
35
+ Object.defineProperty(exports, "Interval", { enumerable: true, get: function () { return codec_1.Interval; } });
35
36
  Object.defineProperty(exports, "Struct", { enumerable: true, get: function () { return codec_1.Struct; } });
36
37
  const api_1 = require("@opentelemetry/api");
37
38
  const backup_1 = require("./backup");
@@ -44,6 +45,7 @@ const instance_config_1 = require("./instance-config");
44
45
  Object.defineProperty(exports, "InstanceConfig", { enumerable: true, get: function () { return instance_config_1.InstanceConfig; } });
45
46
  const google_gax_1 = require("google-gax");
46
47
  const protos_1 = require("../protos/protos");
48
+ var IsolationLevel = protos_1.google.spanner.v1.TransactionOptions.IsolationLevel;
47
49
  const common_1 = require("./common");
48
50
  const session_1 = require("./session");
49
51
  Object.defineProperty(exports, "Session", { enumerable: true, get: function () { return session_1.Session; } });
@@ -62,6 +64,7 @@ const grpcGcp = grpcGcpModule(google_gax_1.grpc);
62
64
  const v1 = require("./v1");
63
65
  exports.v1 = v1;
64
66
  const instrument_1 = require("./instrument");
67
+ const request_id_header_1 = require("./request_id_header");
65
68
  // eslint-disable-next-line @typescript-eslint/no-var-requires
66
69
  const gcpApiConfig = require('./spanner_grpc_config.json');
67
70
  /**
@@ -163,6 +166,12 @@ class Spanner extends service_1.GrpcService {
163
166
  ? options.directedReadOptions
164
167
  : null;
165
168
  delete options.directedReadOptions;
169
+ const defaultTransactionOptions = options.defaultTransactionOptions
170
+ ? options.defaultTransactionOptions
171
+ : {
172
+ isolationLevel: IsolationLevel.ISOLATION_LEVEL_UNSPECIFIED,
173
+ };
174
+ delete options.defaultTransactionOptions;
166
175
  const emulatorHost = Spanner.getSpannerEmulatorHost();
167
176
  if (emulatorHost &&
168
177
  emulatorHost.endpoint &&
@@ -199,9 +208,11 @@ class Spanner extends service_1.GrpcService {
199
208
  this.projectIdReplaced_ = false;
200
209
  this.projectFormattedName_ = 'projects/' + this.projectId;
201
210
  this.directedReadOptions = directedReadOptions;
211
+ this.defaultTransactionOptions = defaultTransactionOptions;
202
212
  this._observabilityOptions = options.observabilityOptions;
203
213
  this.commonHeaders_ = (0, common_1.getCommonHeaders)(this.projectFormattedName_, (_a = this._observabilityOptions) === null || _a === void 0 ? void 0 : _a.enableEndToEndTracing);
204
214
  (0, instrument_1.ensureInitialContextManagerSet)();
215
+ this._nthClientId = (0, request_id_header_1.nextSpannerClientId)();
205
216
  }
206
217
  /**
207
218
  * Gets the InstanceAdminClient object.
@@ -691,6 +702,8 @@ class Spanner extends service_1.GrpcService {
691
702
  carrier[key] = value; // Set the span context (trace and span ID)
692
703
  },
693
704
  });
705
+ // Attach the x-goog-spanner-request-id to the currently active span.
706
+ (0, request_id_header_1.attributeXGoogSpannerRequestIdToActiveSpan)(config);
694
707
  const requestFn = gaxClient[config.method].bind(gaxClient, reqOpts,
695
708
  // Add headers to `gaxOpts`
696
709
  extend(true, {}, config.gaxOpts, {
@@ -698,7 +711,48 @@ class Spanner extends service_1.GrpcService {
698
711
  headers: config.headers,
699
712
  },
700
713
  }));
701
- callback(null, requestFn);
714
+ // Wrap requestFn to inject the spanner request id into every returned error.
715
+ const wrappedRequestFn = (...args) => {
716
+ const hasCallback = args &&
717
+ args.length > 0 &&
718
+ typeof args[args.length - 1] === 'function';
719
+ switch (hasCallback) {
720
+ case true: {
721
+ const cb = args[args.length - 1];
722
+ const priorArgs = args.slice(0, args.length - 1);
723
+ requestFn(...priorArgs, (...results) => {
724
+ if (results && results.length > 0) {
725
+ const err = results[0];
726
+ (0, request_id_header_1.injectRequestIDIntoError)(config, err);
727
+ }
728
+ cb(...results);
729
+ });
730
+ return;
731
+ }
732
+ case false: {
733
+ const res = requestFn(...args);
734
+ const stream = res;
735
+ if (stream) {
736
+ stream.on('error', err => {
737
+ (0, request_id_header_1.injectRequestIDIntoError)(config, err);
738
+ });
739
+ }
740
+ const originallyPromise = res instanceof Promise;
741
+ if (!originallyPromise) {
742
+ return res;
743
+ }
744
+ return new Promise((resolve, reject) => {
745
+ requestFn(...args)
746
+ .then(resolve)
747
+ .catch(err => {
748
+ (0, request_id_header_1.injectRequestIDIntoError)(config, err);
749
+ reject(err);
750
+ });
751
+ });
752
+ }
753
+ }
754
+ };
755
+ callback(null, wrappedRequestFn);
702
756
  });
703
757
  }
704
758
  /**
@@ -936,6 +990,23 @@ class Spanner extends service_1.GrpcService {
936
990
  static pgJsonb(value) {
937
991
  return new codec_1.codec.PGJsonb(value);
938
992
  }
993
+ /**
994
+ * Helper function to get a Cloud Spanner Interval object.
995
+ *
996
+ * @param {number} months The months part of Interval as number.
997
+ * @param {number} days The days part of Interval as number.
998
+ * @param {bigint} nanoseconds The nanoseconds part of Interval as bigint.
999
+ * @returns {Interval}
1000
+ *
1001
+ * @example
1002
+ * ```
1003
+ * const {Spanner} = require('@google-cloud/spanner');
1004
+ * const interval = Spanner.Interval(10, 20, BigInt(30));
1005
+ * ```
1006
+ */
1007
+ static interval(months, days, nanoseconds) {
1008
+ return new codec_1.codec.Interval(months, days, nanoseconds);
1009
+ }
939
1010
  /**
940
1011
  * @typedef IProtoMessageParams
941
1012
  * @property {object} value Proto Message value as serialized-buffer or message object.
@@ -1040,6 +1111,7 @@ Spanner.GOOGLE_STANDARD_SQL = protos_1.google.spanner.admin.database.v1.Database
1040
1111
  'pgJsonb',
1041
1112
  'operation',
1042
1113
  'timestamp',
1114
+ 'interval',
1043
1115
  'getInstanceAdminClient',
1044
1116
  'getDatabaseAdminClient',
1045
1117
  ],
@@ -515,6 +515,10 @@ class Instance extends common.GrpcServiceObject {
515
515
  if (!this.databases_.has(key)) {
516
516
  const db = new database_1.Database(this, name, poolOptions, queryOptions);
517
517
  db._observabilityOptions = this._observabilityOptions;
518
+ const parent = this.parent;
519
+ if (parent && parent._nthClientId) {
520
+ db._clientId = parent._nthClientId;
521
+ }
518
522
  this.databases_.set(key, db);
519
523
  }
520
524
  return this.databases_.get(key);
@@ -39,6 +39,8 @@ interface traceConfig {
39
39
  sql?: string | SQLStatement;
40
40
  tableName?: string;
41
41
  dbName?: string;
42
+ transactionTag?: string | null;
43
+ requestTag?: string | null;
42
44
  opts?: ObservabilityOptions;
43
45
  }
44
46
  declare const SPAN_NAMESPACE_PREFIX = "CloudSpanner";
@@ -79,27 +79,32 @@ function startTrace(spanNameSuffix, config, cb) {
79
79
  }
80
80
  return getTracer((_a = config.opts) === null || _a === void 0 ? void 0 : _a.tracerProvider).startActiveSpan(SPAN_NAMESPACE_PREFIX + '.' + spanNameSuffix, { kind: api_1.SpanKind.CLIENT }, span => {
81
81
  var _a;
82
- span.setAttribute(semantic_conventions_1.SEMATTRS_DB_SYSTEM, 'spanner');
83
82
  span.setAttribute(semantic_conventions_1.ATTR_OTEL_SCOPE_NAME, TRACER_NAME);
84
83
  span.setAttribute(semantic_conventions_1.ATTR_OTEL_SCOPE_VERSION, TRACER_VERSION);
85
84
  span.setAttribute('gcp.client.service', 'spanner');
86
85
  span.setAttribute('gcp.client.version', TRACER_VERSION);
87
86
  span.setAttribute('gcp.client.repo', 'googleapis/nodejs-spanner');
88
87
  if (config.tableName) {
89
- span.setAttribute(semantic_conventions_1.SEMATTRS_DB_SQL_TABLE, config.tableName);
88
+ span.setAttribute('db.sql.table', config.tableName);
90
89
  }
91
90
  if (config.dbName) {
92
- span.setAttribute(semantic_conventions_1.SEMATTRS_DB_NAME, config.dbName);
91
+ span.setAttribute('db.name', config.dbName);
92
+ }
93
+ if (config.requestTag) {
94
+ span.setAttribute('request.tag', config.requestTag);
95
+ }
96
+ if (config.transactionTag) {
97
+ span.setAttribute('transaction.tag', config.transactionTag);
93
98
  }
94
99
  const allowExtendedTracing = optedInPII || ((_a = config.opts) === null || _a === void 0 ? void 0 : _a.enableExtendedTracing);
95
100
  if (config.sql && allowExtendedTracing) {
96
101
  const sql = config.sql;
97
102
  if (typeof sql === 'string') {
98
- span.setAttribute(semantic_conventions_1.SEMATTRS_DB_STATEMENT, sql);
103
+ span.setAttribute('db.statement', sql);
99
104
  }
100
105
  else {
101
106
  const stmt = sql;
102
- span.setAttribute(semantic_conventions_1.SEMATTRS_DB_STATEMENT, stmt.sql);
107
+ span.setAttribute('db.statement', stmt.sql);
103
108
  }
104
109
  }
105
110
  // If at all the invoked function throws an exception,
@@ -38,4 +38,7 @@ declare function nextNthRequest(database: any): number;
38
38
  export interface RequestIDError extends grpc.ServiceError {
39
39
  requestID: string;
40
40
  }
41
- export { AtomicCounter, X_GOOG_SPANNER_REQUEST_ID_HEADER, craftRequestId, injectRequestIDIntoError, injectRequestIDIntoHeaders, nextNthRequest, nextSpannerClientId, newAtomicCounter, randIdForProcess, };
41
+ declare const X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR = "x_goog_spanner_request_id";
42
+ declare function attributeXGoogSpannerRequestIdToActiveSpan(config: any): void;
43
+ declare const X_GOOG_REQ_ID_REGEX: RegExp;
44
+ export { AtomicCounter, X_GOOG_REQ_ID_REGEX, X_GOOG_SPANNER_REQUEST_ID_HEADER, X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR, attributeXGoogSpannerRequestIdToActiveSpan, craftRequestId, injectRequestIDIntoError, injectRequestIDIntoHeaders, nextNthRequest, nextSpannerClientId, newAtomicCounter, randIdForProcess, };
@@ -15,8 +15,9 @@
15
15
  * limitations under the License.
16
16
  */
17
17
  Object.defineProperty(exports, "__esModule", { value: true });
18
- exports.randIdForProcess = exports.X_GOOG_SPANNER_REQUEST_ID_HEADER = exports.AtomicCounter = void 0;
18
+ exports.randIdForProcess = exports.X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR = exports.X_GOOG_SPANNER_REQUEST_ID_HEADER = exports.X_GOOG_REQ_ID_REGEX = exports.AtomicCounter = void 0;
19
19
  exports.resetNthClientId = resetNthClientId;
20
+ exports.attributeXGoogSpannerRequestIdToActiveSpan = attributeXGoogSpannerRequestIdToActiveSpan;
20
21
  exports.craftRequestId = craftRequestId;
21
22
  exports.injectRequestIDIntoError = injectRequestIDIntoError;
22
23
  exports.injectRequestIDIntoHeaders = injectRequestIDIntoHeaders;
@@ -24,6 +25,7 @@ exports.nextNthRequest = nextNthRequest;
24
25
  exports.nextSpannerClientId = nextSpannerClientId;
25
26
  exports.newAtomicCounter = newAtomicCounter;
26
27
  const crypto_1 = require("crypto");
28
+ const instrument_1 = require("./instrument");
27
29
  const randIdForProcess = (0, crypto_1.randomBytes)(8)
28
30
  .readUint32LE(0)
29
31
  .toString(16)
@@ -135,4 +137,22 @@ function nextNthRequest(database) {
135
137
  }
136
138
  return database._nextNthRequest();
137
139
  }
140
+ const X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR = 'x_goog_spanner_request_id';
141
+ exports.X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR = X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR;
142
+ /*
143
+ * attributeXGoogSpannerRequestIdToActiveSpan extracts the x-goog-spanner-request-id
144
+ * from config, if possible and then adds it as an attribute to the current/active span.
145
+ * Since x-goog-spanner-request-id is associated with RPC invoking methods, it is invoked
146
+ * long after tracing has been performed.
147
+ */
148
+ function attributeXGoogSpannerRequestIdToActiveSpan(config) {
149
+ const reqId = extractRequestID(config);
150
+ if (!(reqId && reqId.length > 0)) {
151
+ return;
152
+ }
153
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
154
+ span.setAttribute(X_GOOG_SPANNER_REQUEST_ID_SPAN_ATTR, reqId);
155
+ }
156
+ const X_GOOG_REQ_ID_REGEX = /^1\.[0-9A-Fa-f]{8}(\.\d+){3}\.\d+/;
157
+ exports.X_GOOG_REQ_ID_REGEX = X_GOOG_REQ_ID_REGEX;
138
158
  //# sourceMappingURL=request_id_header.js.map