diff --git a/src/main/java/com/flagsmith/threads/AnalyticsProcessor.java b/src/main/java/com/flagsmith/threads/AnalyticsProcessor.java index da631f5..70029bf 100644 --- a/src/main/java/com/flagsmith/threads/AnalyticsProcessor.java +++ b/src/main/java/com/flagsmith/threads/AnalyticsProcessor.java @@ -6,6 +6,7 @@ import com.flagsmith.MapperFactory; import com.flagsmith.interfaces.FlagsmithSdk; import java.time.Instant; +import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; @@ -112,44 +113,58 @@ private HttpUrl getAnalyticsUrl() { /** * Push the analytics to the server. */ - public void flush() { - // Make sure analytics data is only flushed once. - if (isFlushing.compareAndSet(false, true)) { + public synchronized void flush() { + if (!isFlushing.compareAndSet(false, true)) { + return; + } + + try { if (analyticsData.isEmpty()) { - isFlushing.set(false); return; } - String response; - + Map batch = new HashMap<>(analyticsData); + String payload; try { ObjectMapper mapper = MapperFactory.getMapper(); - response = mapper.writeValueAsString(analyticsData); - analyticsData.clear(); + payload = mapper.writeValueAsString(batch); } catch (JsonProcessingException jpe) { logger.error("Error parsing analytics data to JSON.", jpe); - isFlushing.set(false); return; } MediaType json = MediaType.get("application/json; charset=utf-8"); - RequestBody body = RequestBody.create(response, json); - + RequestBody body = RequestBody.create(payload, json); Request request = api.newPostRequest(getAnalyticsUrl(), body); - - getRequestProcessor().executeAsync(request, Boolean.FALSE); + analyticsData.clear(); + try { + getRequestProcessor().submitForStatus(request).whenComplete((success, error) -> { + if (!Boolean.TRUE.equals(success)) { + restore(batch); + } + }); + } catch (RuntimeException e) { + restore(batch); + throw e; + } setNextFlush(); + } finally { isFlushing.set(false); } } + private synchronized void restore(Map batch) { + batch.forEach((feature, count) -> + analyticsData.computeIfAbsent(feature, key -> new LongAdder()).add(count.longValue())); + } + /** * Track the feature usage for analytics. * * @param featureName name of the feature to track evaluation for */ - public void trackFeature(String featureName) { + public synchronized void trackFeature(String featureName) { analyticsData.computeIfAbsent(featureName, k -> new LongAdder()).increment(); if (nextFlush.compareTo(Instant.now().getEpochSecond()) < 0) { diff --git a/src/main/java/com/flagsmith/threads/RequestProcessor.java b/src/main/java/com/flagsmith/threads/RequestProcessor.java index 36bc4bc..9689000 100644 --- a/src/main/java/com/flagsmith/threads/RequestProcessor.java +++ b/src/main/java/com/flagsmith/threads/RequestProcessor.java @@ -96,6 +96,23 @@ public Future executeAsync( */ public CompletableFuture submit( Request request, TypeReference clazz, Boolean doThrow, Retry retries) { + return submit(request, doThrow, retries, response -> { + ObjectMapper mapper = MapperFactory.getMapper(); + return mapper.readValue(response.body().string(), clazz); + }); + } + + CompletableFuture submitForStatus(Request request) { + return submit(request, false, retries, response -> true); + } + + @FunctionalInterface + private interface ResponseReader { + T read(Response response) throws IOException; + } + + private CompletableFuture submit( + Request request, Boolean doThrow, Retry retries, ResponseReader reader) { CompletableFuture completableFuture = new CompletableFuture<>(); Retry localRetry = retries.toBuilder().build(); // run the execute method in a fixed thread with retries. @@ -111,8 +128,7 @@ public CompletableFuture submit( try (Response response = call.execute()) { statusCode = response.code(); if (response.isSuccessful()) { - ObjectMapper mapper = MapperFactory.getMapper(); - completableFuture.complete(mapper.readValue(response.body().string(), clazz)); + completableFuture.complete(reader.read(response)); // break the while break; diff --git a/src/test/java/com/flagsmith/threads/AnalyticsProcessorTest.java b/src/test/java/com/flagsmith/threads/AnalyticsProcessorTest.java index 6895f4b..dc8e352 100644 --- a/src/test/java/com/flagsmith/threads/AnalyticsProcessorTest.java +++ b/src/test/java/com/flagsmith/threads/AnalyticsProcessorTest.java @@ -16,13 +16,25 @@ import com.flagsmith.config.FlagsmithConfig; import com.flagsmith.config.Retry; import java.io.IOException; +import java.util.Collections; +import java.util.HashMap; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import lombok.SneakyThrows; +import okhttp3.Protocol; +import okhttp3.RequestBody; import okhttp3.Response; +import okhttp3.ResponseBody; +import okio.Buffer; import okhttp3.mock.MockInterceptor; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; public class AnalyticsProcessorTest { @@ -47,6 +59,8 @@ public void init() { .build(); api = mock(FlagsmithApiWrapper.class); requestProcessor = mock(RequestProcessor.class); + when(requestProcessor.submitForStatus(any())) + .thenReturn(CompletableFuture.completedFuture(true)); when(api.getConfig()).thenReturn(defaultConfig); analytics = new AnalyticsProcessor(api, flagsmithLogger, requestProcessor); } @@ -75,7 +89,7 @@ public void AnalyticsProcessor_checkAnalyticsDataCheckFlushRuns() throws Interru Assertions.assertEquals(analytics.getAnalyticsData().size(), 0); Assertions.assertNotEquals(nextFlush, analytics.getNextFlush()); verify(api, times(1)).newPostRequest(any(), any()); - verify(requestProcessor, times(1)).executeAsync(any(), any()); + verify(requestProcessor, times(1)).submitForStatus(any()); } @Test @@ -88,7 +102,63 @@ public void AnalyticsProcessor_checkAnalyticsRequestCheckFlushRuns() { analytics.flush(); verify(api, times(1)).newPostRequest(any(), any()); - verify(requestProcessor, times(1)).executeAsync(any(), any()); + verify(requestProcessor, times(1)).submitForStatus(any()); + } + + @Test + public void testFlush_RestoresCountsAfterRetriesAreExhausted() throws Exception { + BlockingQueue bodies = new LinkedBlockingQueue<>(); + AtomicInteger attempts = new AtomicInteger(); + FlagsmithConfig config = FlagsmithConfig.newBuilder().baseUri("http://base-uri/") + .addHttpInterceptor(chain -> { + Buffer body = new Buffer(); + chain.request().body().writeTo(body); + bodies.add(body.readUtf8()); + int status = attempts.incrementAndGet() <= 2 ? 503 : 200; + return new Response.Builder().request(chain.request()).protocol(Protocol.HTTP_1_1) + .code(status).message("").body(ResponseBody.create("", null)).build(); + }).build(); + Retry retry = new Retry(2, 0, 0f, 15f, Collections.singleton(503), true); + RequestProcessor processor = new RequestProcessor(config.getHttpClient(), flagsmithLogger, + retry); + FlagsmithApiWrapper wrapper = + new FlagsmithApiWrapper(config, new HashMap<>(), flagsmithLogger, "test-key", processor); + AnalyticsProcessor tracker = new AnalyticsProcessor(wrapper, flagsmithLogger, processor); + + try { + tracker.trackFeature("foo"); + tracker.trackFeature("foo"); + tracker.flush(); + Assertions.assertEquals("{\"foo\":2}", bodies.poll(5, TimeUnit.SECONDS)); + Assertions.assertEquals("{\"foo\":2}", bodies.poll(5, TimeUnit.SECONDS)); + + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2); + while (!tracker.getAnalyticsData().containsKey("foo") && System.nanoTime() < deadline) { + Thread.sleep(10); + } + tracker.trackFeature("foo"); + tracker.flush(); + Assertions.assertEquals("{\"foo\":3}", bodies.poll(5, TimeUnit.SECONDS)); + } finally { + tracker.close(); + } + } + + @Test + public void testFlush_DoesNotResendSuccessfulCounts() throws IOException { + analytics.trackFeature("foo"); + analytics.trackFeature("foo"); + analytics.flush(); + analytics.trackFeature("foo"); + analytics.flush(); + + ArgumentCaptor bodies = ArgumentCaptor.forClass(RequestBody.class); + verify(api, times(2)).newPostRequest(any(), bodies.capture()); + Buffer body = new Buffer(); + bodies.getAllValues().get(0).writeTo(body); + Assertions.assertEquals("{\"foo\":2}", body.readUtf8()); + bodies.getAllValues().get(1).writeTo(body); + Assertions.assertEquals("{\"foo\":1}", body.readUtf8()); } @Test