EconnRefused Heroku Trailhead Quick Start: Heroku Connect Change and Redeploy the Application - heroku

working through the salesforce trailhead on Heroku Connect. Everything has worked up until the step Change and Redeploy the Application. After stopping the application and modifying the server.js file, I am unable to connect/update the database records. restored the server.js file, same issue. I am on windows 7, npm --version = 4.6.1, node --version = v8.11.1, git --version = 2.14.2.windows.2. Any idea what might be causing the following error:
{
Error: connect ECONNREFUSED 127.0.0.1:5432
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 5432
}
Thanks!
Here's the commands to set/start the application:
SET DATABASE_URL=`heroku config:get DATABASE_URL`
SET PGSSLMODE=require
npm start
Here's the contents of the server.js file:
var express = require('express');
var bodyParser = require('body-parser');
var pg = require('pg');
var app = express();
app.set('port', process.env.PORT || 5000);
app.use(express.static('public'));
app.use(bodyParser.json());
app.post('/update', function(req, res) {
pg.connect(process.env.DATABASE_URL, function (err, conn, done) {
// watch for any connect issues
if (err) console.log(err);
conn.query(
'UPDATE salesforce.Contact SET Phone = $1, MobilePhone = $1 WHERE LOWER(FirstName) = LOWER($2) AND LOWER(LastName) = LOWER($3) AND
LOWER(Email) = LOWER($4)',
[req.body.phone.trim(), req.body.firstName.trim(),
req.body.lastName.trim(), req.body.email.trim()],
function(err, result) {
if (err != null || result.rowCount == 0) {
conn.query('INSERT INTO salesforce.Contact (Phone,
MobilePhone, FirstName, LastName, Email) VALUES ($1, $2, $3, $4, $5)',
[req.body.phone.trim(), req.body.phone.trim(),
req.body.firstName.trim(), req.body.lastName.trim(),
req.body.email.trim()],
function(err, result) {
done();
if (err) {
res.status(400).json({error: err.message});
}
else {
// this will still cause jquery to display 'Record
updated!'
// eventhough it was inserted
res.json(result);
}
});
}
else {
done();
res.json(result);
}
}
);
});
});
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});

You're attempting to connect to a local database (127.0.0.1) where you need to connect to the Heroku Postgres instance. This is the relevant config from the application code. Make sure that server.js is connecting to DATABASE_URL which Heroku manages on your behalf.

Related

NestJs Websocket, how to test and debug "Socket hang up"?

I have a fairly simple Websocket Server, all I am trying to achieve is to have a socket gateway that would emit events to listening/connected clients based on db status updates.
here is my implementation:
#WebSocketGateway(5010, { transports: ['websocket'], cors: true })
export class SocketGateway
implements OnGatewayConnection, OnGatewayDisconnect
{
private readonly logger: Logger = new Logger(SocketGateway.name);
#WebSocketServer() server: Server;
constructor(private readonly socketService: SocketService) {}
#SubscribeMessage('statusUpdate')
updateStatus(data: any) {
this.server.emit('statusUpdate', data);
}
handleConnection(client: any, ...args: any[]): any {
return this.logger.log(`Client disconnected: ${client.id}`);
}
handleDisconnect(client: any): any {
return this.logger.log(`Client connected: ${client.id}`);
}
}
Now I am trying to connect using postman by connecting to this URL
ws://localhost:5010
which results in this error socket hang up
not really sure why is it behaving this way and no sufficient information to debug it.
would really appreciate if someone could share a hint on where to look.
I am on macOS Monterey: 12.0.1 ( last update )
installed Websocket libs:
#nestjs/platform-socket.io: 8.2.4
#nestjs/websockets": 8.2.4
Thanks
Through e2e testing, you can try with this example:
import * as WebSocket from 'ws'
beforeAll(async () => {
const moduleFixture = await Test.createTestingModule({
imports: [
SocketModule,
],
}).compile()
app = moduleFixture.createNestApplication()
app.useWebSocketAdapter(new WsAdapter(app))
await app.init()
})
it('should connect successfully', (done) => {
const address = app.getHttpServer().listen().address()
const baseAddress = `http://[${address.address}]:${address.port}`
const socket = new WebSocket(baseAddress)
socket.on('open', () => {
console.log('I am connected! YEAAAP')
done()
})
socket.on('close', (code, reason) => {
done({ code, reason })
})
socket.on ('error', (error) => {
done(error)
})
})
this example is based on this answer

Package: chrome-aws-lambda Error: Navigation failed because browser has disconnected

I'm using mocha, puppeteer, and running test cases in the AWS lambda. I'm opening multiple tabs in the browser using the below code.
browser = await chromium.puppeteer.launch({
args: chromium.args,
defaultViewport: chromium.defaultViewport,
executablePath: await chromium.executablePath,
headless: chromium.headless,
ignoreHTTPSErrors: true,
});
let browerTabs = Array.from({length: 50}).map(() => {
return openTab(browser)
})
const openTab = async (browser) => {
try{
url1 = process.env.URL || 'https://www.google.com/'
let page = await browser.newPage();
await page.goto(url1, { waitUntil: ["load", "networkidle2"] });
const content = await page.evaluate(() => document.body.innerHTML);
}catch(err) {
console.log("browser tab open error ==> ", err)
}
return content
}
If I'm opening 40 tabs it's working fine. But If I trying to open 50 tabs then I'm getting the below issue. RAM is not even 30% used. What could be the reason for this error?
Everything is fine in the local
at /var/task/node_modules/puppeteer-core/lib/cjs/puppeteer/common/LifecycleWatcher.js:51:147
at /var/task/node_modules/puppeteer-core/lib/cjs/vendor/mitt/src/index.js:47:62
at Array.map (<anonymous>)
at Object.emit (/var/task/node_modules/puppeteer-core/lib/cjs/vendor/mitt/src/index.js:47:43)
at CDPSession.emit (/var/task/node_modules/puppeteer-core/lib/cjs/puppeteer/common/EventEmitter.js:72:22)
at CDPSession._onClosed (/var/task/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.js:247:14)
at Connection._onClose (/var/task/node_modules/puppeteer-core/lib/cjs/puppeteer/common/Connection.js:128:21)
at WebSocket.<anonymous> (/var/task/node_modules/puppeteer-core/lib/cjs/puppeteer/common/WebSocketTransport.js:17:30)
at WebSocket.onClose (/var/task/node_modules/ws/lib/event-target.js:129:16)
at WebSocket.emit (events.js:315:20)

How to manage typeORM connection of Aurora Serverless data api inside Lambda using Serverless Framework

I'm using:
Aurora Serverless Data API (Postgres)
TypeORM with typeorm-aurora-data-api-driver
AWS Lambda with Serverless framework (TypeScript, WebPack)
I'm connecting to the db like it's described in github,
const connection = await createConnection({
type: 'aurora-data-api-pg',
database: 'test-db',
secretArn: 'arn:aws:secretsmanager:eu-west-1:537011205135:secret:xxxxxx/xxxxxx/xxxxxx',
resourceArn: 'arn:aws:rds:eu-west-1:xxxxx:xxxxxx:xxxxxx',
region: 'eu-west-1'
})
And this is how I use it inside of my Lambda function
export const testConfiguration: APIGatewayProxyHandler = async (event, _context) => {
let response;
try {
const connectionOptions: ConnectionOptions = await getConnectionOptions();
const connection = await createConnection({
...connectionOptions,
entities,
});
const userRepository = connection.getRepository(User);
const users = await userRepository.find();
response = {
statusCode: 200,
body: JSON.stringify({ users }),
};
} catch (e) {
response = {
statusCode: 500,
body: JSON.stringify({ error: 'server side error' }),
};
}
return response;
};
When I execute is first time it works just well.
But second and next times I'm getting an error
AlreadyHasActiveConnectionError: Cannot create a new connection named "default", because connection with such name already exist and it now has an active connection session.
So, what is the proper way to manage this connection?
Should it be somehow reused?
I've found some resolutions for simple RDS but the whole point of Aurora Serverless Data API is that you don't have to manage the connection
when you try to establish a connection, you need to check if there is already a connection it can use. this is my Database class used to handle connections
export default class Database {
private connectionManager: ConnectionManager;
constructor() {
this.connectionManager = getConnectionManager();
}
async getConnection(): Promise<Connection> {
const CONNECTION_NAME = 'default';
let connection: Connection;
if (this.connectionManager.has(CONNECTION_NAME)) {
logMessage(`Database.getConnection()-using existing connection::: ${CONNECTION_NAME}`);
connection = await this.connectionManager.get(CONNECTION_NAME);
if (!connection.isConnected) {
connection = await connection.connect();
}
} else {
logMessage('Database.getConnection()-creating connection ...');
logMessage(`DB host::: ${process.env.DB_HOST}`);
const connectionOptions: ConnectionOptions = {
name: CONNECTION_NAME,
type: 'postgres',
port: 5432,
logger: 'advanced-console',
logging: ['error'],
host: process.env.DB_HOST,
username: process.env.DB_USERNAME,
database: process.env.DB_DATABASE,
password: process.env.DB_PASSWORD,
namingStrategy: new SnakeNamingStrategy(),
entities: Object.keys(entities).map((module) => entities[module]),
};
connection = await createConnection(connectionOptions);
}
return connection;
}
}

Heroku Error: ENOENT: no such file or directory, stat '/app/build/index.html'

I am getting this error in my heroku logs.
Same Question
All the solutions provided here did not address the issue.
I tried the different variations of the get method:
app.use(express.static('build'));
app.get('*', function (req, res) {
res.sendFile('index.html');
});
What else could I try or am I missing from here?
App.js
const configuration = require('#feathersjs/configuration');
const feathers = require('#feathersjs/feathers');
const express = require('#feathersjs/express');
const socketio = require('#feathersjs/socketio');
const moment = require('moment');
class IdeaService {
constructor() {
this.ideas = [];
}
async find() {
return this.ideas;
}
async create(data) {
const idea = {
id: this.ideas.length,
text: data.text,
tech: data.tech,
viewer: data.viewer
};
idea.time = moment().format('h:mm:ss a');
this.ideas.push(idea);
return idea;
}
}
const app = express(feathers());
app.feathers().configure(configuration());
app.use(express.static('build'));
app.get('*', function (req, res) {
res.sendFile('index.html');
});
// Parse JSON
app.use(express.json());
// Configure SocketIO realtime API
app.configure(socketio());
// Enable REST services
app.configure(express.rest());
// Register services
app.use('/ideas', new IdeaService());
// Connect new streams
app.on('connection', conn => app.channel('stream').join(conn));
// Publish events to stream
app.publish(data => app.channel('stream'));
const PORT = process.env.PORT || 3030;
app.listen(PORT).on('listening', () => console.log(`Server running on port ${PORT}`));
app.service('ideas').create({
text: 'Build a cool app',
tech: 'Node.js',
viewer: 'John Doe'
});
export default IdeaService;
package.json

Hapi server on heroku fails to bind port

I'm working on a Hapi server for a ReactJS app but when I try to deploy to Heroku, I get the R10 error "Failed to bind to $PORT within 60 seconds of launch". What is going on? I'm using process.env.PORT. I also tried parseInt() around it. Also tried disabling varying packages. The build is successful always.
In the Heroku logs, I see the console log from the index.js ("Hapi running on ...") but then the R10 error shows up and the server restarts, then crashes.
==> 🌎 Hapi Production Server (API) is listening on http://localhost:14316
2016-01-22T15:10:33.947571+00:00 heroku[web.1]: Stopping process with SIGKILL
2016-01-22T15:10:33.947571+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2016-01-22T15:10:34.737554+00:00 heroku[web.1]: State changed from starting to crashed
2016-01-22T15:10:34.724233+00:00 heroku[web.1]: Process exited with status 137
This all runs fine locally when I run with NODE_ENV=production
src/server.js
import Hapi from 'hapi';
import Inert from 'inert';
import jwt from 'hapi-auth-jwt2';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { RoutingContext, match } from 'react-router';
import { Provider } from 'react-redux';
import createRoutes from './routes';
import configureStore from './store/configureStore';
import Html from './Html';
const PROTOCOL = 'http://';
const SERVER_HOST = process.env.HOST || 'localhost';
const SERVER_PORT = process.env.PORT || 3000;
const API_HOST = process.env.API_HOST || 'localhost';
const API_PORT = process.env.API_PORT || 8000;
export default function(callback) {
const server = new Hapi.Server();
server.connection({
host: SERVER_HOST,
port: SERVER_PORT,
labels: ['api'],
// routes: {
// cors: {
// origin: [PROTOCOL + API_HOST + ':' + API_PORT]
// }
// }
});
server.connections[0].name = 'API';
server.register([
{ register: Inert },
{ register: jwt },
// {
// register: api,
// routes: {
// prefix: '/api'
// }
// }
], (err) => {
if(err) {
console.error('ERROR:', err)
throw err;
}
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: 'static'
}
}
});
server.ext('onPreResponse', (request, reply) => {
if (typeof request.response.statusCode !== 'undefined') {
return reply.continue();
}
const assets = {
javascript: {
main: '/dist/bundle.js'
}
};
const store = configureStore();
const routes = createRoutes(store);
// this gets called if server side rendering/routing has problems and errors
function hydrateOnClient() {
reply('<!doctype html>\n' +
renderToString(<Html assets={assets} store={store} />)).code(500);
}
match({ routes, location: request.path }, (error, redirectLocation, renderProps) => {
if (redirectLocation) {
res.redirect(301, redirectLocation.pathname + redirectLocation.search)
} else if (error) {
console.error('ROUTER ERROR:', error) // eslint-disable-line no-console
hydrateOnClient();
} else if (!renderProps) {
// in some cases this would act as a 404 but that should be handled in the routes
hydrateOnClient();
} else {
const component = (
<Provider store={store}>
<RoutingContext {...renderProps} />
</Provider>
);
reply('<!doctype html>\n' +
renderToString(<Html assets={assets} component={component} store={store} />)
);
}
});
});
});
return server.start((err) => {
if(err) {
console.log(err);
throw err;
}
callback(server)
});
}
index.js
require('babel-core/register');
global.__DEVELOPMENT__ = process.env.NODE_ENV !== 'production';
global.__SERVER__ = true;
global.__CLIENT__ = false;
const server = require('./src/server');
server(server => {
for (var key of Object.keys(server.connections)) {
console.info('==> 🌎 Hapi Production Server (' + server.connections[key].name + ') is listening on', server.connections[key].info.uri);
}
});
process.env.HOST was undefined on Heroku, and for some reason it didn't like localhost as the host, which caused the issue.
I simply removed the host var all together, so connection looks like:
server.connection({
port: process.env.PORT || 3000,
labels: ['api'],
})

Resources