@google-cloud/spanner 7.18.0 → 7.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +1 -0
  3. package/build/protos/google/spanner/admin/database/v1/backup.proto +773 -0
  4. package/build/protos/google/spanner/admin/database/v1/backup_schedule.proto +230 -0
  5. package/build/protos/google/spanner/admin/database/v1/common.proto +132 -0
  6. package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +1279 -0
  7. package/build/protos/google/spanner/admin/instance/v1/common.proto +64 -0
  8. package/build/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto +2110 -0
  9. package/build/protos/google/spanner/executor/v1/cloud_executor.proto +1520 -0
  10. package/build/protos/google/spanner/v1/commit_response.proto +59 -0
  11. package/build/protos/google/spanner/v1/keys.proto +163 -0
  12. package/build/protos/google/spanner/v1/mutation.proto +107 -0
  13. package/build/protos/google/spanner/v1/query_plan.proto +128 -0
  14. package/build/protos/google/spanner/v1/result_set.proto +237 -0
  15. package/build/protos/google/spanner/v1/spanner.proto +1389 -0
  16. package/build/protos/google/spanner/v1/transaction.proto +622 -0
  17. package/build/protos/google/spanner/v1/type.proto +214 -0
  18. package/build/protos/protos.d.ts +39869 -0
  19. package/build/protos/protos.js +101659 -0
  20. package/build/protos/protos.json +10391 -0
  21. package/build/src/backup.d.ts +349 -0
  22. package/build/src/backup.js +246 -0
  23. package/build/src/batch-transaction.d.ts +247 -0
  24. package/build/src/batch-transaction.js +384 -0
  25. package/build/src/codec.d.ts +362 -0
  26. package/build/src/codec.js +791 -0
  27. package/build/src/common-grpc/service-object.d.ts +80 -0
  28. package/build/src/common-grpc/service-object.js +101 -0
  29. package/build/src/common-grpc/service.d.ts +445 -0
  30. package/build/src/common-grpc/service.js +826 -0
  31. package/build/src/common.d.ts +66 -0
  32. package/build/src/common.js +54 -0
  33. package/build/src/database.d.ts +2103 -0
  34. package/build/src/database.js +1660 -0
  35. package/build/src/extra_proto_list.json +1 -0
  36. package/build/src/helper.d.ts +45 -0
  37. package/build/src/helper.js +71 -0
  38. package/build/src/index.d.ts +1195 -0
  39. package/build/src/index.js +1059 -0
  40. package/build/src/instance-config.d.ts +294 -0
  41. package/build/src/instance-config.js +216 -0
  42. package/build/src/instance.d.ts +832 -0
  43. package/build/src/instance.js +781 -0
  44. package/build/src/instrument.d.ts +85 -0
  45. package/build/src/instrument.js +215 -0
  46. package/build/src/multiplexed-session.d.ts +135 -0
  47. package/build/src/multiplexed-session.js +194 -0
  48. package/build/src/partial-result-stream.d.ts +253 -0
  49. package/build/src/partial-result-stream.js +400 -0
  50. package/build/src/request_id_header.d.ts +41 -0
  51. package/build/src/request_id_header.js +138 -0
  52. package/build/src/session-factory.d.ts +115 -0
  53. package/build/src/session-factory.js +106 -0
  54. package/build/src/session-pool.d.ts +471 -0
  55. package/build/src/session-pool.js +765 -0
  56. package/build/src/session.d.ts +258 -0
  57. package/build/src/session.js +348 -0
  58. package/build/src/spanner_grpc_config.json +92 -0
  59. package/build/src/table.d.ts +831 -0
  60. package/build/src/table.js +277 -0
  61. package/build/src/transaction-runner.d.ts +185 -0
  62. package/build/src/transaction-runner.js +282 -0
  63. package/build/src/transaction.d.ts +1691 -0
  64. package/build/src/transaction.js +2003 -0
  65. package/build/src/v1/database_admin_client.d.ts +2332 -0
  66. package/build/src/v1/database_admin_client.js +2364 -0
  67. package/build/src/v1/database_admin_client_config.json +165 -0
  68. package/build/src/v1/database_admin_proto_list.json +6 -0
  69. package/build/src/v1/gapic_metadata.json +27 -0
  70. package/build/src/v1/index.d.ts +4 -0
  71. package/build/src/v1/index.js +29 -0
  72. package/build/src/v1/instance_admin_client.d.ts +1985 -0
  73. package/build/src/v1/instance_admin_client.js +1768 -0
  74. package/build/src/v1/instance_admin_client_config.json +129 -0
  75. package/build/src/v1/instance_admin_proto_list.json +4 -0
  76. package/build/src/v1/spanner_client.d.ts +1250 -0
  77. package/build/src/v1/spanner_client.js +1086 -0
  78. package/build/src/v1/spanner_client_config.json +119 -0
  79. package/build/src/v1/spanner_executor_proxy_client.d.ts +418 -0
  80. package/build/src/v1/spanner_executor_proxy_client.js +706 -0
  81. package/build/src/v1/spanner_executor_proxy_client_config.json +30 -0
  82. package/build/src/v1/spanner_executor_proxy_proto_list.json +14 -0
  83. package/build/src/v1/spanner_proto_list.json +10 -0
  84. package/package.json +1 -1
@@ -0,0 +1,765 @@
1
+ "use strict";
2
+ /*!
3
+ * Copyright 2016 Google Inc. 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.SessionPool = exports.SessionPoolExhaustedError = exports.SessionLeakError = exports.ReleaseError = void 0;
19
+ exports.isSessionNotFoundError = isSessionNotFoundError;
20
+ const events_1 = require("events");
21
+ const is = require("is");
22
+ const p_queue_1 = require("p-queue");
23
+ const google_gax_1 = require("google-gax");
24
+ const trace = require("stack-trace");
25
+ const instrument_1 = require("./instrument");
26
+ const helper_1 = require("./helper");
27
+ const DEFAULTS = {
28
+ acquireTimeout: Infinity,
29
+ concurrency: Infinity,
30
+ fail: false,
31
+ idlesAfter: 10,
32
+ keepAlive: 30,
33
+ labels: {},
34
+ max: 100,
35
+ maxIdle: 1,
36
+ min: 25,
37
+ incStep: 25,
38
+ databaseRole: null,
39
+ };
40
+ /**
41
+ * Error to be thrown when attempting to release unknown resources.
42
+ *
43
+ * @private
44
+ */
45
+ class ReleaseError extends google_gax_1.GoogleError {
46
+ constructor(resource) {
47
+ super('Unable to release unknown resource.');
48
+ this.resource = resource;
49
+ }
50
+ }
51
+ exports.ReleaseError = ReleaseError;
52
+ /**
53
+ * Error to be thrown when session leaks are detected.
54
+ *
55
+ * @private
56
+ */
57
+ class SessionLeakError extends google_gax_1.GoogleError {
58
+ constructor(leaks) {
59
+ super(`${leaks.length} session leak(s) detected.`);
60
+ // Restore error name that was overwritten by the super constructor call.
61
+ this.name = SessionLeakError.name;
62
+ this.messages = leaks;
63
+ }
64
+ }
65
+ exports.SessionLeakError = SessionLeakError;
66
+ /**
67
+ * Error to be thrown when the session pool is exhausted.
68
+ */
69
+ class SessionPoolExhaustedError extends google_gax_1.GoogleError {
70
+ constructor(leaks) {
71
+ super("No resources available." /* errors.Exhausted */);
72
+ // Restore error name that was overwritten by the super constructor call.
73
+ this.name = SessionPoolExhaustedError.name;
74
+ this.messages = leaks;
75
+ }
76
+ }
77
+ exports.SessionPoolExhaustedError = SessionPoolExhaustedError;
78
+ /**
79
+ * Checks whether the given error is a 'Session not found' error.
80
+ * @param error the error to check
81
+ * @return true if the error is a 'Session not found' error, and otherwise false.
82
+ */
83
+ function isSessionNotFoundError(error) {
84
+ return (error !== undefined &&
85
+ error.code === google_gax_1.grpc.status.NOT_FOUND &&
86
+ error.message.includes('Session not found'));
87
+ }
88
+ /**
89
+ * Class used to manage connections to Spanner.
90
+ *
91
+ * **You don't need to use this class directly, connections will be handled for
92
+ * you.**
93
+ *
94
+ * @class
95
+ * @extends {EventEmitter}
96
+ */
97
+ class SessionPool extends events_1.EventEmitter {
98
+ /**
99
+ * Formats stack trace objects into Node-like stack trace.
100
+ *
101
+ * @param {object[]} trace The trace object.
102
+ * @return {string}
103
+ */
104
+ static formatTrace(frames) {
105
+ const stack = frames.map(frame => {
106
+ const name = frame.getFunctionName() || frame.getMethodName();
107
+ const file = frame.getFileName();
108
+ const lineno = frame.getLineNumber();
109
+ const columnno = frame.getColumnNumber();
110
+ return ` at ${name} (${file}:${lineno}:${columnno})`;
111
+ });
112
+ return `Session leak detected!\n${stack.join('\n')}`;
113
+ }
114
+ /**
115
+ * Total number of available sessions.
116
+ * @type {number}
117
+ */
118
+ get available() {
119
+ return this._inventory.sessions.length;
120
+ }
121
+ /** @deprecated Starting from v6.5.0 the same session can be reused for
122
+ * different types of transactions.
123
+ */
124
+ get currentWriteFraction() {
125
+ return 0;
126
+ }
127
+ /**
128
+ * Total number of borrowed sessions.
129
+ * @type {number}
130
+ */
131
+ get borrowed() {
132
+ return this._inventory.borrowed.size + this._pending;
133
+ }
134
+ /**
135
+ * Flag to determine if Pool is full.
136
+ * @type {boolean}
137
+ */
138
+ get isFull() {
139
+ return this.size >= this.options.max;
140
+ }
141
+ /** @deprecated Use `size()` instead. */
142
+ get reads() {
143
+ return this.size;
144
+ }
145
+ /**
146
+ * Total size of pool.
147
+ * @type {number}
148
+ */
149
+ get size() {
150
+ return this.available + this.borrowed;
151
+ }
152
+ /** @deprecated Use `size()` instead. */
153
+ get writes() {
154
+ return this.size;
155
+ }
156
+ /** @deprecated Starting v6.5.0 the pending prepare state is obsolete. */
157
+ get pendingPrepare() {
158
+ return 0;
159
+ }
160
+ /**
161
+ * Number of sessions being created or prepared for a read/write transaction.
162
+ * @type {number}
163
+ */
164
+ get totalPending() {
165
+ return this._pending;
166
+ }
167
+ /** @deprecated Use totalWaiters instead. */
168
+ get numReadWaiters() {
169
+ return this.totalWaiters;
170
+ }
171
+ /** @deprecated Use totalWaiters instead. */
172
+ get numWriteWaiters() {
173
+ return this.totalWaiters;
174
+ }
175
+ /**
176
+ * Sum of read and write waiters.
177
+ * @type {number}
178
+ */
179
+ get totalWaiters() {
180
+ return this._waiters;
181
+ }
182
+ /**
183
+ * @constructor
184
+ * @param {Database} database The DB instance.
185
+ * @param {SessionPoolOptions} [options] Configuration options.
186
+ */
187
+ constructor(database, options) {
188
+ super();
189
+ this._pending = 0;
190
+ this._waiters = 0;
191
+ if (options && options.min && options.max && options.min > options.max) {
192
+ throw new TypeError('Min sessions may not be greater than max sessions.');
193
+ }
194
+ this.isOpen = false;
195
+ this.database = database;
196
+ this.options = Object.assign({}, DEFAULTS, options);
197
+ this.options.min = Math.min(this.options.min, this.options.max);
198
+ this.options.databaseRole = this.options.databaseRole
199
+ ? this.options.databaseRole
200
+ : database.databaseRole;
201
+ this._inventory = {
202
+ sessions: [],
203
+ borrowed: new Set(),
204
+ };
205
+ this._waiters = 0;
206
+ this._requests = new p_queue_1.default({
207
+ concurrency: this.options.concurrency,
208
+ });
209
+ this._acquires = new p_queue_1.default({
210
+ concurrency: 1,
211
+ });
212
+ this._traces = new Map();
213
+ this._observabilityOptions = database._observabilityOptions;
214
+ }
215
+ /**
216
+ * Closes and the pool.
217
+ *
218
+ * @emits SessionPool#close
219
+ * @param {SessionPoolCloseCallback} callback The callback function.
220
+ */
221
+ close(callback) {
222
+ const sessions = [
223
+ ...this._inventory.sessions,
224
+ ...this._inventory.borrowed,
225
+ ];
226
+ this.isOpen = false;
227
+ this._stopHouseKeeping();
228
+ this.emit('close');
229
+ sessions.forEach(session => this._destroy(session));
230
+ this._requests.onIdle().then(() => {
231
+ const leaks = this._getLeaks();
232
+ let error;
233
+ this._inventory.sessions = [];
234
+ this._inventory.borrowed.clear();
235
+ if (leaks.length) {
236
+ error = new SessionLeakError(leaks);
237
+ }
238
+ callback(error);
239
+ });
240
+ }
241
+ /**
242
+ * Retrieve a read session.
243
+ *
244
+ * @deprecated Use getSession instead.
245
+ * @param {GetReadSessionCallback} callback The callback function.
246
+ */
247
+ getReadSession(callback) {
248
+ this.getSession((error, session) => callback(error, session));
249
+ }
250
+ /**
251
+ * Retrieve a read/write session.
252
+ *
253
+ * @deprecated use getSession instead.
254
+ * @param {GetWriteSessionCallback} callback The callback function.
255
+ */
256
+ getWriteSession(callback) {
257
+ this.getSession(callback);
258
+ }
259
+ /**
260
+ * Retrieve a session.
261
+ *
262
+ * @param {GetSessionCallback} callback The callback function.
263
+ */
264
+ getSession(callback) {
265
+ this._acquire().then(session => callback(null, session, session.txn), callback);
266
+ }
267
+ /**
268
+ * Opens the pool, filling it to the configured number of read and write
269
+ * sessions.
270
+ *
271
+ * @emits SessionPool#open
272
+ * @return {Promise}
273
+ */
274
+ open() {
275
+ this._onClose = new Promise(resolve => this.once('close', resolve));
276
+ this._startHouseKeeping();
277
+ this.isOpen = true;
278
+ this.emit('open');
279
+ this._fill().catch(err => {
280
+ // Ignore `Database not found` error. This allows a user to call instance.database('db-name')
281
+ // for a database that does not yet exist with SessionPoolOptions.min > 0.
282
+ if ((0, helper_1.isDatabaseNotFoundError)(err) ||
283
+ (0, helper_1.isInstanceNotFoundError)(err) ||
284
+ (0, helper_1.isCreateSessionPermissionError)(err) ||
285
+ (0, helper_1.isDefaultCredentialsNotSetError)(err) ||
286
+ (0, helper_1.isProjectIdNotSetInEnvironmentError)(err)) {
287
+ return;
288
+ }
289
+ this.emit('error', err);
290
+ });
291
+ }
292
+ /**
293
+ * Releases session back into the pool.
294
+ *
295
+ * @throws {Error} For unknown sessions.
296
+ * @emits SessionPool#available
297
+ * @emits SessionPool#error
298
+ * @fires SessionPool#session-available
299
+ * @fires @deprecated SessionPool#readonly-available
300
+ * @fires @deprecated SessionPool#readwrite-available
301
+ * @param {Session} session The session to release.
302
+ */
303
+ release(session) {
304
+ if (!this._inventory.borrowed.has(session)) {
305
+ throw new ReleaseError(session);
306
+ }
307
+ delete session.txn;
308
+ session.lastUsed = Date.now();
309
+ if (isSessionNotFoundError(session.lastError)) {
310
+ // Remove the session from the pool. It is not necessary to call _destroy,
311
+ // as the session is already removed from the backend.
312
+ this._inventory.borrowed.delete(session);
313
+ this._traces.delete(session.id);
314
+ return;
315
+ }
316
+ session.lastError = undefined;
317
+ // Delete the trace associated with this session to mark the session as checked
318
+ // back into the pool. This will prevent the session to be marked as leaked if
319
+ // the pool is closed while the session is being prepared.
320
+ this._traces.delete(session.id);
321
+ // Release it into the pool as a session if there are more waiters than
322
+ // there are sessions available. Releasing it will unblock a waiter as soon
323
+ // as possible.
324
+ this._release(session);
325
+ }
326
+ /**
327
+ * Attempts to borrow a session from the pool.
328
+ *
329
+ * @private
330
+ *
331
+ * @returns {Promise<Session>}
332
+ */
333
+ async _acquire() {
334
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
335
+ if (!this.isOpen) {
336
+ span.addEvent('SessionPool is closed');
337
+ throw new google_gax_1.GoogleError("Database is closed." /* errors.Closed */);
338
+ }
339
+ // Get the stacktrace of the caller before we call any async methods, as calling an async method will break the stacktrace.
340
+ const frames = trace.get();
341
+ const startTime = Date.now();
342
+ const timeout = this.options.acquireTimeout;
343
+ // wrapping this logic in a function to call recursively if the session
344
+ // we end up with is already dead
345
+ const getSession = async () => {
346
+ span.addEvent('Acquiring session');
347
+ const elapsed = Date.now() - startTime;
348
+ if (elapsed >= timeout) {
349
+ span.addEvent('Could not acquire session due to an exceeded timeout');
350
+ throw new google_gax_1.GoogleError("Timeout occurred while acquiring session." /* errors.Timeout */);
351
+ }
352
+ const session = await this._getSession(startTime);
353
+ if (this._isValidSession(session)) {
354
+ span.addEvent('Acquired session', {
355
+ 'time.elapsed': Date.now() - startTime,
356
+ 'session.id': session.id.toString(),
357
+ });
358
+ return session;
359
+ }
360
+ span.addEvent('Could not acquire session because it was invalid. Retrying', {
361
+ 'session.id': session.id.toString(),
362
+ });
363
+ this._inventory.borrowed.delete(session);
364
+ return getSession();
365
+ };
366
+ const session = await this._acquires.add(getSession);
367
+ this._prepareTransaction(session);
368
+ this._traces.set(session.id, frames);
369
+ return session;
370
+ }
371
+ /**
372
+ * Moves a session into the borrowed group.
373
+ *
374
+ * @private
375
+ *
376
+ * @param {Session} session The session object.
377
+ */
378
+ _borrow(session) {
379
+ const index = this._inventory.sessions.indexOf(session);
380
+ this._inventory.borrowed.add(session);
381
+ this._inventory.sessions.splice(index, 1);
382
+ }
383
+ /**
384
+ * Borrows the first session from the inventory.
385
+ *
386
+ * @private
387
+ *
388
+ * @return {Session}
389
+ */
390
+ _borrowFrom() {
391
+ const session = this._inventory.sessions.pop();
392
+ this._inventory.borrowed.add(session);
393
+ return session;
394
+ }
395
+ /**
396
+ * Grabs the next available session.
397
+ *
398
+ * @private
399
+ *
400
+ * @returns {Promise<Session>}
401
+ */
402
+ _borrowNextAvailableSession() {
403
+ return this._borrowFrom();
404
+ }
405
+ /**
406
+ * Attempts to create a single session.
407
+ *
408
+ * @private
409
+ *
410
+ * @returns {Promise}
411
+ */
412
+ _createSession() {
413
+ return this._createSessions(1);
414
+ }
415
+ /**
416
+ * Batch creates sessions.
417
+ *
418
+ * @private
419
+ *
420
+ * @param {number} [amount] Config specifying how many sessions to create.
421
+ * @returns {Promise}
422
+ * @emits SessionPool#createError
423
+ */
424
+ async _createSessions(amount) {
425
+ const labels = this.options.labels;
426
+ const databaseRole = this.options.databaseRole;
427
+ if (amount <= 0) {
428
+ return;
429
+ }
430
+ this._pending += amount;
431
+ let nReturned = 0;
432
+ const nRequested = amount;
433
+ // TODO: Inlining this code for now and later on shall go
434
+ // extract _traceConfig to the constructor when we have plenty of time.
435
+ const traceConfig = {
436
+ opts: this._observabilityOptions,
437
+ dbName: this.database.formattedName_,
438
+ };
439
+ return (0, instrument_1.startTrace)('SessionPool.createSessions', traceConfig, async (span) => {
440
+ span.addEvent(`Requesting ${amount} sessions`);
441
+ // while we can request as many sessions be created as we want, the backend
442
+ // will return at most 100 at a time, hence the need for a while loop.
443
+ while (amount > 0) {
444
+ let sessions = null;
445
+ span.addEvent(`Creating ${amount} sessions`);
446
+ try {
447
+ [sessions] = await this.database.batchCreateSessions({
448
+ count: amount,
449
+ labels: labels,
450
+ databaseRole: databaseRole,
451
+ });
452
+ amount -= sessions.length;
453
+ nReturned += sessions.length;
454
+ }
455
+ catch (e) {
456
+ this._pending -= amount;
457
+ this.emit('createError', e);
458
+ span.addEvent(`Requested for ${nRequested} sessions returned ${nReturned}`);
459
+ (0, instrument_1.setSpanErrorAndException)(span, e);
460
+ span.end();
461
+ throw e;
462
+ }
463
+ sessions.forEach((session) => {
464
+ setImmediate(() => {
465
+ this._inventory.borrowed.add(session);
466
+ this._pending -= 1;
467
+ this.release(session);
468
+ });
469
+ });
470
+ }
471
+ span.addEvent(`Requested for ${nRequested} sessions returned ${nReturned}`);
472
+ span.end();
473
+ });
474
+ }
475
+ /**
476
+ * Attempts to delete a session, optionally creating a new one of the same
477
+ * type if the pool is still open and we're under the configured min value.
478
+ *
479
+ * @private
480
+ *
481
+ * @fires SessionPool#error
482
+ * @param {Session} session The session to delete.
483
+ * @returns {Promise}
484
+ */
485
+ async _destroy(session) {
486
+ try {
487
+ await this._requests.add(() => session.delete());
488
+ }
489
+ catch (e) {
490
+ this.emit('error', e);
491
+ }
492
+ }
493
+ /**
494
+ * Deletes idle sessions that exceed the maxIdle configuration.
495
+ *
496
+ * @private
497
+ */
498
+ _evictIdleSessions() {
499
+ const { maxIdle, min } = this.options;
500
+ const size = this.size;
501
+ const idle = this._getIdleSessions();
502
+ let count = idle.length;
503
+ let evicted = 0;
504
+ while (count-- > maxIdle && size - evicted++ > min) {
505
+ const session = idle.pop();
506
+ if (!session) {
507
+ continue;
508
+ }
509
+ const index = this._inventory.sessions.indexOf(session);
510
+ this._inventory.sessions.splice(index, 1);
511
+ this._destroy(session);
512
+ }
513
+ }
514
+ /**
515
+ * Fills the pool with the minimum number of sessions.
516
+ *
517
+ * @return {Promise}
518
+ */
519
+ async _fill() {
520
+ const needed = this.options.min - this.size;
521
+ if (needed <= 0) {
522
+ return;
523
+ }
524
+ await this._createSessions(needed);
525
+ }
526
+ /**
527
+ * Retrieves a list of all the idle sessions.
528
+ *
529
+ * @private
530
+ *
531
+ * @returns {Session[]}
532
+ */
533
+ _getIdleSessions() {
534
+ const idlesAfter = this.options.idlesAfter * 60000;
535
+ const sessions = this._inventory.sessions;
536
+ return sessions.filter(session => {
537
+ return Date.now() - session.lastUsed >= idlesAfter;
538
+ });
539
+ }
540
+ /**
541
+ * Returns stack traces for sessions that have not been released.
542
+ *
543
+ * @return {string[]}
544
+ */
545
+ _getLeaks() {
546
+ return [...this._traces.values()].map(SessionPool.formatTrace);
547
+ }
548
+ /**
549
+ * Returns true if the pool has a usable session.
550
+ * @private
551
+ */
552
+ _hasSessionUsableFor() {
553
+ return this._inventory.sessions.length > 0;
554
+ }
555
+ /**
556
+ * Attempts to get a session.
557
+ *
558
+ * @private
559
+ *
560
+ * @param {number} startTime Timestamp to use when determining timeouts.
561
+ * @returns {Promise<Session>}
562
+ */
563
+ async _getSession(startTime) {
564
+ const span = (0, instrument_1.getActiveOrNoopSpan)();
565
+ if (this._hasSessionUsableFor()) {
566
+ span.addEvent('Cache hit: has usable session');
567
+ return this._borrowNextAvailableSession();
568
+ }
569
+ if (this.isFull && this.options.fail) {
570
+ span.addEvent('Session pool is full and failFast=true');
571
+ throw new SessionPoolExhaustedError(this._getLeaks());
572
+ }
573
+ let removeOnceCloseListener;
574
+ let removeListener;
575
+ // Wait for a session to become available.
576
+ span.addEvent('Waiting for a session to become available');
577
+ const availableEvent = 'session-available';
578
+ const promises = [
579
+ new Promise((_, reject) => {
580
+ const onceCloseListener = () => reject(new google_gax_1.GoogleError("Database is closed." /* errors.Closed */));
581
+ this.once('close', onceCloseListener);
582
+ removeOnceCloseListener = this.removeListener.bind(this, 'close', onceCloseListener);
583
+ }),
584
+ new Promise(resolve => {
585
+ this.once(availableEvent, resolve);
586
+ removeListener = this.removeListener.bind(this, availableEvent, resolve);
587
+ }),
588
+ ];
589
+ const timeout = this.options.acquireTimeout;
590
+ let removeTimeoutListener = () => { };
591
+ if (!is.infinite(timeout)) {
592
+ const elapsed = Date.now() - startTime;
593
+ const remaining = timeout - elapsed;
594
+ promises.push(new Promise((_, reject) => {
595
+ const error = new Error("Timeout occurred while acquiring session." /* errors.Timeout */);
596
+ const timeoutFunction = setTimeout(reject.bind(null, error), remaining);
597
+ removeTimeoutListener = () => clearTimeout(timeoutFunction);
598
+ }));
599
+ }
600
+ // Only create a new session if there are more waiters than sessions already
601
+ // being created. The current requester will be waiter number _numWaiters+1.
602
+ if (!this.isFull && this.totalPending <= this.totalWaiters) {
603
+ let amount = this.options.incStep
604
+ ? this.options.incStep
605
+ : DEFAULTS.incStep;
606
+ // Create additional sessions if the configured minimum has not been reached.
607
+ const min = this.options.min ? this.options.min : 0;
608
+ if (this.size + this.totalPending + amount < min) {
609
+ amount = min - this.size - this.totalPending;
610
+ }
611
+ // Make sure we don't create more sessions than the pool should have.
612
+ if (amount + this.size > this.options.max) {
613
+ amount = this.options.max - this.size;
614
+ }
615
+ if (amount > 0) {
616
+ this._pending += amount;
617
+ promises.push(new Promise((_, reject) => {
618
+ this._pending -= amount;
619
+ this._createSessions(amount).catch(reject);
620
+ }));
621
+ }
622
+ }
623
+ let removeErrorListener;
624
+ promises.push(new Promise((_, reject) => {
625
+ this.once('createError', reject);
626
+ removeErrorListener = this.removeListener.bind(this, 'createError', reject);
627
+ }));
628
+ try {
629
+ this._waiters++;
630
+ await Promise.race(promises);
631
+ }
632
+ finally {
633
+ this._waiters--;
634
+ removeOnceCloseListener();
635
+ removeListener();
636
+ removeErrorListener();
637
+ removeTimeoutListener();
638
+ }
639
+ return this._borrowNextAvailableSession();
640
+ }
641
+ /**
642
+ * Checks to see whether or not session is expired.
643
+ *
644
+ * @param {Session} session The session to check.
645
+ * @returns {boolean}
646
+ */
647
+ _isValidSession(session) {
648
+ // unpinged sessions only stay good for 1 hour
649
+ const MAX_DURATION = 60000 * 60;
650
+ return Date.now() - session.lastUsed < MAX_DURATION;
651
+ }
652
+ /**
653
+ * Pings an individual session.
654
+ *
655
+ * @private
656
+ *
657
+ * @param {Session} session The session to ping.
658
+ * @returns {Promise}
659
+ */
660
+ async _ping(session) {
661
+ // NOTE: Please do not trace Ping as it gets quite spammy
662
+ // with many root spans polluting the main span.
663
+ // Please see https://github.com/googleapis/google-cloud-go/issues/1691
664
+ this._borrow(session);
665
+ if (!this._isValidSession(session)) {
666
+ this._inventory.borrowed.delete(session);
667
+ return;
668
+ }
669
+ try {
670
+ await session.keepAlive();
671
+ this.release(session);
672
+ }
673
+ catch (e) {
674
+ this._inventory.borrowed.delete(session);
675
+ this._destroy(session);
676
+ }
677
+ }
678
+ /**
679
+ * Makes a keep alive request to all the idle sessions.
680
+ *
681
+ * @private
682
+ *
683
+ * @returns {Promise}
684
+ */
685
+ async _pingIdleSessions() {
686
+ const sessions = this._getIdleSessions();
687
+ const pings = sessions.map(session => this._ping(session));
688
+ await Promise.all(pings);
689
+ try {
690
+ await this._fill();
691
+ }
692
+ catch (error) {
693
+ // Ignore `Database not found` error. This allows a user to call instance.database('db-name')
694
+ // for a database that does not yet exist with SessionPoolOptions.min > 0.
695
+ const err = error;
696
+ if ((0, helper_1.isDatabaseNotFoundError)(err) ||
697
+ (0, helper_1.isInstanceNotFoundError)(err) ||
698
+ (0, helper_1.isCreateSessionPermissionError)(err) ||
699
+ (0, helper_1.isDefaultCredentialsNotSetError)(err) ||
700
+ (0, helper_1.isProjectIdNotSetInEnvironmentError)(err)) {
701
+ return;
702
+ }
703
+ this.emit('error', err);
704
+ }
705
+ return;
706
+ }
707
+ /**
708
+ * Creates a transaction for a session.
709
+ *
710
+ * @private
711
+ *
712
+ * @param {Session} session The session object.
713
+ * @param {object} options The transaction options.
714
+ */
715
+ _prepareTransaction(session) {
716
+ const transaction = session.transaction(session.parent.queryOptions_);
717
+ session.txn = transaction;
718
+ }
719
+ /**
720
+ * Releases a session back into the pool.
721
+ *
722
+ * @private
723
+ *
724
+ * @fires SessionPool#available
725
+ * @fires SessionPool#session-available
726
+ * @fires @deprecated SessionPool#readonly-available
727
+ * @fires @deprecated SessionPool#readwrite-available
728
+ * @param {Session} session The session object.
729
+ */
730
+ _release(session) {
731
+ this._inventory.sessions.push(session);
732
+ this._inventory.borrowed.delete(session);
733
+ this._traces.delete(session.id);
734
+ this.emit('available');
735
+ this.emit('session-available');
736
+ this.emit('readonly-available');
737
+ this.emit('readwrite-available');
738
+ }
739
+ /**
740
+ * Starts housekeeping (pinging/evicting) of idle sessions.
741
+ *
742
+ * @private
743
+ */
744
+ _startHouseKeeping() {
745
+ const evictRate = this.options.idlesAfter * 60000;
746
+ this._evictHandle = setInterval(() => this._evictIdleSessions(), evictRate);
747
+ this._evictHandle.unref();
748
+ const pingRate = this.options.keepAlive * 60000;
749
+ this._pingHandle = setInterval(() => this._pingIdleSessions(), pingRate);
750
+ this._pingHandle.unref();
751
+ }
752
+ /**
753
+ * Stops housekeeping.
754
+ *
755
+ * @private
756
+ */
757
+ _stopHouseKeeping() {
758
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
759
+ clearInterval(this._pingHandle);
760
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
761
+ clearInterval(this._evictHandle);
762
+ }
763
+ }
764
+ exports.SessionPool = SessionPool;
765
+ //# sourceMappingURL=session-pool.js.map