Better detection of stream exhaustion.

Fixes an issue where we'd fail to notice that the stream was out of bytes, and
fall into an infinite loop waiting for more bytes to upload.