@ragestudio/scylla-odm 0.22.2 → 0.22.3

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 (153) hide show
  1. package/batch/index.d.ts +3 -3
  2. package/batch/index.d.ts.map +1 -1
  3. package/client.d.ts +6 -5
  4. package/client.d.ts.map +1 -1
  5. package/client.js +7 -7
  6. package/client.js.map +1 -1
  7. package/cql_gen/create_table.d.ts +1 -1
  8. package/cql_gen/create_table.d.ts.map +1 -1
  9. package/document/index.d.ts +3 -3
  10. package/document/index.d.ts.map +1 -1
  11. package/driver/LICENSE.txt +177 -0
  12. package/driver/NOTICE.txt +67 -0
  13. package/driver/auth/index.d.ts +37 -0
  14. package/driver/auth/index.js +37 -0
  15. package/driver/auth/no-auth-provider.js +73 -0
  16. package/driver/auth/plain-text-auth-provider.js +81 -0
  17. package/driver/auth/provider.js +77 -0
  18. package/driver/client-options.js +442 -0
  19. package/driver/client.js +1267 -0
  20. package/driver/concurrent/index.d.ts +49 -0
  21. package/driver/concurrent/index.js +366 -0
  22. package/driver/connection.js +1034 -0
  23. package/driver/control-connection.js +1282 -0
  24. package/driver/encoder.js +2316 -0
  25. package/driver/errors.js +223 -0
  26. package/driver/execution-options.js +612 -0
  27. package/driver/execution-profile.js +274 -0
  28. package/driver/host-connection-pool.js +587 -0
  29. package/driver/host.js +699 -0
  30. package/driver/index.d.ts +387 -0
  31. package/driver/index.js +81 -0
  32. package/driver/mapping/cache.js +214 -0
  33. package/driver/mapping/doc-info-adapter.js +171 -0
  34. package/driver/mapping/index.d.ts +219 -0
  35. package/driver/mapping/index.js +57 -0
  36. package/driver/mapping/mapper.js +225 -0
  37. package/driver/mapping/mapping-handler.js +641 -0
  38. package/driver/mapping/model-batch-item.js +215 -0
  39. package/driver/mapping/model-batch-mapper.js +141 -0
  40. package/driver/mapping/model-mapper.js +315 -0
  41. package/driver/mapping/model-mapping-info.js +225 -0
  42. package/driver/mapping/object-selector.js +417 -0
  43. package/driver/mapping/q.js +156 -0
  44. package/driver/mapping/query-generator.js +556 -0
  45. package/driver/mapping/result-mapper.js +123 -0
  46. package/driver/mapping/result.js +139 -0
  47. package/driver/mapping/table-mappings.js +133 -0
  48. package/driver/mapping/tree.js +160 -0
  49. package/driver/metadata/aggregate.js +79 -0
  50. package/driver/metadata/client-state.js +119 -0
  51. package/driver/metadata/data-collection.js +182 -0
  52. package/driver/metadata/event-debouncer.js +174 -0
  53. package/driver/metadata/index.d.ts +276 -0
  54. package/driver/metadata/index.js +1156 -0
  55. package/driver/metadata/materialized-view.js +49 -0
  56. package/driver/metadata/schema-function.js +98 -0
  57. package/driver/metadata/schema-index.js +166 -0
  58. package/driver/metadata/schema-parser.js +1399 -0
  59. package/driver/metadata/table-metadata.js +77 -0
  60. package/driver/operation-state.js +206 -0
  61. package/driver/policies/address-resolution.js +145 -0
  62. package/driver/policies/index.d.ts +241 -0
  63. package/driver/policies/index.js +110 -0
  64. package/driver/policies/load-balancing.js +970 -0
  65. package/driver/policies/reconnection.js +166 -0
  66. package/driver/policies/retry.js +326 -0
  67. package/driver/policies/speculative-execution.js +150 -0
  68. package/driver/policies/timestamp-generation.js +176 -0
  69. package/driver/prepare-handler.js +347 -0
  70. package/driver/promise-utils.js +191 -0
  71. package/driver/readers.js +624 -0
  72. package/driver/request-execution.js +644 -0
  73. package/driver/request-handler.js +332 -0
  74. package/driver/requests.js +618 -0
  75. package/driver/stream-id-stack.js +209 -0
  76. package/driver/streams.js +745 -0
  77. package/driver/token.js +325 -0
  78. package/driver/tokenizer.js +631 -0
  79. package/driver/types/big-decimal.js +282 -0
  80. package/driver/types/duration.js +576 -0
  81. package/driver/types/index.d.ts +486 -0
  82. package/driver/types/index.js +733 -0
  83. package/driver/types/inet-address.js +262 -0
  84. package/driver/types/integer.js +818 -0
  85. package/driver/types/local-date.js +280 -0
  86. package/driver/types/local-time.js +299 -0
  87. package/driver/types/mutable-long.js +385 -0
  88. package/driver/types/protocol-version.js +391 -0
  89. package/driver/types/result-set.js +287 -0
  90. package/driver/types/result-stream.js +164 -0
  91. package/driver/types/row.js +85 -0
  92. package/driver/types/time-uuid.js +414 -0
  93. package/driver/types/tuple.js +103 -0
  94. package/driver/types/uuid.js +160 -0
  95. package/driver/types/vector.js +130 -0
  96. package/driver/types/version-number.js +153 -0
  97. package/driver/utils.js +1485 -0
  98. package/driver/writers.js +350 -0
  99. package/global.d.ts +1 -1
  100. package/global.d.ts.map +1 -1
  101. package/index.d.ts +6 -6
  102. package/index.d.ts.map +1 -1
  103. package/index.js +6 -6
  104. package/index.js.map +1 -1
  105. package/migrate/index.d.ts +1 -1
  106. package/migrate/index.d.ts.map +1 -1
  107. package/migrate/index.js +1 -1
  108. package/migrate/index.js.map +1 -1
  109. package/model/index.d.ts +6 -6
  110. package/model/index.d.ts.map +1 -1
  111. package/model/index.js +10 -10
  112. package/model/index.js.map +1 -1
  113. package/operations/countAll.d.ts +1 -1
  114. package/operations/countAll.d.ts.map +1 -1
  115. package/operations/delete.d.ts +3 -4
  116. package/operations/delete.d.ts.map +1 -1
  117. package/operations/delete.js +1 -1
  118. package/operations/delete.js.map +1 -1
  119. package/operations/find.d.ts +2 -2
  120. package/operations/find.d.ts.map +1 -1
  121. package/operations/find.js +1 -1
  122. package/operations/find.js.map +1 -1
  123. package/operations/findOne.d.ts +2 -2
  124. package/operations/findOne.d.ts.map +1 -1
  125. package/operations/findOne.js +1 -1
  126. package/operations/findOne.js.map +1 -1
  127. package/operations/insert.d.ts +3 -3
  128. package/operations/insert.d.ts.map +1 -1
  129. package/operations/insert.js +2 -2
  130. package/operations/insert.js.map +1 -1
  131. package/operations/sync.d.ts +1 -1
  132. package/operations/sync.d.ts.map +1 -1
  133. package/operations/sync.js +1 -1
  134. package/operations/sync.js.map +1 -1
  135. package/operations/tableExists.d.ts +1 -1
  136. package/operations/tableExists.d.ts.map +1 -1
  137. package/operations/update.d.ts +3 -3
  138. package/operations/update.d.ts.map +1 -1
  139. package/operations/update.js +2 -2
  140. package/operations/update.js.map +1 -1
  141. package/package.json +4 -12
  142. package/schema/index.d.ts +1 -1
  143. package/schema/index.d.ts.map +1 -1
  144. package/types.d.ts +4 -4
  145. package/types.d.ts.map +1 -1
  146. package/utils/queryParser.d.ts +1 -1
  147. package/utils/queryParser.d.ts.map +1 -1
  148. package/utils/queryParser.js +1 -1
  149. package/utils/queryParser.js.map +1 -1
  150. package/utils/typeChecker.d.ts +1 -1
  151. package/utils/typeChecker.d.ts.map +1 -1
  152. package/utils/typeChecker.js +1 -1
  153. package/utils/typeChecker.js.map +1 -1
@@ -0,0 +1,1034 @@
1
+ /*
2
+ * Licensed to the Apache Software Foundation (ASF) under one
3
+ * or more contributor license agreements. See the NOTICE file
4
+ * distributed with this work for additional information
5
+ * regarding copyright ownership. The ASF licenses this file
6
+ * to you under the Apache License, Version 2.0 (the
7
+ * "License"); you may not use this file except in compliance
8
+ * with the License. You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ import events from "events"
20
+ import util from "util"
21
+ import tls from "tls"
22
+ import net from "net"
23
+
24
+ import Encoder from "./encoder.js"
25
+ import { WriteQueue } from "./writers.js"
26
+ import requests from "./requests.js"
27
+ import streams from "./streams.js"
28
+ import utils from "./utils.js"
29
+ import types from "./types/index.js"
30
+ import errors from "./errors.js"
31
+ import StreamIdStack from "./stream-id-stack.js"
32
+ import OperationState from "./operation-state.js"
33
+ import promiseUtils from "./promise-utils.js"
34
+ import { ExecutionOptions } from "./execution-options.js"
35
+
36
+ /**
37
+ * Represents a connection to a Cassandra node
38
+ */
39
+ class Connection extends events.EventEmitter {
40
+ /**
41
+ * Creates a new instance of Connection.
42
+ * @param {String} endpoint An string containing ip address and port of the host
43
+ * @param {Number|null} protocolVersion
44
+ * @param {ClientOptions} options
45
+ */
46
+ constructor(endpoint, protocolVersion, options) {
47
+ super()
48
+
49
+ this.setMaxListeners(0)
50
+
51
+ if (!options) {
52
+ throw new Error("options is not defined")
53
+ }
54
+
55
+ /**
56
+ * Gets the ip and port of the server endpoint.
57
+ * @type {String}
58
+ */
59
+ this.endpoint = endpoint
60
+
61
+ /**
62
+ * Gets the friendly name of the host, used to identify the connection in log messages.
63
+ * With direct connect, this is the address and port.
64
+ * With SNI, this will be the address and port of the proxy, plus the server name.
65
+ * @type {String}
66
+ */
67
+ this.endpointFriendlyName = this.endpoint
68
+
69
+ if (options.sni) {
70
+ this._serverName = endpoint
71
+ this.endpoint = `${options.sni.addressResolver.getIp()}:${options.sni.port}`
72
+ this.endpointFriendlyName = `${this.endpoint} (${this._serverName})`
73
+ }
74
+
75
+ if (!this.endpoint || this.endpoint.indexOf(":") < 0) {
76
+ throw new Error(
77
+ "EndPoint must contain the ip address and port separated by : symbol",
78
+ )
79
+ }
80
+
81
+ const portSeparatorIndex = this.endpoint.lastIndexOf(":")
82
+ this.address = this.endpoint.substr(0, portSeparatorIndex)
83
+ this.port = this.endpoint.substr(portSeparatorIndex + 1)
84
+
85
+ Object.defineProperty(this, "options", {
86
+ value: options,
87
+ enumerable: false,
88
+ writable: false,
89
+ })
90
+
91
+ if (protocolVersion === null) {
92
+ // Set initial protocol version
93
+ protocolVersion = types.protocolVersion.maxSupported
94
+ if (options.protocolOptions.maxVersion) {
95
+ // User provided the protocol version
96
+ protocolVersion = options.protocolOptions.maxVersion
97
+ }
98
+ // Allow to check version using this connection instance
99
+ this._checkingVersion = true
100
+ }
101
+
102
+ this.log = utils.log
103
+ this.protocolVersion = protocolVersion
104
+ this._operations = new Map()
105
+ this._pendingWrites = []
106
+ this._preparing = new Map()
107
+
108
+ /**
109
+ * The timeout state for the idle request (heartbeat)
110
+ */
111
+ this._idleTimeout = null
112
+ /**
113
+ * Single timer shared across all in-flight operations for request timeouts.
114
+ */
115
+ this._requestTimeoutTimer = null
116
+ this.timedOutOperations = 0
117
+ this._streamIds = new StreamIdStack(this.protocolVersion)
118
+ this._metrics = options.metrics
119
+
120
+ this.encoder = new Encoder(protocolVersion, options)
121
+ this.keyspace = null
122
+ this.emitDrain = false
123
+ /**
124
+ * Determines if the socket is open and startup succeeded, whether the connection can be used to send requests /
125
+ * receive events
126
+ */
127
+ this.connected = false
128
+ /**
129
+ * Determines if the socket can be considered as open
130
+ */
131
+ this.isSocketOpen = false
132
+
133
+ this.send = util.promisify(this.sendStream)
134
+ this.closeAsync = util.promisify(this.close)
135
+ this.openAsync = util.promisify(this.open)
136
+ this.prepareOnceAsync = util.promisify(this.prepareOnce)
137
+ }
138
+
139
+ /**
140
+ * Binds the necessary event listeners for the socket
141
+ */
142
+ bindSocketListeners() {
143
+ //Remove listeners that were used for connecting
144
+ this.netClient.removeAllListeners("connect")
145
+ this.netClient.removeAllListeners("timeout")
146
+ // The socket is expected to be open at this point
147
+ this.isSocketOpen = true
148
+ this.netClient.on("close", () => {
149
+ this.log(
150
+ "info",
151
+ `Connection to ${this.endpointFriendlyName} closed`,
152
+ )
153
+ this.isSocketOpen = false
154
+ const wasConnected = this.connected
155
+ this.close()
156
+ if (wasConnected) {
157
+ // Emit only when it was closed unexpectedly
158
+ this.emit("socketClose")
159
+ }
160
+ })
161
+
162
+ this.protocol = new streams.Protocol({ objectMode: true })
163
+ this.parser = new streams.Parser({ objectMode: true }, this.encoder)
164
+ const resultEmitter = new streams.ResultEmitter({ objectMode: true })
165
+ resultEmitter.on("result", this.handleResult.bind(this))
166
+ resultEmitter.on("row", this.handleRow.bind(this))
167
+ resultEmitter.on("frameEnded", this.freeStreamId.bind(this))
168
+ resultEmitter.on("nodeEvent", this.handleNodeEvent.bind(this))
169
+
170
+ this.netClient.pipe(this.protocol).pipe(this.parser).pipe(resultEmitter)
171
+
172
+ this.writeQueue = new WriteQueue(
173
+ this.netClient,
174
+ this.encoder,
175
+ this.options,
176
+ )
177
+ }
178
+
179
+ /**
180
+ * Connects a socket and sends the startup protocol messages.
181
+ * Note that when open() callbacks in error, the caller should immediately call {@link Connection#close}.
182
+ */
183
+ open(callback) {
184
+ const self = this
185
+ this.log("info", `Connecting to ${this.endpointFriendlyName}`)
186
+
187
+ if (!this.options.sslOptions) {
188
+ this.netClient = new net.Socket({
189
+ highWaterMark: this.options.socketOptions.coalescingThreshold,
190
+ })
191
+ this.netClient.connect(
192
+ this.port,
193
+ this.address,
194
+ function connectCallback() {
195
+ self.log(
196
+ "verbose",
197
+ `Socket connected to ${self.endpointFriendlyName}`,
198
+ )
199
+ self.bindSocketListeners()
200
+ self.startup(callback)
201
+ },
202
+ )
203
+ } else {
204
+ // Use TLS
205
+ const sslOptions = utils.extend(
206
+ { rejectUnauthorized: false },
207
+ this.options.sslOptions,
208
+ )
209
+
210
+ if (this.options.sni) {
211
+ sslOptions.servername = this._serverName
212
+ }
213
+
214
+ this.netClient = tls.connect(
215
+ this.port,
216
+ this.address,
217
+ sslOptions,
218
+ function tlsConnectCallback() {
219
+ self.log(
220
+ "verbose",
221
+ `Secure socket connected to ${self.endpointFriendlyName} with protocol ${self.netClient.getProtocol()}`,
222
+ )
223
+ self.bindSocketListeners()
224
+ self.startup(callback)
225
+ },
226
+ )
227
+
228
+ // TLSSocket will validate for values from 512 to 16K (depending on the SSL protocol version)
229
+ this.netClient.setMaxSendFragment(
230
+ this.options.socketOptions.coalescingThreshold,
231
+ )
232
+ }
233
+
234
+ this.netClient.once("error", function socketError(err) {
235
+ self.errorConnecting(err, false, callback)
236
+ })
237
+
238
+ this.netClient.once("timeout", function connectTimedOut() {
239
+ const err = new types.DriverError("Connection timeout")
240
+ self.errorConnecting(err, true, callback)
241
+ })
242
+
243
+ this.netClient.setTimeout(this.options.socketOptions.connectTimeout)
244
+
245
+ // Improve failure detection with TCP keep-alives
246
+ if (this.options.socketOptions.keepAlive) {
247
+ this.netClient.setKeepAlive(
248
+ true,
249
+ this.options.socketOptions.keepAliveDelay,
250
+ )
251
+ }
252
+
253
+ this.netClient.setNoDelay(!!this.options.socketOptions.tcpNoDelay)
254
+ }
255
+
256
+ /**
257
+ * Determines the protocol version to use and sends the STARTUP request
258
+ * @param {Function} callback
259
+ */
260
+ startup(callback) {
261
+ if (this._checkingVersion) {
262
+ this.log(
263
+ "info",
264
+ "Trying to use protocol version 0x" +
265
+ this.protocolVersion.toString(16),
266
+ )
267
+ }
268
+
269
+ const self = this
270
+ const request = new requests.StartupRequest({
271
+ noCompact: this.options.protocolOptions.noCompact,
272
+ clientId: this.options.id,
273
+ applicationName: this.options.applicationName,
274
+ applicationVersion: this.options.applicationVersion,
275
+ })
276
+
277
+ this.sendStream(
278
+ request,
279
+ null,
280
+ function responseCallback(err, response) {
281
+ if (err && self._checkingVersion) {
282
+ let invalidProtocol =
283
+ err instanceof errors.ResponseError &&
284
+ err.code === types.responseErrorCodes.protocolError &&
285
+ err.message.indexOf(
286
+ "Invalid or unsupported protocol version",
287
+ ) >= 0
288
+
289
+ if (
290
+ !invalidProtocol &&
291
+ types.protocolVersion.canStartupResponseErrorBeWrapped(
292
+ self.protocolVersion,
293
+ )
294
+ ) {
295
+ //For some versions of Cassandra, the error is wrapped into a server error
296
+ //See CASSANDRA-9451
297
+ invalidProtocol =
298
+ err instanceof errors.ResponseError &&
299
+ err.code === types.responseErrorCodes.serverError &&
300
+ err.message.indexOf(
301
+ "ProtocolException: Invalid or unsupported protocol version",
302
+ ) > 0
303
+ }
304
+
305
+ if (invalidProtocol) {
306
+ // The server can respond with a message using the lower protocol version supported
307
+ // or using the same version as the one provided
308
+ let lowerVersion = self.protocol.version
309
+
310
+ if (lowerVersion === self.protocolVersion) {
311
+ lowerVersion =
312
+ types.protocolVersion.getLowerSupported(
313
+ self.protocolVersion,
314
+ )
315
+ } else if (
316
+ !types.protocolVersion.isSupported(
317
+ self.protocol.version,
318
+ )
319
+ ) {
320
+ // If we have an unsupported protocol version or a beta version we need to switch
321
+ // to something we can support. Note that dseV1 and dseV2 are excluded from this
322
+ // logic as they are supported. Also note that any v5 and greater beta protocols
323
+ // are included here since the beta flag was introduced in v5.
324
+ self.log(
325
+ "info",
326
+ `Protocol version ${self.protocol.version} not supported by this driver, downgrading`,
327
+ )
328
+ lowerVersion =
329
+ types.protocolVersion.getLowerSupported(
330
+ self.protocol.version,
331
+ )
332
+ }
333
+
334
+ if (!lowerVersion) {
335
+ return startupCallback(
336
+ new Error(
337
+ "Connection was unable to STARTUP using protocol version " +
338
+ self.protocolVersion,
339
+ ),
340
+ )
341
+ }
342
+
343
+ self.log(
344
+ "info",
345
+ "Protocol 0x" +
346
+ self.protocolVersion.toString(16) +
347
+ " not supported, using 0x" +
348
+ lowerVersion.toString(16),
349
+ )
350
+ self.decreaseVersion(lowerVersion)
351
+
352
+ // The host closed the connection, close the socket and start the connection flow again
353
+ setImmediate(function decreasingVersionClosing() {
354
+ self.close(function decreasingVersionOpening() {
355
+ // Attempt to open with the correct protocol version
356
+ self.open(callback)
357
+ })
358
+ })
359
+
360
+ return
361
+ }
362
+ }
363
+
364
+ if (response && response.mustAuthenticate) {
365
+ return self.startAuthenticating(
366
+ response.authenticatorName,
367
+ startupCallback,
368
+ )
369
+ }
370
+
371
+ startupCallback(err)
372
+ },
373
+ )
374
+
375
+ function startupCallback(err) {
376
+ if (err) {
377
+ return self.errorConnecting(err, false, callback)
378
+ }
379
+ //The socket is connected and the connection is authenticated
380
+ return self.connectionReady(callback)
381
+ }
382
+ }
383
+
384
+ errorConnecting(err, destroy, callback) {
385
+ this.log(
386
+ "warning",
387
+ `There was an error when trying to connect to the host ${this.endpointFriendlyName}`,
388
+ err,
389
+ )
390
+ if (destroy) {
391
+ //there is a TCP connection that should be killed.
392
+ this.netClient.destroy()
393
+ }
394
+
395
+ this._metrics.onConnectionError(err)
396
+
397
+ callback(err)
398
+ }
399
+
400
+ /**
401
+ * Sets the connection to ready/connected status
402
+ */
403
+ connectionReady(callback) {
404
+ this.emit("connected")
405
+ this.connected = true
406
+ // Remove existing error handlers as the connection is now ready.
407
+ this.netClient.removeAllListeners("error")
408
+ this.netClient.on("error", this.handleSocketError.bind(this))
409
+ callback()
410
+ }
411
+
412
+ /** @param {Number} lowerVersion */
413
+ decreaseVersion(lowerVersion) {
414
+ // The response already has the max protocol version supported by the Cassandra host.
415
+ this.protocolVersion = lowerVersion
416
+ this.encoder.setProtocolVersion(lowerVersion)
417
+ this._streamIds.setVersion(lowerVersion)
418
+ }
419
+
420
+ /**
421
+ * Handle socket errors, if the socket is not readable invoke all pending callbacks
422
+ */
423
+ handleSocketError(err) {
424
+ this._metrics.onConnectionError(err)
425
+ this.clearAndInvokePending(err)
426
+ }
427
+
428
+ /**
429
+ * Cleans all internal state and invokes all pending callbacks of sent streams
430
+ */
431
+ clearAndInvokePending(innerError) {
432
+ if (this._idleTimeout) {
433
+ //Remove the idle request
434
+ clearTimeout(this._idleTimeout)
435
+ this._idleTimeout = null
436
+ }
437
+ if (this._requestTimeoutTimer) {
438
+ clearTimeout(this._requestTimeoutTimer)
439
+ this._requestTimeoutTimer = null
440
+ }
441
+ this._streamIds.clear()
442
+ if (this.emitDrain) {
443
+ this.emit("drain")
444
+ }
445
+ const err = new types.DriverError("Socket was closed")
446
+ err.isSocketError = true
447
+ if (innerError) {
448
+ err.innerError = innerError
449
+ }
450
+
451
+ // Get all handlers
452
+ const operations = Array.from(this._operations.values())
453
+ // Clear pending operation map
454
+ this._operations = new Map()
455
+
456
+ if (operations.length > 0) {
457
+ this.log(
458
+ "info",
459
+ "Invoking " + operations.length + " pending callbacks",
460
+ )
461
+ }
462
+
463
+ // Invoke all handlers
464
+ utils.each(operations, function (operation, next) {
465
+ operation.setResult(err)
466
+ next()
467
+ })
468
+
469
+ const pendingWritesCopy = this._pendingWrites
470
+ this._pendingWrites = []
471
+ utils.each(pendingWritesCopy, function (operation, next) {
472
+ operation.setResult(err)
473
+ next()
474
+ })
475
+ }
476
+
477
+ /**
478
+ * Starts the SASL flow
479
+ * @param {String} authenticatorName
480
+ * @param {Function} callback
481
+ */
482
+ startAuthenticating(authenticatorName, callback) {
483
+ if (!this.options.authProvider) {
484
+ return callback(
485
+ new errors.AuthenticationError(
486
+ "Authentication provider not set",
487
+ ),
488
+ )
489
+ }
490
+ const authenticator = this.options.authProvider.newAuthenticator(
491
+ this.endpoint,
492
+ authenticatorName,
493
+ )
494
+ const self = this
495
+ authenticator.initialResponse(
496
+ function initialResponseCallback(err, token) {
497
+ // Start the flow with the initial token
498
+ if (err) {
499
+ return self.onAuthenticationError(callback, err)
500
+ }
501
+ self.authenticate(authenticator, token, callback)
502
+ },
503
+ )
504
+ }
505
+
506
+ /**
507
+ * Handles authentication requests and responses.
508
+ * @param {Authenticator} authenticator
509
+ * @param {Buffer} token
510
+ * @param {Function} callback
511
+ */
512
+ authenticate(authenticator, token, callback) {
513
+ const self = this
514
+ let request = new requests.AuthResponseRequest(token)
515
+ if (this.protocolVersion === 1) {
516
+ //No Sasl support, use CREDENTIALS
517
+ if (!authenticator.username) {
518
+ return self.onAuthenticationError(
519
+ callback,
520
+ new errors.AuthenticationError(
521
+ "Only plain text authenticator providers allowed under protocol v1",
522
+ ),
523
+ )
524
+ }
525
+
526
+ request = new requests.CredentialsRequest(
527
+ authenticator.username,
528
+ authenticator.password,
529
+ )
530
+ }
531
+
532
+ this.sendStream(
533
+ request,
534
+ null,
535
+ function authResponseCallback(err, result) {
536
+ if (err) {
537
+ if (
538
+ err instanceof errors.ResponseError &&
539
+ err.code === types.responseErrorCodes.badCredentials
540
+ ) {
541
+ const authError = new errors.AuthenticationError(
542
+ err.message,
543
+ )
544
+ authError.additionalInfo = err
545
+ err = authError
546
+ }
547
+ return self.onAuthenticationError(callback, err)
548
+ }
549
+
550
+ if (result.ready) {
551
+ authenticator.onAuthenticationSuccess()
552
+ return callback()
553
+ }
554
+
555
+ if (result.authChallenge) {
556
+ return authenticator.evaluateChallenge(
557
+ result.token,
558
+ function evaluateCallback(err, t) {
559
+ if (err) {
560
+ return self.onAuthenticationError(callback, err)
561
+ }
562
+ //here we go again
563
+ self.authenticate(authenticator, t, callback)
564
+ },
565
+ )
566
+ }
567
+
568
+ callback(
569
+ new errors.DriverInternalError(
570
+ "Unexpected response from Cassandra: " +
571
+ util.inspect(result),
572
+ ),
573
+ )
574
+ },
575
+ )
576
+ }
577
+
578
+ onAuthenticationError(callback, err) {
579
+ this._metrics.onAuthenticationError(err)
580
+ callback(err)
581
+ }
582
+
583
+ /**
584
+ * Executes a 'USE ' query, if keyspace is provided and it is different from the current keyspace
585
+ * @param {?String} keyspace
586
+ */
587
+ async changeKeyspace(keyspace) {
588
+ if (!keyspace || this.keyspace === keyspace) {
589
+ return
590
+ }
591
+
592
+ if (this.toBeKeyspace === keyspace) {
593
+ // It will be invoked once the keyspace is changed
594
+ return promiseUtils.fromEvent(this, "keyspaceChanged")
595
+ }
596
+
597
+ this.toBeKeyspace = keyspace
598
+
599
+ const query = `USE "${keyspace}"`
600
+
601
+ try {
602
+ await this.send(new requests.QueryRequest(query, null, null), null)
603
+ this.keyspace = keyspace
604
+ this.emit("keyspaceChanged", null, keyspace)
605
+ } catch (err) {
606
+ this.log(
607
+ "error",
608
+ `Connection to ${this.endpointFriendlyName} could not switch active keyspace: ${err}`,
609
+ err,
610
+ )
611
+ this.emit("keyspaceChanged", err)
612
+ throw err
613
+ } finally {
614
+ this.toBeKeyspace = null
615
+ }
616
+ }
617
+
618
+ /**
619
+ * Prepares a query on a given connection. If its already being prepared, it queues the callback.
620
+ * @param {String} query
621
+ * @param {String} keyspace
622
+ * @param {function} callback
623
+ */
624
+ prepareOnce(query, keyspace, callback) {
625
+ const name = (keyspace || "") + query
626
+ let info = this._preparing.get(name)
627
+
628
+ if (info) {
629
+ // Its being already prepared
630
+ return info.once("prepared", callback)
631
+ }
632
+
633
+ info = new events.EventEmitter()
634
+ info.setMaxListeners(0)
635
+ info.once("prepared", callback)
636
+ this._preparing.set(name, info)
637
+
638
+ this.sendStream(
639
+ new requests.PrepareRequest(query, keyspace),
640
+ null,
641
+ (err, response) => {
642
+ info.emit("prepared", err, response)
643
+ this._preparing.delete(name)
644
+ },
645
+ )
646
+ }
647
+
648
+ /**
649
+ * Queues the operation to be written to the wire and invokes the callback once the response was obtained or with an
650
+ * error (socket error or OperationTimedOutError or serialization-related error).
651
+ * @param {Request} request
652
+ * @param {ExecutionOptions|null} execOptions
653
+ * @param {function} callback Function to be called once the response has been received
654
+ * @return {OperationState}
655
+ */
656
+ sendStream(request, execOptions, callback) {
657
+ execOptions = execOptions || ExecutionOptions.empty()
658
+
659
+ // Create a new operation that will contain the request, callback and timeouts
660
+ const operation = new OperationState(
661
+ request,
662
+ execOptions.getRowCallback(),
663
+ (err, response, length) => {
664
+ if (!err || !err.isSocketError) {
665
+ // Emit that a response was obtained when there is a valid response
666
+ // or when the error is not a socket error
667
+ this.emit("responseDequeued")
668
+ }
669
+ callback(err, response, length)
670
+ },
671
+ )
672
+
673
+ const streamId = this._getStreamId()
674
+
675
+ // Start the request timeout without waiting for the request to be written
676
+ operation.setRequestTimeout(
677
+ execOptions,
678
+ this.options.socketOptions.readTimeout,
679
+ this.endpoint,
680
+ () => this.timedOutOperations++,
681
+ () => this.timedOutOperations--,
682
+ )
683
+
684
+ // schedule shared timeout after setting the operation deadline
685
+ this._scheduleRequestTimeout()
686
+
687
+ if (streamId === null) {
688
+ this.log(
689
+ "info",
690
+ "Enqueuing " +
691
+ this._pendingWrites.length +
692
+ ", if this message is recurrent consider configuring more connections per host or lowering the pressure",
693
+ )
694
+ this._pendingWrites.push(operation)
695
+ return operation
696
+ }
697
+ this._write(operation, streamId)
698
+ return operation
699
+ }
700
+
701
+ /**
702
+ * Pushes the item into the queue.
703
+ * @param {OperationState} operation
704
+ * @param {Number} streamId
705
+ * @private
706
+ */
707
+ _write(operation, streamId) {
708
+ operation.streamId = streamId
709
+ const self = this
710
+ this.writeQueue.push(operation, function writeCallback(err) {
711
+ if (err) {
712
+ // The request was not written.
713
+ // There was a serialization error or the operation has already timed out or was cancelled
714
+ self._streamIds.push(streamId)
715
+ return operation.setResult(err)
716
+ }
717
+ self.log(
718
+ "verbose",
719
+ "Sent stream #" + streamId + " to " + self.endpointFriendlyName,
720
+ )
721
+ if (operation.isByRow()) {
722
+ self.parser.setOptions(streamId, { byRow: true })
723
+ }
724
+ self._setIdleTimeout()
725
+ self._operations.set(streamId, operation)
726
+ })
727
+ }
728
+
729
+ _setIdleTimeout() {
730
+ if (!this.options.pooling.heartBeatInterval) {
731
+ return
732
+ }
733
+ const self = this
734
+ // Scheduling the new timeout before de-scheduling the previous performs significantly better
735
+ // than de-scheduling first, see nodejs implementation: https://github.com/nodejs/node/blob/master/lib/timers
736
+ const previousTimeout = this._idleTimeout
737
+ self._idleTimeout = setTimeout(
738
+ () => self._idleTimeoutHandler(),
739
+ self.options.pooling.heartBeatInterval,
740
+ )
741
+ if (previousTimeout) {
742
+ //remove the previous timeout for the idle request
743
+ clearTimeout(previousTimeout)
744
+ }
745
+ }
746
+
747
+ /**
748
+ * Function that gets executed once the idle timeout has passed to issue a request to keep the connection alive
749
+ */
750
+ _idleTimeoutHandler() {
751
+ if (this.sendingIdleQuery) {
752
+ //don't issue another
753
+ //schedule for next time
754
+ this._idleTimeout = setTimeout(
755
+ () => this._idleTimeoutHandler(),
756
+ this.options.pooling.heartBeatInterval,
757
+ )
758
+ return
759
+ }
760
+
761
+ this.log(
762
+ "verbose",
763
+ `Connection to ${this.endpointFriendlyName} idling, issuing a request to prevent disconnects`,
764
+ )
765
+ this.sendingIdleQuery = true
766
+ this.sendStream(requests.options, null, (err) => {
767
+ this.sendingIdleQuery = false
768
+ if (!err) {
769
+ //The sending succeeded
770
+ //There is a valid response but we don't care about the response
771
+ return
772
+ }
773
+ this.log("warning", "Received heartbeat request error", err)
774
+ this.emit("idleRequestError", err, this)
775
+ })
776
+ }
777
+
778
+ /**
779
+ * Returns an available streamId or null if there isn't any available
780
+ * @returns {Number}
781
+ */
782
+ _getStreamId() {
783
+ return this._streamIds.pop()
784
+ }
785
+
786
+ /**
787
+ * Schedules a single timer for the earliest deadline among all in-flight operations.
788
+ * Eliminates per-operation setTimeout overhead.
789
+ * @private
790
+ */
791
+ _scheduleRequestTimeout() {
792
+ if (this._requestTimeoutTimer) {
793
+ clearTimeout(this._requestTimeoutTimer)
794
+ this._requestTimeoutTimer = null
795
+ }
796
+
797
+ let minDeadline = Infinity
798
+ for (const op of this._operations.values()) {
799
+ if (op._deadline && op._deadline < minDeadline) {
800
+ minDeadline = op._deadline
801
+ }
802
+ }
803
+
804
+ if (minDeadline === Infinity) {
805
+ return
806
+ }
807
+
808
+ const delay = Math.max(0, minDeadline - Date.now())
809
+ this._requestTimeoutTimer = setTimeout(
810
+ () => this._onRequestTimeout(),
811
+ delay,
812
+ )
813
+ }
814
+
815
+ /**
816
+ * Handles the shared request timeout: expires timed-out operations and reschedules.
817
+ * @private
818
+ */
819
+ _onRequestTimeout() {
820
+ this._requestTimeoutTimer = null
821
+
822
+ const now = Date.now()
823
+ let nextMinDeadline = Infinity
824
+
825
+ for (const [streamId, op] of this._operations) {
826
+ if (!op._deadline) continue
827
+
828
+ if (op._deadline <= now) {
829
+ // This operation has timed out
830
+ op.checkTimeout(now)
831
+ } else if (op._deadline < nextMinDeadline) {
832
+ nextMinDeadline = op._deadline
833
+ }
834
+ }
835
+
836
+ // Reschedule for the next deadline if any operations remain
837
+ if (nextMinDeadline !== Infinity) {
838
+ const delay = Math.max(0, nextMinDeadline - Date.now())
839
+ this._requestTimeoutTimer = setTimeout(
840
+ () => this._onRequestTimeout(),
841
+ delay,
842
+ )
843
+ }
844
+ }
845
+
846
+ freeStreamId(header) {
847
+ const streamId = header.streamId
848
+
849
+ if (streamId < 0) {
850
+ // Event ids don't have a matching request operation
851
+ return
852
+ }
853
+
854
+ this._operations.delete(streamId)
855
+ this._streamIds.push(streamId)
856
+
857
+ if (
858
+ this.emitDrain &&
859
+ this._streamIds.inUse === 0 &&
860
+ this._pendingWrites.length === 0
861
+ ) {
862
+ this.emit("drain")
863
+ }
864
+
865
+ this._writeNext()
866
+ }
867
+
868
+ _writeNext() {
869
+ if (this._pendingWrites.length === 0) {
870
+ return
871
+ }
872
+ const streamId = this._getStreamId()
873
+ if (streamId === null) {
874
+ // No streamId available
875
+ return
876
+ }
877
+ const self = this
878
+ let operation
879
+ while (
880
+ (operation = this._pendingWrites.shift()) &&
881
+ !operation.canBeWritten()
882
+ ) {
883
+ // Trying to obtain an pending operation that can be written
884
+ }
885
+
886
+ if (!operation) {
887
+ // There isn't a pending operation that can be written
888
+ this._streamIds.push(streamId)
889
+ return
890
+ }
891
+
892
+ // Schedule after current I/O callbacks have been executed
893
+ setImmediate(function writeNextPending() {
894
+ self._write(operation, streamId)
895
+ })
896
+ }
897
+
898
+ /**
899
+ * Returns the number of requests waiting for response
900
+ * @returns {Number}
901
+ */
902
+ getInFlight() {
903
+ return this._streamIds.inUse
904
+ }
905
+
906
+ /**
907
+ * Handles a result and error response
908
+ */
909
+ handleResult(header, err, result) {
910
+ const streamId = header.streamId
911
+ if (streamId < 0) {
912
+ return this.log("verbose", "event received", header)
913
+ }
914
+ const operation = this._operations.get(streamId)
915
+ if (!operation) {
916
+ return this.log(
917
+ "error",
918
+ "The server replied with a wrong streamId #" + streamId,
919
+ )
920
+ }
921
+ this.log(
922
+ "verbose",
923
+ "Received frame #" +
924
+ streamId +
925
+ " from " +
926
+ this.endpointFriendlyName,
927
+ )
928
+ operation.setResult(err, result, header.bodyLength)
929
+ }
930
+
931
+ handleNodeEvent(header, event) {
932
+ switch (event.eventType) {
933
+ case types.protocolEvents.schemaChange:
934
+ this.emit("nodeSchemaChange", event)
935
+ break
936
+ case types.protocolEvents.topologyChange:
937
+ this.emit("nodeTopologyChange", event)
938
+ break
939
+ case types.protocolEvents.statusChange:
940
+ this.emit("nodeStatusChange", event)
941
+ break
942
+ }
943
+ }
944
+
945
+ /**
946
+ * Handles a row response
947
+ */
948
+ handleRow(header, row, meta, rowLength, flags) {
949
+ const streamId = header.streamId
950
+ if (streamId < 0) {
951
+ return this.log("verbose", "Event received", header)
952
+ }
953
+ const operation = this._operations.get(streamId)
954
+ if (!operation) {
955
+ return this.log(
956
+ "error",
957
+ "The server replied with a wrong streamId #" + streamId,
958
+ )
959
+ }
960
+ operation.setResultRow(row, meta, rowLength, flags, header)
961
+ }
962
+
963
+ /**
964
+ * Closes the socket (if not already closed) and cancels all in-flight requests.
965
+ * Multiple calls to this method have no additional side-effects.
966
+ * @param {Function} [callback]
967
+ */
968
+ close(callback) {
969
+ callback = callback || utils.noop
970
+
971
+ if (!this.connected && !this.isSocketOpen) {
972
+ return callback()
973
+ }
974
+
975
+ this.connected = false
976
+ // Drain is never going to be emitted, once it is set to closed
977
+ this.removeAllListeners("drain")
978
+ this.clearAndInvokePending()
979
+
980
+ if (!this.isSocketOpen) {
981
+ return callback()
982
+ }
983
+
984
+ // Set the socket as closed now (before socket.end() is called) to avoid being invoked more than once
985
+ this.isSocketOpen = false
986
+ this.log(
987
+ "verbose",
988
+ `Closing connection to ${this.endpointFriendlyName}`,
989
+ )
990
+ const self = this
991
+
992
+ // If server doesn't acknowledge the half-close within connection timeout, destroy the socket.
993
+ const endTimeout = setTimeout(() => {
994
+ this.log(
995
+ "info",
996
+ `${this.endpointFriendlyName} did not respond to connection close within ` +
997
+ `${this.options.socketOptions.connectTimeout}ms, destroying connection`,
998
+ )
999
+ this.netClient.destroy()
1000
+ }, this.options.socketOptions.connectTimeout)
1001
+
1002
+ this.netClient.once("close", function (hadError) {
1003
+ clearTimeout(endTimeout)
1004
+ if (hadError) {
1005
+ self.log("info", "The socket closed with a transmission error")
1006
+ }
1007
+ setImmediate(callback)
1008
+ })
1009
+
1010
+ // At this point, the error event can be triggered because:
1011
+ // - It's connected and writes haven't completed yet
1012
+ // - The server abruptly closed its end of the connection (ECONNRESET) as a result of protocol error / auth error
1013
+ // We need to remove any listeners and make sure we callback are pending writes
1014
+ this.netClient.removeAllListeners("error")
1015
+ this.netClient.on("error", (err) => this.clearAndInvokePending(err))
1016
+
1017
+ // Half-close the socket, it will result in 'close' event being fired
1018
+ this.netClient.end()
1019
+ }
1020
+
1021
+ /**
1022
+ * Gets the local IP address to which this connection socket is bound to.
1023
+ * @returns {String|undefined}
1024
+ */
1025
+ getLocalAddress() {
1026
+ if (!this.netClient) {
1027
+ return undefined
1028
+ }
1029
+
1030
+ return this.netClient.localAddress
1031
+ }
1032
+ }
1033
+
1034
+ export default Connection