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
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@
* When event delivery may post again after a failure, following the SDK Retry Behavior specification as
* event durability §9 binds it.
* <p>
* A failure never stops delivery, it only makes the next post wait. An ordinary one, such as a 503 or no
* network, waits from a second up to the flush interval, so it is never later than the schedule already
* would be. A refusal that is unlikely to pass soon, such as a 401, waits about eight and a half minutes,
* doubling up to an hour, rather than deleting the batch: a valid key is sometimes refused for minutes
* during an incident, and every event the fleet recorded meanwhile would be lost. A {@code Retry-After}
* sets the wait instead. One accepted delivery puts everything back.
* A failure never stops delivery, it only makes the next post wait. There are two kinds of wait:
* <ul>
* <li>After an ordinary failure, such as no network or a 5xx without {@code Retry-After}, the wait grows
* from a second up to the flush interval, so it is never later than the schedule already would be. Going
* online again ends it.</li>
* <li>The service sets the wait with a {@code Retry-After}, or with a refusal likely to last, such as a
* 401 or 403, which waits about eight and a half minutes, doubling up to an hour, rather than deleting the
* batch: a valid key is sometimes refused for minutes during an incident, and every event the fleet
* recorded meanwhile would be lost. Once refused, every wait until a delivery is accepted is of this kind.
* Going online again keeps it.</li>
* </ul>
* One accepted delivery puts everything back.
* <p>
* One per event processor, so each environment backs off on its own. Held only in memory, so a new run of
* the application posts at once.
Expand Down Expand Up @@ -40,6 +46,10 @@ final class DeliveryRetryState {
private long maxDelayMillis;
private boolean waiting;
private long nextAttemptNanos;
// A refusal since the last accepted delivery, which keeps the extended ceiling.
private boolean refused;
// The wait is a Retry-After's. A refusal's is marked by refused.
private boolean serverDirectedWait;

/**
* @param flushIntervalMillis the normal ceiling; never below the initial delay, so a short interval does
Expand Down Expand Up @@ -69,6 +79,32 @@ synchronized void recordSuccess() {
attempts = 0;
maxDelayMillis = normalCeilingMillis;
waiting = false;
refused = false;
serverDirectedWait = false;
}

/**
* Going online again:
* <ul>
* <li>ends the wait after an ordinary failure, which is most often the network that just came
* back.</li>
* <li>keeps a wait the service set, either a {@code Retry-After} or the longer backoff after a refusal,
* as the network coming back does not change the service's answer.</li>
* </ul>
* The attempt count stays either way, as only an accepted delivery puts it back.
*
* @return true when a post has failed since the last accepted one and no wait holds the next back any
* more, so a delivery may go now rather than at the next flush interval
*/
synchronized boolean endOrdinaryWait() {
if (attempts == 0) {
return false;
}
if (remainingWaitNanos() > 0 && (refused || serverDirectedWait)) {
return false;
}
waiting = false;
return true;
}

/**
Expand All @@ -82,9 +118,11 @@ synchronized long recordFailure(boolean unexpected, long retryAfterMillis) {
if (unexpected) {
attempts = Math.max(attempts + 1, ATTEMPTS_AFTER_UNEXPECTED);
maxDelayMillis = extendedCeilingMillis;
refused = true;
} else {
attempts++;
}
serverDirectedWait = retryAfterMillis >= 0;
long waitMillis;
if (retryAfterMillis >= 0) {
// Every instance hears the same value at the same moment, so it is jittered to keep them from
Expand All @@ -106,7 +144,7 @@ synchronized long recordFailure(boolean unexpected, long retryAfterMillis) {
* not a step of the backoff. It leaves the attempt count and the ceiling as they were, so a caller
* flushing through a refusal several times does not push flush, the periodic delivery and the retry out
* to the hour. A {@code Retry-After} can still make the wait longer, never shorter. Once the wait has run
* out it is an ordinary failure.
* out it is the next step of the backoff.
*
* @param unexpected as {@link #recordFailure}
* @param retryAfterMillis as {@link #recordFailure}
Expand All @@ -124,6 +162,7 @@ synchronized void recordFailureDuringWait(boolean unexpected, long retryAfterMil
long asked = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(waitMillis);
if (asked - nextAttemptNanos > 0) {
nextAttemptNanos = asked;
serverDirectedWait = true;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,13 @@ static final class Pacing {
*/
private volatile boolean launchGateOpen;

/**
* Whether going online again ended an ordinary failure's wait while the gate was still closed, which owes
* the delivery it would have submitted to the gate opening. Ending the wait is not undone, and nothing
* else would deliver before the next flush interval. Guarded by {@link #stateLock}.
*/
private boolean deliveryOwedAtGate;

/** Set once, under {@link #stateLock}, when the SDK first goes online; the gate counts from then. */
private volatile boolean wentOnline;
private volatile long wentOnlineNanos;
Expand Down Expand Up @@ -436,6 +443,16 @@ public void setOffline(boolean offline) {
return;
}
updateScheduledTasks(inBackground.get(), offline);
// Going online again keeps to the flush interval, with one exception: when the last post had an
// ordinary failure, such as no network, its wait ends and a delivery goes now. A wait the service
// set, with a Retry-After or a refusal, stands.
if (!offline && !closed.get() && retryState.endOrdinaryWait()) {
if (launchGateOpen) {
deliveryScheduler.submit(this::deliverPayload);
} else {
deliveryOwedAtGate = true;
}
}
}
deliveryScheduler.wakePacedDelivery();
}
Expand Down Expand Up @@ -1080,8 +1097,14 @@ private void updateScheduledTasks(boolean inBackground, boolean offline) {
// Events a previous run left on disk have already waited out a whole process, so they do not
// wait out an interval as well, only the launch gate. An application that dies within one interval
// of every start would otherwise never deliver them.
if (!stopped && !offline && launchGateOpen && hasEventsFromPreviousRun.compareAndSet(true, false)) {
deliveryScheduler.submit(this::deliverPayload);
if (!stopped && !offline && launchGateOpen) {
// One delivery covers both: it sends what a previous run left first. Offline, going online again
// asks anew.
boolean previousRun = hasEventsFromPreviousRun.compareAndSet(true, false);
if (previousRun || deliveryOwedAtGate) {
deliveryOwedAtGate = false;
deliveryScheduler.submit(this::deliverPayload);
}
}
diagnostics.setMode(!stopped && !offline && !inBackground, launchGateOpen);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,17 @@ public interface LDClientInterface extends Closeable {
* Restores network connectivity for the client, if the client was previously in offline mode.
* This operation may be throttled if it is called too frequently.
* <p>
* If a delivery of events failed, going online again:
* <ul>
* <li>ends the wait after an ordinary failure, such as no network or a 5xx response without
* <code>Retry-After</code>, and delivers the events right away.</li>
* <li>keeps a wait the service set, either a <code>Retry-After</code> or the longer backoff after a
* refusal such as a 401 or 403, which can last up to an hour. This holds even when a captive portal or
* proxy sent the response rather than LaunchDarkly. Where
* <code>EventProcessorBuilder.eventPersistence</code> is <code>DISABLED</code>, events held during
* this wait are lost if the process ends.</li>
* </ul>
* <p>
* Note: The client automatically monitors the device's network connectivity and app foreground
* status, so calling <code>setOffline()</code> or <code>setOnline()</code> is normally
* unnecessary in most situations.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.launchdarkly.sdk.android;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;
Expand Down Expand Up @@ -117,6 +118,51 @@ public void aFailureDuringAWaitThatHasRunOutIsAnOrdinaryOne() throws Interrupted
assertTrue(quick.remainingWaitNanos() > TimeUnit.MILLISECONDS.toNanos(20));
}

@Test
public void goingOnlineEndsAnOrdinaryFailuresWaitButKeepsTheCount() {
assertFalse(state.endOrdinaryWait());
state.recordFailure(false, -1);
state.recordFailure(false, -1);

assertTrue(state.endOrdinaryWait());
assertEquals(0, state.remainingWaitNanos());
assertEquals(4 * SECOND, state.recordFailure(false, -1));
}

@Test
public void goingOnlineKeepsTheServicesWait() {
DeliveryRetryState refused = new DeliveryRetryState(FLUSH_INTERVAL);
refused.recordFailure(true, -1);
assertFalse(refused.endOrdinaryWait());
assertTrue(refused.remainingWaitNanos() > TimeUnit.SECONDS.toNanos(500));

DeliveryRetryState directed = new DeliveryRetryState(FLUSH_INTERVAL);
directed.recordFailure(false, 10 * SECOND);
assertFalse(directed.endOrdinaryWait());
assertTrue(directed.remainingWaitNanos() > TimeUnit.SECONDS.toNanos(4));

DeliveryRetryState lengthened = new DeliveryRetryState(SECOND, FLUSH_INTERVAL, TimeUnit.HOURS.toMillis(1),
new FixedRandom(0));
lengthened.recordFailure(false, -1);
lengthened.recordFailureDuringWait(false, 10 * SECOND);
assertFalse(lengthened.endOrdinaryWait());
}

@Test
public void goingOnlineAfterTheServicesWaitRanOutLetsADeliveryGo() throws InterruptedException {
DeliveryRetryState quick = new DeliveryRetryState(20, 20, 20, new Random());
quick.recordFailure(true, -1);
Thread.sleep(40);
assertTrue(quick.endOrdinaryWait());
}

@Test
public void goingOnlineAfterAnAcceptedDeliveryHasNothingToSend() {
state.recordFailure(false, -1);
state.recordSuccess();
assertFalse(state.endOrdinaryWait());
}

@Test
public void theWaitRunsOut() throws InterruptedException {
DeliveryRetryState quick = new DeliveryRetryState(20, 20, 20, new Random());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3342,6 +3342,115 @@ public void refusedFlushesBypassingTheBackoffDoNotLengthenIt() throws Exception
}
}

@Test
public void goingOnlineAgainAfterAnOrdinaryFailurePostsAtOnceRatherThanSittingOutTheRestOfItsWait()
throws Exception {
ScheduledExecutorService scheduler = EventUtil.makeEventsTaskExecutor();
ExecutorService diagnosticExecutor = EventUtil.makeDiagnosticsTaskExecutor();
diagnosticExecutors.add(diagnosticExecutor);
EventStore store = EventStore.create(eventsDirectory.getRoot(), MOBILE_KEY, DEFAULT_CAPACITY,
persistence() != EventPersistence.DISABLED, logging.logger);
try (HttpServer server = HttpServer.start(Handlers.sequential(
Handlers.status(503), Handlers.status(503), Handlers.status(202)))) {
DirectEventProcessor eventProcessor = makeEventProcessor(new StubEventSender(), server.getUri(),
null, NO_PERIODIC_FLUSH_MILLIS, 60_000, DirectEventProcessor.DEFAULT_CLOSE_BUDGET_MILLIS,
scheduler, diagnosticExecutor, store, DEFAULT_CAPACITY);
try {
eventProcessor.setOffline(false);
eventProcessor.recordCustomEvent(CONTEXT, "held", LDValue.ofNull(), null);
assertFalse(awaitFlush(eventProcessor, 10, TimeUnit.SECONDS));
server.getRecorder().requireRequest(1, TimeUnit.SECONDS);
server.getRecorder().requireRequest(1, TimeUnit.SECONDS);
// Failures while the network was going, which leave about sixteen seconds to wait.
for (int i = 0; i < 3; i++) {
lastRetryState.recordFailure(false, -1);
}

eventProcessor.setOffline(true);
eventProcessor.setOffline(false);

assertTrue(server.getRecorder().requireRequest(2, TimeUnit.SECONDS).getBody()
.contains("\"key\":\"held\""));
} finally {
eventProcessor.close();
scheduler.shutdownNow();
}
}
}

@Test
public void goingOnlineAgainBeforeTheLaunchGateOpensPostsAsItOpens() throws Exception {
assumePersisting();
ScheduledExecutorService scheduler = EventUtil.makeEventsTaskExecutor();
ExecutorService diagnosticExecutor = EventUtil.makeDiagnosticsTaskExecutor();
diagnosticExecutors.add(diagnosticExecutor);
EventStore store = EventStore.create(eventsDirectory.newFolder(), MOBILE_KEY, DEFAULT_CAPACITY, true,
logging.logger);
try (HttpServer server = HttpServer.start(Handlers.sequential(
Handlers.status(503), Handlers.status(503), Handlers.status(202)))) {
DirectEventProcessor eventProcessor = makeEventProcessor(new StubEventSender(), server.getUri(),
null, NO_PERIODIC_FLUSH_MILLIS, 60_000, DirectEventProcessor.DEFAULT_CLOSE_BUDGET_MILLIS,
scheduler, diagnosticExecutor, store, DEFAULT_CAPACITY, false,
new DirectEventProcessor.Pacing(4_000, 0));
try {
eventProcessor.setOffline(false);
eventProcessor.recordCustomEvent(CONTEXT, "held", LDValue.ofNull(), null);
// A flush does not wait for the gate.
assertFalse(awaitFlush(eventProcessor, 10, TimeUnit.SECONDS));
server.getRecorder().requireRequest(1, TimeUnit.SECONDS);
server.getRecorder().requireRequest(1, TimeUnit.SECONDS);
for (int i = 0; i < 3; i++) {
lastRetryState.recordFailure(false, -1);
}

eventProcessor.setOffline(true);
eventProcessor.setOffline(false);

server.getRecorder().requireNoRequests(1_500, TimeUnit.MILLISECONDS);
assertTrue(server.getRecorder().requireRequest(5, TimeUnit.SECONDS).getBody()
.contains("\"key\":\"held\""));
} finally {
eventProcessor.close();
scheduler.shutdownNow();
}
}
}

@Test
public void goingOnlineAgainKeepsToTheWaitARefusalOrARetryAfterSet() throws Exception {
Handler[] refusals = {
Handlers.status(401),
Handlers.all(Handlers.header("Retry-After", "30"), Handlers.status(503))
};
for (Handler refusal : refusals) {
ScheduledExecutorService scheduler = EventUtil.makeEventsTaskExecutor();
ExecutorService diagnosticExecutor = EventUtil.makeDiagnosticsTaskExecutor();
diagnosticExecutors.add(diagnosticExecutor);
EventStore store = EventStore.create(eventsDirectory.newFolder(), MOBILE_KEY, DEFAULT_CAPACITY,
persistence() != EventPersistence.DISABLED, logging.logger);
try (HttpServer server = HttpServer.start(Handlers.sequential(refusal, Handlers.status(202)))) {
DirectEventProcessor eventProcessor = makeEventProcessor(new StubEventSender(),
server.getUri(), null, NO_PERIODIC_FLUSH_MILLIS, 60_000,
DirectEventProcessor.DEFAULT_CLOSE_BUDGET_MILLIS, scheduler, diagnosticExecutor, store,
DEFAULT_CAPACITY);
try {
eventProcessor.setOffline(false);
eventProcessor.recordCustomEvent(CONTEXT, "refused", LDValue.ofNull(), null);
assertFalse(awaitFlush(eventProcessor, 10, TimeUnit.SECONDS));
server.getRecorder().requireRequest(1, TimeUnit.SECONDS);

eventProcessor.setOffline(true);
eventProcessor.setOffline(false);

server.getRecorder().requireNoRequests(1_500, TimeUnit.MILLISECONDS);
} finally {
eventProcessor.close();
scheduler.shutdownNow();
}
}
}
}

@Test
public void dataTooDeeplyNestedToEncodeCostsOnlyItsOwnEvent() throws Exception {
LDValue nested = LDValue.of(1);
Expand Down Expand Up @@ -4825,6 +4934,23 @@ private DirectEventProcessor makeEventProcessor(EventSender diagnosticSender,
EventStore store,
int capacity,
boolean commitOnCallerThread) {
return makeEventProcessor(diagnosticSender, eventsUri, diagnosticStore, flushIntervalMillis,
diagnosticIntervalMillis, closeBudgetMillis, scheduler, diagnosticExecutor, store,
capacity, commitOnCallerThread, DirectEventProcessor.Pacing.NONE);
}

private DirectEventProcessor makeEventProcessor(EventSender diagnosticSender,
URI eventsUri,
DiagnosticStore diagnosticStore,
long flushIntervalMillis,
long diagnosticIntervalMillis,
long closeBudgetMillis,
ScheduledExecutorService scheduler,
ExecutorService diagnosticExecutor,
EventStore store,
int capacity,
boolean commitOnCallerThread,
DirectEventProcessor.Pacing pacing) {
ExecutorService commitExecutor = EventUtil.makeEventsCommitExecutor();
diagnosticExecutors.add(commitExecutor);
lastCommitExecutor = commitExecutor;
Expand All @@ -4845,7 +4971,7 @@ private DirectEventProcessor makeEventProcessor(EventSender diagnosticSender,
flushIntervalMillis,
diagnosticIntervalMillis,
closeBudgetMillis,
DirectEventProcessor.Pacing.NONE,
pacing,
false,
true, // initiallyOffline, as the SDK builds it
scheduler,
Expand Down