diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java index 7126c0f9..e9fdc12b 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/DirectEventProcessor.java @@ -194,6 +194,13 @@ static final class Pacing { */ private long claimedLostEvents; + /** + * Whether a loss was claimed for a caller who stopped waiting before the answer reporting it came, so + * that the next delivery a caller waits on reports it instead. Set from that caller's thread, or the + * thread that answers, and taken on the scheduler thread. + */ + private final AtomicBoolean lossOwed = new AtomicBoolean(false); + /** * How many refusals of the payload in a row drop a batch: a 400, 413, 415 or 422, in any mix * ({@link LDUtil#isEventPayloadRefused}). Each says the service will not take this body, which posting @@ -401,11 +408,13 @@ private void reportDiscarded(int events) { * Runs on the scheduler thread. * * @param mark the loss count as of the close of that delivery's batch - * @return true if a loss at or before the mark belonged to no earlier delivery a caller waited on + * @return true if a loss at or before the mark belonged to no earlier delivery a caller waited on, or + * one was claimed for a caller who stopped waiting before it heard of it */ private boolean claimEventsLost(long mark) { + boolean owed = lossOwed.getAndSet(false); if (mark <= claimedLostEvents) { - return false; + return owed; } claimedLostEvents = mark; return true; @@ -510,7 +519,7 @@ private Future queueDelivery(boolean answersACaller, boolean bypassBack * on had passed them, because a delivery that finds nothing to send is not evidence that everything * recorded arrived. */ - private void runDelivery(LDAwaitFuture result, EventDeliveryScheduler.Joined joined) { + private void runDelivery(EventDeliveryScheduler.RequestedAnswer result, EventDeliveryScheduler.Joined joined) { DeliveryOutcome outcome; try { outcome = commitAndDeliverReportingOutcome(deliveryScheduler.requestedRun(joined.bypassesBackoff)); @@ -522,6 +531,12 @@ private void runDelivery(LDAwaitFuture result, EventDeliveryScheduler.J } // Claimed before the next delivery can run, however long this one's retry takes to answer. boolean lostEvents = joined.answersACaller && claimEventsLost(outcome.lostEventsMark); + if (lostEvents) { + // Claimed for this delivery's callers, a loss a caller does not stay to hear of is not heard + // of at all unless the next delivery reports it too. Two callers joined to this one may then + // both hear of it, which is the safe direction. + result.lossUnheard = () -> lossOwed.set(true); + } if (outcome.retry == null) { answer(result, outcome.delivered, lostEvents); } else { diff --git a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/EventDeliveryScheduler.java b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/EventDeliveryScheduler.java index 1d9f2a32..63351d3f 100644 --- a/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/EventDeliveryScheduler.java +++ b/launchdarkly-android-client-sdk/src/main/java/com/launchdarkly/sdk/android/EventDeliveryScheduler.java @@ -1,5 +1,7 @@ package com.launchdarkly.sdk.android; +import androidx.annotation.NonNull; + import com.launchdarkly.logging.LDLogger; import java.util.concurrent.Callable; @@ -8,6 +10,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; /** * Puts the event processor's deliveries on its scheduler thread, one at a time, and decides when that thread @@ -21,7 +24,46 @@ final class EventDeliveryScheduler { /** A requested delivery, given the future its callers wait on and who joined it by the time it began. */ interface RequestedDelivery { - void run(LDAwaitFuture result, Joined joined); + void run(RequestedAnswer result, Joined joined); + } + + /** + * What a requested delivery answers its callers. Where the answer reports events lost for good, a caller + * whose wait times out or is interrupted before it comes leaves the loss for the next caller to hear about. + */ + static final class RequestedAnswer extends LDAwaitFuture { + /** Set by the delivery before it answers, where the answer reports a loss: what leaves it unheard. */ + volatile Runnable lossUnheard; + + @Override + public Boolean get() throws ExecutionException, InterruptedException { + try { + return super.get(); + } catch (InterruptedException e) { + stoppedWaiting(); + throw e; + } + } + + @Override + public Boolean get(long timeout, @NonNull TimeUnit unit) + throws ExecutionException, TimeoutException, InterruptedException { + try { + return super.get(timeout, unit); + } catch (TimeoutException | InterruptedException e) { + stoppedWaiting(); + throw e; + } + } + + private void stoppedWaiting() { + addListener(() -> { + Runnable unheard = lossUnheard; + if (unheard != null) { + unheard.run(); + } + }); + } } /** Who joined a requested delivery by the time it began. */ @@ -79,7 +121,7 @@ private Joined(boolean answersACaller, boolean bypassesBackoff) { * on instead of queuing another. Null while nothing is queued, and cleared again as the queued * delivery begins, which is the point past which it can no longer speak for what is recorded. */ - private LDAwaitFuture pendingFlush; + private RequestedAnswer pendingFlush; /** * Whether a caller who is there to hear the outcome is waiting on {@link #pendingFlush}, as opposed to only @@ -154,14 +196,14 @@ private EventDeliveryRun newRun(boolean throughTheBackoff, boolean paced) { * @return what the delivery answers, or false at once if it is shutting down and nothing will be sent */ Future queue(boolean answersACaller, boolean bypassBackoff, RequestedDelivery delivery) { - LDAwaitFuture result; + RequestedAnswer result; synchronized (flushLock) { if (pendingFlush != null) { pendingFlushAnswersACaller |= answersACaller; pendingFlushBypassesBackoff |= bypassBackoff; return pendingFlush; } - LDAwaitFuture queued = new LDAwaitFuture<>(); + RequestedAnswer queued = new RequestedAnswer(); if (submit(() -> delivery.run(queued, begin(queued))) == null) { return new LDSuccessFuture<>(false); } @@ -182,7 +224,7 @@ Future queue(boolean answersACaller, boolean bypassBackoff, RequestedDe * * @return who joined it */ - private Joined begin(LDAwaitFuture result) { + private Joined begin(RequestedAnswer result) { synchronized (flushLock) { if (pendingFlush != result) { return Joined.NOBODY; diff --git a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java index a00ac2c8..f569646e 100644 --- a/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java +++ b/launchdarkly-android-client-sdk/src/test/java/com/launchdarkly/sdk/android/DirectEventProcessorTest.java @@ -575,6 +575,38 @@ public void aLossADeliveryNobodyWaitedOnPassedIsToldToTheNextFlush() throws Exce } } + @Test + public void aLossClaimedForAFlushThatStoppedWaitingIsToldToTheNextFlush() throws Exception { + Semaphore letFirstResponseFinish = new Semaphore(0); + try (HttpServer server = HttpServer.start(Handlers.sequential( + Handlers.all(Handlers.waitFor(letFirstResponseFinish), Handlers.status(202)), + Handlers.status(202)))) { + EventProcessor eventProcessor = makeEventProcessor(server, DEFAULT_CAPACITY); + try { + eventProcessor.recordCustomEvent(CONTEXT, "poison", LDValue.ofNull(), Double.NaN); + eventProcessor.recordCustomEvent(CONTEXT, "kept", LDValue.ofNull(), null); + + // The delivery loses the poison event, and answers only once its caller has stopped waiting, + // as a flushAndWait that times out does. + Future first = eventProcessor.flushAsync(); + server.getRecorder().requireRequest(5, TimeUnit.SECONDS); + try { + first.get(100, TimeUnit.MILLISECONDS); + fail("expected the wait to time out"); + } catch (TimeoutException expected) { + // The caller gives up here, before it hears of the loss. + } + letFirstResponseFinish.release(); + + assertFalse(awaitFlush(eventProcessor, 5, TimeUnit.SECONDS)); + assertTrue(awaitFlush(eventProcessor, 5, TimeUnit.SECONDS)); + } finally { + letFirstResponseFinish.release(Integer.MAX_VALUE); + eventProcessor.close(); + } + } + } + @Test public void aFailedDeliveryIsRetriedOnceUnderTheSamePayloadId() throws Exception { try (HttpServer server = HttpServer.start(Handlers.sequential(Handlers.status(503),