Skip to content

Commit

Permalink
Don't let geo requests take forever
Browse files Browse the repository at this point in the history
httpc defaults to infinite timeouts. Since whenwhere servers should always
respond quickly so that they can be used for time purposes, make the
timeout default to 10s. This is much longer than anything anyone should
see in practice and also significantly better than waiting forever.
  • Loading branch information
fhunleth committed Sep 15, 2024
1 parent bbb2662 commit 00cebc9
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 5 additions & 1 deletion lib_src/core/geo.ex
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ defmodule Toolshed.Core.Geo do
* `:ifname` - Network interface to use (e.g., `"eth0"`)
* `:whenwhere_url` - URL for the whenwhere server to query. Defaults to http://whenwhere.nerves-project.org
* `:timeout` - Milliseconds to wait for a response. Defaults to 10_000.
* `:connect_timeout` - Milliseconds to wait for the connection. Defaults to `:timeout` value
"""
@spec geo(keyword()) :: :"do not show this result in output"
def geo(options \\ []) do
Expand All @@ -20,6 +22,8 @@ defmodule Toolshed.Core.Geo do

defp do_geo(options) do
url = Keyword.get(options, :whenwhere_url, @whenwhere_url)
timeout = Keyword.get(options, :timeout, 10_000)
connect_timeout = Keyword.get(options, :connect_timeout, timeout)

request_headers = [
{~c"user-agent", ~c"toolshed"},
Expand All @@ -29,7 +33,7 @@ defmodule Toolshed.Core.Geo do
case :httpc.request(
:get,
{url, request_headers},
[ssl: [verify: :verify_none]],
[ssl: [verify: :verify_none], connect_timeout: connect_timeout, timeout: timeout],
socket_opts: socket_opts(options)
) do
{:ok, {_status, _headers, body}} ->
Expand Down
6 changes: 5 additions & 1 deletion test/toolshed/geo_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ defmodule Toolshed.GeoTest do
test "geo/1 supports overriding the server" do
assert capture_io(fn ->
Toolshed.geo(whenwhere_url: "http://not_a_server.nerves-project.org")
end) =~ "Something went wrong when making an HTTP request"
end) =~ "nxdomain"
end

test "geo/1 can time out" do
assert capture_io(fn -> Toolshed.geo(timeout: 1) end) =~ "timeout"
end
end

0 comments on commit 00cebc9

Please sign in to comment.