It seems the await()
method loses context:
public static action() {
session.put("key", "value");
await(someAsyncCall());
// Now, for some reason the session doesn't have "key"
}
Is this a known issue? Any workarounds?
It seems the await()
method loses context:
public static action() {
session.put("key", "value");
await(someAsyncCall());
// Now, for some reason the session doesn't have "key"
}
Is this a known issue? Any workarounds?
Workaround for Play 1.2.5, if all that is required is to persist the session id, use the following in place of direct call to await(...)
The code above is a workaround for the issue outlined here where a new session is created after the await(..) call instead of reusing the existing session. A reference to the original session id is used to reset the session id after the await call (i.e. session.put("___ID", sessionId) resets the session id to its pre-await value).
That is unfortunate. Since session is a thread local variable it does not get passed between new threads (which happens in your example). What is misleading and surprising, is that when the code resumes after the await method there is a session variable (but it is a different instance).
I would say this is a bug - I'd expect the session context to be maintained around the await call.
That said, I understand why this is tricky. When you use await, you are actually writing code in at least three threads. The before part, the job/async call, and the after part. Trace into it, it is kind of amazing.
Even so, I agree that the session state for the request should be maintained, so I suggest you file an issue: https://play.lighthouseapp.com/projects/57987-play-framework/tickets/new
Below is a workaround that copies the session map by passing it through the async call. You could write a simple wrapper Job that always does this.
EDIT:
Alternatively, you could store the session map using Cache.set() - this is perhaps cleaner than passing it around.
As an aside, I seldom use session to store user data. Each cookie (which is what a session is in play) slows down your http requests (read about how cookies work). What I prefer to do is create a map on the server side using the Cache (eg Cache.set(session.getId(),userDataMap)). Clearly each use case may be different, but I prefer this way to maintain user state.