diff --git a/CHANGELOG.md b/CHANGELOG.md index fd2cb4a..476e9d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ ## [Unreleased] +### Added + +- **`retry_transient_errors` setting** (default `false`). When on, 429 + responses, and 5xx responses, timeouts and dropped connections on GET, PUT + and DELETE, are retried up to `max_retries` without calling the + authentication's `on_rejected`, which then only sees the other failures. + These retries wait for the response's `Retry-After` header (seconds or an + HTTP date, 1 second without one or without a response); one asking for + more than 10 seconds raises instead. A retry that `on_rejected` asks for + is still made at once. Off by default, since PUT + and DELETE are only safe to repeat on APIs that implement them + idempotently. + ## [1.4.2] - 2026-09-23 ### Fixed diff --git a/README.md b/README.md index 34bf734..aee448d 100644 --- a/README.md +++ b/README.md @@ -101,6 +101,7 @@ end | `log_bodies` | `false` | When `true`, request/response bodies are logged. Off by default to avoid leaking domain secrets | | `logger` | `nil` | When set, attaches Faraday's logger middleware and writes HTTP request/response details to it | | `max_retries` | `3` | Retry count on request failure | +| `retry_transient_errors` | `false` | When `true`, 429 responses, and 5xx responses, timeouts and dropped connections on GET, PUT and DELETE, are retried without calling `on_rejected`; see [the retry lifecycle](#custom-authentication) | ### Logging HTTP traffic @@ -655,6 +656,14 @@ The retry lifecycle: - Return normally → retry (up to `max_retries`) - Raise → propagate error +With `retry_transient_errors` on, a 429 skips step 3 and is retried directly, up to `max_retries`. So is a 5xx on GET, PUT or DELETE. A 5xx on POST still goes through step 3, because the server may already have acted on it, and repeating a POST that creates something can create it twice. + +A timeout or a dropped connection (`Faraday::TimeoutError`, `Faraday::ConnectionFailed`) has no response to pass to `on_rejected`, so it is normally raised straight away. With the setting on, it is retried on GET, PUT or DELETE in the same way, for the same reason. On POST it is still raised. + +Before each of these retries the request waits for as long as the response's `Retry-After` header says, either in seconds or as an HTTP date, and 1 second without one or without a response. If `Retry-After` asks for more than 10 seconds the error is raised straight away, since retrying sooner than the server allows would only fail again. A retry that `on_rejected` asks for, such as after a 5xx on POST, is made straight away, as it is without the setting. + +It is off by default because a PUT or DELETE is only safe to repeat when the API implements them idempotently. Turn it on for APIs that do. + ## CRUD operations Resources provide standard CRUD methods: diff --git a/lib/rest_easy.rb b/lib/rest_easy.rb index 9a24b90..e07dec4 100644 --- a/lib/rest_easy.rb +++ b/lib/rest_easy.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "rubygems" +require "time" require "dry/types" require "faraday" require "zeitwerk" @@ -17,6 +18,9 @@ module RestEasy # Make Boolean available as a bare type constant (Ruby has no built-in Boolean) ::Object.const_set(:Boolean, Dry::Types["params.bool"]) unless defined?(::Boolean) + DEFAULT_RETRY_AFTER_IN_SECONDS = 1 + MAX_RETRY_AFTER_IN_SECONDS = 10 + # ── Error hierarchy ────────────────────────────────────────────────── class Error < StandardError; end @@ -69,6 +73,9 @@ module ClassMethods STANDARD_AUTH_HEADERS = %w[Authorization Proxy-Authorization Cookie Set-Cookie].freeze private_constant :STANDARD_AUTH_HEADERS + IDEMPOTENT_METHODS = %i[get put delete].freeze + private_constant :IDEMPOTENT_METHODS + def config self::Settings.config end @@ -166,13 +173,50 @@ def request_with_auth(method, path, body: nil, params: {}, headers: {}) rescue RequestError => e attempts += 1 if attempts <= max_retries - auth.on_rejected(e.response) + if config.retry_transient_errors && transient?(method, e.response) + wait = retry_after(e.response) + raise if wait > MAX_RETRY_AFTER_IN_SECONDS + + Kernel.sleep(wait) + else + auth.on_rejected(e.response) + end retry end raise + + rescue Faraday::TimeoutError, Faraday::ConnectionFailed + attempts += 1 + raise unless attempts <= max_retries && config.retry_transient_errors && IDEMPOTENT_METHODS.include?(method) + + Kernel.sleep(DEFAULT_RETRY_AFTER_IN_SECONDS) + retry end end + # A 429 means the server did not act on the request, so any method can be + # repeated. A 5xx may come after it did, so only idempotent ones are. + def transient?(method, response) + return false unless response + return true if response.status == 429 + + (500..599).cover?(response.status) && IDEMPOTENT_METHODS.include?(method) + end + + def retry_after(response) + value = response.headers["Retry-After"] + return DEFAULT_RETRY_AFTER_IN_SECONDS unless value + + seconds = Integer(value, 10, exception: false) || seconds_until(value) || DEFAULT_RETRY_AFTER_IN_SECONDS + seconds.clamp(0..) + end + + def seconds_until(http_date) + (Time.httpdate(http_date) - Time.now).ceil + rescue ArgumentError + nil + end + end # ── Type bridge ───────────────────────────────────────────────────── diff --git a/lib/rest_easy/settings.rb b/lib/rest_easy/settings.rb index 2e03d9a..9f4639d 100644 --- a/lib/rest_easy/settings.rb +++ b/lib/rest_easy/settings.rb @@ -12,6 +12,7 @@ class Settings setting :log_bodies, default: false, reader: true setting :logger, reader: true setting :max_retries, default: 3, reader: true + setting :retry_transient_errors, default: false, reader: true setting :conversions do setting :json_attributes, default: Conventions::DEFAULT, reader: true diff --git a/spec/rest_easy/resource/http_spec.rb b/spec/rest_easy/resource/http_spec.rb index 7b85c33..04d3439 100644 --- a/spec/rest_easy/resource/http_spec.rb +++ b/spec/rest_easy/resource/http_spec.rb @@ -287,6 +287,241 @@ def apply(request); end end end + # ── Transient errors ───────────────────────────────────────────────── + + describe "retry_transient_errors" do + let(:rejected) { [] } + let(:auth) do + rejected_statuses = rejected + Class.new do + def apply(request); end + + define_method(:on_rejected) do |response| + rejected_statuses << response.status + raise RestEasy::RequestError.new(response) + end + end.new + end + let(:invoice) { '{"Invoice": {"DocumentNumber": 1, "CustomerName": "Test", "Amount": 0.0}}' } + + def respond_with(*responses, method: :get) + setup_test_connection(HttpTestApi) do |stub| + stub.public_send(method, "/v1/invoices/1") do + response = responses.shift + raise response if response.is_a?(Exception) + + response + end + end + end + + before do + HttpTestApi.configure do |c| + c.authentication = auth + c.retry_transient_errors = true + end + allow(Kernel).to receive(:sleep) + end + + after do + HttpTestApi.configure do |c| + c.authentication = RestEasy::Auth::Null.new + c.retry_transient_errors = false + end + end + + it "is off by default" do + expect(RestEasy::Settings.config.retry_transient_errors).to be(false) + end + + it "retries a 5xx without asking the authentication" do + respond_with([500, {}, "Error"], [200, { "Content-Type" => "application/json" }, invoice]) + + expect(HttpTestApi::Invoice.find(1).document_number).to eq(1) + expect(rejected).to be_empty + expect(Kernel).to have_received(:sleep).with(RestEasy::DEFAULT_RETRY_AFTER_IN_SECONDS) + end + + it "waits for Retry-After before retrying a 503" do + respond_with([503, { "Retry-After" => "3" }, ""], [200, { "Content-Type" => "application/json" }, invoice]) + + HttpTestApi::Invoice.find(1) + + expect(Kernel).to have_received(:sleep).with(3) + expect(rejected).to be_empty + end + + it "waits for Retry-After before retrying a 429" do + respond_with([429, { "Retry-After" => "2" }, ""], [200, { "Content-Type" => "application/json" }, invoice]) + + HttpTestApi::Invoice.find(1) + + expect(Kernel).to have_received(:sleep).with(2) + expect(rejected).to be_empty + end + + it "waits a default time on a 429 without Retry-After" do + respond_with([429, {}, ""], [200, { "Content-Type" => "application/json" }, invoice]) + + HttpTestApi::Invoice.find(1) + + expect(Kernel).to have_received(:sleep).with(RestEasy::DEFAULT_RETRY_AFTER_IN_SECONDS) + end + + it "reads Retry-After as a date" do + now = Time.utc(2026, 1, 1, 12, 0, 0) + 0.5 + allow(Time).to receive(:now).and_return(now) + respond_with([429, { "Retry-After" => (now + 5).httpdate }, ""], + [200, { "Content-Type" => "application/json" }, invoice]) + + HttpTestApi::Invoice.find(1) + + expect(Kernel).to have_received(:sleep).with(5) + end + + it "does not wait for a Retry-After date in the past" do + respond_with([429, { "Retry-After" => (Time.now - 60).httpdate }, ""], + [200, { "Content-Type" => "application/json" }, invoice]) + + HttpTestApi::Invoice.find(1) + + expect(Kernel).to have_received(:sleep).with(0) + end + + it "reads Retry-After in base 10" do + respond_with([429, { "Retry-After" => "010" }, ""], [200, { "Content-Type" => "application/json" }, invoice]) + + HttpTestApi::Invoice.find(1) + + expect(Kernel).to have_received(:sleep).with(10) + end + + it "raises without retrying when Retry-After is over the max" do + wait = RestEasy::MAX_RETRY_AFTER_IN_SECONDS + 1 + respond_with([429, { "Retry-After" => wait.to_s }, ""]) + + expect { HttpTestApi::Invoice.find(1) }.to raise_error(RestEasy::RequestError, "Request failed: 429") + expect(Kernel).not_to have_received(:sleep) + expect(rejected).to be_empty + end + + %i[put delete].each do |method| + it "retries a 5xx on #{method.upcase}" do + respond_with([503, {}, ""], [204, {}, ""], method:) + + HttpTestApi.public_send(method, path: "invoices/1") + + expect(rejected).to be_empty + end + end + + it "retries a 429 on POST" do + respond_with([429, {}, ""], [204, {}, ""], method: :post) + + HttpTestApi.post(path: "invoices/1") + + expect(rejected).to be_empty + end + + it "passes a 5xx on POST to the authentication" do + respond_with([503, {}, ""], method: :post) + + expect { HttpTestApi.post(path: "invoices/1") }.to raise_error(RestEasy::RequestError) + expect(rejected).to eq([503]) + expect(Kernel).not_to have_received(:sleep) + end + + [Faraday::TimeoutError, Faraday::ConnectionFailed].each do |error| + it "retries a #{error} on GET" do + respond_with(error.new("network"), [200, { "Content-Type" => "application/json" }, invoice]) + + expect(HttpTestApi::Invoice.find(1).document_number).to eq(1) + expect(Kernel).to have_received(:sleep).with(RestEasy::DEFAULT_RETRY_AFTER_IN_SECONDS) + expect(rejected).to be_empty + end + + %i[put delete].each do |method| + it "retries a #{error} on #{method.upcase}" do + respond_with(error.new("network"), [204, {}, ""], method:) + + HttpTestApi.public_send(method, path: "invoices/1") + + expect(Kernel).to have_received(:sleep).once + end + end + + it "raises a #{error} on POST without retrying" do + respond_with(error.new("network"), method: :post) + + expect { HttpTestApi.post(path: "invoices/1") }.to raise_error(error) + expect(Kernel).not_to have_received(:sleep) + expect(rejected).to be_empty + end + + it "raises a #{error} once max_retries is used up" do + respond_with(*Array.new(4) { error.new("network") }) + + expect { HttpTestApi::Invoice.find(1) }.to raise_error(error) + expect(Kernel).to have_received(:sleep).exactly(3).times + end + + it "raises a #{error} without retrying when turned off" do + HttpTestApi.configure { |c| c.retry_transient_errors = false } + respond_with(error.new("network")) + + expect { HttpTestApi::Invoice.find(1) }.to raise_error(error) + expect(Kernel).not_to have_received(:sleep) + expect(rejected).to be_empty + end + end + + context "when the authentication raises a RequestError without a response" do + let(:auth) do + rejected_responses = rejected + Class.new do + def apply(_request) + raise RestEasy::RequestError, "No credentials" + end + + define_method(:on_rejected) do |response| + rejected_responses << response + raise RestEasy::RequestError, "Rejected" + end + end.new + end + + it "passes it to the authentication" do + respond_with([200, { "Content-Type" => "application/json" }, invoice]) + + expect { HttpTestApi::Invoice.find(1) }.to raise_error(RestEasy::RequestError, "Rejected") + expect(rejected).to eq([nil]) + end + end + + it "still passes other failures to the authentication" do + respond_with([401, {}, "Unauthorized"]) + + expect { HttpTestApi::Invoice.find(1) }.to raise_error(RestEasy::RequestError) + expect(rejected).to eq([401]) + end + + it "raises once max_retries is used up" do + respond_with(*Array.new(4) { [503, {}, "Unavailable"] }) + + expect { HttpTestApi::Invoice.find(1) }.to raise_error(RestEasy::RequestError, "Request failed: 503") + expect(Kernel).to have_received(:sleep).exactly(3).times + expect(rejected).to be_empty + end + + it "passes transient errors to the authentication when turned off" do + HttpTestApi.configure { |c| c.retry_transient_errors = false } + respond_with([503, {}, "Unavailable"]) + + expect { HttpTestApi::Invoice.find(1) }.to raise_error(RestEasy::RequestError) + expect(rejected).to eq([503]) + end + end + # ── Connection configuration ───────────────────────────────────────── describe "connection block" do