Skip to content

Commit

Permalink
#41 Discard old session from pool when renewing session id - to prese…
Browse files Browse the repository at this point in the history
…rve pool size . Thanks @bjet007
  • Loading branch information
testinfected committed Feb 2, 2016
1 parent e88ef69 commit f88a4e5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
10 changes: 6 additions & 4 deletions src/main/java/com/vtence/molecule/session/SessionPool.java
Expand Up @@ -63,6 +63,8 @@ public Session load(String id) {

public String save(Session data) {
if (data.invalid()) throw new IllegalStateException("Session invalidated");
if (shouldRenew(data)) destroy(data.id());

String sid = sessionId(data);
Session session = makeSession(sid, data);
Instant now = now();
Expand All @@ -77,6 +79,10 @@ public String save(Session data) {
return sid;
}

private boolean shouldRenew(Session data) {
return data.exists() && renew;
}

public void destroy(String sid) {
if (sessions.remove(sid) != null) listener.sessionDropped(sid);
}
Expand All @@ -102,10 +108,6 @@ private Session makeSession(String sid, Session data) {
return session;
}

private boolean contains(String id) {
return sessions.containsKey(id);
}

private boolean validate(Session session) {
if (expired(session) || stale(session) || tooOld(session)) session.invalidate();
return !session.invalid();
Expand Down
25 changes: 20 additions & 5 deletions src/test/java/com/vtence/molecule/session/SessionPoolTest.java
Expand Up @@ -64,14 +64,29 @@ public class SessionPoolTest {

@Test
public void
renewsSessionIdsOnSave() {
canRenewExistingSessionsIdsOnSave() {
pool.renewIds();

Session data = new Session();
String old = pool.save(data);
assertThat("old id", old, equalTo("1"));

Session session = pool.load(old);
String newId = pool.save(session);

assertThat("renewed id", newId, equalTo("2"));
assertThat("old session", pool.load(old), nullValue());
assertThat("new session", pool.load(newId), notNullValue());
}

@Test
public void
renewalHandlesNewSessionsGracefully() {
pool.renewIds();

Session data = new Session();
String id = pool.save(data);
assertThat("original id", id, equalTo("1"));
Session session = pool.load(id);
pool.clear();
assertThat("renewed id", pool.save(session), equalTo("2"));
assertThat("id", id, equalTo("1"));
}

@Test
Expand Down

0 comments on commit f88a4e5

Please sign in to comment.