Skip to content
This repository has been archived by the owner on Aug 28, 2021. It is now read-only.

Commit

Permalink
fixes #82
Browse files Browse the repository at this point in the history
  • Loading branch information
didimitrie committed Nov 22, 2018
1 parent f091c37 commit efef296
Show file tree
Hide file tree
Showing 7 changed files with 67 additions and 72 deletions.
6 changes: 3 additions & 3 deletions app/api/projects/ProjectPut.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@ module.exports = ( req, res ) => {

Project.findOne( { _id: req.params.projectId } )
.then( resource => PermissionCheck( req.user, 'read', resource ) )
.then( resource => resource.set( req.body ).save() )
.then( resource => {
res.send( { success: true, message: `Patched ${Object.keys(req.body)} for ${req.params.projectId}.` } )
.then( resource => resource.set( req.body ).save( ) )
.then( ( ) => {
res.send( { success: true, message: `Patched ${Object.keys( req.body )} for ${req.params.projectId}.` } )
} )
.catch( err => {
winston.error( err )
Expand Down
76 changes: 48 additions & 28 deletions app/ws/ClientStore.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,67 @@
const winston = require( '../../config/logger' )
const chalk = require( 'chalk' )
const redis = require( 'redis' )



// this is where we keep track on each process what clients are connected.
module.exports = {
clients: [ ],

redisClient: redis.createClient( process.env.REDIS_URL ),
// adds a ws to the local store, and initialises a heartbeat pinger
add ( ws ) {
// setup vars
ws.alive = true
ws.missedPingsCount = 0

// setup pinging system
ws.pinger = setInterval( ws => {
if ( !ws.alive ) {
ws.missedPingsCount++
if ( ws.missedPingsCount > 25 ) { ws.send( 'Warning: you missed 25 pings. 50 missed pings will get you kicked.' ) }
if ( ws.missedPingsCount > 50 ) {
winston.error( chalk.red( 'Removing client socket, missed too many pings.' ) )
ws.send( 'You missed 50 pings. Bye!' )
this.remove( ws )
return
add( ws ) {
this.redisClient.get( ws.clientId, ( err, reply ) => {
if ( reply !== null ) {
winston.debug( `duplicate client id found: ${ws.clientId}. Will not add.` )
ws.send( 'dupe key boss. try a new identity.' )
ws.clientId = 'dupe'
ws.close( )
return
}
// add his identity to the redis datastore
this.redisClient.set( ws.clientId, ws.clientId )

// setup vars
ws.alive = true
ws.missedPingsCount = 0

// setup pinging system
ws.pinger = setInterval( ws => {
if ( !ws.alive ) {
ws.missedPingsCount++
if ( ws.missedPingsCount > 25 ) { ws.send( 'Warning: you missed 25 pings. 50 missed pings will get you kicked.' ) }
if ( ws.missedPingsCount > 50 ) {
winston.error( chalk.red( 'Removing client socket, missed too many pings.' ) )
ws.send( 'You missed 50 pings. Bye!' )
this.remove( ws )
return
}
ws.alive = false
}
ws.alive = false
}
ws.alive = false
ws.send( 'ping' )
}, 10000, ws ) // ping every 10 seconds, after 500 seconds of no pingbacks we kick the socket

// push to my amazing datastore
this.clients.push( ws )
winston.debug( chalk.green("(add) Clients: " + this.clients.length + ".") )
winston.debug( chalk.blue( `There are now ${this.clients.length} ws clients in ${process.pid}: ${this.clients.map( cl => cl.clientId )}` ) )
ws.send( 'ping' )
}, 10000, ws ) // ping every 10 seconds, after 500 seconds of no pingbacks we kick the socket

// push to my amazing datastore
this.clients.push( ws )
winston.debug( chalk.green( "(add) Clients: " + this.clients.length + "." ) )
winston.debug( chalk.blue( `There are now ${this.clients.length} ws clients in ${process.pid}: ${this.clients.map( cl => cl.clientId )}` ) )
} )
},

remove ( ws ) {
remove( ws ) {
// escape the jaws of destruction
if ( this.clients.indexOf( ws ) === -1 ) return
// stop pinging this guy
clearInterval( ws.pinger )
// cut him out
this.clients.splice( this.clients.indexOf( ws ), 1 )
ws.close()
this.clients = this.clients.filter( c => c.clientId !== ws.clientId )
ws.close( )

this.redisClient.del( ws.clientId, ( ) => {} )

winston.debug( chalk.bgRed( 'Socket removed', ws.clientId ) )
winston.debug( chalk.blue( `There are now ${this.clients.length} ws clients in ${process.pid}.` ) )
winston.debug( chalk.blue( `There are now ${this.clients.length} ws clients in ${process.pid}.\n${this.clients.map( c => c.clientId ) }` ) )
}
}
11 changes: 0 additions & 11 deletions app/ws/RadioTower.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,17 +33,6 @@ module.exports = {
winston.error( err.message )
} )
}
if ( channel === 'id-check' ) {
// TODO
console.log( 'id checking bot', message )
let existingClient = ClientStore.clients.find( client => client.clientId === message )
if ( existingClient ) {
console.log( 'Heya boy.' )
this.publisher.publish( 'id-check-response', 'true' )
}

//return existingClient === null
}
} )
},

Expand Down
23 changes: 6 additions & 17 deletions app/ws/SpeckleSockets.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,16 @@ const radioTower = require( './RadioTower' )

const User = require( '../../models/User' )

// start a redis publisher & subscriber
let redisPublisher = redis.createClient( process.env.REDIS_URL )
redisPublisher.on( 'connect', ( ) => {
winston.debug( `${process.pid} connected to redis.` )
} )

module.exports = function( wss ) {
// start a redis subscriber in the radio tower
radioTower.initRedis( )

// start a redis publisher
let redisPublisher = redis.createClient( process.env.REDIS_URL )
let redisSubscriber = redis.createClient( process.env.REDIS_URL )
redisSubscriber.subscribe( 'id-check-response' )

redisPublisher.on( 'connect', ( ) => {
winston.debug( `${process.pid} connected to redis.` )
} )

wss.on( 'connection', function( ws, req ) {
winston.debug( chalk.blue( `Ws connection request in PID ${process.pid}` ) )

Expand All @@ -32,13 +29,6 @@ module.exports = function( wss ) {
}
let token = location.query.access_token

redisPublisher.publish( 'id-check', location.query.client_id )
redisSubscriber.on( 'message', ( channel, message ) => {
if ( channel !== 'id-check-response' ) return
ws.send('Bad boy, dupe ids and all that.')
ws.close( )
} )

ws.authorised = false
ws.clientId = location.query.client_id
ws.rooms = [ location.query.stream_id ]
Expand All @@ -63,7 +53,6 @@ module.exports = function( wss ) {
ws.missedPingsCount = 0
return
}

// pub to redis otherwise
redisPublisher.publish( 'speckle-message', JSON.stringify( { content: message, clientId: ws.clientId } ) )
} )
Expand Down
10 changes: 2 additions & 8 deletions config/logger.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
'use strict'
const fs = require( 'fs' )
const path = require( 'path' )
const { createLogger, format, transports } = require( 'winston' )
const drf = require( 'winston-daily-rotate-file' )
require( 'winston-daily-rotate-file' )


const env = process.env.NODE_ENV || 'dev'
const logDir = 'logs'

if ( !fs.existsSync( logDir ) ) {
Expand All @@ -26,10 +23,7 @@ const logger = createLogger( {
transports: [
new transports.Console( {
level: 'debug',
format: format.combine(
format.colorize( ),
format.timestamp( { format: 'YYYY-MM-DD HH:mm:ss' } ),
format.printf( info => `${info.timestamp} ${info.level}: ${info.message}` ), )
format: format.combine( format.colorize( ), format.timestamp( { format: 'YYYY-MM-DD HH:mm:ss' } ), format.printf( info => `${info.timestamp} ${info.level}: ${info.message}` ) )
} ),
drfTransport
]
Expand Down
5 changes: 0 additions & 5 deletions config/passport.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
'use strict'
const winston = require( '../config/logger' )
const chalk = require( 'chalk' )

var JwtStrategy = require( 'passport-jwt' ).Strategy
var AnonymousStrategy = require( 'passport-anonymous' )
var ExtractJwt = require( 'passport-jwt' ).ExtractJwt
Expand All @@ -19,11 +16,9 @@ module.exports = function ( passport ) {
User.findOne( { _id: jwtPayload._id } )
.then( user => {
if ( !user ) throw new Error( 'No user found.' )
// winston.debug( chalk.bgBlue( 'Strict authentication' ), chalk.bgGreen( 'OK' ) )
done( null, user )
} )
.catch( err => {
// winston.debug( chalk.bgBlue( 'Strict authentication' ), chalk.bgRed( 'FAILED' ) )
done( err, false ) // not ok
} )
} ) )
Expand Down
8 changes: 8 additions & 0 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const passport = require( 'passport' )
const chalk = require( 'chalk' )
const mongoose = require( 'mongoose' ).set( 'debug', false )
const expressWinston = require( 'express-winston' )
const redis = require( 'redis' )
const logger = require( './config/logger' )

// load up .env
Expand Down Expand Up @@ -42,6 +43,13 @@ if ( cluster.isMaster ) {
cluster.fork( )
} )

// flush redis
let redisClient = redis.createClient( process.env.REDIS_URL )
redisClient.on( 'connect', ( ) => {
logger.debug( `Flushing redis database.` )
redisClient.flushdb( )
} )

/////////////////////////////////////////////////////////////////////////
/// CHILD processes /////.
/////////////////////////////////////////////////////////////////////////
Expand Down

0 comments on commit efef296

Please sign in to comment.