moleculerjs / moleculer

:rocket: Progressive microservices framework for Node.js
https://moleculer.services/
MIT License
6.17k stars 587 forks source link

moleculer crash if ioredis can not change state to "ready" #1257

Closed 0x0a0d closed 10 months ago

0x0a0d commented 1 year ago

Today, I accidentally entered the wrong Redis server address, which was actually another TCP service address, resulting in the application crashing After hours of debugging, I see that It was happen because on the Redis transporter class https://github.com/moleculerjs/moleculer/blob/6a58b174e75038b076741f17bd3f0a726b4bea07/src/transporters/redis.js#L45 and https://github.com/moleculerjs/moleculer/blob/6a58b174e75038b076741f17bd3f0a726b4bea07/src/transporters/redis.js#L51 "connect" event not tell the redis client is "ready", just emits when a connection is established to the Redis server. @icebob you can try with this code

const net = require('net')
const { ServiceBroker } = require('moleculer')

const localhost = '127.0.0.1'
const server = net.createServer()
server.on('connection', socket => {
  socket.end()
})
server.listen(0, localhost, () => {
  const broker = new ServiceBroker({
    transporter: `redis://${localhost}:${server.address().port}}`
  })
  broker.start().then(() => {
    console.log('Broker started.')
  }).catch(err => {
    console.error(err)
  })
})

After a moment, it will crash with error image

I found just 1 way to keep moleculer does not crash that is changing line 45,51 of redis transporter class to

// line 45
clientSub.on("ready", () => { // was: clientSub.on("connect", () => {
// line 51
clientPub.on("ready", () => { // was: clientPub.on("connect", () => {
icebob commented 10 months ago

Nice catch