Prisma binding unable to connect to prisma server. request to http://localhost:4466/ failed, reason: connect ECONNREFUSED 127.0.0.1:4466 - node.js

I am running two separate docker services. One for my GraphQL server and the other one is a prisma service connecting to a local Postgres database. I am able to run prisma deploy and test it out directly in http://localhost:4466. But When I try to query using my app’s GraphQL server in http://localhost:8080, it gives the following response.
{
"data": null,
"errors": [
{
"message": "request to http://localhost:4466/ failed, reason: connect ECONNREFUSED 127.0.0.1:4466",
"locations": [
{
"line": 2,
"column": 3
}
],
"path": [
"feed"
]
}
]
}
This is the stack trace.
graphql-server_1 | [Network error]: FetchError: request to http://localhost:4466/ failed, reason: connect ECONNREFUSED 127.0.0.1:4466
graphql-server_1 | Error: request to http://localhost:4466/ failed, reason: connect ECONNREFUSED 127.0.0.1:4466
graphql-server_1 | at new CombinedError (/usr/src/app/node_modules/graphql-binding/node_modules/graphql-tools/dist/stitching/errors.js:83:28)
graphql-server_1 | at Object.checkResultAndHandleErrors (/usr/src/app/node_modules/graphql-binding/node_modules/graphql-tools/dist/stitching/errors.js:101:15)
graphql-server_1 | at CheckResultAndHandleErrors.transformResult (/usr/src/app/node_modules/graphql-binding/node_modules/graphql-tools/dist/transforms/CheckResultAndHandleErrors.js:10:25)
graphql-server_1 | at /usr/src/app/node_modules/graphql-binding/node_modules/graphql-tools/dist/transforms/transforms.js:19:54
graphql-server_1 | at Array.reduce (<anonymous>)
graphql-server_1 | at applyResultTransforms (/usr/src/app/node_modules/graphql-binding/node_modules/graphql-tools/dist/transforms/transforms.js:18:23)
graphql-server_1 | at /usr/src/app/node_modules/graphql-binding/node_modules/graphql-tools/dist/stitching/delegateToSchema.js:82:50
graphql-server_1 | at step (/usr/src/app/node_modules/graphql-binding/node_modules/graphql-tools/dist/stitching/delegateToSchema.js:32:23)
graphql-server_1 | at Object.next (/usr/src/app/node_modules/graphql-binding/node_modules/graphql-tools/dist/stitching/delegateToSchema.js:13:53)
graphql-server_1 | at fulfilled (/usr/src/app/node_modules/graphql-binding/node_modules/graphql-tools/dist/stitching/delegateToSchema.js:4:58)
This is how I created the binding
const server = new GraphQLServer({
typeDefs: './src/schema.graphql',
resolvers,
context: req => ({
...req,
db: new Prisma({
typeDefs: './src/generated/prisma.graphql',
endpoint: 'http://localhost:4466',
secret: 'my-secret',
debug: true,
})
})
});
I am not sure as to what is the problem.
Full Code can be found here: https://github.com/dhanushuUzumaki/Journal/tree/feature/setup

Got Help from prisma forum to solve this.
Using localhost within a container points to the container itself and not the host on which the containers are running. So in order to connect to the Prisma instance, you have to use the internal service name which resolves to the respective Prisma container.
...
db: new Prisma({
typeDefs: './src/generated/prisma.graphql',
endpoint: 'http://prisma:4466',
secret: 'my-secret',
debug: true,
})
...
Prisma Forum - ECONNREFUSED - Unable to connect to prisma service through binding

This happened to me when using Docker Toolbox on windows, the endpoint had to be changed from using localhost to the VirtualBox default ip within prisma.yml:
endpoint: http://192.168.99.100:4466

Related

Getting MongoServerSelectionError in localhost

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

Node AWS Lambda fetch request failing

I am using node-fetch to perform a request to an API (hosted on AWS Lambda/API Gateway with Serverless Framework) from a lambda. The lambda is failing with the below invocation error:
{
"errorType": "FetchError",
"errorMessage": "request to https://[API].us-east-2.amazonaws.com/[ENDPOINT] failed, reason: connect ETIMEDOUT [IP]:443",
"code": "ETIMEDOUT",
"message": "request to https://[API].us-east-2.amazonaws.com/[ENDPOINT] failed, reason: connect ETIMEDOUT [IP]:443",
"type": "system",
"errno": "ETIMEDOUT",
"stack": [
"FetchError: request to https://[API].us-east-2.amazonaws.com/[ENDPOINT] failed, reason: connect ETIMEDOUT [IP]:443",
" at ClientRequest.<anonymous> (/var/task/node_modules/node-fetch/lib/index.js:1461:11)",
" at ClientRequest.emit (events.js:315:20)",
" at TLSSocket.socketErrorListener (_http_client.js:426:9)",
" at TLSSocket.emit (events.js:315:20)",
" at emitErrorNT (internal/streams/destroy.js:92:8)",
" at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)",
" at processTicksAndRejections (internal/process/task_queues.js:84:21)"
]
}
Here is the lambda in question with extraneous code removed:
"use strict";
import { PrismaClient } from "#prisma/client";
import fetch from "node-fetch";
const prisma = new PrismaClient();
module.exports.handler = async (event, context, callback) => {
const users = await prisma.user.findMany();
for (const user of users) {
await fetch(...); // this is where the error occurs
}
};
The code works fine locally (the code in the lambda itself as well as manaully making the request). Because of that, I thought this might be fixed by setting up a NAT for the lambda/configuring the VPC to have external internet access, though I'm not sure how to do that with Serverless Framework if that is indeed the issue. The lambda attempting to perform the fetch request is in the same VPC as the API. Any help or ideas is greatly appreciated!
I solved this by adding a VPC endpoint for the lambda function. I believe an alternative solution (though possibly more expensive) is to set up a NAT gateway for the Lambda.

Connecting to an Azure Redis Cluster using node.js ioredis not working

I've been trying to connect to a Redis three node cluster in Azure using ioredis.
When I connect using the Redis.Cluster constructor:
new Redis.Cluster(['host.redis.cache.windows.net', 6380], {
scaleReads: 'all',
slotsRefreshTimeout: 2000,
redisOptions: {
password: 'some-secret',
tls: true as any
},
});
The error I get is:
2020-06-04T13:05:41.787Z ioredis:cluster getting slot cache from 127.0.0.1:6380
2020-06-04T13:05:41.788Z ioredis:redis status[127.0.0.1:6380 (ioredisClusterRefresher)]: [empty] -> wait
2020-06-04T13:05:41.788Z ioredis:redis status[127.0.0.1:6380 (ioredisClusterRefresher)]: wait -> connecting
2020-06-04T13:05:41.788Z ioredis:redis queue command[127.0.0.1:6380 (ioredisClusterRefresher)]: 0 -> cluster([ 'slots' ])
2020-06-04T13:05:41.790Z ioredis:connection error: Error: connect ECONNREFUSED 127.0.0.1:6380
2020-06-04T13:05:41.791Z ioredis:redis status[127.0.0.1:6380 (ioredisClusterRefresher)]: connecting -> close
2020-06-04T13:05:41.791Z ioredis:connection skip reconnecting because `retryStrategy` is not a function
2020-06-04T13:05:41.791Z ioredis:redis status[127.0.0.1:6380 (ioredisClusterRefresher)]: close -> end
2020-06-04T13:05:41.792Z [auth-middleware] Redis error { ClusterAllFailedError: Failed to refresh slots cache.
at tryNode (/app/node_modules/ioredis/built/cluster/index.js:359:31)
at /app/node_modules/ioredis/built/cluster/index.js:376:21
at duplicatedConnection.cluster.utils_2.timeout (/app/node_modules/ioredis/built/cluster/index.js:624:24)
at run (/app/node_modules/ioredis/built/utils/index.js:156:22)
at tryCatcher (/app/node_modules/standard-as-callback/built/utils.js:11:23)
at promise.then (/app/node_modules/standard-as-callback/built/index.js:30:51)
at process._tickCallback (internal/process/next_tick.js:68:7)
lastNodeError:
Error: Connection is closed.
at close (/app/node_modules/ioredis/built/redis/event_handler.js:179:25)
at TLSSocket.<anonymous> (/app/node_modules/ioredis/built/redis/event_handler.js:150:20)
at Object.onceWrapper (events.js:277:13)
at TLSSocket.emit (events.js:194:15)
at _handle.close (net.js:600:12)
at TCP.done (_tls_wrap.js:388:7) }
When I connect using a non-cluster Redis connection:
new Redis(6380, 'host.redis.cache.windows.net', { password: 'some-secret' });
The error I get is:
020-06-04T15:04:08.609Z ioredis:redis status[10.211.x.x:6380]: connecting -> connect
2020-06-04T15:04:08.614Z ioredis:redis write command[10.211.x.x:6380]: 0 -> auth([ 'some-secret' ])
2020-06-04T15:04:08.616Z ioredis:redis write command[10.211.x.x:6380]: 0 -> info([])
2020-06-04T15:05:16.114Z ioredis:connection error: Error: read ECONNRESET
2020-06-04T15:05:16.115Z [auth-middleware] Redis error { Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27) errno: 'ECONNRESET', code: 'ECONNRESET', syscall: 'read' }
As you can see it is using TLS on port 6380. Azure provides me with one host+port combination and two different access-keys (primary/seconday) - which I find weird, which access-key should I use? Also I'm not sure if I should be connecting in Cluster mode, but I'd prefer to to gain the benefits of clustering. When I do it appears it tries to find the slots at 127.0.0.1:6380 which is probably not correct.
In Azure's quickstart they connect using node_redis with:
var redis = require("redis");
// Add your cache name and access key.
var client = redis.createClient(6380, process.env.REDISCACHEHOSTNAME,
{auth_pass: process.env.REDISCACHEKEY, tls: {servername: process.env.REDISCACHEHOSTNAME}});
I was hoping someone here would have come across the same issue and solved it.
Thanks!
Okay I've managed to connect to Azure Redis Cluster using a non-tls connection:
new Redis.Cluster(['host.redis.cache.windows.net', 3679], {
scaleReads: 'all',
slotsRefreshTimeout: 2000,
redisOptions: {
password: 'some-secret',
},
})
For some reason connecting to 6380 with TLS enabled does not work.

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