Class: Parse::Webhooks::ReplayProtection::LruCache

Inherits:
Object
  • Object
show all
Includes:
MonitorMixin
Defined in:
lib/parse/webhooks/replay_protection.rb

Overview

Bounded, thread-safe LRU keyed on a digest string with per-entry insertion timestamps. Used only by ReplayProtection; intentionally private to avoid leaking another caching primitive into the public API. Ruby Hashes preserve insertion order, so a delete+insert on touch is enough to maintain LRU ordering.

Instance Method Summary collapse

Constructor Details

#initialize ⇒ LruCache

Returns a new instance of LruCache.



202
203
204
205
# File 'lib/parse/webhooks/replay_protection.rb', line 202

def initialize
  super()
  @entries = {}
end

Instance Method Details

#clear ⇒ Object



231
232
233
# File 'lib/parse/webhooks/replay_protection.rb', line 231

def clear
  synchronize { @entries.clear }
end

#record(key, max_size) ⇒ Object



221
222
223
224
225
226
227
228
229
# File 'lib/parse/webhooks/replay_protection.rb', line 221

def record(key, max_size)
  synchronize do
    @entries.delete(key)
    @entries[key] = Time.now.to_i
    while @entries.size > max_size
      @entries.shift
    end
  end
end

#seen?(key, window_seconds) ⇒ Boolean

Returns:

  • (Boolean)


207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/parse/webhooks/replay_protection.rb', line 207

def seen?(key, window_seconds)
  synchronize do
    ts = @entries[key]
    return false unless ts
    if Time.now.to_i - ts > window_seconds
      @entries.delete(key)
      return false
    end
    @entries.delete(key)
    @entries[key] = ts # touch
    true
  end
end

#size ⇒ Object



235
236
237
# File 'lib/parse/webhooks/replay_protection.rb', line 235

def size
  synchronize { @entries.size }
end