@google-cloud/spanner 7.13.0 → 7.15.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,6 +30,7 @@ import { SessionPool } from './session-pool';
30
30
  import { Table } from './table';
31
31
  import { MutationGroup, MutationSet, PartitionedDml, Snapshot, Transaction } from './transaction';
32
32
  import * as v1 from './v1';
33
+ import { ObservabilityOptions } from './instrument';
33
34
  export type IOperation = instanceAdmin.longrunning.IOperation;
34
35
  export type GetInstancesOptions = PagedOptionsWithFilter;
35
36
  export type GetInstancesResponse = PagedResponse<Instance, instanceAdmin.spanner.admin.instance.v1.IListInstancesResponse>;
@@ -52,6 +53,7 @@ export type GetInstanceConfigOperationsCallback = PagedCallback<IOperation, inst
52
53
  * @property {google.spanner.v1.IDirectedReadOptions} [directedReadOptions] Sets the DirectedReadOptions for all ReadRequests and ExecuteSqlRequests for the Client.
53
54
  * Indicates which replicas or regions should be used for non-transactional reads or queries.
54
55
  * DirectedReadOptions won't be set for readWrite transactions"
56
+ * @property {ObservabilityOptions} [observabilityOptions] Sets the observability options to be used for OpenTelemetry tracing
55
57
  */
56
58
  export interface SpannerOptions extends GrpcClientOptions {
57
59
  apiEndpoint?: string;
@@ -60,6 +62,7 @@ export interface SpannerOptions extends GrpcClientOptions {
60
62
  sslCreds?: grpc.ChannelCredentials;
61
63
  routeToLeaderEnabled?: boolean;
62
64
  directedReadOptions?: google.spanner.v1.IDirectedReadOptions | null;
65
+ observabilityOptions?: ObservabilityOptions;
63
66
  }
64
67
  export interface RequestConfig {
65
68
  client: string;
@@ -165,6 +168,7 @@ declare class Spanner extends GrpcService {
165
168
  };
166
169
  routeToLeaderEnabled: boolean;
167
170
  directedReadOptions: google.spanner.v1.IDirectedReadOptions | null;
171
+ _observabilityOptions: ObservabilityOptions | undefined;
168
172
  /**
169
173
  * Placeholder used to auto populate a column with the commit timestamp.
170
174
  * This can only be used for timestamp columns that have set the option
@@ -1188,3 +1192,4 @@ declare const _default: {
1188
1192
  };
1189
1193
  export default _default;
1190
1194
  export { Float32, Float, Int, Struct, Numeric, PGNumeric, SpannerDate };
1195
+ export { ObservabilityOptions };
@@ -60,6 +60,7 @@ const grpcGcpModule = require("grpc-gcp");
60
60
  const grpcGcp = grpcGcpModule(google_gax_1.grpc);
61
61
  const v1 = require("./v1");
62
62
  exports.v1 = v1;
63
+ const instrument_1 = require("./instrument");
63
64
  // eslint-disable-next-line @typescript-eslint/no-var-requires
64
65
  const gcpApiConfig = require('./spanner_grpc_config.json');
65
66
  /**
@@ -199,6 +200,8 @@ class Spanner extends service_1.GrpcService {
199
200
  [common_1.CLOUD_RESOURCE_HEADER]: this.projectFormattedName_,
200
201
  };
201
202
  this.directedReadOptions = directedReadOptions;
203
+ this._observabilityOptions = options.observabilityOptions;
204
+ (0, instrument_1.ensureInitialContextManagerSet)();
202
205
  }
203
206
  /**
204
207
  * Gets the InstanceAdminClient object.
@@ -295,6 +298,7 @@ class Spanner extends service_1.GrpcService {
295
298
  return;
296
299
  }
297
300
  const instance = this.instance(formattedName);
301
+ instance._observabilityOptions = this._observabilityOptions;
298
302
  callback(null, instance, operation, resp);
299
303
  });
300
304
  }
@@ -26,6 +26,7 @@ import { google as instanceAdmin } from '../protos/protos';
26
26
  import { google as databaseAdmin } from '../protos/protos';
27
27
  import { google as spannerClient } from '../protos/protos';
28
28
  import { CreateInstanceRequest } from './index';
29
+ import { ObservabilityOptions } from './instrument';
29
30
  export type IBackup = databaseAdmin.spanner.admin.database.v1.IBackup;
30
31
  export type IDatabase = databaseAdmin.spanner.admin.database.v1.IDatabase;
31
32
  export type IInstance = instanceAdmin.spanner.admin.instance.v1.IInstance;
@@ -100,6 +101,7 @@ declare class Instance extends common.GrpcServiceObject {
100
101
  resourceHeader_: {
101
102
  [k: string]: string;
102
103
  };
104
+ _observabilityOptions?: ObservabilityOptions;
103
105
  constructor(spanner: Spanner, name: string);
104
106
  /**
105
107
  * Get a reference to a Backup object.
@@ -117,6 +117,7 @@ class Instance extends common.GrpcServiceObject {
117
117
  this.resourceHeader_ = {
118
118
  [common_1.CLOUD_RESOURCE_HEADER]: this.formattedName_,
119
119
  };
120
+ this._observabilityOptions = spanner._observabilityOptions;
120
121
  }
121
122
  /**
122
123
  * Get a reference to a Backup object.
@@ -471,6 +472,7 @@ class Instance extends common.GrpcServiceObject {
471
472
  return;
472
473
  }
473
474
  const database = this.database(name, poolOptions || poolCtor);
475
+ database._observabilityOptions = this._observabilityOptions;
474
476
  callback(null, database, operation, resp);
475
477
  });
476
478
  }
@@ -512,7 +514,9 @@ class Instance extends common.GrpcServiceObject {
512
514
  }
513
515
  const key = name.split('/').pop() + optionsKey;
514
516
  if (!this.databases_.has(key)) {
515
- this.databases_.set(key, new database_1.Database(this, name, poolOptions, queryOptions));
517
+ const db = new database_1.Database(this, name, poolOptions, queryOptions);
518
+ db._observabilityOptions = this._observabilityOptions;
519
+ this.databases_.set(key, db);
516
520
  }
517
521
  return this.databases_.get(key);
518
522
  }
@@ -627,6 +631,7 @@ class Instance extends common.GrpcServiceObject {
627
631
  databases = rowDatabases.map(database => {
628
632
  const databaseInstance = self.database(database.name, { min: 0 });
629
633
  databaseInstance.metadata = database;
634
+ databaseInstance._observabilityOptions = this._observabilityOptions;
630
635
  return databaseInstance;
631
636
  });
632
637
  }
@@ -0,0 +1,84 @@
1
+ /*!
2
+ * Copyright 2024 Google LLC. All Rights Reserved.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { Span, TracerProvider } from '@opentelemetry/api';
17
+ interface SQLStatement {
18
+ sql: string;
19
+ }
20
+ interface ObservabilityOptions {
21
+ tracerProvider: TracerProvider;
22
+ enableExtendedTracing?: boolean;
23
+ }
24
+ export type { ObservabilityOptions };
25
+ export type { Span };
26
+ declare const TRACER_NAME = "cloud.google.com/nodejs/spanner";
27
+ declare const TRACER_VERSION: any;
28
+ export { TRACER_NAME, TRACER_VERSION };
29
+ /**
30
+ * getTracer fetches the tracer from the provided tracerProvider.
31
+ * @param {TracerProvider} [tracerProvider] optional custom tracer provider
32
+ * to use for fetching the tracer. If not provided, the global provider will be used.
33
+ *
34
+ * @returns {Tracer} The tracer instance associated with the provided or global provider.
35
+ */
36
+ export declare function getTracer(tracerProvider?: TracerProvider): import("@opentelemetry/api").Tracer;
37
+ interface traceConfig {
38
+ sql?: string | SQLStatement;
39
+ tableName?: string;
40
+ dbName?: string;
41
+ opts?: ObservabilityOptions;
42
+ }
43
+ declare const SPAN_NAMESPACE_PREFIX = "CloudSpanner";
44
+ export { SPAN_NAMESPACE_PREFIX, traceConfig };
45
+ declare function ensureInitialContextManagerSet(): void;
46
+ export { ensureInitialContextManagerSet };
47
+ /**
48
+ * startTrace begins an active span in the current active context
49
+ * and passes it back to the set callback function. Each span will
50
+ * be prefixed with "cloud.google.com/nodejs/spanner". It is the
51
+ * responsibility of the caller to invoke [span.end] when finished tracing.
52
+ *
53
+ * @returns {Span} The created span.
54
+ */
55
+ export declare function startTrace<T>(spanNameSuffix: string, config: traceConfig | undefined, cb: (span: Span) => T): T;
56
+ /**
57
+ * Sets the span status with err, if non-null onto the span with
58
+ * status.code=ERROR and the message of err.toString()
59
+ *
60
+ * @returns {boolean} to signify if the status was set.
61
+ */
62
+ export declare function setSpanError(span: Span, err: Error | String): boolean;
63
+ /**
64
+ * Sets err, if non-null onto the span with
65
+ * status.code=ERROR and the message of err.toString()
66
+ * as well as recording an exception on the span.
67
+ * @param {Span} [span] the subject span
68
+ * @param {Error} [err] the error whose message to use to record
69
+ * the span error and the span exception.
70
+ *
71
+ * @returns {boolean} to signify if the status and exception were set.
72
+ */
73
+ export declare function setSpanErrorAndException(span: Span, err: Error | String): boolean;
74
+ /**
75
+ * getActiveOrNoopSpan queries the global tracer for the currently active
76
+ * span and returns it, otherwise if there is no active span available, it'll
77
+ * simply create a NoopSpan. This is important in the cases where we don't
78
+ * want to create a new span, such as in sensitive and frequently called code
79
+ * for which the new spans would be too many and thus pollute the trace,
80
+ * but yet we'd like to record an important annotation.
81
+ *
82
+ * @returns {Span} the non-null span.
83
+ */
84
+ export declare function getActiveOrNoopSpan(): Span;
@@ -0,0 +1,213 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright 2024 Google LLC. All Rights Reserved.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.SPAN_NAMESPACE_PREFIX = exports.TRACER_VERSION = exports.TRACER_NAME = void 0;
19
+ exports.getTracer = getTracer;
20
+ exports.ensureInitialContextManagerSet = ensureInitialContextManagerSet;
21
+ exports.startTrace = startTrace;
22
+ exports.setSpanError = setSpanError;
23
+ exports.setSpanErrorAndException = setSpanErrorAndException;
24
+ exports.getActiveOrNoopSpan = getActiveOrNoopSpan;
25
+ const semantic_conventions_1 = require("@opentelemetry/semantic-conventions");
26
+ const api_1 = require("@opentelemetry/api");
27
+ const optedInPII = process.env.SPANNER_ENABLE_EXTENDED_TRACING === 'true';
28
+ const TRACER_NAME = 'cloud.google.com/nodejs/spanner';
29
+ exports.TRACER_NAME = TRACER_NAME;
30
+ const TRACER_VERSION = require('../../package.json').version;
31
+ exports.TRACER_VERSION = TRACER_VERSION;
32
+ /**
33
+ * getTracer fetches the tracer from the provided tracerProvider.
34
+ * @param {TracerProvider} [tracerProvider] optional custom tracer provider
35
+ * to use for fetching the tracer. If not provided, the global provider will be used.
36
+ *
37
+ * @returns {Tracer} The tracer instance associated with the provided or global provider.
38
+ */
39
+ function getTracer(tracerProvider) {
40
+ if (tracerProvider) {
41
+ return tracerProvider.getTracer(TRACER_NAME, TRACER_VERSION);
42
+ }
43
+ // Otherwise use the global tracer.
44
+ return api_1.trace.getTracer(TRACER_NAME, TRACER_VERSION);
45
+ }
46
+ const SPAN_NAMESPACE_PREFIX = 'CloudSpanner'; // TODO: discuss & standardize this prefix.
47
+ exports.SPAN_NAMESPACE_PREFIX = SPAN_NAMESPACE_PREFIX;
48
+ const { AsyncHooksContextManager, } = require('@opentelemetry/context-async-hooks');
49
+ /*
50
+ * This function ensures that async/await works correctly by
51
+ * checking if context.active() returns an invalid/unset context
52
+ * and if so, sets a global AsyncHooksContextManager otherwise
53
+ * spans resulting from async/await invocations won't be correctly
54
+ * associated in their respective hierarchies.
55
+ */
56
+ function ensureInitialContextManagerSet() {
57
+ if (api_1.context.active() === api_1.ROOT_CONTEXT) {
58
+ // If no active context was set previously, trace context propagation cannot
59
+ // function correctly with async/await for OpenTelemetry
60
+ // See {@link https://opentelemetry.io/docs/languages/js/context/#active-context}
61
+ api_1.context.disable(); // Disable any prior contextManager.
62
+ const contextManager = new AsyncHooksContextManager();
63
+ contextManager.enable();
64
+ api_1.context.setGlobalContextManager(contextManager);
65
+ }
66
+ }
67
+ /**
68
+ * startTrace begins an active span in the current active context
69
+ * and passes it back to the set callback function. Each span will
70
+ * be prefixed with "cloud.google.com/nodejs/spanner". It is the
71
+ * responsibility of the caller to invoke [span.end] when finished tracing.
72
+ *
73
+ * @returns {Span} The created span.
74
+ */
75
+ function startTrace(spanNameSuffix, config, cb) {
76
+ var _a;
77
+ const origConfig = config;
78
+ if (!config) {
79
+ config = {};
80
+ }
81
+ return getTracer((_a = config.opts) === null || _a === void 0 ? void 0 : _a.tracerProvider).startActiveSpan(SPAN_NAMESPACE_PREFIX + '.' + spanNameSuffix, { kind: api_1.SpanKind.CLIENT }, span => {
82
+ var _a;
83
+ span.setAttribute(semantic_conventions_1.SEMATTRS_DB_SYSTEM, 'spanner');
84
+ span.setAttribute(semantic_conventions_1.ATTR_OTEL_SCOPE_NAME, TRACER_NAME);
85
+ span.setAttribute(semantic_conventions_1.ATTR_OTEL_SCOPE_VERSION, TRACER_VERSION);
86
+ if (config.tableName) {
87
+ span.setAttribute(semantic_conventions_1.SEMATTRS_DB_SQL_TABLE, config.tableName);
88
+ }
89
+ if (config.dbName) {
90
+ span.setAttribute(semantic_conventions_1.SEMATTRS_DB_NAME, config.dbName);
91
+ }
92
+ const allowExtendedTracing = optedInPII || ((_a = config.opts) === null || _a === void 0 ? void 0 : _a.enableExtendedTracing);
93
+ if (config.sql && allowExtendedTracing) {
94
+ const sql = config.sql;
95
+ if (typeof sql === 'string') {
96
+ span.setAttribute(semantic_conventions_1.SEMATTRS_DB_STATEMENT, sql);
97
+ }
98
+ else {
99
+ const stmt = sql;
100
+ span.setAttribute(semantic_conventions_1.SEMATTRS_DB_STATEMENT, stmt.sql);
101
+ }
102
+ }
103
+ // If at all the invoked function throws an exception,
104
+ // record the exception and then end this span.
105
+ try {
106
+ return cb(span);
107
+ }
108
+ catch (e) {
109
+ setSpanErrorAndException(span, e);
110
+ span.end();
111
+ // Finally re-throw the exception.
112
+ throw e;
113
+ }
114
+ });
115
+ }
116
+ /**
117
+ * Sets the span status with err, if non-null onto the span with
118
+ * status.code=ERROR and the message of err.toString()
119
+ *
120
+ * @returns {boolean} to signify if the status was set.
121
+ */
122
+ function setSpanError(span, err) {
123
+ if (!err || !span) {
124
+ return false;
125
+ }
126
+ let message = '';
127
+ if (typeof err === 'object' && 'message' in err) {
128
+ message = err.message;
129
+ }
130
+ else {
131
+ message = err.toString();
132
+ }
133
+ span.setStatus({
134
+ code: api_1.SpanStatusCode.ERROR,
135
+ message: message,
136
+ });
137
+ return true;
138
+ }
139
+ /**
140
+ * Sets err, if non-null onto the span with
141
+ * status.code=ERROR and the message of err.toString()
142
+ * as well as recording an exception on the span.
143
+ * @param {Span} [span] the subject span
144
+ * @param {Error} [err] the error whose message to use to record
145
+ * the span error and the span exception.
146
+ *
147
+ * @returns {boolean} to signify if the status and exception were set.
148
+ */
149
+ function setSpanErrorAndException(span, err) {
150
+ if (setSpanError(span, err)) {
151
+ span.recordException(err);
152
+ return true;
153
+ }
154
+ return false;
155
+ }
156
+ /**
157
+ * getActiveOrNoopSpan queries the global tracer for the currently active
158
+ * span and returns it, otherwise if there is no active span available, it'll
159
+ * simply create a NoopSpan. This is important in the cases where we don't
160
+ * want to create a new span, such as in sensitive and frequently called code
161
+ * for which the new spans would be too many and thus pollute the trace,
162
+ * but yet we'd like to record an important annotation.
163
+ *
164
+ * @returns {Span} the non-null span.
165
+ */
166
+ function getActiveOrNoopSpan() {
167
+ const span = api_1.trace.getActiveSpan();
168
+ if (span) {
169
+ return span;
170
+ }
171
+ return new noopSpan();
172
+ }
173
+ /**
174
+ * noopSpan is a pass-through Span that does nothing and shall not
175
+ * be exported, nor added into any context. It serves as a placeholder
176
+ * to allow calls in sensitive areas like sessionPools to transparently
177
+ * add attributes to spans without lots of ugly null checks.
178
+ *
179
+ * It exists because OpenTelemetry-JS does not seem to export the NoopSpan.
180
+ */
181
+ class noopSpan {
182
+ constructor() { }
183
+ spanContext() {
184
+ return api_1.INVALID_SPAN_CONTEXT;
185
+ }
186
+ setAttribute(key, value) {
187
+ return this;
188
+ }
189
+ setAttributes(attributes) {
190
+ return this;
191
+ }
192
+ addEvent(name, attributes) {
193
+ return this;
194
+ }
195
+ addLink(link) {
196
+ return this;
197
+ }
198
+ addLinks(links) {
199
+ return this;
200
+ }
201
+ setStatus(status) {
202
+ return this;
203
+ }
204
+ end(endTime) { }
205
+ isRecording() {
206
+ return false;
207
+ }
208
+ recordException(exc, timeAt) { }
209
+ updateName(name) {
210
+ return this;
211
+ }
212
+ }
213
+ //# sourceMappingURL=instrument.js.map
@@ -21,6 +21,7 @@ import { Transaction } from './transaction';
21
21
  import { NormalCallback } from './common';
22
22
  import { GoogleError, grpc } from 'google-gax';
23
23
  import trace = require('stack-trace');
24
+ import { ObservabilityOptions } from './instrument';
24
25
  /**
25
26
  * @callback SessionPoolCloseCallback
26
27
  * @param {?Error} error Closing error, if any.
@@ -241,6 +242,7 @@ export declare class SessionPool extends EventEmitter implements SessionPoolInte
241
242
  _pingHandle: NodeJS.Timer;
242
243
  _requests: PQueue;
243
244
  _traces: Map<string, trace.StackFrame[]>;
245
+ _observabilityOptions?: ObservabilityOptions;
244
246
  /**
245
247
  * Formats stack trace objects into Node-like stack trace.
246
248
  *
@@ -27,6 +27,7 @@ const is = require("is");
27
27
  const p_queue_1 = require("p-queue");
28
28
  const google_gax_1 = require("google-gax");
29
29
  const trace = require("stack-trace");
30
+ const instrument_1 = require("./instrument");
30
31
  const DEFAULTS = {
31
32
  acquireTimeout: Infinity,
32
33
  concurrency: Infinity,
@@ -261,6 +262,7 @@ class SessionPool extends events_1.EventEmitter {
261
262
  concurrency: 1,
262
263
  });
263
264
  this._traces = new Map();
265
+ this._observabilityOptions = database._observabilityOptions;
264
266
  }
265
267
  /**
266
268
  * Closes and the pool.
@@ -381,7 +383,9 @@ class SessionPool extends events_1.EventEmitter {
381
383
  * @returns {Promise<Session>}
382
384
  */
383
385
  async _acquire() {
386
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
384
387
  if (!this.isOpen) {
388
+ span.addEvent('SessionPool is closed');
385
389
  throw new google_gax_1.GoogleError("Database is closed." /* errors.Closed */);
386
390
  }
387
391
  // Get the stacktrace of the caller before we call any async methods, as calling an async method will break the stacktrace.
@@ -391,14 +395,23 @@ class SessionPool extends events_1.EventEmitter {
391
395
  // wrapping this logic in a function to call recursively if the session
392
396
  // we end up with is already dead
393
397
  const getSession = async () => {
398
+ span.addEvent('Acquiring session');
394
399
  const elapsed = Date.now() - startTime;
395
400
  if (elapsed >= timeout) {
401
+ span.addEvent('Could not acquire session due to an exceeded timeout');
396
402
  throw new google_gax_1.GoogleError("Timeout occurred while acquiring session." /* errors.Timeout */);
397
403
  }
398
404
  const session = await this._getSession(startTime);
399
405
  if (this._isValidSession(session)) {
406
+ span.addEvent('Acquired session', {
407
+ 'time.elapsed': Date.now() - startTime,
408
+ 'session.id': session.id.toString(),
409
+ });
400
410
  return session;
401
411
  }
412
+ span.addEvent('Could not acquire session because it was invalid. Retrying', {
413
+ 'session.id': session.id.toString(),
414
+ });
402
415
  this._inventory.borrowed.delete(session);
403
416
  return getSession();
404
417
  };
@@ -467,31 +480,49 @@ class SessionPool extends events_1.EventEmitter {
467
480
  return;
468
481
  }
469
482
  this._pending += amount;
470
- // while we can request as many sessions be created as we want, the backend
471
- // will return at most 100 at a time, hence the need for a while loop.
472
- while (amount > 0) {
473
- let sessions = null;
474
- try {
475
- [sessions] = await this.database.batchCreateSessions({
476
- count: amount,
477
- labels: labels,
478
- databaseRole: databaseRole,
483
+ let nReturned = 0;
484
+ const nRequested = amount;
485
+ // TODO: Inlining this code for now and later on shall go
486
+ // extract _traceConfig to the constructor when we have plenty of time.
487
+ const traceConfig = {
488
+ opts: this._observabilityOptions,
489
+ dbName: this.database.formattedName_,
490
+ };
491
+ return (0, instrument_1.startTrace)('SessionPool.createSessions', traceConfig, async (span) => {
492
+ span.addEvent(`Requesting ${amount} sessions`);
493
+ // while we can request as many sessions be created as we want, the backend
494
+ // will return at most 100 at a time, hence the need for a while loop.
495
+ while (amount > 0) {
496
+ let sessions = null;
497
+ span.addEvent(`Creating ${amount} sessions`);
498
+ try {
499
+ [sessions] = await this.database.batchCreateSessions({
500
+ count: amount,
501
+ labels: labels,
502
+ databaseRole: databaseRole,
503
+ });
504
+ amount -= sessions.length;
505
+ nReturned += sessions.length;
506
+ }
507
+ catch (e) {
508
+ this._pending -= amount;
509
+ this.emit('createError', e);
510
+ span.addEvent(`Requested for ${nRequested} sessions returned ${nReturned}`);
511
+ (0, instrument_1.setSpanErrorAndException)(span, e);
512
+ span.end();
513
+ throw e;
514
+ }
515
+ sessions.forEach((session) => {
516
+ setImmediate(() => {
517
+ this._inventory.borrowed.add(session);
518
+ this._pending -= 1;
519
+ this.release(session);
520
+ });
479
521
  });
480
- amount -= sessions.length;
481
- }
482
- catch (e) {
483
- this._pending -= amount;
484
- this.emit('createError', e);
485
- throw e;
486
522
  }
487
- sessions.forEach((session) => {
488
- setImmediate(() => {
489
- this._inventory.borrowed.add(session);
490
- this._pending -= 1;
491
- this.release(session);
492
- });
493
- });
494
- }
523
+ span.addEvent(`Requested for ${nRequested} sessions returned ${nReturned}`);
524
+ span.end();
525
+ });
495
526
  }
496
527
  /**
497
528
  * Attempts to delete a session, optionally creating a new one of the same
@@ -587,15 +618,19 @@ class SessionPool extends events_1.EventEmitter {
587
618
  * @returns {Promise<Session>}
588
619
  */
589
620
  async _getSession(startTime) {
621
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
590
622
  if (this._hasSessionUsableFor()) {
623
+ span.addEvent('Cache hit: has usable session');
591
624
  return this._borrowNextAvailableSession();
592
625
  }
593
626
  if (this.isFull && this.options.fail) {
627
+ span.addEvent('Session pool is full and failFast=true');
594
628
  throw new SessionPoolExhaustedError(this._getLeaks());
595
629
  }
596
630
  let removeOnceCloseListener;
597
631
  let removeListener;
598
632
  // Wait for a session to become available.
633
+ span.addEvent('Waiting for a session to become available');
599
634
  const availableEvent = 'session-available';
600
635
  const promises = [
601
636
  new Promise((_, reject) => {
@@ -680,6 +715,9 @@ class SessionPool extends events_1.EventEmitter {
680
715
  * @returns {Promise}
681
716
  */
682
717
  async _ping(session) {
718
+ // NOTE: Please do not trace Ping as it gets quite spammy
719
+ // with many root spans polluting the main span.
720
+ // Please see https://github.com/googleapis/google-cloud-go/issues/1691
683
721
  this._borrow(session);
684
722
  if (!this._isValidSession(session)) {
685
723
  this._inventory.borrowed.delete(session);
@@ -344,12 +344,6 @@ exports.Session = Session;
344
344
  * that a callback is omitted.
345
345
  */
346
346
  (0, promisify_1.promisifyAll)(Session, {
347
- exclude: [
348
- 'delete',
349
- 'getMetadata',
350
- 'partitionedDml',
351
- 'snapshot',
352
- 'transaction',
353
- ],
347
+ exclude: ['delete', 'partitionedDml', 'snapshot', 'transaction'],
354
348
  });
355
349
  //# sourceMappingURL=session.js.map
@@ -20,6 +20,7 @@ import { ReadRequest, TimestampBounds, CommitOptions, CommitResponse, ReadRespon
20
20
  import { google as databaseAdmin } from '../protos/protos';
21
21
  import { Schema, LongRunningCallback } from './common';
22
22
  import IRequestOptions = databaseAdmin.spanner.v1.IRequestOptions;
23
+ import { ObservabilityOptions } from './instrument';
23
24
  export type Key = string | string[];
24
25
  export type CreateTableResponse = [
25
26
  Table,
@@ -70,6 +71,7 @@ export type UpsertRowsOptions = MutateRowsOptions;
70
71
  declare class Table {
71
72
  database: Database;
72
73
  name: string;
74
+ _observabilityOptions?: ObservabilityOptions;
73
75
  constructor(database: Database, name: string);
74
76
  /**
75
77
  * Create a table.
@@ -128,6 +130,7 @@ declare class Table {
128
130
  create(schema: Schema, gaxOptions?: CallOptions): Promise<CreateTableResponse>;
129
131
  create(schema: Schema, callback: CreateTableCallback): void;
130
132
  create(schema: Schema, gaxOptions: CallOptions, callback: CreateTableCallback): void;
133
+ protected getDBName(): string;
131
134
  /**
132
135
  * Create a readable object stream to receive rows from the database using key
133
136
  * lookups and scans.