dudleycarr / nsqjs

NodeJS client library for NSQ
https://nsqjs.com
MIT License
557 stars 76 forks source link

Handle "uncaughtException: write after end" #369

Closed bsdelf closed 2 years ago

bsdelf commented 2 years ago

We found following log on server:

{"code":"ERR_STREAM_WRITE_AFTER_END"},"level":"ERROR","message":"uncaughtException: write after end\nError [ERR_STREAM_WRITE_AFTER_END]: write after end\n    at writeAfterEnd (_stream_writable.js:266:14)\n    at Socket.Writable.write (_stream_writable.js:315:5)\n    at NSQDConnection._flush (/var/app/node_modules/nsqjs/lib/nsqdconnection.js:434:19)

the related code block in nsqjs is:

427   _flush () {
428     if (this.writeQueue.length > 0) {
429       const data = Buffer.concat(this.writeQueue)
430
431       if (this.deflater) {
432         this.deflater.write(data, () => this.conn.write(this.deflater.read()))
433       } else {
434         this.conn.write(data)
435       }
436     }
437
438     this.writeQueue = []
439   }

As nodejs documented (https://nodejs.org/api/errors.html#err_stream_write_after_end ), the error is caused by writing to an ended stream.

Since the uncaught exception is raised in nsqjs, there is no chance for our application to handle it gracefully. So I'm thinking, is it possible to add a try-catch block in nsqjs to handle this kind of error properly?

dudleycarr commented 2 years ago

Thanks for reporting. The state should be guarded against so I'll investigate. What version of nsqjs are you using?

bsdelf commented 2 years ago

We are using:

dudleycarr commented 2 years ago

I believe this issue has been resolved in 0.13.0 with the removal of setImmediate use in write: https://github.com/dudleycarr/nsqjs/commit/219888385f51c20bcacbdc588f576d32253accdc

Could you please upgrade to 0.13.0 and see if that resolves the issue?

bsdelf commented 2 years ago

Thanks, unfortunately our property code is freezed at this moment, I have to try it in next release.

Seems it's OK to close this issue now, if it happens again I will reopen it.