Skip to content

Commit

Permalink
Fix :socket_closed_remotely error on travis
Browse files Browse the repository at this point in the history
  • Loading branch information
ericmj committed Mar 14, 2016
1 parent b252a7d commit 0235638
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
6 changes: 4 additions & 2 deletions lib/hex/api.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ defmodule Hex.API do
http_opts = [ssl: ssl_opts(url), relaxed: true, timeout: @request_timeout] ++ Hex.Utils.proxy_config(url)
opts = [body_format: :binary]
url = String.to_char_list(url)
profile = Hex.State.fetch!(:httpc_profile)

request =
cond do
Expand All @@ -37,7 +38,7 @@ defmodule Hex.API do
{url, Map.to_list(headers)}
end

case :httpc.request(method, request, http_opts, opts, :hex) do
case :httpc.request(method, request, http_opts, opts, profile) do
{:ok, response} ->
handle_response(response)
{:error, reason} ->
Expand Down Expand Up @@ -101,6 +102,7 @@ defmodule Hex.API do
http_opts = [ssl: ssl_opts(url), relaxed: true, timeout: @request_timeout] ++ Hex.Utils.proxy_config(url)
opts = [body_format: :binary]
url = String.to_char_list(url)
profile = Hex.State.fetch!(:httpc_profile)

body = fn
size when size < byte_size(body) ->
Expand All @@ -114,7 +116,7 @@ defmodule Hex.API do

request = {url, Map.to_list(headers), 'application/octet-stream', {body, 0}}

case :httpc.request(method, request, http_opts, opts, :hex) do
case :httpc.request(method, request, http_opts, opts, profile) do
{:ok, response} ->
handle_response(response)
{:error, reason} ->
Expand Down
22 changes: 19 additions & 3 deletions lib/hex/state.ex
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,35 @@ defmodule Hex.State do
check_cert?: load_config(config, ["HEX_UNSAFE_HTTPS"], :unsafe_https) |> to_boolean |> default(true),
check_registry?: load_config(config, ["HEX_UNSAFE_REGISTRY"], :unsafe_registry) |> to_boolean |> default(true),
hexpm_pk: @hexpm_pk,
registry_updated: false}
registry_updated: false,
httpc_profile: :hex}
end

# Work around for :socket_closed_remotely errors in httpc
# Use a unique profile for each request to avoid races
if Mix.env == :test do
def fetch(:httpc_profile) do
profile = make_ref() |> :erlang.ref_to_list |> List.to_atom
{:ok, _pid} = :httpc_manager.start_link(profile, :only_session_cookies, :stand_alone)
end
end

def fetch(key) do
Agent.get(@name, Map, :fetch, [key])
end

def fetch!(key) do
Agent.get(@name, Map, :fetch!, [key])
case fetch(key) do
{:ok, value} -> value
:error -> raise KeyError, key: key, term: Hex.State
end
end

def get(key, default \\ nil) do
Agent.get(@name, Map, :get, [key, default])
case fetch(key) do
{:ok, value} -> value
:error -> default
end
end

def put(key, value) do
Expand Down

0 comments on commit 0235638

Please sign in to comment.