Rack::Session::Memcache and nested Hashes stored in the session

39 views
Skip to first unread message

miguelgodinho

unread,
Nov 15, 2009, 7:07:39 PM11/15/09
to Rack Development
Using sinatra+thin I could not store nested hashes in a memcache based
session, although Pool gives no problems.
Looking at the code, a simple substitution

76c76
< old_session = new_session.instance_variable_get('@old') ||
{}
---
> old_session = session.instance_variable_get('@old') || {}

is solving the experienced problem.

looking at the private method 'merge_sessions' it is clear why the
problem happens with Memcache and not with Pool (as @pool is an
instance variable)

Unfortunately I cannot not fully understand the module's logic and
would like to know if the above detailed substitution has any 'side-
effects'.

Thanks!
Miguel

reverri

unread,
Nov 24, 2009, 1:43:52 AM11/24/09
to Rack Development
Hi Miguel,

I noticed the same problem while trying implement my own custom
session handler. The old_session and new_session variables were always
equal when evaluating set_session.

In the case of Rack::Session::Pool it looks like @pool holds a
reference to the session hash rather than a copy. When the session is
pulled from pool (@pool[session_id]) the object is the same as
new_session.

I ended up just storing the new_session directly without any kind of
merging but I am not sure if there will be any negative consequences.
Can someone provide a scenario where merge_sessions is necessary?

Thanks,
Dan

Scytrin dai Kinthra

unread,
Nov 24, 2009, 2:30:55 AM11/24/09
to rack-...@googlegroups.com
In a non-threaded environment, no. However if an application, or
applications, write two different keys in two different threads, then
there is the possibility of data loss, same reason for the mutexes.

After re-examining the code, the reason why merge_sessions was failing
when comparing nested hashes is because @old is a shallow copy of the
session when it was originally requested. The reason why the two or
three patches I've seen work is essentially a short circuit that
suffers the possible outcome presented above.

I am reviewing the code and examining possible ways to better resolve an update.
--
stadik.net
Reply all
Reply to author
Forward
0 new messages