Skip to content

Commit

Permalink
wip: use uuid to prevent process id collisions
Browse files Browse the repository at this point in the history
  • Loading branch information
nlwstein committed Jan 16, 2024
1 parent d9ccff0 commit 6941a1e
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
20 changes: 17 additions & 3 deletions apps/api_web/lib/api_web/rate_limiter/rate_limiter_concurrent.ex
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ defmodule ApiWeb.RateLimiter.RateLimiterConcurrent do
Keyword.fetch!(Application.get_env(:api_web, :rate_limiter_concurrent), :connection_opts)

{:ok, pid} = if memcache?(), do: Memcache.start_link(connection_opts), else: {:ok, nil}
{:ok, %{memcache_pid: pid}}
{:ok, %{memcache_pid: pid, uuid: UUID.uuid1()}}
end

defp lookup(%ApiWeb.User{} = user, event_stream?) do
Expand All @@ -27,6 +27,20 @@ defmodule ApiWeb.RateLimiter.RateLimiterConcurrent do
}
end

def get_pid_key(pid) do
sub_key = pid |> :erlang.pid_to_list() |> to_string
get_uuid() <> sub_key
end

defp get_uuid() do
{:ok, uuid} = GenServer.call(__MODULE__, :get_uuid)
uuid
end

def handle_call(:get_uuid, _from, state) do
{:reply, {:ok, state.uuid}, state}
end

defp get_current_unix_ts do
System.system_time(:second)
end
Expand Down Expand Up @@ -107,7 +121,7 @@ defmodule ApiWeb.RateLimiter.RateLimiterConcurrent do
def add_lock(%ApiWeb.User{} = user, pid, event_stream?) do
if enabled?() do
{_type, key} = lookup(user, event_stream?)
pid_key = pid |> :erlang.pid_to_list() |> to_string
pid_key = get_pid_key(pid)
timestamp = get_current_unix_ts()

Logger.info(
Expand All @@ -134,7 +148,7 @@ defmodule ApiWeb.RateLimiter.RateLimiterConcurrent do
) do
if enabled?() do
{_type, key} = lookup(user, event_stream?)
pid_key = if pid_key, do: pid_key, else: pid |> :erlang.pid_to_list() |> to_string
pid_key = if pid_key, do: pid_key, else: get_pid_key(pid)
locks_before = get_locks(user, event_stream?)
locks = locks_before |> Map.delete(pid_key)

Expand Down
3 changes: 2 additions & 1 deletion apps/api_web/mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ defmodule ApiWeb.Mixfile do
{:recaptcha, git: "https://github.com/samueljseay/recaptcha.git", tag: "71cd746"},
{:sentry, "~> 8.0"},
{:qr_code, "~> 3.0"},
{:nimble_totp, "~> 1.0"}
{:nimble_totp, "~> 1.0"},
{:uuid, "~> 1.1"}
]
end
end

0 comments on commit 6941a1e

Please sign in to comment.