brianhempel/mongo_session_store — pull request #29 by mru2 (2014-06-06 10:42:35+00:00)
Title: Always generate a new session_id when no session is found

This pull request makes sure that when a session is not found in the database, the new one which is instanciated uses a new unique id, and returns it to the client.

It solves a bug with multi-process apps and session cleaners :

* A user is inactive for a long period of time.
* His MongoDB session is destroyed to free space, but the client still has a cookie with his former session_id.
* The user visits the app again and send multiple requests which are routed to separate processes.
* All processes will try to find the session with the cookie's session_id.
* When not found, they will instanciate a new empty one with the given id, and try to persist it at the end of the request.
* If MongoDB uses the acknowledged write concern, the mongo client will raise an error like : `Mongo::OperationFailure: 11000: E11000 duplicate key error index: rails.sessions.$_id_ dup key: { : "BBQBDKbwO9uZSmbIpZDfdLt2K1c" }`
* If MongoDB uses the unacknowledged write concern, one of the sessions will not be persisted

This pull request does not solve the race condition itself : the last returning response to the client will set its new session_id. If other sessions are generated simultaneously, they will no be accessed again. However, when MongoDB uses the acknowledged write concern, an error will not be raised.