diff --git a/lib/Discord/Gateway/gateway.ex b/lib/Discord/Gateway/gateway.ex index 2ea7836..ca039f2 100644 --- a/lib/Discord/Gateway/gateway.ex +++ b/lib/Discord/Gateway/gateway.ex @@ -15,12 +15,19 @@ defmodule Alchemy.Discord.Gateway do def start_link(token, shard) do :crypto.start() :ssl.start() + # request_url will return a protocol to execute - url = Manager.request_url().() + # which either returns the url or another protocol + # to execute. + url = Manager.request_url().() |> get_url Logger.info("Shard #{inspect(shard)} connecting to the gateway") + :websocket_client.start_link(url, __MODULE__, %State{token: token, shard: shard}) end + def get_url(s) when is_binary(s), do: s + def get_url(f), do: get_url(f.()) + def init(state) do {:once, state} end diff --git a/lib/Discord/Gateway/manager.ex b/lib/Discord/Gateway/manager.ex index b7835c9..0286f43 100644 --- a/lib/Discord/Gateway/manager.ex +++ b/lib/Discord/Gateway/manager.ex @@ -73,19 +73,24 @@ defmodule Alchemy.Discord.Gateway.Manager do now = now() wait_time = state.url_reset - now - response = - cond do - wait_time <= 0 -> - fn -> state.url end - - true -> - fn -> - Process.sleep(wait_time * 1000) - request_url() - end - end - - {:reply, response, %{state | url_reset: now + 5}} + cond do + wait_time <= 0 -> + response = fn -> state.url end + + # Increase the url_reset time as a process + # has successfull requested the url + {:reply, response, %{state | url_reset: now + 5}} + + true -> + response = fn -> + Process.sleep(wait_time * 1000) + request_url() + end + + # Don't increate the url_reset as the process + # has not been successfull in requesting the url. + {:reply, response, state} + end end def handle_cast({:start_shard, num}, %{shards: shards} = state)