Class: Rack::Session::Redis

Inherits:
Abstract::PersistedSecure
  • Object
show all
Defined in:
lib/rack/session/redis.rb

Constant Summary collapse

DEFAULT_OPTIONS =
Abstract::ID::DEFAULT_OPTIONS.merge(
  :redis_server => 'redis://127.0.0.1:6379/0/rack:session'
)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Redis

Returns a new instance of Redis.



15
16
17
18
19
20
# File 'lib/rack/session/redis.rb', line 15

def initialize(app, options = {})
  super

  @mutex = Mutex.new
  @conn = ::Redis::Rack::Connection.new(@default_options)
end

Instance Attribute Details

#mutexObject (readonly)

Returns the value of attribute mutex.



9
10
11
# File 'lib/rack/session/redis.rb', line 9

def mutex
  @mutex
end

Instance Method Details

#delete_session(req, sid, options) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/rack/session/redis.rb', line 54

def delete_session(req, sid, options)
  with_lock(req) do
    with do |c|
      c.del(sid.public_id)
      c.del(sid.private_id)
    end
    generate_sid unless options[:drop]
  end
end

#find_session(req, sid) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rack/session/redis.rb', line 33

def find_session(req, sid)
  if req.session.options[:skip]
    [generate_sid, {}]
  else
    with_lock(req, [nil, {}]) do
      unless sid and session = get_session_with_fallback(sid)
        session = {}
        sid = generate_unique_sid(session)
      end
      [sid, session]
    end
  end
end

#generate_unique_sid(session) ⇒ Object



22
23
24
25
26
27
28
29
30
31
# File 'lib/rack/session/redis.rb', line 22

def generate_unique_sid(session)
  return generate_sid if session.empty?
  loop do
    sid = generate_sid
    first = with do |c|
      [*c.setnx(sid.private_id, session, @default_options.to_hash)].first
    end
    break sid if [1, true].include?(first)
  end
end

#threadsafe?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/rack/session/redis.rb', line 64

def threadsafe?
  @default_options.fetch(:threadsafe, true)
end

#with(&block) ⇒ Object



81
82
83
# File 'lib/rack/session/redis.rb', line 81

def with(&block)
  @conn.with(&block)
end

#with_lock(req, default = nil) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/rack/session/redis.rb', line 68

def with_lock(req, default = nil)
  @mutex.lock if req.multithread? && threadsafe?
  yield
rescue Errno::ECONNREFUSED
  if $VERBOSE
    warn "#{self} is unable to find Redis server."
    warn $!.inspect
  end
  default
ensure
  @mutex.unlock if @mutex.locked?
end

#write_session(req, sid, new_session, options = {}) ⇒ Object



47
48
49
50
51
52
# File 'lib/rack/session/redis.rb', line 47

def write_session(req, sid, new_session, options = {})
  with_lock(req, false) do
    with { |c| c.set(sid.private_id, new_session, options.to_hash) }
    sid
  end
end