2018-01-08 13:06:01 -08:00
|
|
|
import { Server } from 'net'
|
|
|
|
import { unlink as fileDelete } from 'fs'
|
2018-05-27 13:05:38 -07:00
|
|
|
import { promisify } from 'util'
|
2018-03-02 08:34:10 -08:00
|
|
|
import path from 'path'
|
|
|
|
import mkdir from 'make-dir'
|
2018-01-08 13:06:01 -08:00
|
|
|
import btc from 'better-try-catch'
|
2018-02-03 13:33:25 -08:00
|
|
|
import _ON_DEATH from 'death' //this is intentionally ugly
|
2018-02-01 16:58:17 -08:00
|
|
|
import JSONStream from './json-stream'
|
2018-02-14 13:26:35 -08:00
|
|
|
import clone from 'clone'
|
2018-02-01 16:58:17 -08:00
|
|
|
|
2018-02-17 18:26:17 -08:00
|
|
|
// import logger from '../../uci-logger/src/logger'
|
|
|
|
import logger from '@uci/logger'
|
2018-02-01 16:58:17 -08:00
|
|
|
let log = {}
|
2018-05-16 07:21:51 -07:00
|
|
|
|
2018-03-02 08:34:10 -08:00
|
|
|
// TODO change default pipe dir for windows and mac os
|
|
|
|
const DEFAULT_PIPE_DIR = (process.env.SOCKETS_DIR || '/tmp/UCI')
|
|
|
|
const DEFAULT_SOCKET_NAME = 'uci-sock'
|
2018-01-08 13:06:01 -08:00
|
|
|
|
|
|
|
export default class Socket extends Server {
|
2018-02-03 13:33:25 -08:00
|
|
|
constructor (opts={}) {
|
2018-01-08 13:06:01 -08:00
|
|
|
super()
|
2018-02-01 16:58:17 -08:00
|
|
|
this.id = opts.id || opts.name || 'socket:'+ new Date().getTime()
|
2018-02-03 13:33:25 -08:00
|
|
|
if (!opts.path) {
|
|
|
|
opts.host = opts.host || '0.0.0.0'
|
|
|
|
opts.port = opts.port || 8080
|
2018-03-02 08:34:10 -08:00
|
|
|
} else {
|
|
|
|
if (typeof opts.path === 'boolean') opts.path = path.join(DEFAULT_PIPE_DIR,DEFAULT_SOCKET_NAME )
|
|
|
|
if (path.dirname(opts.path)==='.') opts.path = path.join(DEFAULT_PIPE_DIR,opts.path )
|
|
|
|
}
|
2018-05-24 12:28:30 -07:00
|
|
|
this.clientTracking = opts.clientTracking || true
|
|
|
|
this.clients = [] // track consumers (i.e. clients)
|
2018-03-02 08:34:10 -08:00
|
|
|
this.opts = opts // for use to recover from selected errors
|
2018-02-03 13:33:25 -08:00
|
|
|
//self bindings
|
2018-01-31 11:30:32 -08:00
|
|
|
this._listen = this._listen.bind(this)
|
2018-01-25 18:07:45 -08:00
|
|
|
this.create = this.create.bind(this)
|
2018-05-16 07:21:51 -07:00
|
|
|
log = logger({file:'src/socket.js',class:'Socket',name:'socket',id:this.id})
|
2018-01-13 20:46:14 -08:00
|
|
|
} // end constructor
|
2018-01-08 13:06:01 -08:00
|
|
|
|
2018-01-30 16:59:57 -08:00
|
|
|
async create () {
|
2018-01-22 12:18:34 -08:00
|
|
|
|
2018-01-18 21:21:06 -08:00
|
|
|
return new Promise( async (resolve,reject) => {
|
2018-02-12 14:41:06 -08:00
|
|
|
// couple ways to kill socket process when needed
|
2018-02-03 13:33:25 -08:00
|
|
|
_ON_DEATH( async () => {
|
2018-02-01 16:58:17 -08:00
|
|
|
log.info('\nhe\'s dead jim')
|
2018-01-31 11:30:32 -08:00
|
|
|
await this._destroy()
|
2018-01-13 20:46:14 -08:00
|
|
|
})
|
|
|
|
process.once('SIGUSR2', async () => {
|
2018-01-31 11:30:32 -08:00
|
|
|
await this._destroy
|
2018-01-13 20:46:14 -08:00
|
|
|
process.kill(process.pid, 'SIGUSR2')
|
|
|
|
})
|
|
|
|
|
2018-02-12 14:41:06 -08:00
|
|
|
this.once('error', async (err) => {
|
2018-01-13 20:46:14 -08:00
|
|
|
// recover from socket file that was not removed
|
|
|
|
if (err.code === 'EADDRINUSE') {
|
2018-03-02 08:34:10 -08:00
|
|
|
if (this.opts.path) { // if TCP socket should already be dead
|
2018-07-30 19:07:03 -07:00
|
|
|
let [err, res] = await btc(promisify(fileDelete))(this.opts.path)
|
2018-05-27 13:05:38 -07:00
|
|
|
if(!err) {
|
|
|
|
log.info({res:res, socket: this.opts.path}, 'socket already exists.....deleted')
|
|
|
|
return await this._listen(this.opts)
|
|
|
|
}
|
|
|
|
log.fatal({err:err},'error deleting socket. Can not establish a socket')
|
|
|
|
return err
|
2018-01-18 21:21:06 -08:00
|
|
|
}
|
2018-01-13 20:46:14 -08:00
|
|
|
}
|
2018-03-02 08:34:10 -08:00
|
|
|
if (err.code ==='EACCES'){
|
|
|
|
console.log({socket: this.opts.path}, 'directory does not exist...creating')
|
|
|
|
await mkdir(path.dirname(this.opts.path))
|
|
|
|
console.log({socket: this.opts.path}, 'created')
|
|
|
|
log.warn({socket: this.opts.path}, 'directory does not exist...creating')
|
|
|
|
return await this._listen(this.opts)
|
|
|
|
}
|
2018-01-13 20:46:14 -08:00
|
|
|
// otherwise fatally exit
|
2018-02-01 16:58:17 -08:00
|
|
|
log.info(err, 'creating socket')
|
2018-01-13 20:46:14 -08:00
|
|
|
reject(err)
|
|
|
|
})
|
|
|
|
|
2018-02-03 13:33:25 -08:00
|
|
|
let [err, res] = await btc(this._listen)(this.opts)
|
2018-01-18 21:21:06 -08:00
|
|
|
if (err) reject(err)
|
|
|
|
resolve(res)
|
|
|
|
|
2018-02-11 19:58:22 -08:00
|
|
|
}) // end creeate promise
|
2018-01-18 21:21:06 -08:00
|
|
|
} // end create
|
|
|
|
|
2018-02-03 13:33:25 -08:00
|
|
|
registerPacketProcessor (func) {
|
|
|
|
this._packetProcess = func
|
|
|
|
}
|
2018-01-18 21:21:06 -08:00
|
|
|
|
2018-02-03 13:33:25 -08:00
|
|
|
async _listen (opts) {
|
|
|
|
super.listen(opts, async (err, res) => {
|
2018-01-18 21:21:06 -08:00
|
|
|
if (err) return err
|
2018-02-12 14:41:06 -08:00
|
|
|
// this gets called for each client connection and is unique to each
|
2018-02-11 19:58:22 -08:00
|
|
|
this.on('connection', async (socket) => {
|
2018-02-01 16:58:17 -08:00
|
|
|
const stream = new JSONStream()
|
2018-05-24 12:28:30 -07:00
|
|
|
socket.stream = stream // need this to track clients
|
|
|
|
let send = this._send.bind(socket)
|
|
|
|
if (this.clientTracking) this.clients.push(socket)
|
|
|
|
// TODO add 'close' listener to socket to remove from this.clients
|
|
|
|
log.info('new consumer connecting')
|
|
|
|
log.info(await send(await stream.serialize({'_handshake':true})))
|
2018-07-31 09:45:32 -07:00
|
|
|
if (this.opts.conPacket) {
|
|
|
|
this.opts.conPacket._header = { id:'pushed'}
|
|
|
|
log.info({conPacket:this.opts.conPacket},'pushing a preset command to just connected consumer')
|
|
|
|
send(await stream.serialize(this.opts.conPacket)) // send a packet command on to consumer on connection
|
|
|
|
}
|
2018-01-21 19:55:47 -08:00
|
|
|
socket.on('data', stream.onData)
|
2018-02-11 19:58:22 -08:00
|
|
|
// TODO need to start error listener for stream so errors can be processed
|
2018-05-24 12:28:30 -07:00
|
|
|
stream.on('message', messageProcess.bind(this,socket))
|
|
|
|
|
|
|
|
async function messageProcess (client, packet) {
|
|
|
|
log.info({packet:packet},'incoming packet on socket side')
|
|
|
|
let res = {}
|
|
|
|
if (this.clientTracking && packet.clientID) {
|
|
|
|
client.ID = packet.clientID
|
|
|
|
res.cmd='ackID'
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
res = await this._packetProcess(clone(packet)) || {}
|
|
|
|
if (Object.keys(res).length === 0) res = { error: 'socket packet command function likely did not return a promise', packet:packet}
|
|
|
|
}
|
|
|
|
if (packet) {
|
|
|
|
res._header = clone(packet._header,false) || {} //make sure return packet has header with id in case it was removed in processing
|
|
|
|
delete packet._header // remove before adding to response header as request
|
|
|
|
} else res._header = {}
|
2018-02-14 13:26:35 -08:00
|
|
|
res._header.request = clone(packet,false)
|
|
|
|
res._header.responder = {name:this.name,instanceID:this.id}
|
2018-05-24 12:28:30 -07:00
|
|
|
res._header.socket = this.address()
|
2018-02-14 13:26:35 -08:00
|
|
|
if (!res.cmd) res.cmd = 'reply' // by default return command is 'reply'
|
|
|
|
let [err, ser] = await btc(stream.serialize)(res)
|
|
|
|
if (err) ser = await stream.serialize({ error: 'was not able to serialze the res packet', err:err, _header:{id:res._header.id}})
|
2018-05-24 12:28:30 -07:00
|
|
|
log.info(await send(ser))
|
|
|
|
} // end process message
|
|
|
|
|
2018-02-03 13:33:25 -08:00
|
|
|
}) // end connecttion consumer
|
|
|
|
log.info({opts: this.opts},'socket created')
|
2018-01-18 21:21:06 -08:00
|
|
|
return res
|
2018-02-03 13:33:25 -08:00
|
|
|
}) // end super listen callback
|
2018-01-08 13:06:01 -08:00
|
|
|
|
2018-02-03 13:33:25 -08:00
|
|
|
} // end listen
|
2018-01-08 13:06:01 -08:00
|
|
|
|
2018-01-31 11:30:32 -08:00
|
|
|
async _destroy () {
|
2018-02-01 16:58:17 -08:00
|
|
|
log.info('closing down socket')
|
2018-01-08 13:06:01 -08:00
|
|
|
await this.close()
|
2018-02-01 16:58:17 -08:00
|
|
|
log.info('all connections closed....exiting')
|
2018-01-08 13:06:01 -08:00
|
|
|
process.exit()
|
2018-01-25 18:07:45 -08:00
|
|
|
}
|
2018-01-08 13:06:01 -08:00
|
|
|
|
2018-02-03 13:33:25 -08:00
|
|
|
// default packet process, just a simple echo
|
2018-02-13 13:51:58 -08:00
|
|
|
async _packetProcess (packet) {
|
2018-02-12 14:41:06 -08:00
|
|
|
return new Promise(resolve => {
|
|
|
|
resolve(packet)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// must have a consumer socket bound to use
|
2018-05-24 12:28:30 -07:00
|
|
|
async _send(packet) {
|
2018-02-12 14:41:06 -08:00
|
|
|
// timeout already set if sockect can't be drained in 10 secs
|
|
|
|
return new Promise(resolve => {
|
|
|
|
const cb = () => resolve('packet written to socket stream')
|
|
|
|
if (!this.write(packet)) {
|
|
|
|
this.once('drain',cb )
|
|
|
|
} else {
|
|
|
|
process.nextTick(cb)
|
|
|
|
}
|
|
|
|
})
|
2018-01-25 18:07:45 -08:00
|
|
|
}
|
2018-01-08 13:06:01 -08:00
|
|
|
|
2018-05-24 12:28:30 -07:00
|
|
|
async push (packet,id) {
|
|
|
|
packet._header = { id:'pushed'}
|
2018-07-30 19:07:03 -07:00
|
|
|
log.info({opts:this.opts,packet:packet},'pushing a packet to all connected consumers')
|
2018-05-24 12:28:30 -07:00
|
|
|
this.clients.forEach(async (client) => {
|
|
|
|
if (client.writable) {
|
|
|
|
let [err, ser] = await btc(client.stream.serialize)(packet)
|
|
|
|
if (err) ser = await client.stream.serialize({ error: 'was not able to serialze the res packet', err:err, _header:{id:packet._header.id}})
|
|
|
|
if (!id || id ===client.ID ) await this._send.bind(client)(ser)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2018-01-08 13:06:01 -08:00
|
|
|
} // end class
|