-
Notifications
You must be signed in to change notification settings - Fork 6
/
ConfigFetcher.java
188 lines (162 loc) · 8.02 KB
/
ConfigFetcher.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package com.configcat;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import java.io.Closeable;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
class ConfigFetcher implements Closeable {
private final AtomicBoolean isClosed = new AtomicBoolean(false);
private final ConfigCatLogger logger;
private final OkHttpClient httpClient;
private final String mode;
private final String sdkKey;
private final boolean urlIsCustom;
private String url;
enum RedirectMode {
NoRedirect,
ShouldRedirect,
ForceRedirect
}
ConfigFetcher(OkHttpClient httpClient,
ConfigCatLogger logger,
String sdkKey,
String url,
boolean urlIsCustom,
String pollingIdentifier) {
this.logger = logger;
this.sdkKey = sdkKey;
this.urlIsCustom = urlIsCustom;
this.url = url;
this.httpClient = httpClient;
this.mode = pollingIdentifier;
}
public CompletableFuture<FetchResponse> fetchAsync(String eTag) {
return this.executeFetchAsync(2, eTag);
}
private CompletableFuture<FetchResponse> executeFetchAsync(int executionCount, String eTag) {
return this.getResponseAsync(eTag).thenComposeAsync(fetchResponse -> {
if (!fetchResponse.isFetched()) {
return CompletableFuture.completedFuture(fetchResponse);
}
try {
Entry entry = fetchResponse.entry();
Config config = entry.getConfig();
if (config.getPreferences() == null) {
return CompletableFuture.completedFuture(fetchResponse);
}
String newUrl = config.getPreferences().getBaseUrl();
if (newUrl == null || newUrl.isEmpty() || this.url.equals(newUrl)) {
return CompletableFuture.completedFuture(fetchResponse);
}
int redirect = config.getPreferences().getRedirect();
// we have a custom url set, and we didn't get a forced redirect
if (this.urlIsCustom && redirect != RedirectMode.ForceRedirect.ordinal()) {
return CompletableFuture.completedFuture(fetchResponse);
}
this.url = newUrl;
if (redirect == RedirectMode.NoRedirect.ordinal()) { // no redirect
return CompletableFuture.completedFuture(fetchResponse);
} else { // redirect
if (redirect == RedirectMode.ShouldRedirect.ordinal()) {
this.logger.warn(3002, ConfigCatLogMessages.DATA_GOVERNANCE_IS_OUT_OF_SYNC_WARN);
}
if (executionCount > 0) {
return this.executeFetchAsync(executionCount - 1, eTag);
}
}
} catch (Exception exception) {
this.logger.error(1103, ConfigCatLogMessages.FETCH_FAILED_DUE_TO_UNEXPECTED_ERROR, exception);
return CompletableFuture.completedFuture(fetchResponse);
}
this.logger.error(1104, ConfigCatLogMessages.FETCH_FAILED_DUE_TO_REDIRECT_LOOP_ERROR);
return CompletableFuture.completedFuture(fetchResponse);
});
}
private CompletableFuture<FetchResponse> getResponseAsync(final String eTag) {
Request request = this.getRequest(eTag);
CompletableFuture<FetchResponse> future = new CompletableFuture<>();
this.httpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
int logEventId = 1103;
String message = ConfigCatLogMessages.FETCH_FAILED_DUE_TO_UNEXPECTED_ERROR;
if (!isClosed.get()) {
if (e instanceof SocketTimeoutException) {
logEventId = 1102;
message = ConfigCatLogMessages.getFetchFailedDueToRequestTimeout(httpClient.connectTimeoutMillis(), httpClient.readTimeoutMillis(), httpClient.writeTimeoutMillis());
}
logger.error(logEventId, message, e);
}
future.complete(FetchResponse.failed(message, false));
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) {
try (ResponseBody body = response.body()) {
if (response.isSuccessful() && body != null) {
String content = body.string();
String eTag = response.header("ETag");
Result<Config> result = deserializeConfig(content);
if (result.error() != null) {
future.complete(FetchResponse.failed(result.error(), false));
return;
}
logger.debug("Fetch was successful: new config fetched.");
future.complete(FetchResponse.fetched(new Entry(result.value(), eTag, content, System.currentTimeMillis())));
} else if (response.code() == 304) {
logger.debug("Fetch was successful: config not modified.");
future.complete(FetchResponse.notModified());
} else if (response.code() == 403 || response.code() == 404) {
String message = ConfigCatLogMessages.FETCH_FAILED_DUE_TO_INVALID_SDK_KEY_ERROR;
logger.error(1100, message);
future.complete(FetchResponse.failed(message, true));
} else {
String message = ConfigCatLogMessages.getFetchFailedDueToUnexpectedHttpResponse(response.code(), response.message());
logger.error(1101, message);
future.complete(FetchResponse.failed(message, false));
}
} catch (SocketTimeoutException e) {
String message = ConfigCatLogMessages.getFetchFailedDueToRequestTimeout(httpClient.connectTimeoutMillis(), httpClient.readTimeoutMillis(), httpClient.writeTimeoutMillis());
logger.error(1102, message, e);
future.complete(FetchResponse.failed(message, false));
} catch (Exception e) {
String message = ConfigCatLogMessages.FETCH_FAILED_DUE_TO_UNEXPECTED_ERROR;
logger.error(1103, message, e);
future.complete(FetchResponse.failed(message, false));
}
}
});
return future;
}
@Override
public void close() throws IOException {
if (!this.isClosed.compareAndSet(false, true)) {
return;
}
if (this.httpClient != null) {
this.httpClient.dispatcher().executorService().shutdownNow();
this.httpClient.connectionPool().evictAll();
Cache cache = this.httpClient.cache();
if (cache != null)
cache.close();
}
}
Request getRequest(String etag) {
String url = this.url + "/configuration-files/" + this.sdkKey + "/" + Constants.CONFIG_JSON_NAME;
Request.Builder builder = new Request.Builder()
.addHeader("X-ConfigCat-UserAgent", "ConfigCat-Java/" + this.mode + "-" + Constants.VERSION);
if (etag != null && !etag.isEmpty())
builder.addHeader("If-None-Match", etag);
return builder.url(url).build();
}
private Result<Config> deserializeConfig(String json) {
try {
return Result.success(Utils.deserializeConfig(json));
} catch (Exception e) {
String message = ConfigCatLogMessages.FETCH_RECEIVED_200_WITH_INVALID_BODY_ERROR;
this.logger.error(1105, message, e);
return Result.error(message, null);
}
}
}