Skip to content

Commit

Permalink
Merge pull request #68 from lovebes/add-create-if-not-exist-for-ets-t…
Browse files Browse the repository at this point in the history
…able

UPDATE: EtsCache.new() to create only if table doesn't exist
  • Loading branch information
victorolinasc authored Aug 10, 2024
2 parents acab9cd + 3664a98 commit dfa5ac9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
26 changes: 16 additions & 10 deletions lib/joken_jwks/ets_cache.ex
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
defmodule JokenJwks.DefaultStrategyTemplate.EtsCache do
@moduledoc "Simple ETS counter based state machine"

@doc "Starts ETS cache"
@doc "Starts ETS cache - will only create if table doesn't exist already"
def new(module) do
:ets.new(name(module), [
:set,
:public,
:named_table,
read_concurrency: true,
write_concurrency: true
])

:ets.insert(name(module), {:counter, 0})
case :ets.whereis(name(module)) do
:undefined ->
:ets.new(name(module), [
:set,
:public,
:named_table,
read_concurrency: true,
write_concurrency: true
])

:ets.insert(name(module), {:counter, 0})

_ ->
true
end
end

@doc "Returns 0 - no need to fetch signers or 1 - need to fetch"
Expand Down
8 changes: 8 additions & 0 deletions test/default_strategy_template_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,14 @@ defmodule JokenJwks.DefaultStrategyTest do
assert Enum.count(EtsCache.get_signers(TestToken.Strategy)[:signers]) == 0
end

test "ets table creation attempt should not error out even if table already exists" do
setup_jwks()
EtsCache.new(TestToken.Strategy)

token = TestToken.generate_and_sign!(%{}, TestUtils.create_signer_with_kid("id2"))
assert {:ok, %{}} == TestToken.verify_and_validate(token)
end

def setup_jwks(time_interval \\ 1_000) do
expect_call(fn %{url: "http://jwks"} ->
{:ok, json(%{"keys" => [TestUtils.build_key("id1"), TestUtils.build_key("id2")]})}
Expand Down

0 comments on commit dfa5ac9

Please sign in to comment.