uci-base/examples/duplex.js

91 lines
2.2 KiB
JavaScript

/*
simple generic consumer sending an ack
*
*/
import Base from '../src/base'
const delay = time => new Promise(res=>setTimeout(()=>res(),time))
const NAME = 'example-duplex'
let opts={name:NAME+process.env.NAME, id:NAME+process.env.NAME}
let duplex = new Base(opts)
;
(async () => {
//
duplex.on('log',ev => {
switch (ev.level) {
// case 'warning':
// case 'error':
case 'testing':
// case 'fatal':
console.log(ev.level.toUpperCase(),'\n',ev)
break
}
})
// example return processor using a namespace, will take precidence over default and root namespaces
duplex.cmds = {
reply: (packet) => {
// console.log('------REPLY--via cmds namespace----')
// console.log(packet)
},
error: (packet) => {
console.log('------Error--via cmds namespace----')
console.log(packet)
}
}
duplex.addNamespace('cmds','c') // comment this out to process via root namespace
duplex.registerSocket(opts.name+'c','c','n',{name:opts.name, path:'pipe-'+process.env.DUPLEX_NAME})
duplex.registerSocket(opts.name+'s','s','n',{ path:'pipe-'+process.env.NAME, duplex:NAME+process.env.DUPLEX_NAME})
duplex.ready.addObserver(opts.name+':another-state')
duplex.on(opts.name+':process', (ready, packet) => {
console.log(opts.name,'process state changed', ready)
})
duplex.ready.subscribe(async ready=>{
console.log(opts.name,'overall ready state change', ready)
})
duplex.ready.makeObserver(NAME+process.env.DUPLEX_NAME+':process')
.subscribe(ready=>console.log(NAME+process.env.DUPLEX_NAME+':process','was observed as',ready))
let res = await duplex.init()
if (res.error) {
console.log('errors during init')
process.kill(process.pid, 'SIGTERM')
}
setTimeout(()=>{
duplex.emit(opts.name+':another-state',true)
console.log(opts.name,'setting test observer to true')
},2000)
process.once('SIGINT', function() {
console.log('Caught interrupt signal')
duplex.removeAllListeners()
process.exit()
})
process.once('SIGUSR2', async () => {
duplex.removeAllListeners()
process.exit()
})
})().catch(err => {
console.error('FATAL: UNABLE TO START SYSTEM!\n',err)
duplex.removeAllListeners()
process.kill(process.pid, 'SIGTERM')
})