|
4 | 4 | import com.google.common.io.CountingInputStream; |
5 | 5 | import com.google.gson.Gson; |
6 | 6 | import com.google.gson.reflect.TypeToken; |
| 7 | +import okhttp3.CacheControl; |
| 8 | +import okhttp3.ConnectionPool; |
| 9 | +import okhttp3.Dns; |
| 10 | +import okhttp3.Headers; |
| 11 | +import okhttp3.HttpUrl; |
| 12 | +import okhttp3.OkHttpClient; |
| 13 | +import okhttp3.Request; |
| 14 | +import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; |
| 15 | +import org.jetbrains.annotations.NotNull; |
7 | 16 | import org.slf4j.Logger; |
8 | 17 | import org.slf4j.LoggerFactory; |
9 | 18 |
|
| 19 | +import java.io.BufferedReader; |
10 | 20 | import java.io.IOException; |
11 | 21 | import java.io.InputStream; |
12 | 22 | import java.io.InputStreamReader; |
13 | | -import java.net.http.HttpClient; |
| 23 | +import java.net.InetAddress; |
| 24 | +import java.net.UnknownHostException; |
14 | 25 | import java.net.http.HttpRequest; |
15 | | -import java.net.http.HttpResponse; |
16 | 26 | import java.nio.charset.StandardCharsets; |
17 | | -import java.util.zip.GZIPInputStream; |
| 27 | +import java.time.Duration; |
| 28 | +import java.util.ArrayList; |
| 29 | +import java.util.Arrays; |
| 30 | +import java.util.Collections; |
| 31 | +import java.util.HashMap; |
| 32 | +import java.util.List; |
| 33 | +import java.util.Map; |
18 | 34 |
|
19 | 35 | public class OrefApiClient { |
20 | 36 | private static final Logger logger = LoggerFactory.getLogger(OrefApiClient.class); |
21 | | - private static final HttpClient client = HttpClient.newHttpClient(); |
| 37 | + private static OkHttpClient client = null; |
| 38 | + private static ConnectionPool connectionPool; |
22 | 39 | private static final int SUCCESS_STATUS_CODE = 200; |
23 | 40 |
|
24 | 41 | public static <T> ApiResponse<T> get(HttpRequest req, TypeToken<T> typeToken) |
25 | 42 | throws IOException, InterruptedException { |
26 | 43 | Gson gson = new Gson(); |
27 | 44 |
|
28 | 45 | Stopwatch stopwatch = Stopwatch.createStarted(); |
29 | | - HttpResponse<InputStream> httpResponse = client.send(req, HttpResponse.BodyHandlers.ofInputStream()); |
30 | | - |
31 | | - // Body stream *MUST* be listed separately because we always want to close it even with there is an error |
32 | | - // creating the gzipReader. Not closing the body stream is a memory leak.. |
33 | | - try (CountingInputStream is = new CountingInputStream(httpResponse.body()); |
34 | | - InputStream gzipReader = wrapWithGzip(httpResponse, is); |
35 | | - InputStreamReader isr = new InputStreamReader(gzipReader, StandardCharsets.UTF_8)) { |
36 | | - if (httpResponse.statusCode() != SUCCESS_STATUS_CODE) { |
37 | | - logger.warn("Failed http request: {} {} {}", req.uri(), httpResponse.statusCode(), httpResponse.headers()); |
38 | | - throw new RuntimeException("Unexpected Status Code " + httpResponse.statusCode()); |
| 46 | + |
| 47 | + List<String> allheaders = convertHeadersToOkHttp(req); |
| 48 | + var okHttpReq = new Request.Builder() |
| 49 | + .cacheControl(new CacheControl.Builder().noCache().build()) |
| 50 | + .headers(Headers.of(allheaders.toArray(new String[0]))) |
| 51 | + .url(req.uri().toURL()) |
| 52 | + .build(); |
| 53 | + var httpResponse = getHttpClient().newCall(okHttpReq).execute(); |
| 54 | + logger.debug("Received resp - content-length {} bytes in Request to {}: Response: {} in {}", |
| 55 | + httpResponse.body() == null ? -1 : httpResponse.body().contentLength(), req.uri(), |
| 56 | + httpResponse.code(), stopwatch.elapsed()); |
| 57 | + |
| 58 | + try (var is = httpResponse.body().byteStream(); |
| 59 | + var wrappedReader = new CountingInputStream(wrapWithGzip(httpResponse.request().url(), httpResponse.headers(), is)); |
| 60 | + var isr = new BufferedReader(new InputStreamReader(wrappedReader, StandardCharsets.UTF_8))) { |
| 61 | + if (httpResponse.code() != SUCCESS_STATUS_CODE) { |
| 62 | + logger.warn("Failed http request: {} {} {}", req.uri(), httpResponse.code(), |
| 63 | + httpResponse.headers()); |
| 64 | + throw new RuntimeException("Unexpected Status Code " + httpResponse.code()); |
39 | 65 | } else { |
40 | 66 | T ret = gson.fromJson(isr, typeToken); |
41 | 67 |
|
42 | | - logger.debug("Fetched {} bytes in Request to {}: Response: {} in {}", is.getCount(), req.uri(), |
43 | | - httpResponse.statusCode(), stopwatch.elapsed()); |
44 | | - logger.trace("Request to {}: Response: {} {} {}", req, httpResponse.statusCode(), |
| 68 | + logger.debug("Decoded {} bytes uncompressed: {} bytes in Request to {}: Response: {} in {}", |
| 69 | + httpResponse.body().contentLength(), wrappedReader.getCount(), req.uri(), httpResponse.code(), |
| 70 | + stopwatch.elapsed()); |
| 71 | + logger.trace("Request to {}: Response: {} {} {}", req, httpResponse.code(), |
45 | 72 | httpResponse.headers(), ret); |
46 | 73 |
|
47 | 74 | return new ApiResponse<>(httpResponse, ret); |
48 | 75 | } |
| 76 | + } catch (Exception ex) { |
| 77 | + logger.info("Failed to decode resp {}", httpResponse.request().url()); |
| 78 | + // evicting from the pool forces a reconnect, hopefully to a different host that is not broken. |
| 79 | + connectionPool.evictAll(); |
| 80 | + throw ex; |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + @NotNull |
| 85 | + private static List<String> convertHeadersToOkHttp(HttpRequest req) |
| 86 | + { |
| 87 | + List<String> allheaders = new ArrayList<>(); |
| 88 | + for (var h : req.headers().map().entrySet()) |
| 89 | + { |
| 90 | + for (var val : h.getValue()) |
| 91 | + { |
| 92 | + allheaders.add(h.getKey()); |
| 93 | + allheaders.add(val); |
| 94 | + } |
| 95 | + } |
| 96 | + return allheaders; |
| 97 | + } |
| 98 | + |
| 99 | + private static synchronized OkHttpClient getHttpClient() { |
| 100 | + if (client == null) |
| 101 | + { |
| 102 | + connectionPool = new ConnectionPool(); |
| 103 | + client = new OkHttpClient.Builder() |
| 104 | + .callTimeout(Duration.ofSeconds(8)) |
| 105 | + .connectionPool(connectionPool) |
| 106 | + .dns(new RotatingDns()) |
| 107 | + .build(); |
49 | 108 | } |
| 109 | + return client; |
50 | 110 | } |
51 | 111 |
|
52 | | - private static InputStream wrapWithGzip(HttpResponse<InputStream> httpResponse, InputStream is) throws IOException { |
53 | | - var contentEncoding = httpResponse.headers().allValues("Content-Encoding"); |
| 112 | + private static InputStream wrapWithGzip(HttpUrl url, Headers responseHeaders, InputStream is) throws IOException { |
| 113 | + var contentEncoding = responseHeaders.toMultimap().get("Content-Encoding"); |
54 | 114 | if (!contentEncoding.isEmpty()) { |
55 | 115 | if (contentEncoding.size() == 1 && contentEncoding.get(0).equalsIgnoreCase("gzip")) { |
56 | | - is = new GZIPInputStream(is); |
| 116 | + logger.debug("response is gzipped encoded {}", url); |
| 117 | + return new GzipCompressorInputStream(is); |
57 | 118 | } else { |
58 | 119 | throw new IllegalStateException("Unknown content encoding " + contentEncoding); |
59 | 120 | } |
60 | 121 | } |
| 122 | + logger.debug("response is not gzipped encoded {}", url); |
61 | 123 | return is; |
62 | 124 | } |
| 125 | + |
| 126 | + /** |
| 127 | + * A dns resolver that ensures that the returned hosts are shuffled and the same host is not returned at the start of the list twice |
| 128 | + */ |
| 129 | + private static class RotatingDns implements Dns |
| 130 | + { |
| 131 | + private final Map<String, InetAddress> cachedIps = new HashMap<>(); |
| 132 | + |
| 133 | + @NotNull |
| 134 | + @Override |
| 135 | + public synchronized List<InetAddress> lookup(@NotNull String hostname) throws UnknownHostException |
| 136 | + { |
| 137 | + try |
| 138 | + { |
| 139 | + var ips = InetAddress.getAllByName(hostname); |
| 140 | + if (ips.length > 1 && cachedIps.containsKey(hostname)) |
| 141 | + { |
| 142 | + var oldFirstAddr = cachedIps.get(hostname); |
| 143 | + Collections.shuffle(Arrays.asList(ips)); |
| 144 | + |
| 145 | + // make sure that the last first IP we returned is not the first IP again, since that is likely what was used. |
| 146 | + if (oldFirstAddr.equals(ips[0])) |
| 147 | + { |
| 148 | + ips[0] = ips[ips.length - 1]; |
| 149 | + ips[ips.length - 1] = oldFirstAddr; |
| 150 | + } |
| 151 | + } |
| 152 | + if (ips.length > 0) |
| 153 | + { |
| 154 | + cachedIps.put(hostname, ips[0]); |
| 155 | + } |
| 156 | + var ret = List.of(ips); |
| 157 | + logger.info("resolved {} to {}", hostname, ret); |
| 158 | + return ret; |
| 159 | + } |
| 160 | + catch (NullPointerException e) |
| 161 | + { |
| 162 | + throw new UnknownHostException("Broken system behaviour for dns lookup of " + hostname); |
| 163 | + } |
| 164 | + } |
| 165 | + } |
63 | 166 | } |
0 commit comments