uci-socket/src/socket-class.js

342 lines
13 KiB
JavaScript

// node modules
import { unlink as fileDelete } from 'fs'
import { promisify } from 'util'
import path from 'path'
// npmjs modules
import mkdir from 'make-dir'
import btc from 'better-try-catch'
import _ON_DEATH from 'death' //this is intentionally ugly
import JSONStream from './json-stream'
import clone from 'clone'
// uci modules
import logger from '@uci-utils/logger'
let log = {} // must declare here and set later for module wide access
export default function socketClass(Server) {
// TODO change default pipe dir depending on OS linux,windows,mac
/** @constant {String} DEFAULT_PIPE_DIR
* @description SOCKETS_DIR environment variable or '/tmp/UCI'
*/
const DEFAULT_PIPE_DIR = process.env.SOCKETS_DIR || '/tmp/UCI'
/** @constant {String} DEFAULT_SOCKET_NAME
* @description for named pipe 'uci-sock' if not set in options */
const DEFAULT_SOCKET_NAME = 'uci-sock'
/**
* UCI Socket - class used to create a socket (server) that supports passing json packets
* supports both named pipes and tcp sockets
* also supports push of packets to all connected consumers (clients)
* is extended from {@link https://nodejs.org/api/net.html#net_class_net_server | nodejs net.Server }
* @extends Server
*/
return class Socket extends Server {
/**
* UCI Socket class constructor
* @param {Object} opts hash of options
* @param {String} options.host a tcp host name nornally not used as 0.0.0.0 is set by default
* @param {String} options.port a tcp
* @param {String | Boolean} options.path xeither full path to where socket should be created or if just 'true' then use default
* @param {Boolean} options.clientTracking track connected clients for push notifications - default: true
* @param {Object} options.conPacket A json operson's property
*
*/
constructor(opts = {}) {
super(opts)
delete opts.key
delete opts.cert
this.id = opts.id || opts.name || 'socket:' + new Date().getTime()
if (!opts.path) {
opts.host = opts.host || '0.0.0.0'
opts.port = opts.port || 8080
} else {
if (typeof opts.path === 'boolean')
opts.path = path.join(DEFAULT_PIPE_DIR, DEFAULT_SOCKET_NAME)
if (path.dirname(opts.path) === '.') // relative path sent
opts.path = path.join(DEFAULT_PIPE_DIR, opts.path)
}
this.allowAnonymous = process.env.UCI_ANON || opts.allowAnonymous || false
this.tokens = opts.tokens || []
this.keepAlive = 'keepAlive' in opts ? opts.keepAlive : true
this.pingInterval = opts.pingInterval === false ? opts.pingInterval : (opts.pingInterval * 1000 || 5000)
// this.clientTracking = opts.clientTracking || true
this.clients = [] // track consumers (i.e. clients)
this.nextClientID = 0 // incrementer for default initial client ID
this.opts = opts // for use to recover from selected errors
//self bindings
this._listen = this._listen.bind(this)
this.create = this.create.bind(this)
this.authenticateClient = this.authenticateClient.bind(this)
this._authenticate = this._authenticate.bind(this)
this.close = promisify(this.close).bind(this)
log = logger({
file: 'src/socket.js',
class: 'Socket',
name: 'socket',
id: this.id
})
} // end constructor
/**
* create - Description
*
* @returns {type} Description
*/
async create() {
return new Promise(async (resolve, reject) => {
// set up a couple ways to gracefully destroy socket process is killed/aborted
_ON_DEATH(async () => {
log.error({method:'create', line:84, msg:'\nhe\'s dead jim'})
await this._destroy()
})
process.once('SIGUSR2', async () => {
await this._destroy()
process.kill(process.pid, 'SIGUSR2')
})
this.once('error', async err => {
// recover from socket file that was not removed
if (err.code === 'EADDRINUSE') {
if (this.opts.path) {
// if TCP socket should already be dead
let [err, res] = await btc(promisify(fileDelete))(this.opts.path)
if (!err) {
log.debug({method:'create', line:99, res: res, socket: this.opts.path, msg:'socket already exists.....deleted'})
return await this._listen(this.opts)
}
log.error({method:'create', line:102, err: err, msg:'error deleting socket. Can not establish a socket'})
return err
}
}
if (err.code === 'EACCES') {
log.debug({method:'create', line:107, socket: this.opts.path, msg:'directory does not exist...creating'})
await mkdir(path.dirname(this.opts.path))
log.debug({method:'create', line:109, socket: this.opts.path, msg:'directory created'})
return await this._listen(this.opts)
}
// otherwise fatally exit
log.error({method:'create', line:113, err:err, msg:'error creating socket'})
reject(err)
})
let [err, res] = await btc(this._listen)(this.opts)
if (err) reject(err)
this.enablePing()
resolve(res)
}) // end creeate promise
} // end create
/**
* registerPacketProcessor - Description
* @public
* @param {func} Description
*
*/
registerPacketProcessor(func) {
this._packetProcess = func
}
enablePing () {
if (this.pingInterval > 499) {
this._ping = setInterval( async () =>{
if (this.clients.length > 0) this.push({pingInterval:this.pingInterval},'ping')
},this.pingInterval)
}
}
disablePing() {
clearInterval(this._ping)
}
/**
* push - pushes a supplied UCI object packet to all connected clients
*
* @param {object} packet Description
* @param {string} id the header id string of the pushed packet, default: 'pushed'
*
*/
async push(packet={},id) {
packet._header = {id: id || 'pushed'}
if (this.clients.length > 0) {
log.debug({method:'push', line:142, id:packet._header.id, opts: this.opts, packet: packet, msg:'pushing a packet to all connected consumers'})
this.clients.forEach(async client => {
if (client.writable) {
let [err] = await btc(this._send)(client,packet)
if (err) log.error({msg:err, error:err})
}
})
} else {
log.debug({method:'push', line:165, id:packet._header.id, opts: this.opts, packet: packet, msg:'no connected consumers, push ignored'})
}
}
removeClient (id) {
let index = this.clients.findIndex(client => {return client.id === id })
let client = this.clients[index]
client.removeAllListeners()
client.stream.removeAllListeners()
this.clients.splice(index,1)
log.warn({msg:'client removed from tracking',id:id, curClientCount:this.clients.length})
}
async authenticateClient(client) {
// let server = this
return new Promise(async function(resolve, reject) {
// when consumer gets the handshake they must follow with authentication
client.stream.on('message', authenticate.bind(this,client))
let [err] = await btc(this._send)(client,{_handshake: true, id:client.id})
if (err) {
log.error({msg:'error in handshake send', error:err})
reject(err)
}
async function authenticate (client,packet) {
log.info({msg:`authentication packet from client ${client.id}`, packet:packet})
client.stream.removeAllListeners('message')
if (!packet._authenticate) reject('first client packet was not authentication')
else {
let [err, res] = await btc(this._authenticate)(packet)
client.authenticated = this.allowAnonymous ? 'anonymous' : (err || res)
client.name = packet.clientName
packet.authenticated = client.authenticated
await this._send(client,packet) // send either way
if (err && !this.allowAnonymous) reject(client.authenticated)
else resolve(client.authenticated)
}
}
}.bind(this))
}
// private methods
// default authenticator
async _authenticate (packet) {
if (this.tokens.indexOf(packet.token) === -1) return Promise.reject(false)
return true
}
async _listen(opts) {
return super.listen(opts, async (err, res) => {
if (err) return Promise.reject(err)
// this gets called for each client connection and is unique to each
this.on('connection', async socket => {
log.debug({method:'_listen', line:167, msg:'new consumer connecting'})
socket.id = ++this.nextClientID // server assigned ID
socket.authenticated = false
this.clients.push(socket) // add client to list
const stream = new JSONStream()
socket.stream = stream
socket.setKeepAlive(this.keepAlive,3000)
// add listeners
const clientCloseHandler = (id) => {
log.warn({msg:'client connection closed during listen,',id:id})
this.removeClient(id)
}
socket.on('close', clientCloseHandler.bind(this,socket.id) )
socket.on('error', (err) => {
log.error({msg:'client connection error during listen',error:err})
// TODO do more handling than just logging
})
socket.on('data', stream.onData) // send data to
stream.on('error', (err) => {
log.error({msg:'client-socket stream error during listen',error:err})
// TODO do more handling than just logging
})
let [err] = await btc(this.authenticateClient)(socket)
if (!this.allowAnonymous) {
if (err) {
socket.end()// abort new connection socket, cleanup, remove listeners
this.removeClient(socket.id)
return
}
}
// all's set main message processor
stream.on('message', messageProcess.bind(this, socket))
if (this.opts.conPacket) {
this.opts.conPacket._header = { id: 'pushed' }
log.debug({method:'_listen', line:171, conPacket: this.opts.conPacket, msg:'pushing a preset command to just connected consumer'})
this._send(socket,this.opts.conPacket) // send a packet command on to consumer on connection
}
// that's it. Connection is active
async function messageProcess(client, packet) {
log.info({method:'_listen', line:179, packet: packet, client:client.name, msg:'incoming packet on socket side'})
let 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 = {}
res._header.request = clone(packet, false)
res._header.responder = { name: this.name, instanceID: this.id }
res._header.socket = this.address()
if (!res.cmd) res.cmd = 'reply' // by default return command is 'reply'
let [err] = await btc(this._send)(client,res)
if (err) log.error({msg:err, error:err})
} // end message process
}) // end connecttion handler
log.info({method:'_listen', line:255, opts: this.opt, msg:'socket server created and listening'})
return res
}) // end super listen callback
} // end listen
// call when socket server is going down
async _destroy() {
log.fatal({method:'_destroy', line:217, msg:'closing down socket server'})
// this.push()
clearInterval(this._ping)
await this.close()
this.clients.forEach(client => {
client.removeAllListeners()
client.stream.removeAllListeners()
})
log.debug({method:'_destroy', line:219, msg:'all connections closed....exiting'})
process.exit()
}
// default packet process, just a simple echo, override with registerPacketProcessor
async _packetProcess(packet) {
return new Promise(resolve => {
resolve(packet)
})
}
async _send(client, packet) {
log.debug({msg:`sending to client:${client.id}`, packet:packet})
return new Promise(async (resolve, reject) => {
let [err,ser] = await btc(client.stream.serialize)(packet)
if (err) reject('unable to serialze the packet')
const cb = () => resolve('packet written to socket stream')
if (!client.write(ser)) {
client.once('drain', cb)
} else {
process.nextTick(cb)
}
})
}
} // end class
} // end function makeSocketClass