Last active
April 8, 2021 11:42
-
-
Save myobie/299378b639592627ca212c1e19fc69db to your computer and use it in GitHub Desktop.
GenServer for longpoll requests with backoff in case of errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Example.Poller do | |
use GenServer | |
@backoff [ | |
50, | |
100, | |
150, | |
250, | |
400, | |
650 | |
] | |
@max_backoff 1050 | |
def start_link([notify]), | |
do: GenServer.start_link(__MODULE__, [notify], name: __MODULE__) | |
@impl true | |
def init([notify]) do | |
state = %{notify: notify, backoff_index: 0} | |
{:ok, state, {:continue, :request}} | |
end | |
@impl true | |
def handle_continue( | |
:request, | |
%{notify: notify, backoff_index: backoff_index} = state | |
) do | |
case Example.longpoll_request() do | |
{:ok, response} -> | |
send(notify, {:update, response}) | |
{:noreply, %{state | backoff_index: 0}, {:continue, :request}} | |
{:error, _error} -> | |
timeout = Enum.at(@backoff, backoff_index, @max_backoff) | |
Process.send_after(self(), :retry, timeout) | |
{:noreply, %{state | backoff_index: backoff_index + 1}} | |
end | |
end | |
@impl true | |
def handle_info(:retry, state), | |
do: {:noreply, state, {:continue, :request}} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment