1 /*
2  * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License").
5  * You may not use this file except in compliance with the License.
6  * A copy of the License is located at
7  *
8  *  http://aws.amazon.com/apache2.0
9  *
10  * or in the "license" file accompanying this file. This file is distributed
11  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12  * express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */
15 
16 package software.amazon.awssdk.http.apache.internal;
17 
18 import org.apache.http.HttpResponse;
19 import org.apache.http.impl.client.DefaultClientConnectionReuseStrategy;
20 import org.apache.http.protocol.HttpContext;
21 import software.amazon.awssdk.annotations.SdkInternalApi;
22 
23 /**
24  * Do not reuse connections that returned a 5xx error.
25  *
26  * <p>This is not strictly the behavior we would want in an AWS client, because sometimes we might want to keep a connection open
27  * (e.g. an undocumented service's 503 'SlowDown') and sometimes we might want to close the connection (e.g. S3's 400
28  * RequestTimeout or Glacier's 408 RequestTimeoutException), but this is good enough for the majority of services, and the ones
29  * for which it is not should not be impacted too harshly.
30  */
31 @SdkInternalApi
32 public class SdkConnectionReuseStrategy extends DefaultClientConnectionReuseStrategy {
33     @Override
keepAlive(HttpResponse response, HttpContext context)34     public boolean keepAlive(HttpResponse response, HttpContext context) {
35         if (!super.keepAlive(response, context)) {
36             return false;
37         }
38 
39         if (response == null || response.getStatusLine() == null) {
40             return false;
41         }
42 
43         return !is500(response);
44     }
45 
is500(HttpResponse httpResponse)46     private boolean is500(HttpResponse httpResponse) {
47         return httpResponse.getStatusLine().getStatusCode() / 100 == 5;
48     }
49 }
50