/
pool.rb
82 lines (72 loc) · 2.14 KB
/
pool.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# frozen_string_literal: true
# AUTHOR: blink <blinketje@gmail.com>; blink#ruby-lang@irc.freenode.net
# THANKS:
# apeiros, for session id generation, expiry setup, and threadiness
# sergio, threadiness and bugreps
require 'rack/session/abstract/id'
require 'thread'
module Rack
module Session
# Rack::Session::Pool provides simple cookie based session management.
# Session data is stored in a hash held by @pool.
# In the context of a multithreaded environment, sessions being
# committed to the pool is done in a merging manner.
#
# The :drop option is available in rack.session.options if you wish to
# explicitly remove the session from the session cache.
#
# Example:
# myapp = MyRackApp.new
# sessioned = Rack::Session::Pool.new(myapp,
# :domain => 'foo.com',
# :expire_after => 2592000
# )
# Rack::Handler::WEBrick.run sessioned
class Pool < Abstract::Persisted
attr_reader :mutex, :pool
DEFAULT_OPTIONS = Abstract::ID::DEFAULT_OPTIONS.merge drop: false
def initialize(app, options = {})
super
@pool = Hash.new
@mutex = Mutex.new
end
def generate_sid
loop do
sid = super
break sid unless @pool.key? sid
end
end
def find_session(req, sid)
with_lock(req) do
unless !sid.nil? and session = @pool[sid.public_id]
sid, session = generate_sid, {}
@pool.store sid.public_id, session
end
[sid, session]
end
end
def write_session(req, session_id, new_session, options)
with_lock(req) do
@pool.store session_id.public_id, new_session
session_id
end
end
def delete_session(req, session_id, options)
with_lock(req) do
@pool.delete(session_id.public_id)
if options[:drop]
NullSessionId.new
else
generate_sid
end
end
end
def with_lock(req)
@mutex.lock if req.multithread?
yield
ensure
@mutex.unlock if @mutex.locked?
end
end
end
end