Class: AxHub::Data::SchemaCache

Inherits:
Object
  • Object
show all
Defined in:
lib/axhub_sdk/data/schema_cache.rb

Defined Under Namespace

Classes: Entry

Instance Method Summary collapse

Constructor Details

#initialize(max_entries: nil, ttl_ms: nil, negative_ttl_ms: nil) ⇒ SchemaCache

Returns a new instance of SchemaCache.



29
30
31
32
33
34
# File 'lib/axhub_sdk/data/schema_cache.rb', line 29

def initialize(max_entries: nil, ttl_ms: nil, negative_ttl_ms: nil)
  @store = {}
  @max_entries = [1, max_entries.nil? ? DEFAULT_SCHEMA_CACHE_MAX_ENTRIES : max_entries].max
  @ttl_ms = [1, ttl_ms.nil? ? DEFAULT_SCHEMA_CACHE_TTL_MS : ttl_ms].max
  @negative_ttl_ms = [0, negative_ttl_ms.nil? ? DEFAULT_SCHEMA_CACHE_NEGATIVE_TTL_MS : negative_ttl_ms].max
end

Instance Method Details

#get(key) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/axhub_sdk/data/schema_cache.rb', line 40

def get(key)
  entry = @store[key]
  return nil if entry.nil?

  if entry.expires_at <= _now_ms
    @store.delete(key)
    return nil
  end
  # refresh recency: move to end (delete + reinsert)
  @store.delete(key)
  @store[key] = entry
  entry.schema
end

#get_or_set(key, fresh: nil, ttl_ms: nil) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/axhub_sdk/data/schema_cache.rb', line 70

def get_or_set(key, fresh: nil, ttl_ms: nil)
  unless fresh
    cached = get(key)
    return cached unless cached.nil?
  end
  previous = @store[key]
  begin
    schema = yield
  rescue StandardError => e
    if !previous.nil? && @negative_ttl_ms.positive? && _transient_server_error?(e)
      @store.delete(key)
      @store[key] = Entry.new(schema: previous.schema, expires_at: _now_ms + @negative_ttl_ms)
    end
    raise
  end
  set(key, schema, ttl_ms)
  schema
end

#invalidate(key = nil) ⇒ Object



61
62
63
64
65
66
67
68
# File 'lib/axhub_sdk/data/schema_cache.rb', line 61

def invalidate(key = nil)
  if key.nil?
    @store.clear
  else
    @store.delete(key)
  end
  nil
end

#set(key, schema, ttl_ms = nil) ⇒ Object



54
55
56
57
58
59
# File 'lib/axhub_sdk/data/schema_cache.rb', line 54

def set(key, schema, ttl_ms = nil)
  @store.delete(key)
  @store[key] = Entry.new(schema: schema, expires_at: _now_ms + [1, ttl_ms.nil? ? @ttl_ms : ttl_ms].max)
  _evict_overflow
  nil
end

#sizeObject



36
37
38
# File 'lib/axhub_sdk/data/schema_cache.rb', line 36

def size
  @store.size
end