First Contribution to Open Source

August 10, 2011

Most of the apps I’ve built stand on the shoulder of giants. Open source projects enabled me to jump ahead of building frameworks or webservers and dive straight into building the end product. I’ve always been thankful and felt a need to give back, even in a small way. Recently (while procrastinating from exams) I’ve finally done such a thing.

I’ve recently been working on a flash card-esque site for learning kana. Using redis as the backend I proceeded to use connect-redis to implement sessions. Unfortunately this cluttered my app’s data keyspace with session data with no clear way of being able to separate the two.

Luckily enough for me redis has multiple databases to store data in separate keyspaces. All you had to do was run a select <db num> command. connect-redis even foresaw this issue and has a db option in the RedisStore constructor.

The Ugly ‘Bug’

After running the server for a while I would notice a peculiar bug. It seemed my session data kept resetting after a day or two. Inspecting the redis db I saw that my app data’s database suddenly had session data in it even though I told the RedisStore to use the session db.

Digging around I found that the node redis client doesn’t reselect db’s on reconnection. What was happening was the redis client connection was dropping randomly overnight but was able to re-connect. Good recovery, except now it’s connected to the default db 0 as per the select command docs. Fun stuff.

Working Around It

Since the issue didn’t seem conclusive at the time and this was affecting connect-redis I thought to patch it up with the following code taken from the discussion of issue 86 of node redis.

client.on("connect", function() {
  client.send_anyway = true;;
  client.send_anyway = false;

Ugly? Yes. Necessary? Unfortunately also Yes.

The client.send_anyway dictates whether commands should be enqueued onto the offline queue when the client has not connected. Since we want to select the proper db before the offline queue is executed the send_anyway needs to be set true when issuing the select command.

I added this to my existing redis connections which used other databases and patched it to connect-redis in this pull request. It was picked up by visionmedia in no time (like 2 minutes!) and merged into connect-redis for v1.0.7.

Thoughts and More Ramblings

It was quite satisfying contributing to this library even if though I did almost no work of my own. Although this was a quick patch to ensure the connect-redis always used the db it was passed, a cleaner solution stemming within node redis would be best. Maybe I’ll take my time and invest in providing such an option in the future.

Click to load comments