Skip to content

Commit 2dcf32b

Browse files
committed
Tweak content caching
1 parent 49711f0 commit 2dcf32b

File tree

3 files changed

+39
-29
lines changed

3 files changed

+39
-29
lines changed

src/main/java/io/apitally/common/ApitallyClient.java

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ public enum HubRequestStatus {
6666
private ScheduledFuture<?> syncTask;
6767
private StartupData startupData;
6868
private boolean startupDataSent = false;
69+
private boolean enabled = true;
6970

7071
public final RequestCounter requestCounter;
7172
public final RequestLogger requestLogger;
@@ -89,6 +90,10 @@ public ApitallyClient(String clientId, String env, RequestLoggingConfig requestL
8990
this.consumerRegistry = new ConsumerRegistry();
9091
}
9192

93+
public boolean isEnabled() {
94+
return enabled;
95+
}
96+
9297
private HttpClient createHttpClient() {
9398
return HttpClient.newBuilder()
9499
.version(HttpClient.Version.HTTP_1_1)
@@ -193,7 +198,10 @@ private void sendLogData() {
193198
.POST(HttpRequest.BodyPublishers.ofInputStream(() -> inputStream))
194199
.build();
195200
HubRequestStatus status = sendHubRequest(request).join();
196-
if (status == HubRequestStatus.RETRYABLE_ERROR) {
201+
if (status == HubRequestStatus.PAYMENT_REQUIRED) {
202+
requestLogger.clear();
203+
requestLogger.setSuspendUntil(System.currentTimeMillis() + (3600 * 1000L));
204+
} else if (status == HubRequestStatus.RETRYABLE_ERROR) {
197205
requestLogger.retryFileLater(logFile);
198206
break;
199207
} else {
@@ -219,22 +227,11 @@ public CompletableFuture<HubRequestStatus> sendHubRequest(HttpRequest request) {
219227
if (response.statusCode() >= 200 && response.statusCode() < 300) {
220228
return HubRequestStatus.OK;
221229
} else if (response.statusCode() == 402) {
222-
// 402 is only returned by the log endpoint, meaning request logging is not
223-
// allowed for this client
224-
Optional<String> retryAfter = response.headers().firstValue("Retry-After");
225-
if (retryAfter.isPresent()) {
226-
try {
227-
int retryAfterSeconds = Integer.parseInt(retryAfter.get());
228-
requestLogger
229-
.setSuspendUntil(System.currentTimeMillis() + (retryAfterSeconds * 1000L));
230-
} catch (NumberFormatException e) {
231-
// Ignore invalid Retry-After header
232-
}
233-
}
234-
requestLogger.clear();
235230
return HubRequestStatus.PAYMENT_REQUIRED;
236231
} else if (response.statusCode() == 404) {
232+
enabled = false;
237233
stopSync();
234+
requestLogger.close();
238235
logger.error("Invalid Apitally client ID: {}", clientId);
239236
return HubRequestStatus.INVALID_CLIENT_ID;
240237
} else if (response.statusCode() == 422) {
@@ -304,6 +301,7 @@ private void sync() {
304301

305302
public void shutdown() {
306303
try {
304+
enabled = false;
307305
boolean syncRunning = syncTask != null;
308306
stopSync();
309307
if (syncRunning) {

src/main/java/io/apitally/common/RequestLogger.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,12 @@
2121
import org.slf4j.Logger;
2222
import org.slf4j.LoggerFactory;
2323

24+
import com.fasterxml.jackson.databind.ObjectMapper;
25+
import com.fasterxml.jackson.databind.node.ObjectNode;
26+
2427
import io.apitally.common.dto.Header;
2528
import io.apitally.common.dto.Request;
2629
import io.apitally.common.dto.Response;
27-
import com.fasterxml.jackson.databind.ObjectMapper;
28-
import com.fasterxml.jackson.databind.node.ObjectNode;
2930

3031
public class RequestLogger {
3132
private static final Logger logger = LoggerFactory.getLogger(RequestLogger.class);
@@ -37,7 +38,7 @@ public class RequestLogger {
3738
private static final byte[] BODY_TOO_LARGE = "<body too large>".getBytes(StandardCharsets.UTF_8);
3839
private static final byte[] BODY_MASKED = "<masked>".getBytes(StandardCharsets.UTF_8);
3940
private static final String MASKED = "******";
40-
private static final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList("application/json", "text/plain");
41+
public static final List<String> ALLOWED_CONTENT_TYPES = Arrays.asList("application/json", "text/plain");
4142
private static final List<String> EXCLUDE_PATH_PATTERNS = Arrays.asList(
4243
"/_?healthz?$",
4344
"/_?health[_-]?checks?$",

src/main/java/io/apitally/spring/ApitallyFilter.java

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
import io.apitally.common.ApitallyClient;
1717
import io.apitally.common.ConsumerRegistry;
18+
import io.apitally.common.RequestLogger;
1819
import io.apitally.common.dto.Consumer;
1920
import io.apitally.common.dto.Header;
2021
import io.apitally.common.dto.Request;
@@ -38,23 +39,33 @@ public ApitallyFilter(ApitallyClient client) {
3839
@Override
3940
protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response,
4041
@NonNull FilterChain filterChain) throws ServletException, IOException {
41-
final boolean isContentCachingEnabled = client.requestLogger.getConfig().isEnabled()
42-
&& (client.requestLogger.getConfig().isRequestBodyIncluded() || client.requestLogger.getConfig()
43-
.isResponseBodyIncluded());
42+
if (!client.isEnabled()) {
43+
filterChain.doFilter(request, response);
44+
return;
45+
}
46+
47+
String requestContentType = request.getContentType();
48+
final boolean shouldCacheRequest = client.requestLogger.getConfig().isEnabled()
49+
&& client.requestLogger.getConfig().isRequestBodyIncluded()
50+
&& requestContentType != null
51+
&& RequestLogger.ALLOWED_CONTENT_TYPES.stream()
52+
.anyMatch(allowedContentType -> requestContentType.startsWith(allowedContentType));
53+
final boolean shouldCacheResponse = client.requestLogger.getConfig().isEnabled()
54+
&& client.requestLogger.getConfig().isResponseBodyIncluded();
55+
ContentCachingRequestWrapper cachingRequest = shouldCacheRequest
56+
? new ContentCachingRequestWrapper(request)
57+
: null;
58+
ContentCachingResponseWrapper cachingResponse = shouldCacheResponse
59+
? new ContentCachingResponseWrapper(response)
60+
: null;
4461

4562
Exception exception = null;
4663
final long startTime = System.currentTimeMillis();
47-
ContentCachingRequestWrapper cachingRequest = null;
48-
ContentCachingResponseWrapper cachingResponse = null;
4964

5065
try {
51-
if (isContentCachingEnabled) {
52-
cachingRequest = new ContentCachingRequestWrapper(request);
53-
cachingResponse = new ContentCachingResponseWrapper(response);
54-
filterChain.doFilter(cachingRequest, cachingResponse);
55-
} else {
56-
filterChain.doFilter(request, response);
57-
}
66+
filterChain.doFilter(
67+
cachingRequest != null ? cachingRequest : request,
68+
cachingResponse != null ? cachingResponse : response);
5869
} catch (Exception e) {
5970
exception = e;
6071
throw e;

0 commit comments

Comments
 (0)