whitfin / cachex

A powerful caching library for Elixir with support for transactions, fallbacks and expirations
https://hexdocs.pm/cachex/
MIT License
1.6k stars 103 forks source link

Using Cachex with Phoenix and iex #316

Closed tbm206 closed 8 months ago

tbm206 commented 1 year ago

Originally posted on Elixirforum


I’m exploring using Cachex to implement a simple one time password (OTP). In its simplest form, there is a custom Plug that looks like the following:

defmodule MyAppWeb.OTP do
  import Plug.Conn

  def init(options), do: options

  def call(%Plug.Conn{path_params: path_params} = conn, opts) do
    access_code = path_params["code"]

    case Cachex.get(:passcode, :"#{access_code}") do
      {:ok, %{user_id: user_id}} -> ...

      _ ->
        conn |> send_resp(:unauthorized, "") |> halt()
    end
  end
end

The issue here is that Cachex.get(:passcode, :"#{access_code}" will always give me nil. Similarly, if I use Cachex.keys(:passcode), it will return an empty list while I’m sure there are keys that I had added via iex.

Here’s how Cachex is initialised in application.ex

  def start(_type, _args) do
    children = [
      # Start the Telemetry supervisor
      MyAppWeb.Telemetry,
      ...
      %{id: :cachex_passcode, start: {Cachex, :start_link, [[name: :passcode]]}},
      MyAppWeb.Endpoint
    ]
    ...

I have a feeling there is something missing in the setup?


Further details

I run phoenix in a docker container. I then exec into it and run iex -S mix. That has worked well with other tasks so far but maybe Cachex is different.

The exact command I use is:

Cachex.put(:passcode, :"#{uuid}", %{user_id: user_id}, ttl: :timer.minutes(30))

What’s confusing is that the :passcode cache is available in the interactive terminal.

tbm206 commented 1 year ago

When the cache is set through the normal workflow within the Phoenix app, it works just fine. However, I want the flexibility to set/view the cache from iex during development.

whitfin commented 10 months ago

@tbm206 as far as I know, there's nothing that should be inside Cachex causing this. It's just ETS behind the scenes; if you can even put things into your cache from iex, then that alone proves that it's the same instance (otherwise you'd have to start a cache inside iex).

Which version of OTP is this using? (OTP as in Erlang, not your passcode stuff).

whitfin commented 9 months ago

@tbm206 just following up to see if you have any further information on this?

whitfin commented 8 months ago

Going to tentatively close this as I cannot reproduce and there has been no follow up. Feel free to re-open if you can reproduce!