Search code examples
mysqlsocket.ioconnectiondatabase-connection

Node + Mysql + Socket IO + PROTOCOL_CONNECTION_LOST


Versions:

Node JS : 7.2.1

Express : 4.15.3

MySQL NPM : 2.14.1

Socket IO : 2.1.1

We just introduced sockets in our application in an attempt to get notifications running. But since then, my database just wont connect.

I keep getting the PROTOCOL_CONNECTION_LOST : Connection lost: The server closed the connection. error. I have tried this and this. They don't seem to work.

The connection is NOT established the first time, but if I setInterval on the error event and try to reconnect after some time, it does connect.. but some how the new connection object is not used..

I switch my branch.. the connection works flawlessly. There are other team members working simultaneously and they don't have any problems with the connection. So I am guessing it have something to do with the way I have implemented the notifications.

These are my files below:

//socket.js

import server from './../../server.js';
import SocketIO from "socket.io";
import nconf from "nconf";
import eventService from "../../events/service.js";

module.exports.initSocket = (IO) => {
    let event = eventService(IO);
    let notificationEmissionInterval = nconf.get('NOTIFICATION_INTERVAL_MILLISECONDS');

    IO.on("connection", (socket) => {
        setInterval(() => {
            event.emitNotifications(socket);
        }, notificationEmissionInterval);
    });
};

if (server) {
    let IO = new SocketIO(server);
    module.exports.initSocket(IO);
}

//service.js

import path from 'path';
import logger from '../config/lib/logger.js';
import notificationController from "../module/notification/controller/notification.controller.js";

module.exports = (IO) => {
    let emitNotifications = (socket) => {   
        notificationController.getUnreadNotifications(params)
        .then((notifications) => {
        //Do something
        )
    };

    return {
        emitNotifications: emitNotifications,
    }
};

//Model.js

import connection from '../../../config/lib/db.js';
import logger from 'logger';
import Promise from 'bluebird';

class NotificationModel {

    getUnreadNotifications = () => {
        return new Promise((resolve, reject) => {
            let query = `CALL GetUnreadNotification()`;
            connection.query(query, (err, result) => {
                if (err) {
                    logger.error('Sql error in NotificationModel.getUnreadNotifications : ', err);
                    reject(err);
                }
                else {
                    logger.info('Unread notifications fetched successfully');
                    resolve(result);
                }
            });
        });
    };

}
export default new NotificationModel();

My database file currently [after a lot of debugging] looks like below. Commenting out this file from the import in the notification model resolves the error.

//db.js

import mysql from 'mysql';
import nconf from 'nconf';
import logger from './logger.js';
import path from 'path';

nconf.argv()
    .env()
    .file({
        file: path.resolve('./config.json')
    });

let dbConfig = {
    "host": nconf.get('MYSQL_HOST'),
    "port": nconf.get('MYSQL_PORT'),
    "user": nconf.get('MYSQL_USER'),
    "password": nconf.get('MYSQL_PASSWORD'),
    "database": nconf.get('MYSQL_DATABASE'),
    "stringifyObjects":true,
    "multipleStatements": true,
    "dateStrings" : 'DATETIME',
    "connectTimeout" : 60000
};

function connectToDatabase() {
    logger.info('Trying to connect to the database');
    let _conn = mysql.createConnection(dbConfig);

    _conn.connect((err) => {
        if (err) {
            logger.error('Error connecting to the database');
            logger.debug(err.code + ' : ' + err.message);
            setTimeout(connectToDatabase, 3000);
        }
        else {
            logger.info('Connected to the database via threadId : ' + _conn.threadId);
            return _conn;
        }
    });

    _conn.on('error', (err) => {
        logger.error('Error connecting to the database');
        logger.debug(err.code + ' : ' + err.message);
        setTimeout(connectToDatabase, 3000);
    });
}

let connection = connectToDatabase();

export default connection;

Any help is appreciated.


Solution

  • Answering my own question.. I solved it using a connection pool..

    //db.js

    let pool = mysql.createPool(dbConfig);
    
    pool.on('connection', function (_conn) {
        if (_conn) {
            logger.info('Connected the database via threadId %d!!', _conn.threadId);
            _conn.query('SET SESSION auto_increment_increment=1');
        }
    });