forked from datastax/nodejs-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient-options.js
361 lines (315 loc) · 11.6 KB
/
client-options.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
/*
* 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 util = require('util');
const policies = require('./policies');
const types = require('./types');
const utils = require('./utils');
const tracker = require('./tracker');
const metrics = require('./metrics');
const auth = require('./auth');
/** Core connections per host for protocol versions 1 and 2 */
const coreConnectionsPerHostV2 = {
[types.distance.local]: 2,
[types.distance.remote]: 1,
[types.distance.ignored]: 0
};
/** Core connections per host for protocol version 3 and above */
const coreConnectionsPerHostV3 = {
[types.distance.local]: 1,
[types.distance.remote]: 1,
[types.distance.ignored]: 0
};
/** Default maxRequestsPerConnection value for protocol v1 and v2 */
const maxRequestsPerConnectionV2 = 128;
/** Default maxRequestsPerConnection value for protocol v3+ */
const maxRequestsPerConnectionV3 = 2048;
const continuousPageUnitBytes = 'bytes';
const continuousPageDefaultSize = 5000;
const continuousPageDefaultHighWaterMark = 10000;
/**
* @returns {ClientOptions}
*/
function defaultOptions () {
return ({
policies: {
addressResolution: policies.defaultAddressTranslator(),
loadBalancing: policies.defaultLoadBalancingPolicy(),
reconnection: policies.defaultReconnectionPolicy(),
retry: policies.defaultRetryPolicy(),
speculativeExecution: policies.defaultSpeculativeExecutionPolicy(),
timestampGeneration: policies.defaultTimestampGenerator()
},
queryOptions: {
fetchSize: 5000,
prepare: false,
captureStackTrace: false
},
protocolOptions: {
port: 9042,
maxSchemaAgreementWaitSeconds: 10,
maxVersion: 0,
noCompact: false
},
pooling: {
heartBeatInterval: 30000,
warmup: true
},
socketOptions: {
connectTimeout: 5000,
defunctReadTimeoutThreshold: 64,
keepAlive: true,
keepAliveDelay: 0,
readTimeout: 12000,
tcpNoDelay: true,
coalescingThreshold: 65536
},
authProvider: null,
requestTracker: null,
metrics: new metrics.DefaultMetrics(),
maxPrepared: 500,
refreshSchemaDelay: 1000,
isMetadataSyncEnabled: true,
prepareOnAllHosts: true,
rePrepareOnUp: true,
encoding: {
copyBuffer: true,
useUndefinedAsUnset: true
},
monitorReporting: {
enabled: true
}
});
}
/**
* Extends and validates the user options
* @param {Object} [baseOptions] The source object instance that will be overridden
* @param {Object} userOptions
* @returns {Object}
*/
function extend(baseOptions, userOptions) {
if (arguments.length === 1) {
userOptions = arguments[0];
baseOptions = {};
}
const options = utils.deepExtend(baseOptions, defaultOptions(), userOptions);
if (!options.cloud) {
if (!Array.isArray(options.contactPoints) || options.contactPoints.length === 0) {
throw new TypeError('Contacts points are not defined.');
}
for (let i = 0; i < options.contactPoints.length; i++) {
const hostName = options.contactPoints[i];
if (!hostName) {
throw new TypeError(util.format('Contact point %s (%s) is not a valid host name, ' +
'the following values are valid contact points: ipAddress, hostName or ipAddress:port', i, hostName));
}
}
options.sni = undefined;
} else {
validateCloudOptions(options);
}
if (!options.logEmitter) {
options.logEmitter = function () {};
}
if (!options.queryOptions) {
throw new TypeError('queryOptions not defined in options');
}
if (options.requestTracker !== null && !(options.requestTracker instanceof tracker.RequestTracker)) {
throw new TypeError('requestTracker must be an instance of RequestTracker');
}
if (!(options.metrics instanceof metrics.ClientMetrics)) {
throw new TypeError('metrics must be an instance of ClientMetrics');
}
validatePoliciesOptions(options.policies);
validateProtocolOptions(options.protocolOptions);
validateSocketOptions(options.socketOptions);
validateAuthenticationOptions(options);
options.encoding = options.encoding || {};
validateEncodingOptions(options.encoding);
if (options.profiles && !Array.isArray(options.profiles)) {
throw new TypeError('profiles must be an Array of ExecutionProfile instances');
}
validateApplicationInfo(options);
validateMonitorReporting(options);
return options;
}
/**
* Validates the options to connect to a cloud instance.
* @private
*/
function validateCloudOptions(options) {
const bundle = options.cloud.secureConnectBundle;
// eslint-disable-next-line no-undef
if (!(typeof bundle === 'string' || (typeof URL !== 'undefined' && bundle instanceof URL))) {
throw new TypeError('secureConnectBundle in cloud options must be of type string');
}
if (options.contactPoints) {
throw new TypeError('Contact points can not be defined when cloud settings are provided');
}
if (options.sslOptions) {
throw new TypeError('SSL options can not be defined when cloud settings are provided');
}
}
/**
* Validates the policies from the client options.
* @param {ClientOptions.policies} policiesOptions
* @private
*/
function validatePoliciesOptions(policiesOptions) {
if (!policiesOptions) {
throw new TypeError('policies not defined in options');
}
if (!(policiesOptions.loadBalancing instanceof policies.loadBalancing.LoadBalancingPolicy)) {
throw new TypeError('Load balancing policy must be an instance of LoadBalancingPolicy');
}
if (!(policiesOptions.reconnection instanceof policies.reconnection.ReconnectionPolicy)) {
throw new TypeError('Reconnection policy must be an instance of ReconnectionPolicy');
}
if (!(policiesOptions.retry instanceof policies.retry.RetryPolicy)) {
throw new TypeError('Retry policy must be an instance of RetryPolicy');
}
if (!(policiesOptions.addressResolution instanceof policies.addressResolution.AddressTranslator)) {
throw new TypeError('Address resolution policy must be an instance of AddressTranslator');
}
if (policiesOptions.timestampGeneration !== null &&
!(policiesOptions.timestampGeneration instanceof policies.timestampGeneration.TimestampGenerator)) {
throw new TypeError('Timestamp generation policy must be an instance of TimestampGenerator');
}
}
/**
* Validates the protocol options.
* @param {ClientOptions.protocolOptions} protocolOptions
* @private
*/
function validateProtocolOptions(protocolOptions) {
if (!protocolOptions) {
throw new TypeError('protocolOptions not defined in options');
}
const version = protocolOptions.maxVersion;
if (version && (typeof version !== 'number' || !types.protocolVersion.isSupported(version))) {
throw new TypeError(util.format('protocolOptions.maxVersion provided (%s) is invalid', version));
}
}
/**
* Validates the socket options.
* @param {ClientOptions.socketOptions} socketOptions
* @private
*/
function validateSocketOptions(socketOptions) {
if (!socketOptions) {
throw new TypeError('socketOptions not defined in options');
}
if (typeof socketOptions.readTimeout !== 'number') {
throw new TypeError('socketOptions.readTimeout must be a Number');
}
if (typeof socketOptions.coalescingThreshold !== 'number' || socketOptions.coalescingThreshold <= 0) {
throw new TypeError('socketOptions.coalescingThreshold must be a positive Number');
}
}
/**
* Validates authentication provider and credentials.
* @param {ClientOptions} options
* @private
*/
function validateAuthenticationOptions(options) {
if (!options.authProvider) {
const credentials = options.credentials;
if (credentials) {
if (typeof credentials.username !== 'string' || typeof credentials.password !== 'string') {
throw new TypeError('credentials username and password must be a string');
}
options.authProvider = new auth.PlainTextAuthProvider(credentials.username, credentials.password);
} else {
options.authProvider = new auth.NoAuthProvider();
}
} else if (!(options.authProvider instanceof auth.AuthProvider)) {
throw new TypeError('options.authProvider must be an instance of AuthProvider');
}
}
/**
* Validates the encoding options.
* @param {ClientOptions.encoding} encodingOptions
* @private
*/
function validateEncodingOptions(encodingOptions) {
if (encodingOptions.map) {
const mapConstructor = encodingOptions.map;
if (typeof mapConstructor !== 'function' ||
typeof mapConstructor.prototype.forEach !== 'function' ||
typeof mapConstructor.prototype.set !== 'function') {
throw new TypeError('Map constructor not valid');
}
}
if (encodingOptions.set) {
const setConstructor = encodingOptions.set;
if (typeof setConstructor !== 'function' ||
typeof setConstructor.prototype.forEach !== 'function' ||
typeof setConstructor.prototype.add !== 'function') {
throw new TypeError('Set constructor not valid');
}
}
if ((encodingOptions.useBigIntAsLong || encodingOptions.useBigIntAsVarint) && typeof BigInt === 'undefined') {
throw new TypeError('BigInt is not supported by the JavaScript engine');
}
}
function validateApplicationInfo(options) {
function validateString(key) {
const str = options[key];
if (str !== null && str !== undefined && typeof str !== 'string') {
throw new TypeError(`${key} should be a String`);
}
}
validateString('applicationName');
validateString('applicationVersion');
if (options.id !== null && options.id !== undefined && !(options.id instanceof types.Uuid)) {
throw new TypeError('Client id must be a Uuid');
}
}
function validateMonitorReporting(options) {
const o = options.monitorReporting;
if (o === null || typeof o !== 'object') {
throw new TypeError(`Monitor reporting must be an object, obtained: ${o}`);
}
}
/**
* Sets the default options that depend on the protocol version and other metadata.
* @param {Client} client
*/
function setMetadataDependent(client) {
const version = client.controlConnection.protocolVersion;
let coreConnectionsPerHost = coreConnectionsPerHostV3;
let maxRequestsPerConnection = maxRequestsPerConnectionV3;
if (!types.protocolVersion.uses2BytesStreamIds(version)) {
coreConnectionsPerHost = coreConnectionsPerHostV2;
maxRequestsPerConnection = maxRequestsPerConnectionV2;
}
if (client.options.queryOptions.consistency === undefined) {
client.options.queryOptions.consistency =
client.metadata.isDbaas() ? types.consistencies.localQuorum : types.consistencies.localOne;
}
client.options.pooling = utils.deepExtend(
{}, { coreConnectionsPerHost, maxRequestsPerConnection }, client.options.pooling);
}
exports.extend = extend;
exports.defaultOptions = defaultOptions;
exports.coreConnectionsPerHostV2 = coreConnectionsPerHostV2;
exports.coreConnectionsPerHostV3 = coreConnectionsPerHostV3;
exports.maxRequestsPerConnectionV2 = maxRequestsPerConnectionV2;
exports.maxRequestsPerConnectionV3 = maxRequestsPerConnectionV3;
exports.setMetadataDependent = setMetadataDependent;
exports.continuousPageUnitBytes = continuousPageUnitBytes;
exports.continuousPageDefaultSize = continuousPageDefaultSize;
exports.continuousPageDefaultHighWaterMark = continuousPageDefaultHighWaterMark;