Skip to content

Commit

Permalink
Store Cluster config in a ets table to prevent timeout while fetching…
Browse files Browse the repository at this point in the history
… cluster config
  • Loading branch information
nitinstp23 committed Jul 29, 2020
1 parent 40a4d3a commit c98f6b1
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion lib/elasticsearch/cluster/cluster.ex
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,8 @@ defmodule Elasticsearch.Cluster do
quote do
use GenServer

@table_name :"#{__MODULE__}.Config"

alias Elasticsearch.Cluster.Config

# Cache configuration into the state of the GenServer so that
Expand All @@ -157,6 +159,9 @@ defmodule Elasticsearch.Cluster do
# Ensure that the configuration is validated on startup
with {:ok, pid} <- GenServer.start_link(__MODULE__, config, name: __MODULE__),
:ok <- GenServer.call(pid, :validate) do
# Ensure that the configuration is saved
GenServer.call(pid, :save_config, 10_000)

{:ok, pid}
else
error ->
Expand All @@ -170,7 +175,7 @@ defmodule Elasticsearch.Cluster do

@doc false
def __config__ do
GenServer.call(__MODULE__, :config)
Elasticsearch.Cluster.read_config(@table_name)
end

@impl GenServer
Expand All @@ -189,7 +194,33 @@ defmodule Elasticsearch.Cluster do
end
end

@impl GenServer
def handle_call(:save_config, _from, config) do
Elasticsearch.Cluster.save_config(@table_name, config)
{:reply, :ok, config}
end

defoverridable init: 1
end
end

@doc false
def save_config(table_name, config) do
if :ets.info(table_name) == :undefined do
:ets.new(table_name, [:named_table, :protected])
end

:ets.insert(table_name, {:config, config})
end

@doc false
def read_config(table_name) do
case :ets.lookup(table_name, :config) do
[{:config, config} | _] ->
config

_ ->
:error
end
end
end

0 comments on commit c98f6b1

Please sign in to comment.