-
-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathcache_controller.ex
46 lines (38 loc) · 1.13 KB
/
cache_controller.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
defmodule ElixirProvider.CacheController do
@moduledoc """
Controller for caching flag evaluations to avoid redundant API calls.
"""
use GenServer
@flag_table :flag_cache
@spec start_link(any()) :: GenServer.on_start()
def start_link(_args) do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
def get(flag_key, evaluation_hash) do
cache_key = build_cache_key(flag_key, evaluation_hash)
case :ets.lookup(@flag_table, cache_key) do
[{^cache_key, cached_value}] -> {:ok, cached_value}
[] -> :miss
end
end
def set(flag_key, evaluation_hash, value) do
cache_key = build_cache_key(flag_key, evaluation_hash)
:ets.insert(@flag_table, {cache_key, value})
:ok
end
def clear do
GenServer.stop(__MODULE__)
:ets.delete_all_objects(@flag_table)
:ets.insert(@flag_table, {:context, %{}})
:ok
end
defp build_cache_key(flag_key, evaluation_hash) do
"#{flag_key}-#{evaluation_hash}"
end
@impl true
def init(:ok) do
:ets.new(@flag_table, [:named_table, :set, :public])
:ets.insert(@flag_table, {:context, %{}})
{:ok, nil, :hibernate}
end
end