import to from 'await-to-js' import logger from '@uci-utils/logger' let log = logger({ package: 'base',file:'processing.js'}) // this._processing refers to this module/hash // processing errors that are caught should be sent back to consumer in packets with :error property // but they might also throw local errors/execptions so they should bubble up here and get caught and logged // messaging errors on socket will not be fatal to the entire socket server // common processor, will call based on type s or c the ones below const processor = async function (packet,socket) { let [err,res] = await to(_process[this.getSocket(socket).type].bind(this)(packet,socket)) if (err) { let error = {error:err, socket:socket, packet:packet, function:'processor', line: 15, msg:'some possibly unhandled badness happened during packet processing'} log.error(error) if (process.env.UCI_SHOW_UNHANDLED==='true') console.log(error) } else return res } export { processor, defaultCmds, namespaces } // default processors for socket/server and consumer/client const _process = { s: async function (packet,socket) { if (!packet.cmd) return {error: 'no command (cmd:) in packet for socket', packet: packet } // this call will search the namespace and envoke a function and return a repsonse packet let response = await this._callCmdFunc(packet,socket); if(response!=='failed') return response return {error: 'no socket processing function supplied for command', packet: packet } }, c: async function (packet,socket) { // the the end of life for a consumer packet that has been sent and returned or a packet that was pushed. if (packet.error) return await this._c.error(packet) if (packet.cmd) { let response = await this._callCmdFunc(packet,socket); if(response!=='failed') return response packet = {error:'no consumer reply processing function supplied for command',packet:packet} this._c.error(packet) } else { packet = {error:'[consumer] no command in reply packet',packet:packet} return await this._c.error(packet) } } } const namespaces = { s: ['_s'], c: ['_c'], cn: ['cn'], ct: ['ct'], sn: ['sn'], st: ['st'], cm: ['cm'], sm: ['sm'], sw: ['sw'], } /* * * Default packet command processing functions * */ const defaultCmds ={ s:{ echo: async packet => { packet.processed = true packet.info = 'default socket echo' return packet }, // add sedning along an ack to any consumers and or pushing to other sockets on this device ack: async packet => { packet.cmd = 'reply' packet.ack = true packet.info = 'this is the base default ack, superceed in your extended class' return packet } }, c:{ error: function (packet) { if (process.env.UCI_ENV==='dev') log.error({error:packet.error, packet:packet, msg:'==========Consumer Sent Packet returned with ERROR ========='}) }, reply: function(packet) { if (process.env.UCI_ENV==='dev') log.debug({packet:packet, msg:'====Packet returned from socket - debug default reply logger==='}) } } }