Getting MongoServerSelectionError in localhost - node.js

I have a node.js application deployed in Azure which connects to Azure CosmosDB (MongoDb database).
To connect to to mongo-db i use this code
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
}
client = new MongoClient(mongoConnectionUri, options)
// #ts-ignore
global._mongoClientPromise = client.connect()
clientPromise = global._mongoClientPromise
this is working fine when deployed in Azure as containerapp, but when i try to run it from localhost
npm run dev -- -- open
When the part to connect to mongo-db comes, I am getting this error,
MongoServerSelectionError: Server selection timed out after 30000 ms
at Timeout._onTimeout (xyz/node_modules/mongodb/lib/sdam/topology.js:293:38)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
reason: TopologyDescription {
type: 'ReplicaSetNoPrimary',
servers: Map(1) {
'my-db.mongo.cosmos.azure.com:10255' => [ServerDescription]
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
setName: 'globaldb',
logicalSessionTimeoutMinutes: undefined
},
code: undefined,
[Symbol(errorLabels)]: Set(0) {}
}
MongoDB connection string:
mongodb://my-db:abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz==#my-db.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=#my-db#
there are no network restrictions
My node version
node --version
v16.17.1
npm version
{
npm: '8.15.0',
node: '16.17.1',
v8: '9.4.146.26-node.22',
uv: '1.43.0',
zlib: '1.2.11',
brotli: '1.0.9',
ares: '1.18.1',
modules: '93',
nghttp2: '1.47.0',
napi: '8',
llhttp: '6.0.9',
openssl: '1.1.1q+quic',
cldr: '41.0',
icu: '71.1',
tz: '2022a',
unicode: '14.0',
ngtcp2: '0.1.0-DEV',
nghttp3: '0.1.0-DEV'
}
This was working from local before , but suddenly it is not working,
From Az cli in my local I am able to retrieve the database details in cosmosdb
az cosmosdb database show --resource-group rgname --name accountname --db-name dbname
Update:
If i try the connection string by installing mongosh
mongosh and the command
mongosh "mongodb://my-db:abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz==#my-db.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=#my-db#"
MongoServerSelectionError: Server selection timed out after 30000 ms
I am getting the same errorMongoServerSelectionError: Server selection timed out after 30000 ms
Can anyone please help?
Update:
Mobile hotspot:
Able to connect with my mobile-hotspot in the same machine (macOS big slur) to the same remote db without any errors.
Tried this will different versions of node.js and mongodb libraries including latest but the same error when connecting with Home wifi. Before recently i had changed the wifi security from wpa to wpa2 personal and ever since this error occurs

Related

Validation Error in running Hyperledger Caliper V0.4.2 with Fabric 2.1

When I have been running the Caliper V0.4.2 for measuring the benchmarks of Fabric 2.1.0 1.4.7, I got the below error
ValidationError: child "version" fails because ["version" must be one of [1.0]]. child "clients" fails because ["clients" is required]. child "channels" fails because ["channels" must be an object]. child "organizations" fails because ["organizations" must be an object]. child "orderers" fails because ["orderers" is required]. child "peers" fails because ["peers" is required]
at Object.exports.process (/home/gow/fabric-benchmarks/caliper-benchmarks/node_modules/#hapi/joi/lib/errors.js:202:19)
at internals.Object._validateWithOptions (/home/gow/fabric-benchmarks/caliper-benchmarks/node_modules/#hapi/joi/lib/types/any/index.js:763:31)
at module.exports.internals.Any.root.validate (/home/gow/fabric-benchmarks/caliper-benchmarks/node_modules/#hapi/joi/lib/index.js:145:23)
at Function._validateTopLevel (/home/gow/fabric-benchmarks/caliper-benchmarks/node_modules/#hyperledger/caliper-fabric/lib/configValidator.js:208:26)
at Function.validateNetwork (/home/gow/fabric-benchmarks/caliper-benchmarks/node_modules/#hyperledger/caliper-fabric/lib/configValidator.js:58:25)
at new FabricConnector (/home/gow/fabric-benchmarks/caliper-benchmarks/node_modules/#hyperledger/caliper-fabric/lib/fabric-connector.js:107:25)
at CaliperEngine.connectorFactory [as adapterFactory] (/home/gow/fabric-benchmarks/caliper-benchmarks/node_modules/#hyperledger/caliper-fabric/lib/connectorFactory.js:26:23)
at CaliperEngine.run (/home/gow/fabric-benchmarks/caliper-benchmarks/node_modules/#hyperledger/caliper-core/lib/manager/caliper-engine.js:93:36)
at Function.handler (/home/gow/fabric-benchmarks/caliper-benchmarks/node_modules/#hyperledger/caliper-cli/lib/launch/lib/launchManager.js:62:43)
at Object.module.exports.handler (/home/gow/fabric-benchmarks/caliper-benchmarks/node_modules/#hyperledger/caliper-cli/lib/launch/launchManagerCommand.js:46:44)
isJoi: true,
name: 'ValidationError',
details:
[ { message: '"version" must be one of [1.0]',
path: [Array],
type: 'any.allowOnly',
context: [Object] },
{ message: '"clients" is required',
path: [Array],
type: 'any.required',
context: [Object] },
{ message: '"channels" must be an object',
path: [Array],
type: 'object.base',
context: [Object] },
{ message: '"organizations" must be an object',
path: [Array],
type: 'object.base',
context: [Object] },
{ message: '"orderers" is required',
path: [Array],
type: 'any.required',
context: [Object] },
{ message: '"peers" is required',
path: [Array],
type: 'any.required',
context: [Object] } ],
_object:
{ name: 'Caliper Benchmarks',
version: '2.1.0',
caliper: { blockchain: 'fabric' },
channels: [ [Object] ],
organizations: [ [Object] ] },
annotate: [Function] }
Command that I run are,
npm init -y
npm install --only=prod #hyperledger/caliper-cli#0.4.0
npx caliper bind --caliper-bind-sut fabric:2.1
./network.sh deployCC -ccn simple -ccp ../../caliper-benchmarks/src/fabric/scenario/simple/node -ccl javascript
npx caliper launch manager --caliper-workspace ./ --caliper-networkconfig networks/fabric/test-network.yaml --caliper-benchconfig benchmarks/scenario/simple/config.yaml --caliper-flow-only-test --caliper-fabric-gateway-enabled
Hyperledger network creation, channel creation and Chaincode deployment all were successful.
How to solve this error?
Looks like you are using the main branch of caliper-benchmarks. I would suggest you https://github.com/hyperledger/caliper-benchmarks/blob/main/networks/fabric/README.md
From what you have posted, you should use the latest available version of caliper which is 0.4.2, not 0.4.0. To do so the command you should issue is
npm install --only=prod #hyperledger/caliper-cli
You should bind to the latest 2.2 sdk (don't bind to 2.1 as fabric doesn't support 2.1). Note this is selecting the version of the sdk used to interact with a fabric network, not the version of the fabric network you are using. 2.2 will work with a fabric 2.2 and later 2.x versions
npx caliper bind --caliper-bind-sut fabric:2.2
Finally it looks like you tried to change the version number in the network configuration file. Don't change the version (it must be 2.0.0) as it refers to the version of the network configuration file and not the version of fabric you want to test
As you look to be using test-network, depending on which branch of fabric-samples you are using defines the version of fabric. The main branch tests the latest version of fabric which should have no problems.

Truffle migrate --network bsc error: header not found

When trying to run truffle migrate --network bsc, truffle usually (not always) manages to deploy the migrations contract, then fails with an error: header not found.
Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({ code: -32000, message: 'header not found' })
at new NodeError (node:internal/errors:363:5)
at Web3ProviderEngine.emit (node:events:354:17)
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:54:14
at afterRequest (D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:148:21)
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:174:21
at D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:232:9
at D:\Contracts\novaria\node_modules\async\internal\once.js:12:16
at replenish (D:\Contracts\novaria\node_modules\async\internal\eachOfLimit.js:61:25)
at D:\Contracts\novaria\node_modules\async\internal\eachOfLimit.js:71:9
at eachLimit (D:\Contracts\novaria\node_modules\async\eachLimit.js:43:36)
at D:\Contracts\novaria\node_modules\async\internal\doLimit.js:9:16
at end (D:\Contracts\novaria\node_modules\web3-provider-engine\index.js:211:5)
at Request._callback (D:\Contracts\novaria\node_modules\web3-provider-engine\subproviders\rpc.js:70:28)
at Request.self.callback (D:\Contracts\novaria\node_modules\request\request.js:185:22)
at Request.emit (node:events:365:28)
at Request.<anonymous> (D:\Contracts\novaria\node_modules\request\request.js:1154:10)
at Request.emit (node:events:365:28)
at IncomingMessage.<anonymous> (D:\Contracts\novaria\node_modules\request\request.js:1076:12)
at Object.onceWrapper (node:events:471:28)
at IncomingMessage.emit (node:events:377:35)
at endReadableNT (node:internal/streams/readable:1312:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)
Here's the config for bsc network:
bsc: {
provider: () => { return new HDWalletProvider(mnemonic, `https://bsc-dataseed2.binance.org/`)},
network_id: 56,
confirmations: 10,
timeoutBlocks: 200,
skipDryRun: true,
},
compilers: {
solc: {
version: "0.8.7", // Fetch exact version from solc-bin (default: truffle's version)
// docker: true, // Use "0.5.1" you've installed locally with docker (default: false)
settings: { // See the solidity docs for advice about optimization and evmVersion
optimizer: {
enabled: true,
runs: 200
},
Deploying to testnet and development works without issue. I have in the past deployed to bsc with truffle (been a while though). I've tried changing RPC urls, and messed around with timeout and confirmations (pretty sure that doesn't make a difference for this error). After searching the internet for solutions, the only answer that seems to have worked for people is to change the RPC, but I haven't had any luck with that. Does anyone have any suggestions?
I had the same problem today. Fixed it by using the Websocket endpoint wss://bsc-ws-node.nariox.org:443 from the smart chain docs https://docs.binance.org/smart-chain/developer/rpc.html

Node.js SSL error: wrong version number: ../deps/openssl/openssl/ssl/record/ssl3_record.c:332

Using Node.js and cross-fetch, I receive an error accessing an HTTPS site (see title and comments below). There is no proxy involved. The code below is a simplified version that reproduces the error. The comments in the code contain the exact error text.
This had been working until something (?) changed, which leads me to believe a server-side change, which I have no access to. However, Tampermonkey JS scripts that do the same requests using GM_xmlhttpRequest still work correctly.
Any debugging suggestions, or why the "wrong version number" is generated?
Edit: looking in the debugger at the call to tlssock.connect(options, tlssock._start); the 'ciphers' option is set to ciphers: "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384:ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA" and the 'port' option is 443. In the TLSSocket member, I didn't see anything that jumped out at me relating to a version number.
const fetch = require('cross-fetch');
const testURL = 'https://api.torn.com/faction/?selections=upgrades&key=xxxxxxxxxx';
fetch(testURL).then(res => {
console.log('[TEST] res: ', res);
}).then(data => {
console.log('[TEST] data: ', data);
}).catch(err => {
console.error("[TEST] error: ", err);
});
/*
Output:
[TEST] error: FetchError: request to https://api.torn.com/faction/?selections=upgrades&key=xxxxxxxxxx failed,
reason: write EPROTO 140735681590144:
error:1408F10B:SSL routines:ssl3_get_record:
wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:332:
at ClientRequest.<anonymous> (/Users/edlau/Documents/Torn-JS/Fac-chat-generic/node_modules/node-fetch/lib/index.js:1461:11)
at ClientRequest.emit (events.js:400:28)
at TLSSocket.socketErrorListener (_http_client.js:475:9)
at TLSSocket.emit (events.js:400:28)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:82:21) {
type: 'system',
errno: 'EPROTO',
code: 'EPROTO'
}*/
Edit 2: I updated node.js to the latest, with the same results, versioning info is as follows:
npm version
{
facchat: '2.0.0',
npm: '8.3.0',
node: '17.3.0',
v8: '9.6.180.15-node.12',
uv: '1.42.0',
zlib: '1.2.11',
brotli: '1.0.9',
ares: '1.18.1',
modules: '102',
nghttp2: '1.45.1',
napi: '8',
llhttp: '6.0.4',
openssl: '3.0.1+quic',
cldr: '40.0',
icu: '70.1',
tz: '2021a3',
unicode: '14.0',
ngtcp2: '0.1.0-DEV',
nghttp3: '0.1.0-DEV'
}
Edit 3: Using CURL (to the same URL):
curl: (35) error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
After playing with this for hours, reducing it to just using curl and various options, none of which worked - it finally did again. With no options. My test code works as well now. So I conclude that it was server side 'maintainance' going on, or being routed to different servers, the server is hosted, near as I can tell, in a cloudflare environment.
So although I can't say for certain what was causing this, I can no longer reproduce it.

Error! MongoNetworkError: failed to connect to server - after connect to another wifi network

I created an entire, working application with backend in Node.js and Mongodb (Mean stack). Everything is fine, but when I connect to another wifi network there is an error. Please help me.
If I have to send more code from the app, write it.
Error! MongoNetworkError: failed to connect to server [eventsdb-shard-00-00-ydx5k.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to eventsdb-shard-00-00-ydx5k.mongodb.net:27017 closed
at TLSSocket.<anonymous>
at Object.onceWrapper (events.js:300:26)
at TLSSocket.emit (events.js:210:5)
at net.js:659:12
at TCP.done (_tls_wrap.js:481:7) {
name: 'MongoNetworkError',
[Symbol(mongoErrorContextSymbol)]: {}
}]
...\App\server\node_modules\mongodb\lib\core\connection\connection.js:372:9 :
function closeHandler(conn) {
return function(hadError) {
if (connectionAccounting) deleteConnection(conn.id);
if (conn.logger.isDebug()) {
conn.logger.debug(`connection ${conn.id} with for [${conn.address}] closed`);
}
if (!hadError) {
conn.emit(
'close',
new MongoNetworkError(`connection ${conn.id} to ${conn.address} closed`), // <------ 372
conn
);
}
};
}
I solved my problem. On the Mongodb website, where I have a database, I entered "Network Access" -> "Add IP Address", I added my new ip address and there was no error.

Trouble Connecting To DynamoDB Locally with ECONNREFUSED

I'm attempting to save form submissions to a DynamoDB table, however, I'm running into issues connecting locally. I'm running DynamoDB locally for now, but I would later like to move it back to a normal DDB instance accessible from Elastic Beanstalk.
I've downloaded and unzipped dynamodb-local into a directory and ran the java -Djava.library.path=./DynamoDBLocal_lib -jar DynamoDBLocal.jar -sharedDb
command, ensuring that I'm in the appropriate directory. When I run the command I get this:
Initializing DynamoDB Local with the following configuration:
Port: 8000
InMemory: false
DbPath: null
SharedDb: true
shouldDelayTransientStatuses: false
CorsParams: *
At this point I attempt to submit a form to my POST endpoint in app.js, but I get this repeating error in the terminal I'm running DynamoDB local in:
Jan 12, 2019 1:24:25 PM com.almworks.sqlite4java.Internal log
WARNING: [sqlite] cannot open DB[1]:
com.almworks.sqlite4java.SQLiteException: [-91] cannot load library: java.lang.UnsatisfiedLinkError: C:\cygwin64\home\Administrator\dynamodb_local_latest\DynamoDBLocal_lib\sqlite4java-win32-x64.dll: Access is denied
Jan 12, 2019 1:24:25 PM com.almworks.sqlite4java.Internal log
SEVERE: [sqlite] SQLiteQueue[shared-local-instance.db]: error running job queue
com.almworks.sqlite4java.SQLiteException: [-91] cannot load library: java.lang.UnsatisfiedLinkError: C:\cygwin64\home\Administrator\dynamodb_local_latest\DynamoDBLocal_lib\sqlite4java-win32-x64.dll: Access is denied
at com.almworks.sqlite4java.SQLite.loadLibrary(SQLite.java:97)
at com.almworks.sqlite4java.SQLiteConnection.open0(SQLiteConnection.java:1441)
at com.almworks.sqlite4java.SQLiteConnection.open(SQLiteConnection.java:282)
at com.almworks.sqlite4java.SQLiteConnection.open(SQLiteConnection.java:293)
at com.almworks.sqlite4java.SQLiteQueue.openConnection(SQLiteQueue.java:464)
at com.almworks.sqlite4java.SQLiteQueue.queueFunction(SQLiteQueue.java:641)
at com.almworks.sqlite4java.SQLiteQueue.runQueue(SQLiteQueue.java:623)
at com.almworks.sqlite4java.SQLiteQueue.access$000(SQLiteQueue.java:77)
at com.almworks.sqlite4java.SQLiteQueue$1.run(SQLiteQueue.java:205)
at java.base/java.lang.Thread.run(Unknown Source)
Caused by: java.lang.UnsatisfiedLinkError: C:\cygwin64\home\Administrator\dynamodb_local_latest\DynamoDBLocal_lib\sqlite4java-win32-x64.dll: Access is denied
at java.base/java.lang.ClassLoader$NativeLibrary.load0(Native Method)
at java.base/java.lang.ClassLoader$NativeLibrary.load(Unknown Source)
at java.base/java.lang.ClassLoader$NativeLibrary.loadLibrary(Unknown Source)
at java.base/java.lang.ClassLoader.loadLibrary0(Unknown Source)
at java.base/java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.base/java.lang.Runtime.load0(Unknown Source)
at java.base/java.lang.System.load(Unknown Source)
at com.almworks.sqlite4java.Internal.tryLoadFromPath(Internal.java:340)
at com.almworks.sqlite4java.Internal.loadLibraryX(Internal.java:117)
at com.almworks.sqlite4java.SQLite.loadLibrary(SQLite.java:95)
... 9 more
In the terminal that I'm running the cluster of Node workers I'm getting the following error output from each worker (8) and then a DDB error:
Failed to create table in DB.
{ Error: connect ECONNREFUSED 127.0.0.1:8000
at Object.exports._errnoException (util.js:1022:11)
at exports._exceptionWithHostPort (util.js:1045:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:14)
message: 'connect ECONNREFUSED 127.0.0.1:8000',
code: 'NetworkingError',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8000,
region: 'us-west-2',
hostname: 'localhost',
retryable: true,
time: 2019-01-12T20:31:00.742Z }
DDB Error: NetworkingError: connect ECONNREFUSED 127.0.0.1:8000
I promise I'm finishing this up. Here's my code for creating the DDB table (I pass const ddb = new AWS.DynamoDB() as the parameter from app.js):
const AWS = require('aws-sdk');
function createDDBTable(ddb, tableName) {
// console.log('ddb:\n',ddb);
const tableParams = {
AttributeDefinitions: [
{
AttributeName: 'email',
AttributeType: 'S'
},
{
AttributeName: 'id',
AttributeType: 'S'
}
],
KeySchema: [
{
AttributeName: 'email',
KeyType: 'HASH'
},
{
AttributeName: 'id',
KeyType: 'RANGE'
}
],
ProvisionedThroughput: {
ReadCapacityUnits: 8,
WriteCapacityUnits: 8
},
TableName: tableName,
StreamSpecification: {
StreamEnabled: false
}
};
ddb.createTable(tableParams, (err, data) => {
if(err) console.error('Failed to create table in DB.\n', err);
else console.log('Success creating table!', data);
})
}
module.exports = createDDBTable;
I'm at a loss for where I'm going wrong. All of my validation and endpoints work, however, when it comes time to create a table my code keeps me stumbling through errors. I also have a feeling I may need to adjust my options.config file a bit, but I'm not sure how to format that. Thanks in advance for any help! I tried to be thorough about my issue, but let me know if I can expand on anything else.
instead of http://localhost:port use your computer IP. it will work.
ex: http://xxx.yy.zz.aaa:port <--your computer IP

Resources