uci-socket/src/socket.mjs

114 lines
3.5 KiB
JavaScript

import { Server } from 'net'
import { unlink as fileDelete } from 'fs'
import btc from 'better-try-catch'
import _ON_DEATH from 'death' //this is intentionally ugly
import JSONStream from './json-stream'
import logger from '../../uci-logger/src/logger'
let log = {}
const LOG_OPTS = {
repo:'uci-socket',
npm:'@uci/socket',
file:'src/socket.mjs',
class:'Socket',
id:this.id,
instance_created:new Date().getTime()
}
const DEFAULT_PIPE = (process.env.SOCKETS_DIR || __dirname) + '/uci-socket.sock'
export default class Socket extends Server {
constructor (opts={}) {
super()
this.id = opts.id || opts.name || 'socket:'+ new Date().getTime()
if (!opts.path && opts.np) opts.path = DEFAULT_PIPE
if (!opts.path) {
opts.host = opts.host || '0.0.0.0'
opts.port = opts.port || 8080
} else opts.np = true
this.opts = opts
//self bindings
this._listen = this._listen.bind(this)
this.create = this.create.bind(this)
log = logger.child(LOG_OPTS) //create instance logger set LOG_OPTS above
} // end constructor
async create () {
return new Promise( async (resolve,reject) => {
// couple ways to kill socket process when needed
_ON_DEATH( async () => {
log.info('\nhe\'s dead jim')
await this._destroy()
})
process.once('SIGUSR2', async () => {
await this._destroy
process.kill(process.pid, 'SIGUSR2')
})
this.on('error', async (err) => {
// recover from socket file that was not removed
if (err.code === 'EADDRINUSE') {
if (this.opts.np) { // if TCP socket should already be dead
log.info({socket: this.opts.path}, 'already exists...deleting')
await fileDelete(this.opts.path)
return await this._listen(this.opts)
}
}
// otherwise fatally exit
log.info(err, 'creating socket')
reject(err)
})
let [err, res] = await btc(this._listen)(this.opts)
if (err) reject(err)
resolve(res)
}) // end creeate promise
} // end create
registerPacketProcessor (func) {
this._packetProcess = func
}
async _listen (opts) {
super.listen(opts, async (err, res) => {
if (err) return err
// this gets called for each client connection and is unique to each
this.on('connection', async (socket) => {
const stream = new JSONStream()
log.info('new consumer connecting sending handshake')
socket.write(await stream.serialize({'_handshake':true}))
socket.on('data', stream.onData)
// TODO need to start error listener for stream so errors can be processed
stream.on('message', messageProcess.bind(this))
async function messageProcess (packet) {
// console.log('before processing',packet)
let processed = await this._packetProcess(packet)
if (!processed) processed = { error: 'packet command function likely did not return a promise', packet:packet}
// console.log('after processing',processed)
socket.write(await stream.serialize(processed))
}
}) // end connecttion consumer
log.info({opts: this.opts},'socket created')
return res
}) // end super listen callback
} // end listen
async _destroy () {
log.info('closing down socket')
await this.close()
log.info('all connections closed....exiting')
process.exit()
}
// default packet process, just a simple echo
_packetProcess (packet) {
packet.res='echoed'
return packet
}
} // end class