From c892eb3ad3e5e32e79c537f94df102947eaa92a2 Mon Sep 17 00:00:00 2001 From: Akihiko Odaki Date: Sat, 19 Oct 2024 21:11:55 +0900 Subject: [PATCH] Add Octokit::Middleware::Retry Octokit::Middleware::Retry allows incorporating the retry logic without relying on the default middleware stack. --- README.md | 2 +- lib/octokit.rb | 6 ++++++ lib/octokit/middleware/retry.rb | 19 +++++++++++++++++++ spec/octokit/client_spec.rb | 21 +++++++++++++++++++++ 4 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 lib/octokit/middleware/retry.rb diff --git a/README.md b/README.md index 569278ad7..afcb6c753 100644 --- a/README.md +++ b/README.md @@ -597,7 +597,7 @@ traffic: ```ruby stack = Faraday::RackBuilder.new do |builder| - builder.use Faraday::Retry::Middleware, exceptions: Faraday::Request::Retry::DEFAULT_EXCEPTIONS + [Octokit::ServerError] # or Faraday::Request::Retry for Faraday < 2.0 + builder.use Octokit::Middleware::Retry builder.use Octokit::Middleware::FollowRedirects builder.use Octokit::Response::RaiseError builder.use Octokit::Response::FeedParser diff --git a/lib/octokit.rb b/lib/octokit.rb index b029d8bc9..db9c9fcbd 100644 --- a/lib/octokit.rb +++ b/lib/octokit.rb @@ -76,6 +76,12 @@ def method_missing(method_name, *args, &block) super end end + + module Middleware + # In Faraday 2.x, Faraday::Request::Retry was moved to a separate gem + # so we use it only when requested. + autoload :Retry, 'octokit/middleware/retry' + end end Octokit.setup diff --git a/lib/octokit/middleware/retry.rb b/lib/octokit/middleware/retry.rb new file mode 100644 index 000000000..f442b16eb --- /dev/null +++ b/lib/octokit/middleware/retry.rb @@ -0,0 +1,19 @@ +# frozen_string_literal: true + +module Octokit + module Middleware + base = if defined?(Faraday::Request::Retry) + Faraday::Request::Retry + else + require 'faraday/retry' + Faraday::Retry::Middleware + end + + # Public: Retries each request a limited number of times. + class Retry < base + def initialize(app, **kwargs) + super(app, **kwargs, exceptions: DEFAULT_EXCEPTIONS + [Octokit::ServerError]) + end + end + end +end diff --git a/spec/octokit/client_spec.rb b/spec/octokit/client_spec.rb index 0ed906058..1c439315c 100644 --- a/spec/octokit/client_spec.rb +++ b/spec/octokit/client_spec.rb @@ -514,6 +514,27 @@ end end + describe 'retry' do + it 'retries for 504 response' do + client = oauth_client + client.middleware.insert Octokit::Response::RaiseError, Octokit::Middleware::Retry + + requested = false + + request = stub_get('/foo').to_return do + if requested + { status: 200 } + else + requested = true + { status: 504 } + end + end + + client.get('/foo') + assert_requested request, times: 2 + end + end + describe 'redirect handling' do it 'follows redirect for 301 response' do client = oauth_client