forked from datastax/nodejs-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprepare-handler.js
297 lines (252 loc) · 8.27 KB
/
prepare-handler.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const errors = require('./errors');
const utils = require('./utils');
const types = require('./types');
const promiseUtils = require('./promise-utils');
/**
* Encapsulates the logic for dealing with the different prepare request and response flows, including failover when
* trying to prepare a query.
*/
class PrepareHandler {
/**
* Creates a new instance of PrepareHandler
* @param {Client} client
* @param {LoadBalancingPolicy} loadBalancing
*/
constructor(client, loadBalancing) {
this._client = client;
this._loadBalancing = loadBalancing;
this.logEmitter = client.options.logEmitter;
this.log = utils.log;
}
/**
* Gets the query id and metadata for a prepared statement, preparing it on
* single host or on all hosts depending on the options.
* @param {Client} client
* @param {LoadBalancingPolicy} loadBalancing
* @param {String} query
* @param {String} keyspace
* @returns {Promise<{queryId, meta}>}
* @static
*/
static async getPrepared(client, loadBalancing, query, keyspace) {
const info = client.metadata.getPreparedInfo(keyspace, query);
if (info.queryId) {
return info;
}
if (info.preparing) {
// It's already being prepared
return await promiseUtils.fromEvent(info, 'prepared');
}
const instance = new PrepareHandler(client, loadBalancing);
return await instance._prepare(info, query, keyspace);
}
/**
* @param {Client} client
* @param {LoadBalancingPolicy} loadBalancing
* @param {Array} queries
* @param {String} keyspace
* @static
*/
static async getPreparedMultiple(client, loadBalancing, queries, keyspace) {
const result = [];
for (const item of queries) {
let query;
if (item) {
query = typeof item === 'string' ? item : item.query;
}
if (typeof query !== 'string') {
throw new errors.ArgumentError('Query item should be a string');
}
const { queryId, meta } = await PrepareHandler.getPrepared(client, loadBalancing, query, keyspace);
result.push({ query, params: utils.adaptNamedParamsPrepared(item.params, meta.columns), queryId, meta });
}
return result;
}
/**
* Prepares the query on a single host or on all hosts depending on the options.
* Uses the info 'prepared' event to emit the result.
* @param {Object} info
* @param {String} query
* @param {String} keyspace
* @returns {Promise<{queryId, meta}>}
*/
async _prepare(info, query, keyspace) {
info.preparing = true;
let iterator;
try {
iterator = await promiseUtils.newQueryPlan(this._loadBalancing, keyspace, null);
return await this._prepareWithQueryPlan(info, iterator, query, keyspace);
} catch (err) {
info.preparing = false;
err.query = query;
info.emit('prepared', err);
throw err;
}
}
/**
* Uses the query plan to prepare the query on the first host and optionally on the rest of the hosts.
* @param {Object} info
* @param {Iterator} iterator
* @param {String} query
* @param {String} keyspace
* @returns {Promise<{queryId, meta}>}
* @private
*/
async _prepareWithQueryPlan(info, iterator, query, keyspace) {
const triedHosts = {};
while (true) {
const host = PrepareHandler.getNextHost(iterator, this._client.profileManager, triedHosts);
if (host === null) {
throw new errors.NoHostAvailableError(triedHosts);
}
try {
const connection = await PrepareHandler._borrowWithKeyspace(host, keyspace);
const response = await connection.prepareOnceAsync(query, keyspace);
if (this._client.options.prepareOnAllHosts) {
await this._prepareOnAllHosts(iterator, query, keyspace);
}
// Set the prepared metadata
info.preparing = false;
info.queryId = response.id;
info.meta = response.meta;
this._client.metadata.setPreparedById(info);
info.emit('prepared', null, info);
return info;
} catch (err) {
triedHosts[host.address] = err;
if (!err.isSocketError && !(err instanceof errors.OperationTimedOutError)) {
// There's no point in retrying syntax errors and other response errors
throw err;
}
}
}
}
/**
* Gets the next host from the query plan.
* @param {Iterator} iterator
* @param {ProfileManager} profileManager
* @param {Object} [triedHosts]
* @return {Host|null}
*/
static getNextHost(iterator, profileManager, triedHosts) {
let host;
// Get a host that is UP in a sync loop
while (true) {
const item = iterator.next();
if (item.done) {
return null;
}
host = item.value;
// set the distance relative to the client first
const distance = profileManager.getDistance(host);
if (distance === types.distance.ignored) {
//If its marked as ignore by the load balancing policy, move on.
continue;
}
if (host.isUp()) {
break;
}
if (triedHosts) {
triedHosts[host.address] = 'Host considered as DOWN';
}
}
return host;
}
/**
* Prepares all queries on a single host.
* @param {Host} host
* @param {Array} allPrepared
*/
static async prepareAllQueries(host, allPrepared) {
const anyKeyspaceQueries = [];
const queriesByKeyspace = new Map();
allPrepared.forEach(info => {
let arr;
if (info.keyspace) {
arr = queriesByKeyspace.get(info.keyspace);
if (!arr) {
arr = [];
queriesByKeyspace.set(info.keyspace, arr);
}
} else {
arr = anyKeyspaceQueries;
}
arr.push(info.query);
});
for (const [keyspace, queries] of queriesByKeyspace) {
await PrepareHandler._borrowAndPrepare(host, keyspace, queries);
}
await PrepareHandler._borrowAndPrepare(host, null, anyKeyspaceQueries);
}
/**
* Borrows a connection from the host and prepares the queries provided.
* @param {Host} host
* @param {String} keyspace
* @param {Array} queries
* @returns {Promise<void>}
* @private
*/
static async _borrowAndPrepare(host, keyspace, queries) {
if (queries.length === 0) {
return;
}
const connection = await PrepareHandler._borrowWithKeyspace(host, keyspace);
for (const query of queries) {
await connection.prepareOnceAsync(query, keyspace);
}
}
/**
* Borrows a connection and changes the active keyspace on the connection, if needed.
* It does not perform any retry or error handling.
* @param {Host!} host
* @param {string} keyspace
* @returns {Promise<Connection>}
* @throws {errors.BusyConnectionError} When the connection is busy.
* @throws {errors.ResponseError} For invalid keyspaces.
* @throws {Error} For socket errors.
* @private
*/
static async _borrowWithKeyspace(host, keyspace) {
const connection = host.borrowConnection();
if (keyspace && connection.keyspace !== keyspace) {
await connection.changeKeyspace(keyspace);
}
return connection;
}
/**
* Prepares the provided query on all hosts, except the host provided.
* @param {Iterator} iterator
* @param {String} query
* @param {String} keyspace
* @private
*/
_prepareOnAllHosts(iterator, query, keyspace) {
const queries = [ query ];
let h;
const hosts = [];
while ((h = PrepareHandler.getNextHost(iterator, this._client.profileManager)) !== null) {
hosts.push(h);
}
return Promise.all(hosts.map(h =>
PrepareHandler
._borrowAndPrepare(h, keyspace, queries)
.catch(err => this.log('verbose', `Unexpected error while preparing query (${query}) on ${h.address}`, err))));
}
}
module.exports = PrepareHandler;