From 3664a98b3d9815b79eb5bdc4f4f80375a20d7396 Mon Sep 17 00:00:00 2001 From: lovebes Date: Thu, 8 Aug 2024 18:07:13 -0700 Subject: [PATCH] UPDATE: EtsCache.new() to create only if table doesn't exist --- lib/joken_jwks/ets_cache.ex | 26 +++++++++++++++---------- test/default_strategy_template_test.exs | 8 ++++++++ 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/lib/joken_jwks/ets_cache.ex b/lib/joken_jwks/ets_cache.ex index c27c609e..54f39b5a 100644 --- a/lib/joken_jwks/ets_cache.ex +++ b/lib/joken_jwks/ets_cache.ex @@ -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" diff --git a/test/default_strategy_template_test.exs b/test/default_strategy_template_test.exs index 654c34ec..44b9ffbd 100644 --- a/test/default_strategy_template_test.exs +++ b/test/default_strategy_template_test.exs @@ -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")]})}