Class: Seekmodo::Sdk::TenantSnapshot

Inherits:
Object
  • Object
show all
Defined in:
lib/seekmodo/sdk/tenant_snapshot.rb

Constant Summary collapse

DEFAULT_TTL_SECONDS =
300
DEFAULT_STALE_TTL_SECONDS =
60
CACHE_KEY =
"numinix.seekmodo.tenant_snapshot"
CACHE_KEY_FETCHED_AT =
"numinix.seekmodo.tenant_snapshot.fetched_at"

Instance Method Summary collapse

Constructor Details

#initialize(client, cache, ttl_seconds: DEFAULT_TTL_SECONDS, stale_after_seconds: DEFAULT_STALE_TTL_SECONDS, clock: nil) ⇒ TenantSnapshot

Returns a new instance of TenantSnapshot.



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/seekmodo/sdk/tenant_snapshot.rb', line 14

def initialize(
  client,
  cache,
  ttl_seconds: DEFAULT_TTL_SECONDS,
  stale_after_seconds: DEFAULT_STALE_TTL_SECONDS,
  clock: nil
)
  @client = client
  @cache = cache
  @ttl_seconds = ttl_seconds
  @stale_after_seconds = [stale_after_seconds, ttl_seconds].min
  @clock = clock || -> { Time.now.to_i }
end

Instance Method Details

#forgetObject



59
60
61
62
# File 'lib/seekmodo/sdk/tenant_snapshot.rb', line 59

def forget
  @cache.delete(CACHE_KEY)
  @cache.delete(CACHE_KEY_FETCHED_AT)
end

#getObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/seekmodo/sdk/tenant_snapshot.rb', line 28

def get
  cached = @cache.get(CACHE_KEY)
  fetched_at = @cache.get(CACHE_KEY_FETCHED_AT, 0).to_i

  if cached.is_a?(Hash) && fetched_at > 0
    age = @clock.call - fetched_at
    if age < @stale_after_seconds
      return cached
    end

    begin
      return refresh
    rescue StandardError
      return cached
    end
  end

  begin
    refresh
  rescue StandardError
    {}
  end
end

#refreshObject



52
53
54
55
56
57
# File 'lib/seekmodo/sdk/tenant_snapshot.rb', line 52

def refresh
  snapshot = @client.tenant_snapshot
  @cache.set(CACHE_KEY, snapshot, @ttl_seconds)
  @cache.set(CACHE_KEY_FETCHED_AT, @clock.call, @ttl_seconds)
  snapshot
end