Class: Tina4::SessionHandlers::RedisHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/tina4/session_handlers/redis_handler.rb

Overview

Redis-backed session handler. Prefers the redis gem when it is installed (parity with the Python redis-py and Node redis-npm handlers); otherwise speaks raw RESP over a TCP socket via RespClient — zero dependencies, so a Tina4 app stores sessions in Redis with no extra gem.

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ RedisHandler

Connection is configured from TINA4_SESSION_REDIS_* env vars (parity with Python's RedisSessionHandler and the Ruby ValkeyHandler shape) so TINA4_SESSION_BACKEND=redis can actually be pointed at a server by env. An explicit constructor option always wins over the environment.



16
17
18
19
20
21
22
23
24
25
# File 'lib/tina4/session_handlers/redis_handler.rb', line 16

def initialize(options = {})
  @prefix = options[:prefix] || "tina4:session:"
  @ttl = options[:ttl] || 86400
  @host = options[:host] || ENV["TINA4_SESSION_REDIS_HOST"] || "localhost"
  @port = options[:port] || (ENV["TINA4_SESSION_REDIS_PORT"] ? ENV["TINA4_SESSION_REDIS_PORT"].to_i : 6379)
  @db = options[:db] || (ENV["TINA4_SESSION_REDIS_DB"] ? ENV["TINA4_SESSION_REDIS_DB"].to_i : 0)
  @password = options[:password] || ENV["TINA4_SESSION_REDIS_PASSWORD"]
  @redis = build_gem_client
  @resp = @redis ? nil : RespClient.new(host: @host, port: @port, password: @password, db: @db)
end

Instance Method Details

#cleanupObject



51
52
53
# File 'lib/tina4/session_handlers/redis_handler.rb', line 51

def cleanup
  # Redis handles TTL automatically
end

#destroy(session_id) ⇒ Object



46
47
48
49
# File 'lib/tina4/session_handlers/redis_handler.rb', line 46

def destroy(session_id)
  key = "#{@prefix}#{session_id}"
  @redis ? @redis.del(key) : @resp.del(key)
end

#read(session_id) ⇒ Object



27
28
29
30
31
32
33
34
# File 'lib/tina4/session_handlers/redis_handler.rb', line 27

def read(session_id)
  key = "#{@prefix}#{session_id}"
  data = @redis ? @redis.get(key) : @resp.get(key)
  return nil unless data
  JSON.parse(data)
rescue JSON::ParserError
  nil
end

#write(session_id, data) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/tina4/session_handlers/redis_handler.rb', line 36

def write(session_id, data)
  key = "#{@prefix}#{session_id}"
  payload = JSON.generate(data)
  if @redis
    @redis.setex(key, @ttl, payload)
  else
    @resp.setex(key, @ttl, payload)
  end
end