cachex icon indicating copy to clipboard operation
cachex copied to clipboard

Incomplete spec for Cachex.start_link?

Open jonmdev opened this issue 9 months ago • 1 comments

Cachex.start_link can return numerous possibilities including {:ok, pid} and {:error, {:already_started, pid}}

We can see this by running

Cachex.start_link(:my_cache)
{:ok, #PID<0.970.0>}

Cachex.start_link(:my_cache)
{:error, {:already_started, #PID<0.966.0>}}

However, if you write a block like this in VS Code with Elixir LS:

new_state = case Cachex.start_link(@table_name, ttl: @default_ttl * 1000) do
            {:ok, _pid} ->
                %{state | cache_started: true}
            {:error, {:already_started, _pid}} ->
                %{state | cache_started: true}
            _->
                Process.send_after(self(), :start_cache, 5_000)
                %{state | cache_started: false}
        end

You get the error

The pattern can never match the type.

Pattern:
{:error, {:already_started, __pid}}

Type:
{:ok, pid()}

This seems to be as if you look at start_link, the code is:

  @spec start_link(atom, Keyword.t()) :: {atom, pid}
  def start_link(name, options) when is_atom(name) and is_list(options) do
    with {:ok, true} <- ensure_started(),
         {:ok, true} <- ensure_unused(name),
         {:ok, cache} <- Options.parse(name, options),
         {:ok, pid} = Supervisor.start_link(__MODULE__, cache, name: name),
         {:ok, cache} = Services.link(cache),
         {:ok, cache} <- setup_router(cache),
         ^cache <- Overseer.update(name, cache),
         :ok <- setup_warmers(cache) do
      {:ok, pid}
    end
  end

So the spec is not matching the possibilities for what we are actually getting by running this function.

Am I not understanding something or is there some way to fix this? Thanks for any help or fix with this otherwise great library.

jonmdev avatar Apr 22 '25 01:04 jonmdev

Hi @jonmdev!

You're right! Feel free to file an MR for this; if not I can circle to it when I get some time!

whitfin avatar May 22 '25 18:05 whitfin