Class: LruCache

Inherits:
Object
  • Object
show all
Defined in:
lib/instrumentation/postgres.rb

Overview

Copyright The OpenTelemetry Authors

SPDX-License-Identifier: Apache-2.0 A simple LRU cache for the postgres instrumentation.

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ LruCache

Rather than take a dependency on another gem, we implement a very, very basic LRU cache here. We can take advantage of the fact that Ruby hashes are ordered to always keep the recently-accessed keys at the top.

Raises:

  • (ArgumentError)


254
255
256
257
258
259
# File 'lib/instrumentation/postgres.rb', line 254

def initialize(size)
  raise ArgumentError, 'Invalid size' if size < 1

  @limit = size
  @store = {}
end

Instance Method Details

#[](key) ⇒ Object



261
262
263
264
265
266
267
268
269
270
271
# File 'lib/instrumentation/postgres.rb', line 261

def [](key)
  # We need to check for the key explicitly, because `nil` is a valid hash value.
  return unless @store.key?(key)

  # Since the cache contains the item, we delete and re-insert into the hash.
  # This guarantees that hash keys are ordered by access recency.
  value = @store.delete(key)
  @store[key] = value

  value
end

#[]=(key, value) ⇒ Object



273
274
275
276
277
278
279
# File 'lib/instrumentation/postgres.rb', line 273

def []=(key, value)
  # We remove the value if it's already present, so that the hash keys remain ordered
  # by access recency.
  @store.delete(key)
  @store[key] = value
  @store.shift if @store.length > @limit
end