@google-cloud/spanner 7.18.0 → 7.18.1
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.
- package/CHANGELOG.md +7 -0
- package/README.md +1 -0
- package/build/protos/google/spanner/admin/database/v1/backup.proto +757 -0
- package/build/protos/google/spanner/admin/database/v1/backup_schedule.proto +230 -0
- package/build/protos/google/spanner/admin/database/v1/common.proto +132 -0
- package/build/protos/google/spanner/admin/database/v1/spanner_database_admin.proto +1209 -0
- package/build/protos/google/spanner/admin/instance/v1/common.proto +64 -0
- package/build/protos/google/spanner/admin/instance/v1/spanner_instance_admin.proto +2110 -0
- package/build/protos/google/spanner/executor/v1/cloud_executor.proto +1520 -0
- package/build/protos/google/spanner/v1/commit_response.proto +59 -0
- package/build/protos/google/spanner/v1/keys.proto +163 -0
- package/build/protos/google/spanner/v1/mutation.proto +107 -0
- package/build/protos/google/spanner/v1/query_plan.proto +128 -0
- package/build/protos/google/spanner/v1/result_set.proto +237 -0
- package/build/protos/google/spanner/v1/spanner.proto +1389 -0
- package/build/protos/google/spanner/v1/transaction.proto +575 -0
- package/build/protos/google/spanner/v1/type.proto +214 -0
- package/build/protos/protos.d.ts +39317 -0
- package/build/protos/protos.js +100360 -0
- package/build/protos/protos.json +10271 -0
- package/build/src/backup.d.ts +349 -0
- package/build/src/backup.js +246 -0
- package/build/src/batch-transaction.d.ts +247 -0
- package/build/src/batch-transaction.js +384 -0
- package/build/src/codec.d.ts +362 -0
- package/build/src/codec.js +791 -0
- package/build/src/common-grpc/service-object.d.ts +80 -0
- package/build/src/common-grpc/service-object.js +101 -0
- package/build/src/common-grpc/service.d.ts +445 -0
- package/build/src/common-grpc/service.js +826 -0
- package/build/src/common.d.ts +66 -0
- package/build/src/common.js +54 -0
- package/build/src/database.d.ts +2103 -0
- package/build/src/database.js +1655 -0
- package/build/src/extra_proto_list.json +1 -0
- package/build/src/helper.d.ts +45 -0
- package/build/src/helper.js +71 -0
- package/build/src/index.d.ts +1195 -0
- package/build/src/index.js +1059 -0
- package/build/src/instance-config.d.ts +294 -0
- package/build/src/instance-config.js +216 -0
- package/build/src/instance.d.ts +832 -0
- package/build/src/instance.js +781 -0
- package/build/src/instrument.d.ts +85 -0
- package/build/src/instrument.js +215 -0
- package/build/src/multiplexed-session.d.ts +136 -0
- package/build/src/multiplexed-session.js +197 -0
- package/build/src/partial-result-stream.d.ts +253 -0
- package/build/src/partial-result-stream.js +400 -0
- package/build/src/session-factory.d.ts +100 -0
- package/build/src/session-factory.js +93 -0
- package/build/src/session-pool.d.ts +471 -0
- package/build/src/session-pool.js +754 -0
- package/build/src/session.d.ts +258 -0
- package/build/src/session.js +348 -0
- package/build/src/spanner_grpc_config.json +92 -0
- package/build/src/table.d.ts +831 -0
- package/build/src/table.js +277 -0
- package/build/src/transaction-runner.d.ts +185 -0
- package/build/src/transaction-runner.js +282 -0
- package/build/src/transaction.d.ts +1691 -0
- package/build/src/transaction.js +2004 -0
- package/build/src/v1/database_admin_client.d.ts +2301 -0
- package/build/src/v1/database_admin_client.js +2286 -0
- package/build/src/v1/database_admin_client_config.json +160 -0
- package/build/src/v1/database_admin_proto_list.json +6 -0
- package/build/src/v1/gapic_metadata.json +27 -0
- package/build/src/v1/index.d.ts +4 -0
- package/build/src/v1/index.js +29 -0
- package/build/src/v1/instance_admin_client.d.ts +1985 -0
- package/build/src/v1/instance_admin_client.js +1768 -0
- package/build/src/v1/instance_admin_client_config.json +129 -0
- package/build/src/v1/instance_admin_proto_list.json +4 -0
- package/build/src/v1/spanner_client.d.ts +1250 -0
- package/build/src/v1/spanner_client.js +1086 -0
- package/build/src/v1/spanner_client_config.json +119 -0
- package/build/src/v1/spanner_executor_proxy_client.d.ts +418 -0
- package/build/src/v1/spanner_executor_proxy_client.js +706 -0
- package/build/src/v1/spanner_executor_proxy_client_config.json +30 -0
- package/build/src/v1/spanner_executor_proxy_proto_list.json +14 -0
- package/build/src/v1/spanner_proto_list.json +10 -0
- package/package.json +1 -1
|
@@ -0,0 +1,754 @@
|
|
|
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
|
+
try {
|
|
525
|
+
await this._createSessions(needed);
|
|
526
|
+
}
|
|
527
|
+
catch (e) {
|
|
528
|
+
this.emit('error', e);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Retrieves a list of all the idle sessions.
|
|
533
|
+
*
|
|
534
|
+
* @private
|
|
535
|
+
*
|
|
536
|
+
* @returns {Session[]}
|
|
537
|
+
*/
|
|
538
|
+
_getIdleSessions() {
|
|
539
|
+
const idlesAfter = this.options.idlesAfter * 60000;
|
|
540
|
+
const sessions = this._inventory.sessions;
|
|
541
|
+
return sessions.filter(session => {
|
|
542
|
+
return Date.now() - session.lastUsed >= idlesAfter;
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Returns stack traces for sessions that have not been released.
|
|
547
|
+
*
|
|
548
|
+
* @return {string[]}
|
|
549
|
+
*/
|
|
550
|
+
_getLeaks() {
|
|
551
|
+
return [...this._traces.values()].map(SessionPool.formatTrace);
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Returns true if the pool has a usable session.
|
|
555
|
+
* @private
|
|
556
|
+
*/
|
|
557
|
+
_hasSessionUsableFor() {
|
|
558
|
+
return this._inventory.sessions.length > 0;
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Attempts to get a session.
|
|
562
|
+
*
|
|
563
|
+
* @private
|
|
564
|
+
*
|
|
565
|
+
* @param {number} startTime Timestamp to use when determining timeouts.
|
|
566
|
+
* @returns {Promise<Session>}
|
|
567
|
+
*/
|
|
568
|
+
async _getSession(startTime) {
|
|
569
|
+
const span = (0, instrument_1.getActiveOrNoopSpan)();
|
|
570
|
+
if (this._hasSessionUsableFor()) {
|
|
571
|
+
span.addEvent('Cache hit: has usable session');
|
|
572
|
+
return this._borrowNextAvailableSession();
|
|
573
|
+
}
|
|
574
|
+
if (this.isFull && this.options.fail) {
|
|
575
|
+
span.addEvent('Session pool is full and failFast=true');
|
|
576
|
+
throw new SessionPoolExhaustedError(this._getLeaks());
|
|
577
|
+
}
|
|
578
|
+
let removeOnceCloseListener;
|
|
579
|
+
let removeListener;
|
|
580
|
+
// Wait for a session to become available.
|
|
581
|
+
span.addEvent('Waiting for a session to become available');
|
|
582
|
+
const availableEvent = 'session-available';
|
|
583
|
+
const promises = [
|
|
584
|
+
new Promise((_, reject) => {
|
|
585
|
+
const onceCloseListener = () => reject(new google_gax_1.GoogleError("Database is closed." /* errors.Closed */));
|
|
586
|
+
this.once('close', onceCloseListener);
|
|
587
|
+
removeOnceCloseListener = this.removeListener.bind(this, 'close', onceCloseListener);
|
|
588
|
+
}),
|
|
589
|
+
new Promise(resolve => {
|
|
590
|
+
this.once(availableEvent, resolve);
|
|
591
|
+
removeListener = this.removeListener.bind(this, availableEvent, resolve);
|
|
592
|
+
}),
|
|
593
|
+
];
|
|
594
|
+
const timeout = this.options.acquireTimeout;
|
|
595
|
+
let removeTimeoutListener = () => { };
|
|
596
|
+
if (!is.infinite(timeout)) {
|
|
597
|
+
const elapsed = Date.now() - startTime;
|
|
598
|
+
const remaining = timeout - elapsed;
|
|
599
|
+
promises.push(new Promise((_, reject) => {
|
|
600
|
+
const error = new Error("Timeout occurred while acquiring session." /* errors.Timeout */);
|
|
601
|
+
const timeoutFunction = setTimeout(reject.bind(null, error), remaining);
|
|
602
|
+
removeTimeoutListener = () => clearTimeout(timeoutFunction);
|
|
603
|
+
}));
|
|
604
|
+
}
|
|
605
|
+
// Only create a new session if there are more waiters than sessions already
|
|
606
|
+
// being created. The current requester will be waiter number _numWaiters+1.
|
|
607
|
+
if (!this.isFull && this.totalPending <= this.totalWaiters) {
|
|
608
|
+
let amount = this.options.incStep
|
|
609
|
+
? this.options.incStep
|
|
610
|
+
: DEFAULTS.incStep;
|
|
611
|
+
// Create additional sessions if the configured minimum has not been reached.
|
|
612
|
+
const min = this.options.min ? this.options.min : 0;
|
|
613
|
+
if (this.size + this.totalPending + amount < min) {
|
|
614
|
+
amount = min - this.size - this.totalPending;
|
|
615
|
+
}
|
|
616
|
+
// Make sure we don't create more sessions than the pool should have.
|
|
617
|
+
if (amount + this.size > this.options.max) {
|
|
618
|
+
amount = this.options.max - this.size;
|
|
619
|
+
}
|
|
620
|
+
if (amount > 0) {
|
|
621
|
+
this._pending += amount;
|
|
622
|
+
promises.push(new Promise((_, reject) => {
|
|
623
|
+
this._pending -= amount;
|
|
624
|
+
this._createSessions(amount).catch(reject);
|
|
625
|
+
}));
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
let removeErrorListener;
|
|
629
|
+
promises.push(new Promise((_, reject) => {
|
|
630
|
+
this.once('createError', reject);
|
|
631
|
+
removeErrorListener = this.removeListener.bind(this, 'createError', reject);
|
|
632
|
+
}));
|
|
633
|
+
try {
|
|
634
|
+
this._waiters++;
|
|
635
|
+
await Promise.race(promises);
|
|
636
|
+
}
|
|
637
|
+
finally {
|
|
638
|
+
this._waiters--;
|
|
639
|
+
removeOnceCloseListener();
|
|
640
|
+
removeListener();
|
|
641
|
+
removeErrorListener();
|
|
642
|
+
removeTimeoutListener();
|
|
643
|
+
}
|
|
644
|
+
return this._borrowNextAvailableSession();
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Checks to see whether or not session is expired.
|
|
648
|
+
*
|
|
649
|
+
* @param {Session} session The session to check.
|
|
650
|
+
* @returns {boolean}
|
|
651
|
+
*/
|
|
652
|
+
_isValidSession(session) {
|
|
653
|
+
// unpinged sessions only stay good for 1 hour
|
|
654
|
+
const MAX_DURATION = 60000 * 60;
|
|
655
|
+
return Date.now() - session.lastUsed < MAX_DURATION;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Pings an individual session.
|
|
659
|
+
*
|
|
660
|
+
* @private
|
|
661
|
+
*
|
|
662
|
+
* @param {Session} session The session to ping.
|
|
663
|
+
* @returns {Promise}
|
|
664
|
+
*/
|
|
665
|
+
async _ping(session) {
|
|
666
|
+
// NOTE: Please do not trace Ping as it gets quite spammy
|
|
667
|
+
// with many root spans polluting the main span.
|
|
668
|
+
// Please see https://github.com/googleapis/google-cloud-go/issues/1691
|
|
669
|
+
this._borrow(session);
|
|
670
|
+
if (!this._isValidSession(session)) {
|
|
671
|
+
this._inventory.borrowed.delete(session);
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
try {
|
|
675
|
+
await session.keepAlive();
|
|
676
|
+
this.release(session);
|
|
677
|
+
}
|
|
678
|
+
catch (e) {
|
|
679
|
+
this._inventory.borrowed.delete(session);
|
|
680
|
+
this._destroy(session);
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* Makes a keep alive request to all the idle sessions.
|
|
685
|
+
*
|
|
686
|
+
* @private
|
|
687
|
+
*
|
|
688
|
+
* @returns {Promise}
|
|
689
|
+
*/
|
|
690
|
+
async _pingIdleSessions() {
|
|
691
|
+
const sessions = this._getIdleSessions();
|
|
692
|
+
const pings = sessions.map(session => this._ping(session));
|
|
693
|
+
await Promise.all(pings);
|
|
694
|
+
return this._fill();
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* Creates a transaction for a session.
|
|
698
|
+
*
|
|
699
|
+
* @private
|
|
700
|
+
*
|
|
701
|
+
* @param {Session} session The session object.
|
|
702
|
+
* @param {object} options The transaction options.
|
|
703
|
+
*/
|
|
704
|
+
_prepareTransaction(session) {
|
|
705
|
+
const transaction = session.transaction(session.parent.queryOptions_);
|
|
706
|
+
session.txn = transaction;
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Releases a session back into the pool.
|
|
710
|
+
*
|
|
711
|
+
* @private
|
|
712
|
+
*
|
|
713
|
+
* @fires SessionPool#available
|
|
714
|
+
* @fires SessionPool#session-available
|
|
715
|
+
* @fires @deprecated SessionPool#readonly-available
|
|
716
|
+
* @fires @deprecated SessionPool#readwrite-available
|
|
717
|
+
* @param {Session} session The session object.
|
|
718
|
+
*/
|
|
719
|
+
_release(session) {
|
|
720
|
+
this._inventory.sessions.push(session);
|
|
721
|
+
this._inventory.borrowed.delete(session);
|
|
722
|
+
this._traces.delete(session.id);
|
|
723
|
+
this.emit('available');
|
|
724
|
+
this.emit('session-available');
|
|
725
|
+
this.emit('readonly-available');
|
|
726
|
+
this.emit('readwrite-available');
|
|
727
|
+
}
|
|
728
|
+
/**
|
|
729
|
+
* Starts housekeeping (pinging/evicting) of idle sessions.
|
|
730
|
+
*
|
|
731
|
+
* @private
|
|
732
|
+
*/
|
|
733
|
+
_startHouseKeeping() {
|
|
734
|
+
const evictRate = this.options.idlesAfter * 60000;
|
|
735
|
+
this._evictHandle = setInterval(() => this._evictIdleSessions(), evictRate);
|
|
736
|
+
this._evictHandle.unref();
|
|
737
|
+
const pingRate = this.options.keepAlive * 60000;
|
|
738
|
+
this._pingHandle = setInterval(() => this._pingIdleSessions(), pingRate);
|
|
739
|
+
this._pingHandle.unref();
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* Stops housekeeping.
|
|
743
|
+
*
|
|
744
|
+
* @private
|
|
745
|
+
*/
|
|
746
|
+
_stopHouseKeeping() {
|
|
747
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
748
|
+
clearInterval(this._pingHandle);
|
|
749
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
750
|
+
clearInterval(this._evictHandle);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
exports.SessionPool = SessionPool;
|
|
754
|
+
//# sourceMappingURL=session-pool.js.map
|