|
1 | 1 | defmodule Srh.Auth.TokenResolver do |
| 2 | + use GenServer |
| 3 | + |
2 | 4 | @mode Application.fetch_env!(:srh, :mode) |
3 | 5 | @file_path Application.fetch_env!(:srh, :file_path) |
4 | 6 | @file_hard_reload Application.fetch_env!(:srh, :file_hard_reload) |
5 | 7 |
|
6 | | - @config_file_data nil |
| 8 | + @ets_table_name :srh_token_resolver |
| 9 | + |
| 10 | + def start_link() do |
| 11 | + GenServer.start_link(__MODULE__, {}, []) |
| 12 | + end |
| 13 | + |
| 14 | + def child_spec(_opts) do |
| 15 | + %{ |
| 16 | + id: :token_resolver, |
| 17 | + start: {__MODULE__, :start_link, []}, |
| 18 | + type: :supervisor |
| 19 | + } |
| 20 | + end |
| 21 | + |
| 22 | + def init(_arg) do |
| 23 | + IO.puts("Token resolver started") |
| 24 | + |
| 25 | + # Create the ETS table |
| 26 | + table = :ets.new(@ets_table_name, [:named_table, read_concurrency: true]) |
| 27 | + |
| 28 | + # Populate the ETS table with data from storage |
| 29 | + do_init_load(@mode) |
| 30 | + |
| 31 | + { |
| 32 | + :ok, |
| 33 | + %{ |
| 34 | + table: table |
| 35 | + } |
| 36 | + } |
| 37 | + end |
7 | 38 |
|
8 | 39 | def resolve(token) do |
9 | 40 | IO.puts("Resolving token: #{token}") |
10 | 41 |
|
11 | 42 | do_resolve(@mode, token) |
12 | 43 | end |
13 | 44 |
|
14 | | - defp do_resolve("file", token) do |
15 | | - # if @config_file_data == nil || @file_hard_reload do |
16 | | - # @config_file_data = Jason.decode!(File.read!(@file_path)) |
17 | | - # IO.puts("Reloaded config file from disk. #{Jason.encode!(@config_file_data)}") |
18 | | - # end |
| 45 | + # Server methods |
| 46 | + def handle_call(_msg, _from, state) do |
| 47 | + {:reply, :ok, state} |
| 48 | + end |
| 49 | + |
| 50 | + def handle_cast(_msg, state) do |
| 51 | + {:noreply, state} |
| 52 | + end |
19 | 53 |
|
| 54 | + # Internal server |
| 55 | + defp do_init_load("file") do |
20 | 56 | config_file_data = Jason.decode!(File.read!(@file_path)) |
21 | | - IO.puts("Reloaded config file from disk. #{Jason.encode!(config_file_data)}") |
| 57 | + IO.puts("Loaded config file from disk. #{map_size(config_file_data)} entries.") |
| 58 | + # Load this into ETS |
| 59 | + Enum.each( |
| 60 | + config_file_data, |
| 61 | + &(:ets.insert(@ets_table_name, &1)) |
| 62 | + ) |
| 63 | + end |
| 64 | + |
| 65 | + defp do_init_load(_), do: :ok |
| 66 | + |
| 67 | + # Internal, but client side, methods. These are client side to prevent GenServer lockup |
| 68 | + defp do_resolve("file", token) do |
| 69 | + # if @hard_file_reload do |
| 70 | + # do_init_load("file") |
| 71 | + # end |
22 | 72 |
|
23 | | - case Map.get(config_file_data, token) do |
24 | | - nil -> |
25 | | - {:error, "Invalid token"} |
26 | | - connection_info -> |
27 | | - {:ok, connection_info} |
| 73 | + case :ets.lookup(@ets_table_name, token) do |
| 74 | + [{^token, connection_info}] -> {:ok, connection_info} |
| 75 | + [] -> {:error, "Invalid token"} |
28 | 76 | end |
29 | 77 | end |
30 | 78 |
|
|
0 commit comments