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 @@ -88,7 +88,7 @@ public CompletableFuture<FDv2SourceResult> next() {
e.getCause() != null ? e.getCause().toString() : e.toString(),
Instant.now()
);
resultQueue.put(FDv2SourceResult.interrupted(errorInfo, false));
resultQueue.put(FDv2SourceResult.interrupted(errorInfo, null));
} catch (CancellationException e) {
// Start future was canceled (during close) - exit cleanly
} catch (InterruptedException e) {
Expand Down Expand Up @@ -159,7 +159,7 @@ public boolean init(DataStoreTypes.FullDataSet<ItemDescriptor> allData) {
environmentId,
allData.shouldPersist()
);
resultQueue.put(FDv2SourceResult.changeSet(changeSet, false));
resultQueue.put(FDv2SourceResult.changeSet(changeSet, null));
return true;
}

Expand All @@ -181,7 +181,7 @@ public boolean upsert(DataKind kind, String key, ItemDescriptor item) {
environmentId,
true // default to true as this adapter is used for adapting FDv1 data sources which are always persistent
);
resultQueue.put(FDv2SourceResult.changeSet(changeSet, false));
resultQueue.put(FDv2SourceResult.changeSet(changeSet, null));
return true;
}

Expand All @@ -200,15 +200,15 @@ public void updateStatus(DataSourceStatusProvider.State newState, DataSourceStat
if (newError != null
&& newError.getKind() == DataSourceStatusProvider.ErrorKind.ERROR_RESPONSE
&& HttpErrors.classifyHttpFailure(newError.getStatusCode()) == FailureClass.UNEXPECTED) {
resultQueue.put(FDv2SourceResult.terminalError(newError, false));
resultQueue.put(FDv2SourceResult.terminalError(newError, null));
} else {
resultQueue.put(FDv2SourceResult.interrupted(newError, false));
resultQueue.put(FDv2SourceResult.interrupted(newError, null));
}
break;
case OFF:
consecutiveSuccessfulResults = 0;
if (newError != null) {
resultQueue.put(FDv2SourceResult.terminalError(newError, false));
resultQueue.put(FDv2SourceResult.terminalError(newError, null));
} else {
resultQueue.put(FDv2SourceResult.shutdown());
}
Expand All @@ -224,7 +224,7 @@ public void updateStatus(DataSourceStatusProvider.State newState, DataSourceStat
Collections.emptyList(),
environmentId,
/* shouldPersist= */ true);
resultQueue.put(FDv2SourceResult.changeSet(noChanges, false).withResetThresholdMet());
resultQueue.put(FDv2SourceResult.changeSet(noChanges, null).withResetThresholdMet());
}
break;
case INITIALIZING:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.launchdarkly.logging.LogValues;
import com.launchdarkly.sdk.fdv2.SourceSignal;
import com.launchdarkly.sdk.server.datasources.FDv2SourceResult;
import com.launchdarkly.sdk.server.datasources.FDv1Fallback;
import com.launchdarkly.sdk.server.datasources.Initializer;
import com.launchdarkly.sdk.server.datasources.Synchronizer;
import com.launchdarkly.sdk.server.interfaces.DataSourceStatusProvider;
Expand Down Expand Up @@ -182,8 +183,8 @@ private void run() {
}

// If an initializer signalled FDv1 fallback, fall back to FDv1 before any synchronizer runs.
if (initializerOutcome.fallbackToFDv1) {
fallBackToFDv1(jittered(defaultFDv1FallbackTTL), initializerOutcome.errorInfo);
if (initializerOutcome.fallback != null) {
fallBackToFDv1(fallbackTTL(initializerOutcome.fallback), initializerOutcome.errorInfo);
}

if (!sourceManager.hasFDv2Synchronizers() && !sourceManager.hasAvailableSynchronizers()) {
Expand Down Expand Up @@ -245,7 +246,7 @@ private InitializerOutcome runInitializers() {
dataSourceUpdates.updateStatus(DataSourceStatusProvider.State.VALID, null);
startFuture.complete(true);
if (result.isFdv1Fallback()) {
return InitializerOutcome.fallbackToFDv1(null);
return InitializerOutcome.fallbackToFDv1(null, result.getFdv1Fallback());
}
return InitializerOutcome.completed();
}
Expand Down Expand Up @@ -281,7 +282,7 @@ private InitializerOutcome runInitializers() {
// to the FDv1 fallback synchronizer; the eventual VALID status will come
// from the FDv1 synchronizer once it serves a full payload.
if (result.isFdv1Fallback()) {
return InitializerOutcome.fallbackToFDv1(fallbackErrorInfo);
return InitializerOutcome.fallbackToFDv1(fallbackErrorInfo, result.getFdv1Fallback());
}
}
} catch (ExecutionException | InterruptedException | CancellationException e) {
Expand Down Expand Up @@ -318,20 +319,20 @@ private InitializerOutcome runInitializers() {
* server-directed FDv1 fallback before the synchronizer phase begins.
*/
private static final class InitializerOutcome {
final boolean fallbackToFDv1;
final FDv1Fallback fallback;
final DataSourceStatusProvider.ErrorInfo errorInfo;

private InitializerOutcome(boolean fallbackToFDv1, DataSourceStatusProvider.ErrorInfo errorInfo) {
this.fallbackToFDv1 = fallbackToFDv1;
private InitializerOutcome(FDv1Fallback fallback, DataSourceStatusProvider.ErrorInfo errorInfo) {
this.fallback = fallback;
this.errorInfo = errorInfo;
}

static InitializerOutcome completed() {
return new InitializerOutcome(false, null);
return new InitializerOutcome(null, null);
}

static InitializerOutcome fallbackToFDv1(DataSourceStatusProvider.ErrorInfo errorInfo) {
return new InitializerOutcome(true, errorInfo);
static InitializerOutcome fallbackToFDv1(DataSourceStatusProvider.ErrorInfo errorInfo, FDv1Fallback fallback) {
return new InitializerOutcome(fallback, errorInfo);
}
}

Expand Down Expand Up @@ -458,13 +459,13 @@ private void runSynchronizers() {
if (result.isFdv1Fallback()) {
if (sourceManager.isCurrentSynchronizerFDv1Fallback()) {
// A directive during the FDv1 fallback replaces its TTL, and FDv1 keeps running.
Duration fallbackTTL = jittered(defaultFDv1FallbackTTL);
Duration fallbackTTL = fallbackTTL(result.getFdv1Fallback());
sourceManager.startFDv1Fallback(MonotonicTime.now().plus(fallbackTTL));
logger.info("Retrying the configured synchronizers in {}s.", fallbackTTL.getSeconds());
} else {
// A directive to fall back to FDv1 ends the run of an FDv2 synchronizer.
fallBackToFDv1(
jittered(defaultFDv1FallbackTTL),
fallbackTTL(result.getFdv1Fallback()),
result.getStatus() != null ? result.getStatus().getErrorInfo() : null);
// The directive takes over, so there is no failover delay after a park.
parked = false;
Expand Down Expand Up @@ -619,6 +620,13 @@ private static MonotonicTime earliest(MonotonicTime... times) {
return earliest;
}

Duration fallbackTTL(FDv1Fallback fallback) {
Duration serverTTL = fallback.getTtl();
return serverTTL != null && serverTTL.compareTo(Duration.ZERO) > 0
&& serverTTL.compareTo(Duration.ofHours(1)) <= 0
? serverTTL : jittered(defaultFDv1FallbackTTL);
}

/**
* Subtracts a random jitter of up to half of the given delay.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,33 @@
package com.launchdarkly.sdk.server;

import com.launchdarkly.sdk.server.datasources.FDv1Fallback;

import java.time.Duration;

enum HeaderConstants {
ENVIRONMENT_ID("x-ld-envid"),
FDV1_FALLBACK("x-ld-fd-fallback");
FDV1_FALLBACK("x-ld-fd-fallback"),
FDV1_FALLBACK_TTL("x-ld-fd-fallback-ttl");

private final String headerName;

HeaderConstants(String headerName) {
this.headerName = headerName;
}

static FDv1Fallback getFallback(String directive, String value) {
if (!"true".equalsIgnoreCase(directive)) {
return null;
}
Duration ttl = null;
try {
ttl = value == null ? null : Duration.ofSeconds(Long.parseLong(value));
} catch (NumberFormatException e) {
ttl = null;
}
return new FDv1Fallback(ttl);
}

public String getHeaderName() {
return headerName;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.launchdarkly.sdk.internal.fdv2.sources.FDv2ProtocolHandler;
import com.launchdarkly.sdk.fdv2.Selector;
import com.launchdarkly.sdk.server.datasources.FDv2SourceResult;
import com.launchdarkly.sdk.server.datasources.FDv1Fallback;
import com.launchdarkly.sdk.server.interfaces.DataSourceStatusProvider;
import com.launchdarkly.sdk.fdv2.ChangeSet;
import com.launchdarkly.sdk.fdv2.ChangeSetType;
Expand All @@ -16,6 +17,7 @@
import com.launchdarkly.sdk.json.SerializationException;

import java.io.IOException;
import java.time.Duration;
import java.util.Collections;
import java.util.Map;
import java.util.Date;
Expand All @@ -36,13 +38,14 @@ protected void internalShutdown() {
requestor.close();
}

private static boolean getFallback(FDv2Requestor.FDv2PayloadResponse response) {
private static FDv1Fallback getFallback(FDv2Requestor.FDv2PayloadResponse response) {
if (response != null && response.getHeaders() != null) {
String headerValue = response.getHeaders().get(HeaderConstants.FDV1_FALLBACK.getHeaderName());
return headerValue != null && headerValue.equalsIgnoreCase("true");
return HeaderConstants.getFallback(
response.getHeaders().get(HeaderConstants.FDV1_FALLBACK.getHeaderName()),
response.getHeaders().get(HeaderConstants.FDV1_FALLBACK_TTL.getHeaderName()));
}

return false;
return null;
}

private static String getEnvironmentId(FDv2Requestor.FDv2PayloadResponse response) {
Expand All @@ -54,7 +57,7 @@ private static String getEnvironmentId(FDv2Requestor.FDv2PayloadResponse respons

protected CompletableFuture<FDv2SourceResult> poll(Selector selector, boolean oneShot) {
return requestor.Poll(selector).handle(((pollingResponse, ex) -> {
boolean fdv1Fallback = getFallback(pollingResponse);
FDv1Fallback fdv1Fallback = getFallback(pollingResponse);
String environmentId = getEnvironmentId(pollingResponse);
if (ex != null) {
if (ex instanceof IOException) {
Expand Down Expand Up @@ -101,7 +104,7 @@ protected CompletableFuture<FDv2SourceResult> poll(Selector selector, boolean on
true // Polling data from LaunchDarkly should be persisted
),
// Headers would have been processed from the initial response.
false);
null);
}
if(!pollingResponse.isSuccess()) {
int statusCode = pollingResponse.getStatusCode();
Expand Down Expand Up @@ -150,9 +153,12 @@ protected CompletableFuture<FDv2SourceResult> poll(Selector selector, boolean on
return oneShot ? FDv2SourceResult.terminalError(info, fdv1Fallback) : FDv2SourceResult.interrupted(info, fdv1Fallback);
}
case GOODBYE:
String reason = ((FDv2ProtocolHandler.FDv2ActionGoodbye) res).getReason();
FDv2ProtocolHandler.FDv2ActionGoodbye goodbye = (FDv2ProtocolHandler.FDv2ActionGoodbye) res;
String reason = goodbye.getReason();
Long ttlMillis = goodbye.getProtocolFallbackTTLMillis();
logger.info("Goodbye was received from the LaunchDarkly connection with reason: '{}'.", reason);
return FDv2SourceResult.goodbye(reason, fdv1Fallback);
return FDv2SourceResult.goodbye(reason,
ttlMillis == null ? fdv1Fallback : new FDv1Fallback(Duration.ofMillis(ttlMillis)));
case NONE:
break;
case INTERNAL_ERROR: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.launchdarkly.eventsource.HttpConnectStrategy;
import com.launchdarkly.eventsource.MessageEvent;
import com.launchdarkly.eventsource.RetryDelayStrategy;
import com.launchdarkly.eventsource.ResponseHeaders;
import com.launchdarkly.eventsource.StreamClosedByCallerException;
import com.launchdarkly.eventsource.StreamEvent;
import com.launchdarkly.eventsource.StreamException;
Expand All @@ -23,6 +24,7 @@
import com.launchdarkly.sdk.internal.http.HttpHelpers;
import com.launchdarkly.sdk.internal.http.HttpProperties;
import com.launchdarkly.sdk.server.datasources.FDv2SourceResult;
import com.launchdarkly.sdk.server.datasources.FDv1Fallback;
import com.launchdarkly.sdk.server.datasources.SelectorSource;
import com.launchdarkly.sdk.server.datasources.Synchronizer;
import com.launchdarkly.sdk.server.interfaces.DataSourceStatusProvider;
Expand Down Expand Up @@ -312,7 +314,7 @@ private void reportResetThresholdMet() {
Collections.emptyList(),
/* environmentId= */ null,
/* shouldPersist= */ true);
resultQueue.put(FDv2SourceResult.changeSet(noChanges, /* fdv1Fallback= */ false).withResetThresholdMet());
resultQueue.put(FDv2SourceResult.changeSet(noChanges, /* fdv1Fallback= */ null).withResetThresholdMet());
}
}

Expand Down Expand Up @@ -393,9 +395,12 @@ private void handleMessage(MessageEvent event) {
break;

case GOODBYE:
String reason = ((FDv2ProtocolHandler.FDv2ActionGoodbye) action).getReason();
FDv2ProtocolHandler.FDv2ActionGoodbye goodbye = (FDv2ProtocolHandler.FDv2ActionGoodbye) action;
String reason = goodbye.getReason();
Long ttlMillis = goodbye.getProtocolFallbackTTLMillis();
logger.info("Goodbye was received from the LaunchDarkly connection with reason: '{}'.", reason);
result = FDv2SourceResult.goodbye(reason, getFallback(event));
result = FDv2SourceResult.goodbye(reason,
ttlMillis == null ? getFallback(event) : new FDv1Fallback(Duration.ofMillis(ttlMillis)));
// We drop this current connection and attempt to restart the stream.
restartStream(false); // Not a failure - deliberate server-initiated restart
break;
Expand Down Expand Up @@ -537,23 +542,21 @@ private FDv2Event parseFDv2Event(String eventName, Reader eventDataReader) throw
}
}

private static boolean getFallback(Exception ex) {
if(ex instanceof StreamHttpErrorException) {
String headerValue = ((StreamHttpErrorException) ex).getHeaders()
.value(HeaderConstants.FDV1_FALLBACK.getHeaderName());
return headerValue != null && headerValue.equalsIgnoreCase("true");
}
return false;
private static FDv1Fallback getFallback(Exception ex) {
return ex instanceof StreamHttpErrorException
? getFallback(((StreamHttpErrorException) ex).getHeaders()) : null;
}

private static boolean getFallback(StreamEvent event) {
String headerName = HeaderConstants.FDV1_FALLBACK.getHeaderName();
String headerValue = null;
if(event instanceof FaultEvent) {
headerValue = ((FaultEvent) event).getHeaders().value(headerName);
} else if (event instanceof MessageEvent) {
headerValue = ((MessageEvent) event).getHeaders().value(headerName);
private static FDv1Fallback getFallback(StreamEvent event) {
if (event instanceof FaultEvent) {
return getFallback(((FaultEvent) event).getHeaders());
}
return headerValue != null && headerValue.equalsIgnoreCase("true");
return event instanceof MessageEvent ? getFallback(((MessageEvent) event).getHeaders()) : null;
}

private static FDv1Fallback getFallback(ResponseHeaders headers) {
return HeaderConstants.getFallback(
headers.value(HeaderConstants.FDV1_FALLBACK.getHeaderName()),
headers.value(HeaderConstants.FDV1_FALLBACK_TTL.getHeaderName()));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.launchdarkly.sdk.server.datasources;

import java.time.Duration;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is probably fine in server, but we did recently make a PR to change one of these in internal or common. Because it isn't in the android API level that we use. But I wonder if we want to just not use java.time.Duration, or we just avoid it in the common libraries.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is only in the server SDK, which already uses java.time.Duration in 33 main source files on main, including the existing defaultFDv1FallbackTTL. The goodbye TTL comes from the internal lib as nullable Long millis, as of #273, and is converted to a Duration only here. As far as I can tell, lib/shared/common and lib/shared/internal have no java.time.Duration left. So "avoid it in the common libraries" seems to be the rule today, and this PR follows it. I'll leave it as is unless you'd like the server SDK to avoid it too.

Written by Devin

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

aside: I've seen so many bugs from code that disagreed about whether a Long was seconds or millis, I'm inclined to use Duration where we can. But I know we don't want to require desugaring in Android, so... well, I'll deal either way.


/**
* This type is currently experimental and not subject to semantic versioning.
* <p>
* A server directive to fall back to FDv1.
*/
public final class FDv1Fallback {
private final Duration ttl;

/**
* Creates a fallback directive with the server-provided TTL.
*
* @param ttl the TTL, or null if the server gave none
*/
public FDv1Fallback(Duration ttl) {
this.ttl = ttl;
}

/**
* Returns the server-provided TTL.
*
* @return the TTL, or null if the server gave none
*/
public Duration getTtl() {
return ttl;
}
}
Loading