rvagg/node-levelup — pull request #248 by nolanlawson (2014-05-26 03:44:58+00:00)
Title: Fix race condition on read stream's self._iterator

This is a really tricky bug to reproduce, but when testing PouchDB as a client against PouchDB as a server, I can reproduce it pretty consistently. Details here: https://github.com/nick-thompson/express-pouchdb/issues/38.

Since it's a race condition, I don't think there's a unit test I can write that can catch it, but just mentally walking through the code, it seems to me that what happens is this:

1. ReadStream constructor is called
2. ReadmStream `_cleanup` is called, but `self._iterator` hasn't been set yet (hence TypeError)
3. `self._iterator = iteratorFactory(self._options)` is called within the `this._db.once('ready')` callback, so now `self._iterator` is set, but it's too late

You can repro it yourself by running the PouchDB tests in question. Sorry for the messy steps, but here they are:

```
git clone --depth 1 -b 2281 https://github.com/pouchdb/pouchdb.git
git clone --depth 1 https://github.com/nick-thompson/pouchdb-server.git
git clone --depth 1 -b working-version https://github.com/nolanlawson/express-pouchdb.git
cd pouchdb && npm install
cd ../express-pouchdb && npm link ../pouchdb
cd ../pouchdb-server && npm link ../express-pouchdb
cd ../pouchdb && npm link ../pouchdb-server
npm install
SERVER=pouchdb-server npm test
```

Note that the tests still fail after the fix, but that's due to another bug on our end; nothing for you folks to worry about. :)

I'm using Node v0.10.28.