Maxximiliann

Maxximiliann

Using Process.send_after() outside of a GenServer?

defmodule APIResponseProcessor do
  defp update_log(api_url, error_message, {sleep_time, interval}, line_number, attempt_count) do
    log_level =
      case attempt_count < 5 do
        true -> :log_only
        false -> :warning
      end

    LogBook.main(
      "Error: #{inspect(error_message)} (attempt #{attempt_count}) - Retried #{inspect(api_url)} after #{sleep_time} #{interval} . . . ",
      __MODULE__,
      line_number,
      log_level
    )

    {:update_log, :ok}
  end

  defp retry_api_url(api_url, error_message, attempt_count, connection_type)
       when attempt_count <= 29 do
    with {:calculate, delay} <- calculate_delay(attempt_count),
         {:ok, randomized_sleep_interval} <- MiscScripts.random_sleep(delay),
         {:update_log, :ok} <-
           update_log(
             api_url,
             error_message,
             {randomized_sleep_interval / 1000, "seconds"},
             38,
             attempt_count
           ) do
      ApiInterface.connect_to_api(api_url, connection_type, attempt_count)
    else
      glitch ->
        ExceptionsHandler.raise_erroneous_value_alert(glitch, __MODULE__, __ENV__.function)
    end
  end

  defp retry_api_url(_, error_message, attempt_count, _),
    do: raise("Error after #{attempt_count} failed attempts: #{inspect(error_message)}")

  defp calculate_delay(attempt_count) do
    delay =
      case attempt_count do
        1 -> 200
        2 -> 500
        _ -> 1500
      end

    {:calculate, delay}
  end

  def main(
        {:error, %HTTPoison.Error{id: nil, reason: _} = error_message},
        api_url,
        attempt_count,
        connection_type
      ),
      do: retry_api_url(api_url, error_message, attempt_count + 1, connection_type)

  def main(
        {:ok, response = %HTTPoison.Response{status_code: status_code}},
        api_url,
        attempt_count,
        connection_type
      ) do
    case status_code do
      code when code in [200, 301, 404] ->
        {:api_response_processor, response}

      code when code in [400, 429, 502, 503, 520] ->
        error_message = status_code_to_error(code)
        retry_api_url(api_url, error_message, attempt_count + 1, connection_type)

      _ ->
        {:api_response_error, "Unexpected status code: #{status_code}"}
    end
  end

  defp status_code_to_error(error_code) when is_integer(error_code) do
    case error_code do
      400 -> :bad_request_error
      429 -> :too_many_requests
      502 -> :bad_gateway
      503 -> :service_unavailable
      520 -> :no_data_received
    end
  end
end
defmodule MiscScripts do
  @spec random_sleep(integer) :: {:ok, integer}
  def random_sleep(max_interval) do
    random_interval = :rand.uniform(max_interval)
    Process.sleep(random_interval)
    {:ok, random_interval}
  end
end

The api retry function uses Process.sleep() for the delay but I’d like to use Process.send_after() since this seems to be the best practice. All the information I’ve come across suggests that send_after() can only be used within a GenServer which seems like overkill. So, two questions:

  1. How, if possible, can Process.send_after() be used outside of a GenServer?
  2. Is using a GenServer for this really overkill or no?

Most Liked

tfwright

tfwright

I would answer your second question ‘no’. Tracking state is a sound reason to reach for GenServer. The main anti-pattern around GenServer is to use them for code organization. Conversely, docs say:

Use processes only to model runtime properties, such as mutable state, concurrency and failures, never for code organization.

which clearly applies to your case: GenServer — Elixir v1.12.3

That said, have you seen HTTPoison.Retry — httpoison_retry v1.1.0 I think there may also be http libraries with retry support built in…

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

The bit you’re missing is why people suggest to use send_after in a GenServer. The reason is that in a GenServer you don’t want to block the process, because that prevents it from handling other messages. It also already has a receive loop going, so when you get the message there is code to handle it.

If you instead have just linear code though and not a GenServer, how would send_after work? Your code is already written to block for the amount of time it’s going to sleep. Doing

Process.send_after(self(), :try_again, 5_000)

receive do
  :try_again -> :ok
end

is exactly as blocking as just doing Process.sleep(5_000) in the first place.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

What benefit does this gain you? The calling process still blocks, and now you’ve got a genserver and poolboy added to the mix which only complicates things further.

Where Next?

Popular in Questions Top

WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
yawaramin
In the Dialyzer docs ( dialyzer — OTP 29.0.2 (dialyzer 6.0.1) ), there is a way to turn off a specific warning for a function: -dialyzer...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New

Other popular topics Top

New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement