Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bun throws error using the cassandra-driver #4033

Open
notKimu opened this issue Aug 7, 2023 · 20 comments
Open

Bun throws error using the cassandra-driver #4033

notKimu opened this issue Aug 7, 2023 · 20 comments
Labels
bug Something isn't working node.js Compatibility with Node.js APIs

Comments

@notKimu
Copy link

notKimu commented Aug 7, 2023

What version of Bun is running?

0.7.3

What platform is your computer?

Linux 5.4.0-105-generic x86_64 x86_64

What steps can reproduce the bug?

Trying to connect to the cassandra database, it this case It's a ScyllaDB one.

import { Client as ScyllaClient } from "cassandra-driver";
//...
const scyllaClient = new ScyllaClient({
    contactPoints: ['127.0.0.1'],
    localDataCenter: 'datacenter1',
    keyspace: 'my_keyspace',
});

try {
    await scyllaClient.connect();
    logInfo("Connected to ScyllaDB :O")
} catch (error) {
    logError("Error connecting to ScyllaDB >>> ");
    console.log(error);
}

What is the expected behavior?

The application gets connected to the database.

Using node:

[INFO] >>> Connected to ScyllaDB :O

What do you see instead?

A big scary error gets printed and the application can't find any hosts:

[ERROR] >>> Error connecting to ScyllaDB >>> 
{
  stack: "Error: \n    at <anonymous> (/home/kimu/Bots/kiru/node_modules/.pnpm/cassandra-driver@4.6.4/node_modules/cassandra-driver/lib/errors.js:32:17)\n    at <anonymous> (/home/kimu/Bots/kiru/node_modules/.pnpm/cassandra-driver@4.6.4/node_modules/cassandra-driver/lib/errors.js:49:4)\n    at <anonymous> (/home/kimu/Bots/kiru/node_modules/.pnpm/cassandra-driver@4.6.4/node_modules/cassandra-driver/lib/control-connection.js:309:10)\n    at asyncFunctionResume (native)\n    at promiseReactionJobWithoutPromiseUnwrapAsyncContext (native)\n    at promiseReactionJob (native)",
  name: "NoHostAvailableError",
  info: "Represents an error when a query cannot be performed because no host is available or could be reached by the driver.",
  message: "All host(s) tried for query failed. First host tried, 127.0.0.1:9042: Error: Failed to connect. See innerErrors.",
  innerErrors: {
    "127.0.0.1:9042": 1 | (function (){"use strict";const{Duplex}=@getInternalField(@internalModuleRegistry,34)||@createInternalModuleById(34),EventEmitter=@getInternalField(@internalModuleRegistry,15)||@createInternalModuleById(15),IPv4Reg=new RegExp("^((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$"),IPv6Reg=new RegExp("^((?:(?:[0-9a-fA-F]{1,4}):){7}(?:(?:[0-9a-fA-F]{1,4})|:)|(?:(?:[0-9a-fA-F]{1,4}):){6}(?:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|:(?:[0-9a-fA-F]{1,4})|:)|(?:(?:[0-9a-fA-F]{1,4}):){5}(?::((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,2}|:)|(?:(?:[0-9a-fA-F]{1,4}):){4}(?:(:(?:[0-9a-fA-F]{1,4})){0,1}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,3}|:)|(?:(?:[0-9a-fA-F]{1,4}):){3}(?:(:(?:[0-9a-fA-F]{1,4})){0,2}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,4}|:)|(?:(?:[0-9a-fA-F]{1,4}):){2}(?:(:(?:[0-9a-fA-F]{1,4})){0,3}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,5}|:)|(?:(?:[0-9a-fA-F]{1,4}):){1}(?:(:(?:[0-9a-fA-F]{1,4})){0,4}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(:(?:[0-9a-fA-F]{1,4})){1,6}|:)|(?::((?::(?:[0-9a-fA-F]{1,4})){0,5}:((?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])[.]){3}(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])|(?::(?:[0-9a-fA-F]{1,4})){1,7}|:)))(%[0-9a-zA-Z-.:]{1,})?$");function isIPv4(s){return IPv4Reg.test(s)}function isIPv6(s){return IPv6Reg.test(s)}function isIP(s){if(isIPv4(s))return 4;if(isIPv6(s))return 6;return 0}const{connect:bunConnect}=Bun;var{setTimeout}=globalThis;const bunTlsSymbol=Symbol.for("::buntls::"),bunSocketServerHandlers=Symbol.for("::bunsocket_serverhandlers::"),bunSocketServerConnections=Symbol.for("::bunnetserverconnections::"),bunSocketServerOptions=Symbol.for("::bunnetserveroptions::"),bunSocketInternal=Symbol.for("::bunnetsocketinternal::"),bunTLSConnectOptions=Symbol.for("::buntlsconnectoptions::");var SocketClass;const Socket=function(InternalSocket){return SocketClass=InternalSocket,Object.defineProperty(SocketClass.prototype,Symbol.toStringTag,{value:"Socket",enumerable:!1}),Object.defineProperty(function Socket(options){return new InternalSocket(options)},Symbol.hasInstance,{value(instance){return instance instanceof InternalSocket}})}(class Socket2 extends Duplex{static#Handlers={close:Socket2.#Close,connectError(socket,error){socket.data.emit("error",error)},data({data:self},buffer){self.bytesRead+=buffer.length;const queue=self.#readQueue;if(queue.isEmpty()){if(self.push(buffer))return}queue.push(buffer)},drain:Socket2.#Drain,end:Socket2.#Close,error(socket,error){const self=socket.data,callback=self.#writeCallback;if(callback)self.#writeCallback=null,callback(error);self.emit("error",error)},open(socket){const self=socket.data;socket.timeout(self.timeout),socket.ref(),self[bunSocketInternal]=socket,self.connecting=!1;const options=self[bunTLSConnectOptions];if(options){const{session}=options;if(session)self.setSession(session)}if(!self.#upgraded)self.emit("connect",self);Socket2.#Drain(socket)},handshake(socket,success,verifyError){const{data:self}=socket;self._securePending=!1,self.secureConnecting=!1,self._secureEstablished=!!success,self.emit("secure",self);const{checkServerIdentity}=self[bunTLSConnectOptions];if(!verifyError&&typeof checkServerIdentity==="function"&&self.servername){const cert=self.getPeerCertificate(!0);verifyError=checkServerIdentity(self.servername,cert)}if(self._requestCert||self._rejectUnauthorized){if(verifyError){if(self.authorized=!1,self.authorizationError=verifyError.code||verifyError.message,self._rejectUnauthorized){self.destroy(verifyError);return}}}else self.authorized=!0;self.emit("secureConnect",verifyError)},timeout(socket){const self=socket.data;self.emit("timeout",self)},binaryType:"buffer"};static#Close(socket){const self=socket.data;if(self.#closed)return;self.#closed=!0,self[bunSocketInternal]=null;const queue=self.#readQueue;if(queue.isEmpty()){if(self.push(null))return}queue.push(null)}static#Drain(socket){const self=socket.data,callback=self.#writeCallback;if(callback){const chunk=self.#writeChunk,written=socket.write(chunk);if(self.bytesWritten+=written,written<chunk.length)self.#writeChunk=chunk.slice(written);else self.#writeCallback=null,self.#writeChunk=null,callback(null)}}static[bunSocketServerHandlers]={data:Socket2.#Handlers.data,close(socket){Socket2.#Handlers.close(socket),this.data[bunSocketServerConnections]--},end(socket){Socket2.#Handlers.end(socket),this.data[bunSocketServerConnections]--},open(socket){const self=this.data,options=self[bunSocketServerOptions],{pauseOnConnect,connectionListener,InternalSocketClass,requestCert,rejectUnauthorized}=options,_socket=new InternalSocketClass({});if(_socket.isServer=!0,_socket._requestCert=requestCert,_socket._rejectUnauthorized=rejectUnauthorized,_socket.#attach(this.localPort,socket),self.maxConnections&&self[bunSocketServerConnections]>=self.maxConnections){const data={localAddress:_socket.localAddress,localPort:_socket.localPort,localFamily:_socket.localFamily,remoteAddress:_socket.remoteAddress,remotePort:_socket.remotePort,remoteFamily:_socket.remoteFamily||"IPv4"};socket.end(),self.emit("drop",data);return}if(!pauseOnConnect)_socket.resume();if(self[bunSocketServerConnections]++,typeof connectionListener=="function")if(InternalSocketClass.name==="TLSSocket")self.once("secureConnection",()=>connectionListener(_socket));else connectionListener(_socket);self.emit("connection",_socket)},handshake(socket,success,verifyError){const{data:self}=socket;if(self.emit("secure",self),self._securePending=!1,self.secureConnecting=!1,self._secureEstablished=!!success,self._requestCert||self._rejectUnauthorized){if(verifyError){if(self.authorized=!1,self.authorizationError=verifyError.code||verifyError.message,self._rejectUnauthorized){self.destroy(verifyError);return}}}else self.authorized=!0;self.emit("secureConnection",verifyError)},error(socket,error){Socket2.#Handlers.error(socket,error),this.data.emit("error",error)},timeout:Socket2.#Handlers.timeout,connectError:Socket2.#Handlers.connectError,drain:Socket2.#Handlers.drain,binaryType:"buffer"};bytesRead=0;bytesWritten=0;#closed=!1;connecting=!1;localAddress="127.0.0.1";#readQueue=@createFIFO();remotePort;[bunSocketInternal]=null;[bunTLSConnectOptions]=null;timeout=0;#writeCallback;#writeChunk;#pendingRead;isServer=!1;_handle;_parent;_parentWrap;#socket;#upgraded;constructor(options){const{socket,signal,write,read,allowHalfOpen=!1,...opts}=options||{};super({...opts,allowHalfOpen,readable:!0,writable:!0});if(this._handle=this,this._parent=this,this._parentWrap=this,this.#pendingRead=void 0,this.#upgraded=!1,socket instanceof Socket2)this.#socket=socket;signal?.once("abort",()=>this.destroy()),this.once("connect",()=>this.emit("ready"))}address(){return{address:this.localAddress,family:this.localFamily,port:this.localPort}}get bufferSize(){return this.writableLength}#attach(port,socket){if(this.remotePort=port,socket.data=this,socket.timeout(this.timeout),socket.ref(),this[bunSocketInternal]=socket,this.connecting=!1,!this.#upgraded)this.emit("connect",this);Socket2.#Drain(socket)}connect(port,host,connectListener){var path,connection=this.#socket,_checkServerIdentity=void 0;if(typeof port==="string"){if(path=port,port=void 0,typeof host==="function")connectListener=host,host=void 0}else if(typeof host=="function"){if(typeof port==="string")path=port,port=void 0;connectListener=host,host=void 0}if(typeof port=="object"){var{port,host,path,socket,localAddress,localPort,family,hints,lookup,noDelay,keepAlive,keepAliveInitialDelay,requestCert,rejectUnauthorized,pauseOnConnect,servername,checkServerIdentity,session}=port;if(_checkServerIdentity=checkServerIdentity,this.servername=servername,socket)connection=socket}if(!pauseOnConnect)this.resume();this.connecting=!0,this.remotePort=port;const bunTLS=this[bunTlsSymbol];var tls=void 0;if(typeof bunTLS==="function"){if(tls=bunTLS.call(this,port,host,!0),this._requestCert=!0,this._rejectUnauthorized=rejectUnauthorized,tls){if(tls.rejectUnauthorized=rejectUnauthorized,tls.requestCert=!0,tls.session=session||tls.session,this.servername=tls.servername,tls.checkServerIdentity=_checkServerIdentity||tls.checkServerIdentity,this[bunTLSConnectOptions]=tls,!connection&&tls.socket)connection=tls.socket}if(connection){if(typeof connection!=="object"||!(connection instanceof Socket2)||typeof connection[bunTlsSymbol]==="function")@throwTypeError("socket must be an instance of net.Socket")}if(this.authorized=!1,this.secureConnecting=!0,this._secureEstablished=!1,this._securePending=!0,connectListener)this.on("secureConnect",connectListener)}else if(connectListener)this.on("connect",connectListener);if(connection){const socket2=connection[bunSocketInternal];if(socket2){this.connecting=!0,this.#upgraded=!0;const result=socket2.upgradeTLS({data:this,tls,socket:Socket2.#Handlers});if(result){const[raw,tls2]=result;connection[bunSocketInternal]=raw,raw.timeout(raw.timeout),raw.connecting=!1,this[bunSocketInternal]=tls2}else throw this[bunSocketInternal]=null,new Error("Invalid socket")}else connection.once("connect",()=>{const socket3=connection[bunSocketInternal];if(!socket3)return;this.connecting=!0,this.#upgraded=!0;const result=socket3.upgradeTLS({data:this,tls,socket:Socket2.#Handlers});if(result){const[raw,tls2]=result;connection[bunSocketInternal]=raw,raw.timeout(raw.timeout),raw.connecting=!1,this[bunSocketInternal]=tls2}else throw this[bunSocketInternal]=null,new Error("Invalid socket")})}else if(path)bunConnect({data:this,unix:path,socket:Socket2.#Handlers,tls}).catch((error)=>{this.emit("error",error)});else bunConnect({data:this,hostname:host||"localhost",port,socket:Socket2.#Handlers,tls}).catch((error)=>{this.emit("error",error)});return this}_destroy(err,callback){this[bunSocketInternal]?.end(),callback(err)}_final(callback){this[bunSocketInternal]?.end(),callback()}get localAddress(){return"127.0.0.1"}get localFamily(){return"IPv4"}get localPort(){return this[bunSocketInternal]?.localPort}get pending(){return this.connecting}_read(size){const queue=this.#readQueue;let chunk;while(chunk=queue.peek()){if(!this.push(chunk))return;queue.shift()}}get readyState(){if(this.connecting)return"opening";if(this.readable)return this.writable?"open":"readOnly";else return this.writable?"writeOnly":"closed"}ref(){this[bunSocketInternal]?.ref()}get remoteAddress(){return this[bunSocketInternal]?.remoteAddress}get remoteFamily(){return"IPv4"}resetAndDestroy(){this[bunSocketInternal]?.end()}setKeepAlive(enable=!1,initialDelay=0){return this}setNoDelay(noDelay=!0){return this}setTimeout(timeout,callback){if(this[bunSocketInternal]?.timeout(timeout),this.timeout=timeout,callback)this.once("timeout",callback);return this}unref(){this[bunSocketInternal]?.unref()}_write(chunk,encoding,callback){if(typeof chunk=="string"&&encoding!=="ascii")chunk=Buffer.from(chunk,encoding);var written=this[bunSocketInternal]?.write(chunk);if(written==chunk.length)callback();else if(this.#writeCallback)callback(new Error("overlapping _write()"));else{if(written>0)if(typeof chunk=="string")chunk=chunk.slice(written);else chunk=chunk.subarray(written);this.#writeCallback=callback,this.#writeChunk=chunk}}});function createConnection(port,host,connectListener){if(typeof port==="object")return new Socket(port).connect(port,host,connectListener);return new Socket().connect(port,host,connectListener)}const connect=createConnection;class Server extends EventEmitter{#server;#listening=!1;[bunSocketServerConnections]=0;[bunSocketServerOptions];maxConnections=0;constructor(options,connectionListener){super();if(typeof options==="function")connectionListener=options,options={};else if(options==null||typeof options==="object")options={...options};else throw new Error("bun-net-polyfill: invalid arguments");const{maxConnections}=options;this.maxConnections=Number.isSafeInteger(maxConnections)&&maxConnections>0?maxConnections:0,options.connectionListener=connectionListener,this[bunSocketServerOptions]=options}ref(){return this.#server?.ref(),this}unref(){return this.#server?.unref(),this}close(callback){if(this.#server){if(this.#server.stop(!0),this.#server=null,this.#listening=!1,this[bunSocketServerConnections]=0,this.emit("close"),typeof callback==="function")callback();return this}if(typeof callback==="function"){const error=new Error("Server is not running");error.code="ERR_SERVER_NOT_RUNNING",callback(error)}return this}address(){const server=this.#server;if(server){const unix=server.unix;if(unix)return unix;let address=server.hostname;const type=isIP(address),port=server.port;if(typeof port==="number")return{port,address,family:type?`IPv${type}`:void 0};if(type)return{address,family:type?`IPv${type}`:void 0};return address}return null}getConnections(callback){if(typeof callback==="function")callback(null,this.#server?this[bunSocketServerConnections]:0);return this}listen(port,hostname,onListen){let backlog,path,exclusive=!1;if(typeof port==="string"){if(Number.isSafeInteger(hostname)){if(hostname>0)backlog=hostname}else if(typeof hostname==="function")onListen=hostname;path=port,hostname=void 0,port=void 0}else{if(typeof hostname==="function")onListen=hostname,hostname=void 0;if(typeof port==="function")onListen=port,port=0;else if(typeof port==="object"){const options=port;options.signal?.addEventListener("abort",()=>this.close()),hostname=options.host,exclusive=options.exclusive===!0;const path2=options.path;if(port=options.port,!Number.isSafeInteger(port)||port<0)if(path2)hostname=path2,port=void 0;else{let message='The argument \'options\' must have the property "port" or "path"';try{message=`${message}. Received ${JSON.stringify(options)}`}catch{}const error=@makeTypeError(message);throw error.code="ERR_INVALID_ARG_VALUE",error}else if(!Number.isSafeInteger(port)||port<0)port=0;if(typeof port.callback==="function")onListen=port?.callback}else if(!Number.isSafeInteger(port)||port<0)port=0;hostname=hostname||"::"}try{var tls=void 0,TLSSocketClass=void 0;const bunTLS=this[bunTlsSymbol],options=this[bunSocketServerOptions];if(typeof bunTLS==="function")[tls,TLSSocketClass]=bunTLS.call(this,port,hostname,!1),options.servername=tls.serverName,options.InternalSocketClass=TLSSocketClass;else options.InternalSocketClass=SocketClass;this.#server=Bun.listen(path?{exclusive,unix:path,tls,socket:SocketClass[bunSocketServerHandlers]}:{exclusive,port,hostname,tls,socket:SocketClass[bunSocketServerHandlers]}),this.#server.data=this,this.#listening=!0,setTimeout(emitListeningNextTick,1,this,onListen)}catch(err){this.#listening=!1,setTimeout(emitErrorNextTick,1,this,err)}return this}}function emitErrorNextTick(self,error){self.emit("error",error)}function emitListeningNextTick(self,onListen){if(typeof onListen==="function")try{onListen()}catch(err){self.emit("error",err)}self.emit("listening")}function createServer(options,connectionListener){return new Server(options,connectionListener)}return{createServer,Server,createConnection,connect,isIP,isIPv4,isIPv6,Socket,[Symbol.for("::bunternal::")]:SocketClass}})

# A lot of empty  lines

error: Failed to connect
      at connect (node:net:1:15224)
      at open (/home/kimu/Bots/kiru/node_modules/.pnpm/cassandra-driver@4.6.4/node_modules/cassandra-driver/lib/connection.js:176:6)
      at fn (node:util:1:18618)
      at /home/kimu/Bots/kiru/node_modules/.pnpm/cassandra-driver@4.6.4/node_modules/cassandra-driver/lib/control-connection.js:342:12
      at _createConnection (/home/kimu/Bots/kiru/node_modules/.pnpm/cassandra-driver@4.6.4/node_modules/cassandra-driver/lib/control-connection.js:338:26)
      at /home/kimu/Bots/kiru/node_modules/.pnpm/cassandra-driver@4.6.4/node_modules/cassandra-driver/lib/control-connection.js:311:27
      at _borrowFirstConnection (/home/kimu/Bots/kiru/node_modules/.pnpm/cassandra-driver@4.6.4/node_modules/cassandra-driver/lib/control-connection.js:299:31)
      at /home/kimu/Bots/kiru/node_modules/.pnpm/cassandra-driver@4.6.4/node_modules/cassandra-driver/lib/control-connection.js:526:12
      at _initializeConnection (/home/kimu/Bots/kiru/node_modules/.pnpm/cassandra-driver@4.6.4/node_modules/cassandra-driver/lib/control-connection.js:514:32)

  },
  toString: [Function: toString]
}

Additional information

No response

@notKimu notKimu added the bug Something isn't working label Aug 7, 2023
@robobun robobun added the node.js Compatibility with Node.js APIs label Aug 7, 2023
@desplmfao
Copy link

bump

@aMyTimed
Copy link

aMyTimed commented Sep 1, 2023

double bump 👍

@jscul
Copy link

jscul commented Sep 9, 2023

I'm seeing the error:

TypeError: Long.fromInt is not a function. (In 'Long.fromInt(1000)', 'Long.fromInt' is undefined)
      at /home/x/Code/playground/dist/server.js:40386:25
      at /home/x/Code/playground/dist/server.js:18:74
      at /home/x/Code/playground/dist/server.js:40554:15
      at /home/x/Code/playground/dist/server.js:18:74
      at /home/x/Code/playground/dist/server.js:41261:46
      at /home/x/Code/playground/dist/server.js:18:74
      at /home/x/Code/playground/dist/server.js:42217:17
      at /home/x/Code/playground/dist/server.js:18:74
      at /home/x/Code/playground/dist/server.js:57223:22
      at /home/x/Code/playground/dist/server.js:18:74
      at /home/x/Code/playground/dist/server.js:69035:39

It's happening here:

// src/routes.tsx
var import_cassandra_driver2 = __toESM(require_cassandra_driver(), 1);

Do I have my command misconfigured?

bun build src/server.tsx --target=bun --sourcemap=external --outdir=dist/
bun dist/server.js

@Rohit3523
Copy link

{
stack: "Error: \n at (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/errors.js:32:17)\n at (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/errors.js:49:4)\n at (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/datastax/cloud/index.js:214:65)\n at (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/datastax/cloud/index.js:199:91)\n at (native)\n at promiseReactionJob (native)\n at processTicksAndRejections (native)",
name: "NoHostAvailableError",
info: "Represents an error when a query cannot be performed because no host is available or could be reached by the driver.",
message: "There was an error fetching the metadata information",
innerErrors: {
"datastax url": ERR_TLS_CERT_ALTNAME_INVALID: fetch() failed. For more information, pass verbose: true in the second argument to fetch()
path: "datastax url"

},
toString: [Function: toString]
}

@AdamSGit
Copy link

AdamSGit commented Oct 1, 2023

Same issue on mac m2. Scylla, Cassandra driver, Bun, Boum.

@Rohit3523
Copy link

@Jarred-Sumner Can you please check this issue 😅

@Jarred-Sumner
Copy link
Collaborator

@Rohit3523 can you try in the canary build of Bun? bun upgrade --canary

We made a tweak to DNS resolution that may fix this

@Darker-Ink
Copy link

Darker-Ink commented Oct 2, 2023

@Rohit3523 can you try in the canary build of Bun? bun upgrade --canary

We made a tweak to DNS resolution that may fix this

hey I've gone ahead and tried this out on canary and still seem to get the same thing

Here's the logs
# Using Node:

ink@SAMSUNG-S4MCZZA:~/Kastel/Backend$ node test
Connected to ScyllaDB :O
^C

# Using Bun:

ink@SAMSUNG-S4MCZZA:~/Kastel/Backend$ bun run test.js
Error connecting to ScyllaDB >>>
{
  stack: "Error: \n    at DriverError (/home/ink/Kastel/Backend/node_modules/cassandra-driver/lib/errors.js:32:17)\n    at new NoHostAvailableError (/home/ink/Kastel/Backend/node_modules/cassandra-driver/lib/errors.js:49:4)\n    at <anonymous> (/home/ink/Kastel/Backend/node_modules/cassandra-driver/lib/control-connection.js:309:10)\n    at asyncFunctionResume (native)\n    at promiseReactionJobWithoutPromiseUnwrapAsyncContext (native)\n    at promiseReactionJob (native)\n    at processTicksAndRejections (native)",
  name: "NoHostAvailableError",
  info: "Represents an error when a query cannot be performed because no host is available or could be reached by the driver.",
  message: "All host(s) tried for query failed. First host tried, 127.0.0.1:9042: ENOENT: Failed to connect\n    at connect (native)\n    at connect (node:net:225:10)\n    at open (/home/ink/Kastel/Backend/node_modules/cassandra-driver/lib/connection.js:178:21)\n    at fn (node:util:119:14)\n    at <anonymous> (/home/ink/Kastel/Backend/node_modules/cassandra-driver/lib/control-connection.js:342:6)\n    at _createConnection (/home/ink/Kastel/Backend/node_modules/cassandra-driver/lib/control-connection.js:338:29)\n    at <anonymous> (/home/ink/Kastel/Backend/node_modules/cassandra-driver/lib/control-connection.js:311:8)\n    at _borrowFirstConnection (/home/ink/Kastel/Backend/node_modules/cassandra-driver/lib/control-connection.js:299:21)\n    at <anonymous> (/home/ink/Kastel/Backend/node_modules/cassandra-driver/lib/control-connection.js:530:10)\n    at _initializeConnection (/home/ink/Kastel/Backend/node_modules/cassandra-driver/lib/control-connection.js:514:21) {\n  code: 'ENOENT',\n  syscall: 'connect',\n  errno: 0,\n  originalLine: 225,\n  originalColumn: 10\n}. See innerErrors.",
  innerErrors: {
    "127.0.0.1:9042": ENOENT: Failed to connect
 syscall: "connect"

      at node:net:226:10

  },
  toString: [Function: toString]
}
ink@SAMSUNG-S4MCZZA:~/Kastel/Backend$ bun --version
1.0.4

@AdamSGit
Copy link

AdamSGit commented Oct 2, 2023

Same, issue still there with latest canary build.

@Darker-Ink
Copy link

Darker-Ink commented Oct 5, 2023

I tested it on the latest build of canary again and couldn't get it to work still, though if anyone wants a solution I've found one.

The issue is right here (at least when not using ssl though probably will be the same steps below)

      this.netClient.connect(this.port, this.address, function connectCallback() {
        self.log('verbose', `Socket connected to ${self.endpointFriendlyName}`);
        self.bindSocketListeners();
        self.startup(callback);
      });

Changing that code to simply this (Note that code can be found here)

this.netClient.connect({
        host: this.address,
        port: parseInt(this.port, 10)
      }, function connectCallback() {
        self.log('verbose', `Socket connected to ${self.endpointFriendlyName}`);
        self.bindSocketListeners();
        self.startup(callback);
        console.log('connected')
      })

gets it to connect, though I found after that I would run into an issue where the version was invalid and when it went to reconnect it failed to:

log info Connection Trying to use protocol version 0x42
connected
log verbose Connection Sent stream #0 to 127.0.0.1:9042
log verbose Connection Received frame #0 from 127.0.0.1:9042
log info Connection Protocol 0x42 not supported, using 0x4
log verbose Connection Closing connection to 127.0.0.1:9042

After that I just had to define the version of my cassandra / scylladb instance

example code & logs
import { Client as ScyllaClient, types } from "cassandra-driver";

const scyllaClient = new ScyllaClient({
    contactPoints: ['127.0.0.1'],
    localDataCenter: 'datacenter1',
    keyspace: 'keyspace',
    credentials: {
        username: 'usr',
        password: 'pwd'
    },
    protocolOptions: {
        maxVersion: types.protocolVersion.v4
    }
});

try {
    await scyllaClient.connect();
    console.error("Connected to ScyllaDB :O");
} catch (error) {
    console.error("Error connecting to ScyllaDB >>> ");
    console.log(error);
}

image

I've gone ahead and changed that stuff in @kastelll/cassandra-driver (which is a fork of cassandra-driver with a few changes) if you do not want to do it yourself

@Rohit3523
Copy link

Rohit3523 commented Oct 5, 2023

@Jarred-Sumner Getting the following message in 1.0.4 (from website) and 1.0.5 (canary)

NoHostAvailableError: There was an error fetching the metadata information
 info: "Represents an error when a query cannot be performed because no host is available or could be reached by the driver."

But same code is working in node with same file path

Code:

import cassandra_driver from "cassandra-driver";

const cassandra = new cassandra_driver.Client({
    cloud: {
        secureConnectBundle: "./secure-connect-test.zip"
    },
    credentials: {
        username: "username",
        password: "pass"
    }
});

await cassandra.connect();

@Rohit3523
Copy link

@Jarred-Sumner Still facing the same issue in 1.0.20

NoHostAvailableError: All host(s) tried for query failed. First host tried, ip:9042: ENOENT: Failed to connect
    at connect (native)
    at connect (node:net:257:10)
    at open (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/connection.js:48:131)
    at fn (node:util:119:14)
    at <anonymous> (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/control-connection.js:162:26)
    at _createConnection (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/control-connection.js:159:33)
    at <anonymous> (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/control-connection.js:145:52)
    at _borrowFirstConnection (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/control-connection.js:138:38)
    at <anonymous> (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/control-connection.js:240:42)
    at _initializeConnection (/home/ubuntu/Anime/node_modules/cassandra-driver/lib/control-connection.js:236:37) {
  code: 'ENOENT',
  syscall: 'connect',
  errno: 0,
  originalLine: 257,
  originalColumn: 10
}. See innerErrors.
 info: "Represents an error when a query cannot be performed because no host is available or could be reached by the driver."

Please have a look in this comment as they have solved it by changing library code
#4033 (comment)

@Rohit3523
Copy link

Rohit3523 commented Jan 2, 2024

For Datastax Astra Connection File, Bun is not able to verify the certificate file

Code in library: https://github.com/datastax/nodejs-driver/blob/476725efc0e2712b1a001b042890f127bc1eecba/lib/datastax/cloud/index.js#L159C1-L159C1

They are using node https library

Request Object

{
  hostname: "db-uid-datastax.com",
  port: "29080",
  path: "/metadata",
  timeout: 5000,
  ca: [
    Buffer(1345) [ 45, 45, 45, 45, removed by me, ... 832 more ]
  ],
  cert: Buffer(1525) [ 45, 45, 45, 45, removed by me, ... 1012 more ],
  key: Buffer(1675) [ 45, 45, 45, removed by me, ... 1162 more ],
  rejectUnauthorized: true,
}

Error:

UNABLE_TO_VERIFY_LEAF_SIGNATURE: unable to verify the first certificate
 path: "https://db-uid-datastax.com:port/metadata"

Hope both info will help you to fix this issue @Jarred-Sumner, in the mean time i am looking for file solution

I guess something is wrong when converting certificate to buffer

@dolsem
Copy link

dolsem commented Jan 28, 2024

@Darker-Ink's solution worked for me, this clearly looks like a bug in Bun's implementation of the connect function.

@johnnyApplePRNG
Copy link

johnnyApplePRNG commented Mar 8, 2024

Still failing in bun 1.0.30

Failed to connect to ScyllaDB: All host(s) tried for query failed. First host tried, 192.168.0.1:9042: ENOENT: Failed to connect
at connect (native)
at connect (node:net:257:10)
at open (/var/www/js/node_modules/cassandra-driver/lib/connection.js:89:31)
at fn (node:util:119:14)
at (/var/www/js/node_modules/cassandra-driver/lib/control-connection.js:198:26)
at _createConnection (/var/www/js/node_modules/cassandra-driver/lib/control-connection.js:195:33)
at (/var/www/js/node_modules/cassandra-driver/lib/control-connection.js:178:52)
at _borrowFirstConnection (/var/www/js/node_modules/cassandra-driver/lib/control-connection.js:171:38)
at (/var/www/js/node_modules/cassandra-driver/lib/control-connection.js:307:42)
at _initializeConnection (/var/www/js/node_modules/cassandra-driver/lib/control-connection.js:300:37) {
code: 'ENOENT',
syscall: 'connect',
errno: 0,
originalLine: 257,
originalColumn: 10
}. See innerErrors.
126 | console.log('Connected to ScyllaDB successfully!');
127 | return client;
128 |
129 | } catch (error) {
130 | console.error('Failed to connect to ScyllaDB:', error.message);
131 | throw new Error('Unable to connect to ScyllaDB from node ' + live_node_data);
^
error: Unable to connect to ScyllaDB from node [object Object]
at /var/www/js/wss_server.js:131:11
admin@node03:~$ bun --version
1.0.30

@semanticist21
Copy link

Is there any official fix for this?

@rmusaev99
Copy link

For now you can use this patch until they fix the issue:

Add postinstall script to package.json:
"postinstall": "node ./patch-cassandra-driver.js"

add js script "patch-cassandra-driver.js (esm)":

import { promises as fs, constants } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const filePath = join(__dirname, 'node_modules/cassandra-driver/lib/connection.js');

async function patchFile() {
  try {
    // Check if the file exists
    await fs.access(filePath, constants.F_OK);

    // Read the file
    const data = await fs.readFile(filePath, 'utf8');

    // Define the original and replacement strings
    const originalString = `this.netClient.connect(this.port, this.address, function connectCallback() {
        self.log('verbose', \`Socket connected to \${self.endpointFriendlyName}\`);
        self.bindSocketListeners();
        self.startup(callback);
      });`;

    const replacementString = `this.netClient.connect({
        host: this.address,
        port: parseInt(this.port, 10)
      }, function connectCallback() {
        self.log('verbose', \`Socket connected to \${self.endpointFriendlyName}\`);
        self.bindSocketListeners();
        self.startup(callback);
        console.log('connected')
      })`;

    // Replace the string
    const modifiedData = data.replace(originalString, replacementString);

    // Write the file back
    await fs.writeFile(filePath, modifiedData, 'utf8');
    console.log('The connection.js file has been patched successfully.');
  } catch (err) {
    if (err.code === 'ENOENT') {
      console.error('The file connection.js does not exist. The cassandra-driver might not be installed, or the file path has changed.');
    } else {
      console.error('Error:', err);
    }
  }
}

patchFile();

OR (commonjs)":

const fs = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'node_modules/cassandra-driver/lib/connection.js');

// Check if the file exists
fs.exists(filePath, (exists) => {
  if (!exists) {
    return console.error('The file connection.js does not exist. The cassandra-driver might not be installed, or the file path has changed.');
  }

  // Read the file
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      return console.error('Error reading the connection.js file:', err);
    }

    // Define the original and replacement strings
    const originalString = `this.netClient.connect(this.port, this.address, function connectCallback() {
        self.log('verbose', \`Socket connected to \${self.endpointFriendlyName}\`);
        self.bindSocketListeners();
        self.startup(callback);
      });`;

    const replacementString = `this.netClient.connect({
        host: this.address,
        port: parseInt(this.port, 10)
      }, function connectCallback() {
        self.log('verbose', \`Socket connected to \${self.endpointFriendlyName}\`);
        self.bindSocketListeners();
        self.startup(callback);
        console.log('connected')
      })`;

    // Replace the string
    const modifiedData = data.replace(originalString, replacementString);

    // Write the file back
    fs.writeFile(filePath, modifiedData, 'utf8', (writeErr) => {
      if (writeErr) {
        return console.error('Error writing the modified connection.js file:', writeErr);
      }

      console.log('The connection.js file has been patched successfully.');
    });
  });
});

@aMyTimed
Copy link

aMyTimed commented Apr 6, 2024

the temporary fix is change cassandra-driver in package.json to this:

"cassandra-driver": "https://github.com/KastelApp/nodejs-driver.git",

@semanticist21
Copy link

the temporary fix is change cassandra-driver in package.json to this:

"cassandra-driver": "https://github.com/KastelApp/nodejs-driver.git",

It solved connection issue.
Good

@nektro
Copy link
Contributor

nektro commented May 9, 2024

when no host is available the error thrown by bun is near identical to the node one

❯ bun-debug index.js
NoHostAvailableError: All host(s) tried for query failed. First host tried, 127.0.0.1:9042: ENOENT: Failed to connect
    at connect (native)
    at connect (node:net:412:10)
    at open (/Users/meghandenny/src/test/node_modules/cassandra-driver/lib/connection.js:176:28)
    at fn (node:util:217:14)
    at <anonymous> (/Users/meghandenny/src/test/node_modules/cassandra-driver/lib/control-connection.js:342:6)
    at asyncFunctionResume (:1:11)
    at _createConnection (/Users/meghandenny/src/test/node_modules/cassandra-driver/lib/control-connection.js:338:29)
    at <anonymous> (/Users/meghandenny/src/test/node_modules/cassandra-driver/lib/control-connection.js:311:8)
    at asyncFunctionResume (:1:11)
    at _borrowFirstConnection (/Users/meghandenny/src/test/node_modules/cassandra-driver/lib/control-connection.js:299:21) {
  code: 'ENOENT',
  syscall: 'connect',
  errno: 2,
  originalLine: 412,
  originalColumn: 10
}. See innerErrors.
 info: "Represents an error when a query cannot be performed because no host is available or could be reached by the driver."

Bun v1.1.8-debug (macOS arm64)
❯ node index.js 

/Users/meghandenny/src/test/node_modules/cassandra-driver/lib/control-connection.js:307
        throw new errors.NoHostAvailableError(this._triedHosts);
              ^
NoHostAvailableError: All host(s) tried for query failed. First host tried, 127.0.0.1:9042: Error: connect ECONNREFUSED 127.0.0.1:9042
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1606:16) {
  errno: -61,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 9042
}. See innerErrors.
    at ControlConnection._borrowFirstConnection (/Users/meghandenny/src/test/node_modules/cassandra-driver/lib/control-connection.js:307:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async ControlConnection._initializeConnection (/Users/meghandenny/src/test/node_modules/cassandra-driver/lib/control-connection.js:526:7)
    at async ControlConnection.init (/Users/meghandenny/src/test/node_modules/cassandra-driver/lib/control-connection.js:212:5)
    at async Client._connect (/Users/meghandenny/src/test/node_modules/cassandra-driver/lib/client.js:513:5)
    at async file:///Users/meghandenny/src/test/index.js:34:1 {
  info: 'Represents an error when a query cannot be performed because no host is available or could be reached by the driver.',
  innerErrors: {
    '127.0.0.1:9042': Error: connect ECONNREFUSED 127.0.0.1:9042
        at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1606:16) {
      errno: -61,
      code: 'ECONNREFUSED',
      syscall: 'connect',
      address: '127.0.0.1',
      port: 9042
    }
  }
}

Node.js v22.1.0

will have to try this again on a linux machine to test the working case

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working node.js Compatibility with Node.js APIs
Projects
None yet
Development

No branches or pull requests