Skip to content

Commit

Permalink
feat: Retry all http methods
Browse files Browse the repository at this point in the history
  • Loading branch information
monochromata authored and rholshausen committed Apr 22, 2024
1 parent 45e4a9c commit 2d86f44
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import org.apache.hc.client5.http.socket.ConnectionSocketFactory
import org.apache.hc.client5.http.socket.PlainConnectionSocketFactory
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder
import org.apache.hc.client5.http.ssl.TrustSelfSignedStrategy
import org.apache.hc.core5.http.HttpRequest
import org.apache.hc.core5.http.config.RegistryBuilder
import org.apache.hc.core5.http.message.BasicHeader
import org.apache.hc.core5.ssl.SSLContexts
Expand Down Expand Up @@ -70,6 +71,13 @@ sealed class Auth {
}
}

private class RetryAnyMethod(
maxRetries: Int,
defaultRetryInterval: TimeValue
): DefaultHttpRequestRetryStrategy(maxRetries, defaultRetryInterval) {
override fun handleAsIdempotent(request: HttpRequest) = true
}

/**
* HTTP client support functions
*/
Expand All @@ -86,7 +94,7 @@ object HttpClient : KLogging() {
insecureTLS: Boolean = false
): Pair<CloseableHttpClient, CredentialsProvider?> {
val builder = HttpClients.custom().useSystemProperties()
.setRetryStrategy(DefaultHttpRequestRetryStrategy(maxPublishRetries,
.setRetryStrategy(RetryAnyMethod(maxPublishRetries,
TimeValue.ofMilliseconds(publishRetryInterval.toLong())))

val defaultHeaders = mutableMapOf<String, String>()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package au.com.dius.pact.core.support

import org.apache.hc.client5.http.impl.classic.HttpRequestRetryExec
import org.apache.hc.client5.http.impl.classic.ProtocolExec
import org.apache.hc.client5.http.protocol.RequestDefaultHeaders
import org.apache.hc.core5.http.HttpRequest
import org.apache.hc.core5.http.Method
import spock.lang.Specification

class HttpClientSpec extends Specification {
Expand Down Expand Up @@ -30,4 +33,26 @@ class HttpClientSpec extends Specification {
defaultHeaders[0].name == 'Authorization'
defaultHeaders[0].value == 'Bearer 1234abcd'
}

def 'http client should retry any requests for any method'(Method method) {
def uri = new URI('http://localhost')
def request = Mock(HttpRequest)
request.method >> method
def client = HttpClient.INSTANCE.newHttpClient(null, uri, 1, 1, false).component1()
def retryStrategy = null
def execChain = client.execChain
while (retryStrategy == null && execChain != null) {
if (execChain.handler instanceof HttpRequestRetryExec) {
retryStrategy = execChain.handler.retryStrategy
} else {
execChain = execChain.next
}
}

expect:
retryStrategy.handleAsIdempotent(request) == true

where:
method << Method.values()
}
}

0 comments on commit 2d86f44

Please sign in to comment.