From bf08898837d8b3a1747ba3a63385b3e6b67e879f Mon Sep 17 00:00:00 2001 From: evazion Date: Tue, 12 May 2020 15:46:59 -0500 Subject: [PATCH] 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). --- app/logical/danbooru/http.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/app/logical/danbooru/http.rb b/app/logical/danbooru/http.rb index 26b3fd9e8..6e0b21711 100644 --- a/app/logical/danbooru/http.rb +++ b/app/logical/danbooru/http.rb @@ -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