Fix: emit write stream "end" after closing the stream

* This fixes a race condition where the stream may still be open
  after end is emitted and handled