Danbooru::Http: add default connection timeout.

* Add a three second connection timeout to all http requests. By default
  http.rb doesn't have any timeouts, so it can hang forever trying to
  connect if there are any network issues.

* Return a fake 522 error in the event of a timeout so that callers
  don't have to deal with TimeoutError exceptions, instead they can treat
  timeouts as normal 5xx errors (which most callers already handle).
This commit is contained in:
evazion
2020-05-12 15:46:59 -05:00
parent deeb465b72
commit bf08898837

View File

@@ -1,5 +1,7 @@
module Danbooru
class Http
DEFAULT_TIMEOUT = 3
attr_writer :cache, :http
class << self
@@ -42,6 +44,9 @@ module Danbooru
else
raw_request(method, url, **options)
end
rescue HTTP::TimeoutError
# return a synthetic http error on connection timeouts
::HTTP::Response.new(status: 522, body: "", version: "1.1")
end
def cached_request(method, url, **options)
@@ -60,7 +65,7 @@ module Danbooru
end
def http
@http ||= ::HTTP.use(:auto_inflate).headers(Danbooru.config.http_headers).headers("Accept-Encoding" => "gzip")
@http ||= ::HTTP.timeout(DEFAULT_TIMEOUT).use(:auto_inflate).headers(Danbooru.config.http_headers).headers("Accept-Encoding" => "gzip")
end
end
end