Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 29 additions & 14 deletions src/main/java/com/flagsmith/threads/AnalyticsProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String, LongAdder> 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<String, LongAdder> 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) {
Expand Down
20 changes: 18 additions & 2 deletions src/main/java/com/flagsmith/threads/RequestProcessor.java
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,23 @@ public <T> Future<T> executeAsync(
*/
public <T> CompletableFuture<T> submit(
Request request, TypeReference<T> clazz, Boolean doThrow, Retry retries) {
return submit(request, doThrow, retries, response -> {
ObjectMapper mapper = MapperFactory.getMapper();
return mapper.readValue(response.body().string(), clazz);
});
}

CompletableFuture<Boolean> submitForStatus(Request request) {
return submit(request, false, retries, response -> true);
}

@FunctionalInterface
private interface ResponseReader<T> {
T read(Response response) throws IOException;
}

private <T> CompletableFuture<T> submit(
Request request, Boolean doThrow, Retry retries, ResponseReader<T> reader) {
CompletableFuture<T> completableFuture = new CompletableFuture<>();
Retry localRetry = retries.toBuilder().build();
// run the execute method in a fixed thread with retries.
Expand All @@ -111,8 +128,7 @@ public <T> CompletableFuture<T> 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;

Expand Down
74 changes: 72 additions & 2 deletions src/test/java/com/flagsmith/threads/AnalyticsProcessorTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand All @@ -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);
}
Expand Down Expand Up @@ -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
Expand All @@ -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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: These new tests omit the required // Given, // When, and // Then sections; please add the markers to match TE03.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/test/java/com/flagsmith/threads/AnalyticsProcessorTest.java, line 109:

<comment>These new tests omit the required `// Given`, `// When`, and `// Then` sections; please add the markers to match TE03.</comment>

<file context>
@@ -88,7 +102,63 @@ public void AnalyticsProcessor_checkAnalyticsRequestCheckFlushRuns() {
+  }
+
+  @Test
+  public void testFlush_RestoresCountsAfterRetriesAreExhausted() throws Exception {
+    BlockingQueue<String> bodies = new LinkedBlockingQueue<>();
+    AtomicInteger attempts = new AtomicInteger();
</file context>

BlockingQueue<String> 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The two 503 responses call FlagsmithLogger.httpError, but this test does not assert the expected logging calls; please verify them as required by TE05.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/test/java/com/flagsmith/threads/AnalyticsProcessorTest.java, line 117:

<comment>The two 503 responses call `FlagsmithLogger.httpError`, but this test does not assert the expected logging calls; please verify them as required by TE05.</comment>

<file context>
@@ -88,7 +102,63 @@ public void AnalyticsProcessor_checkAnalyticsRequestCheckFlushRuns() {
+          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();
</file context>

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<RequestBody> 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
Expand Down