Module: RobustServerSocket::Cacher

Defined in:
lib/robust_server_socket/cacher.rb

Overview

rubocop:disable Metrics/ModuleLength

Defined Under Namespace

Classes: RedisConnectionError

Constant Summary collapse

CLOCK_SKEW_MS =
30_000

Class Method Summary collapse

Class Method Details

.atomic_validate_and_log(key, ttl, timestamp_ms, expiration_time) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/robust_server_socket/cacher.rb', line 10

def atomic_validate_and_log(key, ttl, timestamp_ms, expiration_time)
  current_ms = Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)
  redis.with do |conn|
    conn.eval(lua_atomic_validate_and_log, keys: [key],
                                           argv: [ttl, timestamp_ms, expiration_time, current_ms])
  end
rescue ::Redis::BaseConnectionError => e
  handle_redis_error(e, 'atomic_validate_and_log')
  raise RedisConnectionError, "Failed to validate token: #{e.message}"
end

.clear_redis_pool_cache!Object

Clear cached Redis connection pool (useful for hot reloading in development)



57
58
59
# File 'lib/robust_server_socket/cacher.rb', line 57

def clear_redis_pool_cache!
  @redis = nil
end

.get(key) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/robust_server_socket/cacher.rb', line 32

def get(key)
  redis.with do |conn|
    conn.get(key)
  end
rescue ::Redis::BaseConnectionError => e
  handle_redis_error(e, 'get')
  nil
end

.health_checkObject



41
42
43
44
45
46
47
# File 'lib/robust_server_socket/cacher.rb', line 41

def health_check
  redis.with do |conn|
    conn.ping == 'PONG'
  end
rescue ::Redis::BaseConnectionError
  false
end

.incr_sliding_window_count(key, window_seconds) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/robust_server_socket/cacher.rb', line 21

def incr_sliding_window_count(key, window_seconds)
  now_ns = Process.clock_gettime(Process::CLOCK_REALTIME, :nanosecond)
  redis.with do |conn|
    conn.eval(lua_sliding_window, keys: [key],
                                  argv: [now_ns, window_seconds * 1_000_000_000, window_seconds, now_ns.to_s])
  end
rescue ::Redis::BaseConnectionError => e
  handle_redis_error(e, 'incr_sliding_window_count')
  raise RedisConnectionError, "Failed to count sliding window: #{e.message}"
end

.with_redis(&block) ⇒ Object



49
50
51
52
53
54
# File 'lib/robust_server_socket/cacher.rb', line 49

def with_redis(&block)
  redis.with(&block)
rescue ::Redis::BaseConnectionError => e
  handle_redis_error(e, 'with_redis')
  raise RedisConnectionError, "Redis operation failed: #{e.message}"
end