Class: Rack::IdempotencyKey::RedisStore

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/idempotency_key/redis_store.rb

Overview

Redis-based store for handling idempotency keys.

This class provides methods to store, retrieve, and delete idempotency keys in a Redis database, ensuring that the same request is not processed multiple times. It supports both direct Redis instances and connection pools.

Examples:

Using a direct Redis instance

redis = Redis.new
store = Rack::IdempotencyKey::RedisStore.new(redis)

Using a Redis connection pool

redis_pool = ConnectionPool.new(size: 5, timeout: 5) { Redis.new }
store = Rack::IdempotencyKey::RedisStore.new(redis_pool)

Constant Summary collapse

DEFAULT_EXPIRATION =

5 minutes in seconds

300

Instance Method Summary collapse

Constructor Details

#initialize(store, expires_in: DEFAULT_EXPIRATION) ⇒ RedisStore

Initializes a new RedisStore instance.

Examples:

redis = Redis.new
store = Rack::IdempotencyKey::RedisStore.new(redis, expires_in: 600)


31
32
33
34
# File 'lib/rack/idempotency_key/redis_store.rb', line 31

def initialize(store, expires_in: DEFAULT_EXPIRATION)
  @store      = store
  @expires_in = expires_in
end

Instance Method Details

#get(key) ⇒ Object?

Retrieves a value from Redis by key.

The stored value is expected to be JSON-encoded and is automatically parsed. If the key does not exist, nil is returned.

Examples:

Retrieve a value from Redis

store.get("key") # => "value"

Raises:



48
49
50
51
52
53
# File 'lib/rack/idempotency_key/redis_store.rb', line 48

def get(key)
  value = with_redis { |redis| redis.get(key) }
  JSON.parse(value) unless value.nil?
rescue Redis::BaseError => e
  raise Rack::IdempotencyKey::StoreError, "#{self.class}: #{e.message}"
end

#set(key, value, ttl: expires_in) ⇒ Object?

Stores a value in Redis with an optional time-to-live (TTL).

This method ensures that the key is only set if it does not already exist (NX flag). If the key is already present, a ConflictError is raised.

Examples:

Store a new idempotency key

store.set("key", "value", ttl: 600)

Raises:



71
72
73
74
75
76
77
78
79
80
# File 'lib/rack/idempotency_key/redis_store.rb', line 71

def set(key, value, ttl: expires_in)
  with_redis do |redis|
    result = redis.set(key, value, nx: true, ex: ttl)
    raise Rack::IdempotencyKey::ConflictError unless result
  end

  get(key)
rescue Redis::BaseError => e
  raise Rack::IdempotencyKey::StoreError, "#{self.class}: #{e.message}"
end

#unset(key) ⇒ Object

Deletes a key from Redis.

This method removes the idempotency key from Redis, allowing the same request to be processed again in the future.

Examples:

Remove an idempotency key

store.unset("key")

Raises:



93
94
95
96
97
# File 'lib/rack/idempotency_key/redis_store.rb', line 93

def unset(key)
  with_redis { |redis| redis.del(key) }
rescue Redis::BaseError => e
  raise Rack::IdempotencyKey::StoreError, "#{self.class}: #{e.message}"
end