Lagom Framework Topic Websocket Timeout connection closed with error - akka-stream

I have created a lagom Topic in my service.
def addingsTopic(): Topic[ProcessDefinitionAdded]
the descriptor:
override def descriptor: Descriptor = {
import Service._
named(ProductionService.TOPIC_NAME).withCalls(
pathCall(pathProcessDef(":id"), getProcessDefinition _)
).withTopics(
topic("processdef", addingsTopic _ )
.addProperty(
KafkaProperties.partitionKeyStrategy,
PartitionKeyStrategy[ProcessDefinitionAdded](_.entityId.toString)
),
topic("productionserviceorder", ordersTopic _)
.addProperty(
KafkaProperties.partitionKeyStrategy,
PartitionKeyStrategy[OrderAddedTopic](_.entityId.toString)
)
).withAutoAcl(true)
}
Until here all is clear. Now I have a play webpage. I have in my controller a Websocket.
val k = productionService.addingsTopic().subscribe.atMostOnceSource.mapAsync(1){e ⇒
productionService.getProcessDefinition(e.entityId).invoke().map{e ⇒
Json.toJson(e)(ProcessDefinitionResponse.format)
}
}.toMat(BroadcastHub.sink(256) )(Keep.right).run().recover{
case e ⇒ println(e)
Json.toJson("error "+e)
}
val f = Flow.fromSinkAndSource(Sink.ignore,k.concat(Source.maybe))
def fetchProcessDefinition() = WebSocket.accept[String,JsValue] { req ⇒
f
}
My javascript website use this to connect:
<script>
try{
console.log("START");
var socket = new WebSocket("ws://localhost:9000/processdef/stream");
socket.onopen = function(s){
console.log("OPEN");
console.log(s);
};
socket.onerror = function(error){
console.log("ERROR: ");
console.log(error);
};
socket.onmessage = function(msg){
console.log("Message:");
console.log(JSON.stringify(msg.data));
};
socket.onclose = function(closeevent){
console.log("CLOSE:");
console.log(closeevent);
};
socket.send("")
}catch (e) {
console.error(e);
}
</script>
I load the page on localhost after sbt runAll. It takes a time then the websockets connects (sometimes a few minutes and sometimes a few seconds). After ~ 90 seconds the console prints that the connection is closed out.
On IDE I get this error:
2018-10-18T10:54:16.655Z [error] akka.actor.ActorSystemImpl [sourceThread=application-akka.actor.default-dispatcher-213, akkaSource=akka.actor.ActorSystemImpl(application), sourceActorSystem=application, akkaTimestamp=10:54:16.654UTC] - Websocket handler failed with The connection closed with error: The connection was reset by peer
akka.stream.StreamTcpException: The connection closed with error: The connection was reset by peer
2018-10-18T10:54:16.674Z [error] akka.actor.ActorSystemImpl [sourceThread=application-akka.actor.default-dispatcher-231, akkaSource=akka.actor.ActorSystemImpl(application), sourceActorSystem=application, akkaTimestamp=10:54:16.674UTC] - Websocket handler failed with The connection closed with error: The connection was reset by peer
akka.stream.StreamTcpException: The connection closed with error: The connection was reset by peer
That is very stressful. Do I have any mistakes in my code?
Thanks for any help.

Related

The requested URL "localhost/pusher/auth" was not found on this server

i am trying to build a video chat web application using laravel for backend and reactjs for frontend. i tried to find the errors here, but i couldn't. please help me to fix my errors.
Errors that are showing:
1/ POST http://localhost/pusher/auth 404 (Not Found)
2/ Pusher : : ["Error: Unable to retrieve auth string from auth endpoint - received status: 404 from /pusher/auth. Clients must be authenticated to join private or presence channels. See: https://pusher.com/docs/authenticating_users"]
My Code from "resources/js/components/App.js"
setupPusher(){
Pusher.logToConsole = true;
this.pusher = new Pusher(APP_KEY,{
authEndpoint: '/pusher/auth',
cluster: 'ap2',
auth:{
params: this.user.id,
headers:{
'X-CSRF-Token': window.csrfToken
}
}
});
this.channel = this.pusher.subscribe('presence-video-channel');
this.channel.bind(`clnt-signal-${this.user.id}`,(signal) => {
let peer = this.peers[signal.userId];
// if peer is not already exists, we got an incoming call
if(peer == undefined){
this.setState({otherUserId: signal.userId});
peer = this.startPeer(signal.userId, false);
}
peer.signal(signal.data);
});
}
My Code from "routes/web.php"
Route::post('/pusher/auth', [App\Http\Controllers\HomeController::class, 'authenticate']);
My Code from "app/Http/Controllers/HomeController.php"
public function authenticate(Request $request){
$socketId = $request->socket_id;
$channelName = $request->channel_name;
$pusher = new Pusher('a384f250f86af1f16f98', 'd30d380941bdec2e4e55', '1147033', [
'cluster' => 'ap2',
'useTLS' => true
]);
$presence_data = ['name' => auth()->user()->name];
$key = $pusher->presence_auth($channelName, $socketId, auth()->id(), $presence_data);
return response($key);
}

unable to connect to ms sql window authetication using node js

Here is my node js code
app.get('/', function (req, res) {
var config = {
server: 'localhost\\SQLEXPRESS2008',
database: 'TestingDB'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from userform', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
console.log(recordset);
});
});
});
Please suggest me to connect sql and getting this error after running this in command prompt
Server is running.. on Port 8020
{ Error: Failed to connect to localhost:undefined in 15000ms
at Connection.tedious.once.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:293:19)
at emitOne (events.js:96:13)
at Connection.emit (events.js:191:7)
at Connection.connectTimeout (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:795:12)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
code: 'ETIMEOUT',
originalError:
{ ConnectionError: Failed to connect to localhost:undefined in 15000ms
at ConnectionError (D:\Nodejs\UsersCreate\node_modules\tedious\lib\errors.js:12:12)
at Connection.connectTimeout (D:\Nodejs\UsersCreate\node_modules\tedious\lib\connection.js:795:28)
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
message: 'Failed to connect to localhost:undefined in 15000ms',
code: 'ETIMEOUT' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1299:37)
at Request._query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:1242:12)
at D:\Nodejs\UsersCreate\app.js:118:17
at _poolCreate.then.catch.err (D:\Nodejs\UsersCreate\node_modules\mssql\lib\base.js:269:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
undefined
This might help :
Start the "SQL SERVER BROWSER" Service in Windows services (I've configured it to start automatically)
allow SQL Server Express to accept remote connections over TCP/IP for port 1433 : http://support.webecs.com/kb/a868/how-do-i-configure-sql-server-express-to-allow-remote-tcp-ip-connections-on-port-1433.aspx
Finally restart 'SQL Server' and 'SQL Browser Agent' services
Installing mssql package I had a similiar problem and I got fixed addiyng an instance and database name to my config.
I thought it was better create an user on db.
After I need to handling the errors, addiyng try catch to my function that will connect in db and closing the connection if the function get an error.
All database connections are in a different file, so I export the modules to use in my application and if I need to use in other application just add a reference to that
let QueryDB = {
Query_SelectAll: 'SELECT [COLUMN] \
, [COLUMN] \
, [COLUMN] \
FROM [DATABASE].[dbo].[TABLE_NAME]',
Query_Delete: 'DELETE FROM [DATABASE].[dbo].[TABLE_NAME] WHERE COLUMN = '
};
I put all queries in an object to simplify the use for me.
let ConnectionString = {
user: 'YOUR_DBUSER',
password: '****',
server: '0.0.000.00',
options: {
instance: 'YOURINSTANCE',
database: 'DATABASE_NAME'
}
};
In the server property, I put the server IP, after add the options with instance and database name.
function SQL_Server(Query, ret) {
sql.close();
sql.connect(ConnectionString).then(() => {
console.log("Connected");
return request(Query, ret);
}).catch((error) => {
console.log("Connect error");
console.error(error);
sql.close();
});
}
function request(Query, ret) {
let returning = undefined;
let request = new sql.Request();
(request.query(Query).then((recordset) => {
sql.close();
returning = recordset.recordset;
}).catch((error) => {
console.error(error);
sql.close();
})).then(() => {
if (ret != undefined)
ret(returning);
console.log("Successful object return");
});
}
Those are my connect and request functions.
module.exports.SQL_Server = SQL_Server;
module.exports.QueryDB = QueryDB;
So I export the modules to use the functions.
An example of using:
let DataBase = require("./Connection_Query");
let FuncSql = DataBase.SQL_Server;
let SQL = DataBase.QueryDB;
APP.get(ProjectName + '/Home', (req, resp) => {
FuncSql(SQL.Query_SelectAll, (rec) => {
resp.render("Home", { YourObjects: rec });
});
});
Think that you use this answer to guide you.
you have to write the database instance in config.options.instanceName
var config = {
server: 'localhost\\SQLEXPRESS2008',
database: 'TestingDB'
};
instead:
const config = {
user: '...',
password: '...',
server: 'localhost',
database: 'TestingDB',
options: {
encrypt: false, // Use this if you're on Windows Azure
instanceName: 'SQLEXPRESS2008'
}
};

Socket.io disconnecting

I have a chat done in nodejs, Express, socket.io and angular. It works well but disconnects sometimes and at random times. Generally the connection lasts no more than 2 minutes. I get several net :: ERR_CONNECTION_TIMED_OUT on the console.
PS.: I'm using apache 2.2 on CentOS with certified ssl.
Any tips?
My server.js header is below
#!/bin/env node
var express = require('express'),
path = require('path'),
app = express(),
logger = require('morgan'),
_m = require("./models/Message"),
Message = _m.m,
NewMessage = _m.n,
Group = _m.g,
Online = _m.o,
DeletedMessage = _m.d,
LastMessage = _m.l,
_mTASK = require("./models/Task"),
_Task = _mTASK.t,
TaskComment = _mTASK.c,
TaskLog = _mTASK.l,
TaskModel = _mTASK.m,
TaskNotification = _mTASK.n,
_d = require("./lib/Connection");
app.use(logger('dev'));
app.set('port', 3000);
app.set('ipaddr', "127.0.0.1");
var server = require('http').createServer(app);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
server.listen(app.get('port'), app.get('ipaddr'), function() {
console.log('Express server listening on IP: ' + app.get('ipaddr') + ' and port ' + app.get('port'));
});
var io = require("socket.io")(server);
io.set("origins", 'https://meusite.me:*');
io.set('transports', ['polling', 'websocket']);
A bit of socket.io background
Server sends a heartbeat to the client every X seconds where X == the
heartbeat interval configuration value.
If the client fails to respond, socket considers the connect dead
Client waits for a heartbeat from the server every N seconds where N == the heartbeat timeout configuration value.
Both of these values are set on the server with heartbeat timeout being sent to the client when an individual connection is opened.
Given the file above, you could set the heartbeat timeout with something like ...
//WARNING io.set() has been depricated
var io = require("socket.io")(server);
io.set('heartbeat interval', '30000');
io.set('heartbeat timeout', '45000');
io.set("origins", 'https://meusite.me:*');
io.set('transports', ['polling', 'websocket']);
//Setting your server configuration is now done via ..
var socket = require('socket.io')({
// options go here
'configOption': 'configValue';
});

Prerender.io throws socket error

I have been trying to make prerender.io working for a week now, I tried everything but nothing worked.
I have a node server:
'use strict';
var path = require('path');
var _ = require('lodash');
var express = require('express');
var app = module.exports = express();
var prerender = require('prerender-node')
.set('prerenderToken', 'My Key');
// These search engine bot do not adheres to google's _escaped_fragment_
// proposal, so we use user agent to detect them.
var moreCrawlerUserAgents = [
'Slurp!',
'MSNBot',
'YoudaoBot',
'JikeSpider',
'Sosospider',
'360Spider',
'Sogou web spider',
'Sogou inst spider',
'baiduspider',
'facebookexternalhit',
'twitterbot',
'rogerbot',
'linkedinbot',
'embedly',
'quora link preview',
'showyoubot',
'outbrain',
'pinterest',
'developers.google.com/+/web/snippet',
'slackbot',
'vkShare',
'W3C_Validator',
'redditbot'
];
prerender.set('crawlerUserAgents', _.union(
prerender.crawlerUserAgents, moreCrawlerUserAgents));
app.use(prerender);
var options = {
maxAge: '60d',
setHeaders: function(res, path, stat) {
// Webfonts need to have CORS * set in order to work.
if (path.match(/ttf|woff|woff2|eot|svg/ig)) {
res.set('Access-Control-Allow-Origin', '*');
}
}
};
var dist_path = '/client/dist/';
app.use(express.static(path.join(__dirname, dist_path), options));
app.use(function(req, res) {
res.sendFile(path.join(__dirname + dist_path + '/index.html'));
});
var port = process.env.PORT || 8000;
app.listen(port, '0.0.0.0');
console.log("Listening on port " + port);
It works fine until I pass _escaped_fragment_= as a query string parameter then it throws these two errors:
Error: getaddrinfo EMFILE
at Object.exports._errnoException (util.js:746:11)
at errnoException (dns.js:49:15)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:94:26)
OR
Error: socket hang up
at createHangUpError (_http_client.js:215:15)
at Socket.socketOnEnd (_http_client.js:300:23)
at Socket.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
I don't know what the problem is, please help!
Thanks.

I am trying to connect to postgres database instance in aws but I can't

I have the following code.
var express = require('express');
var app = express();
var path = require('path');
var pg = require('pg');
var conString = "postgres://user:password#endpoint:5432/StudentRecords";
//this initializes a connection pool
//it will keep idle connections open for a (configurable) 30 seconds
//and set a limit of 20 (also configurable)
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
else{
console.log("asdfaf")
}
});
client.connect();
It shows cannot connect to postgres. But when I try connecting from the terminal using
psql --host=endpoint --port=5432 --username xxxxx --password --dbname=StudentRecords
I can connect. Why is the code not working? Error I am getting is:
could not connect to postgres [Error: Connection terminated]

Resources