From 808b89f2f8cb9dc82a34c712d476f74b43e64a8b Mon Sep 17 00:00:00 2001
From: Ryan Lamb <4955475+kinyoklion@users.noreply.github.com>
Date: Fri, 6 Nov 2026 11:01:26 -0800
Subject: [PATCH 1/9] feat: Add the overrideAffected indicator to
EvaluationReason (#218)
## Summary
The OVERRIDE specification marks an evaluation as override-affected when
any definition it read came from the SDK's override store: the flag
itself, a prerequisite at any depth, or a segment consulted during
matching. The evaluation reason carries that marking as a boolean
indicator named `overrideAffected`, alongside `inExperiment`, so callers
of the variation detail methods can tell such evaluations apart.
`EvaluationReason` gains `isOverrideAffected()` and
`withOverrideAffected(boolean)`. The latter returns the same instance
when the value is unchanged, so the shared static instances stay shared.
The indicator takes part in equality and hashing. The JSON
representation writes `overrideAffected` only when it is true, and
parsing accepts the property. The string representation is unchanged.
Flag overrides are currently experimental and subject to change. The
server SDK change that sets the indicator depends on the release of this
package.
[SDK-3246](https://launchdarkly.atlassian.net/browse/SDK-3246)
[SDK-3246]:
https://launchdarkly.atlassian.net/browse/SDK-3246?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
---
> [!NOTE]
> **Overview**
> Adds an experimental **`overrideAffected`** flag on `EvaluationReason`
so variation-detail callers can see when an evaluation (or a
prerequisite/segment it used) drew from the SDK override store.
>
> **`EvaluationReason`** stores the boolean (default `false`), exposes
`isOverrideAffected()` / `withOverrideAffected(boolean)`
(identity-preserving when unchanged), and includes it in
`equals`/`hashCode` without changing `toString()`.
**`EvaluationReasonTypeAdapter`** reads `overrideAffected` from JSON and
writes it only when `true`, matching `inExperiment`. Tests cover
defaults, copying, equality, and JSON round-trips.
>
> Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b5deba0e6efda6c31ef52c15bedd949d431e56cd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).
---
.../launchdarkly/sdk/EvaluationReason.java | 55 ++++++++++++---
.../sdk/EvaluationReasonTypeAdapter.java | 14 +++-
.../sdk/EvaluationReasonTest.java | 69 ++++++++++++++++++-
...EvaluationReasonJsonSerializationTest.java | 20 ++++++
4 files changed, 146 insertions(+), 12 deletions(-)
diff --git a/lib/shared/common/src/main/java/com/launchdarkly/sdk/EvaluationReason.java b/lib/shared/common/src/main/java/com/launchdarkly/sdk/EvaluationReason.java
index 7c5da7f8..93c95acd 100644
--- a/lib/shared/common/src/main/java/com/launchdarkly/sdk/EvaluationReason.java
+++ b/lib/shared/common/src/main/java/com/launchdarkly/sdk/EvaluationReason.java
@@ -142,9 +142,10 @@ public static enum BigSegmentsStatus {
private final ErrorKind errorKind;
private final Exception exception;
private final BigSegmentsStatus bigSegmentsStatus;
+ private final boolean overrideAffected;
private EvaluationReason(Kind kind, int ruleIndex, String ruleId, String prerequisiteKey, boolean inExperiment,
- ErrorKind errorKind, Exception exception, BigSegmentsStatus bigSegmentsStatus) {
+ ErrorKind errorKind, Exception exception, BigSegmentsStatus bigSegmentsStatus, boolean overrideAffected) {
this.kind = kind;
this.ruleIndex = ruleIndex;
this.ruleId = ruleId;
@@ -153,18 +154,19 @@ private EvaluationReason(Kind kind, int ruleIndex, String ruleId, String prerequ
this.errorKind = errorKind;
this.exception = exception;
this.bigSegmentsStatus = bigSegmentsStatus;
+ this.overrideAffected = overrideAffected;
}
private EvaluationReason(Kind kind) {
- this(kind, -1, null, null, NOT_IN_EXPERIMENT, null, null, null);
+ this(kind, -1, null, null, NOT_IN_EXPERIMENT, null, null, null, false);
}
private EvaluationReason(Kind kind, boolean inExperiment) {
- this(kind, -1, null, null, inExperiment, null, null, null);
+ this(kind, -1, null, null, inExperiment, null, null, null, false);
}
private EvaluationReason(ErrorKind errorKind, Exception exception) {
- this(Kind.ERROR, -1, null, null, NOT_IN_EXPERIMENT, errorKind, exception, null);
+ this(Kind.ERROR, -1, null, null, NOT_IN_EXPERIMENT, errorKind, exception, null, false);
}
/**
@@ -267,7 +269,41 @@ public BigSegmentsStatus getBigSegmentsStatus() {
*/
public EvaluationReason withBigSegmentsStatus(BigSegmentsStatus bigSegmentsStatus) {
return new EvaluationReason(kind, ruleIndex, ruleId, prerequisiteKey, inExperiment, errorKind,
- exception, bigSegmentsStatus);
+ exception, bigSegmentsStatus, overrideAffected);
+ }
+
+ /**
+ * Whether an override affected this evaluation, directly or transitively. Returns true if the
+ * evaluated flag came from the SDK's override store. Also returns true if a prerequisite flag at
+ * any depth, or a segment read during the evaluation, came from that store. Otherwise it returns
+ * false.
+ *
+ * In the JSON representation, the {@code overrideAffected} property appears only when this
+ * value is true.
+ *
+ * Flag overrides are currently experimental and subject to change.
+ *
+ * @return whether an override affected the evaluation
+ */
+ public boolean isOverrideAffected() {
+ return overrideAffected;
+ }
+
+ /**
+ * Returns a copy of this {@link EvaluationReason} with a specific value for
+ * {@link #isOverrideAffected()}. The copy keeps all other properties of the original reason.
+ *
+ * Flag overrides are currently experimental and subject to change.
+ *
+ * @param overrideAffected the new property value
+ * @return a reason object with the given value, which is this same instance if the value is unchanged
+ */
+ public EvaluationReason withOverrideAffected(boolean overrideAffected) {
+ if (this.overrideAffected == overrideAffected) {
+ return this;
+ }
+ return new EvaluationReason(kind, ruleIndex, ruleId, prerequisiteKey, inExperiment, errorKind,
+ exception, bigSegmentsStatus, overrideAffected);
}
/**
@@ -305,7 +341,8 @@ public boolean equals(Object other) {
inExperiment == o.inExperiment &&
Objects.equals(errorKind, o.errorKind) &&
Objects.equals(exception, o.exception) &&
- Objects.equals(bigSegmentsStatus, o.bigSegmentsStatus);
+ Objects.equals(bigSegmentsStatus, o.bigSegmentsStatus) &&
+ overrideAffected == o.overrideAffected;
}
return false;
}
@@ -313,7 +350,7 @@ public boolean equals(Object other) {
@Override
public int hashCode() {
return Objects.hash(kind, ruleIndex, ruleId, prerequisiteKey, inExperiment, errorKind,
- exception, bigSegmentsStatus);
+ exception, bigSegmentsStatus, overrideAffected);
}
/**
@@ -377,7 +414,7 @@ public static EvaluationReason ruleMatch(int ruleIndex, String ruleId) {
* @return a reason object
*/
public static EvaluationReason ruleMatch(int ruleIndex, String ruleId, boolean inExperiment) {
- return new EvaluationReason(Kind.RULE_MATCH, ruleIndex, ruleId, null, inExperiment, null, null, null);
+ return new EvaluationReason(Kind.RULE_MATCH, ruleIndex, ruleId, null, inExperiment, null, null, null, false);
}
/**
@@ -387,7 +424,7 @@ public static EvaluationReason ruleMatch(int ruleIndex, String ruleId, boolean i
* @return a reason object
*/
public static EvaluationReason prerequisiteFailed(String prerequisiteKey) {
- return new EvaluationReason(Kind.PREREQUISITE_FAILED, -1, null, prerequisiteKey, NOT_IN_EXPERIMENT, null, null, null);
+ return new EvaluationReason(Kind.PREREQUISITE_FAILED, -1, null, prerequisiteKey, NOT_IN_EXPERIMENT, null, null, null, false);
}
/**
diff --git a/lib/shared/common/src/main/java/com/launchdarkly/sdk/EvaluationReasonTypeAdapter.java b/lib/shared/common/src/main/java/com/launchdarkly/sdk/EvaluationReasonTypeAdapter.java
index 98ec00a2..0bfa1ec4 100644
--- a/lib/shared/common/src/main/java/com/launchdarkly/sdk/EvaluationReasonTypeAdapter.java
+++ b/lib/shared/common/src/main/java/com/launchdarkly/sdk/EvaluationReasonTypeAdapter.java
@@ -25,6 +25,7 @@ static EvaluationReason parse(JsonReader reader) throws IOException {
boolean inExperiment = false;
EvaluationReason.ErrorKind errorKind = null;
EvaluationReason.BigSegmentsStatus bigSegmentsStatus = null;
+ boolean overrideAffected = false;
reader.beginObject();
while (reader.peek() != JsonToken.END_OBJECT) {
@@ -51,6 +52,9 @@ static EvaluationReason parse(JsonReader reader) throws IOException {
case "bigSegmentsStatus":
bigSegmentsStatus = readEnum(EvaluationReason.BigSegmentsStatus.class, reader);
break;
+ case "overrideAffected":
+ overrideAffected = reader.nextBoolean();
+ break;
default:
reader.skipValue(); // ignore any unexpected property
}
@@ -85,9 +89,9 @@ static EvaluationReason parse(JsonReader reader) throws IOException {
return null;
}
if (bigSegmentsStatus != null) {
- return reason.withBigSegmentsStatus(bigSegmentsStatus);
+ reason = reason.withBigSegmentsStatus(bigSegmentsStatus);
}
- return reason;
+ return reason.withOverrideAffected(overrideAffected);
}
@Override
@@ -134,6 +138,12 @@ public void write(JsonWriter writer, EvaluationReason reason) throws IOException
writer.name("bigSegmentsStatus");
writer.value(reason.getBigSegmentsStatus().name());
}
+
+ // The override marker is written only when it is true, like inExperiment.
+ if (reason.isOverrideAffected()) {
+ writer.name("overrideAffected");
+ writer.value(true);
+ }
writer.endObject();
}
diff --git a/lib/shared/common/src/test/java/com/launchdarkly/sdk/EvaluationReasonTest.java b/lib/shared/common/src/test/java/com/launchdarkly/sdk/EvaluationReasonTest.java
index d7bd0a18..19c546b7 100644
--- a/lib/shared/common/src/test/java/com/launchdarkly/sdk/EvaluationReasonTest.java
+++ b/lib/shared/common/src/test/java/com/launchdarkly/sdk/EvaluationReasonTest.java
@@ -12,8 +12,11 @@
import static com.launchdarkly.sdk.EvaluationReason.Kind.RULE_MATCH;
import static com.launchdarkly.sdk.EvaluationReason.Kind.TARGET_MATCH;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
import static java.util.Arrays.asList;
import org.junit.Test;
@@ -84,6 +87,67 @@ public void bigSegmentsStatus() {
assertNull(reason.getBigSegmentsStatus());
}
+ @Test
+ public void overrideAffectedIsFalseByDefault() {
+ assertFalse(EvaluationReason.off().isOverrideAffected());
+ assertFalse(EvaluationReason.fallthrough().isOverrideAffected());
+ assertFalse(EvaluationReason.fallthrough(true).isOverrideAffected());
+ assertFalse(EvaluationReason.targetMatch().isOverrideAffected());
+ assertFalse(EvaluationReason.ruleMatch(1, "id").isOverrideAffected());
+ assertFalse(EvaluationReason.prerequisiteFailed("key").isOverrideAffected());
+ assertFalse(EvaluationReason.error(FLAG_NOT_FOUND).isOverrideAffected());
+ assertFalse(EvaluationReason.exception(new Exception("sorry")).isOverrideAffected());
+ assertFalse(EvaluationReason.fallthrough().withBigSegmentsStatus(HEALTHY).isOverrideAffected());
+ }
+
+ @Test
+ public void withOverrideAffectedKeepsOtherProperties() {
+ EvaluationReason reason = EvaluationReason.ruleMatch(2, "id", true).withBigSegmentsStatus(STALE);
+ EvaluationReason marked = reason.withOverrideAffected(true);
+
+ assertTrue(marked.isOverrideAffected());
+ assertFalse(reason.isOverrideAffected());
+ assertEquals(RULE_MATCH, marked.getKind());
+ assertEquals(2, marked.getRuleIndex());
+ assertEquals("id", marked.getRuleId());
+ assertTrue(marked.isInExperiment());
+ assertEquals(STALE, marked.getBigSegmentsStatus());
+
+ Exception e = new Exception("sorry");
+ EvaluationReason markedError = EvaluationReason.exception(e).withOverrideAffected(true);
+ assertEquals(ERROR, markedError.getKind());
+ assertEquals(EvaluationReason.ErrorKind.EXCEPTION, markedError.getErrorKind());
+ assertEquals(e, markedError.getException());
+ assertTrue(markedError.isOverrideAffected());
+
+ // The marking survives a later change of another property.
+ assertTrue(marked.withBigSegmentsStatus(HEALTHY).isOverrideAffected());
+ }
+
+ @Test
+ public void withOverrideAffectedReturnsSameInstanceWhenUnchanged() {
+ EvaluationReason reason = EvaluationReason.off();
+ assertSame(reason, reason.withOverrideAffected(false));
+ EvaluationReason marked = reason.withOverrideAffected(true);
+ assertSame(marked, marked.withOverrideAffected(true));
+ assertFalse(marked.withOverrideAffected(false).isOverrideAffected());
+ }
+
+ @Test
+ public void overrideAffectedParticipatesInEquality() {
+ EvaluationReason plain = EvaluationReason.off();
+ EvaluationReason marked = plain.withOverrideAffected(true);
+ assertNotEquals(plain, marked);
+ assertEquals(marked, plain.withOverrideAffected(true));
+ assertEquals(marked.hashCode(), plain.withOverrideAffected(true).hashCode());
+ }
+
+ @Test
+ public void overrideAffectedDoesNotChangeStringRepresentation() {
+ assertEquals("OFF", EvaluationReason.off().withOverrideAffected(true).toString());
+ assertEquals("RULE_MATCH(1,id)", EvaluationReason.ruleMatch(1, "id").withOverrideAffected(true).toString());
+ }
+
@Test
public void simpleStringRepresentations() {
assertEquals("OFF", EvaluationReason.off().toString());
@@ -129,7 +193,10 @@ public void equalInstancesAreEqual() {
asList(EvaluationReason.ruleMatch(2, "id1"), EvaluationReason.ruleMatch(2, "id1")),
asList(EvaluationReason.prerequisiteFailed("a"), EvaluationReason.prerequisiteFailed("a")),
asList(EvaluationReason.error(CLIENT_NOT_READY), EvaluationReason.error(CLIENT_NOT_READY)),
- asList(EvaluationReason.error(WRONG_TYPE), EvaluationReason.error(WRONG_TYPE))
+ asList(EvaluationReason.error(WRONG_TYPE), EvaluationReason.error(WRONG_TYPE)),
+ asList(EvaluationReason.off().withOverrideAffected(true), EvaluationReason.off().withOverrideAffected(true)),
+ asList(EvaluationReason.error(WRONG_TYPE).withOverrideAffected(true),
+ EvaluationReason.error(WRONG_TYPE).withOverrideAffected(true))
);
TestHelpers.doEqualityTests(testValues);
}
diff --git a/lib/shared/common/src/test/java/com/launchdarkly/sdk/json/EvaluationReasonJsonSerializationTest.java b/lib/shared/common/src/test/java/com/launchdarkly/sdk/json/EvaluationReasonJsonSerializationTest.java
index 4512f0c3..d94d02e3 100644
--- a/lib/shared/common/src/test/java/com/launchdarkly/sdk/json/EvaluationReasonJsonSerializationTest.java
+++ b/lib/shared/common/src/test/java/com/launchdarkly/sdk/json/EvaluationReasonJsonSerializationTest.java
@@ -59,6 +59,26 @@ public void reasonJsonSerializations() throws Exception {
verifyDeserializeInvalidJson(EvaluationReason.class, "{\"kind\":\"RULE_MATCH\",\"ruleIndex\":1,\"ruleId\":3}");
}
+ @Test
+ public void overrideAffectedIsSerializedOnlyWhenTrue() throws Exception {
+ verifySerializeAndDeserialize(EvaluationReason.off().withOverrideAffected(true),
+ "{\"kind\":\"OFF\",\"overrideAffected\":true}");
+ verifySerializeAndDeserialize(EvaluationReason.fallthrough(true).withOverrideAffected(true),
+ "{\"kind\":\"FALLTHROUGH\",\"inExperiment\":true,\"overrideAffected\":true}");
+ verifySerializeAndDeserialize(EvaluationReason.ruleMatch(1, "id").withOverrideAffected(true),
+ "{\"kind\":\"RULE_MATCH\",\"ruleIndex\":1,\"ruleId\":\"id\",\"overrideAffected\":true}");
+ verifySerializeAndDeserialize(EvaluationReason.prerequisiteFailed("key").withOverrideAffected(true),
+ "{\"kind\":\"PREREQUISITE_FAILED\",\"prerequisiteKey\":\"key\",\"overrideAffected\":true}");
+ verifySerializeAndDeserialize(EvaluationReason.error(EvaluationReason.ErrorKind.MALFORMED_FLAG).withOverrideAffected(true),
+ "{\"kind\":\"ERROR\",\"errorKind\":\"MALFORMED_FLAG\",\"overrideAffected\":true}");
+ verifySerializeAndDeserialize(EvaluationReason.fallthrough().withBigSegmentsStatus(HEALTHY).withOverrideAffected(true),
+ "{\"kind\":\"FALLTHROUGH\",\"bigSegmentsStatus\":\"HEALTHY\",\"overrideAffected\":true}");
+
+ // A false value is never written, and an explicit false parses the same as an absent property.
+ verifySerialize(EvaluationReason.off().withOverrideAffected(false), "{\"kind\":\"OFF\"}");
+ verifyDeserialize(EvaluationReason.off(), "{\"kind\":\"OFF\",\"overrideAffected\":false}");
+ }
+
@Test
public void errorSerializationWithException() throws Exception {
// We do *not* want the JSON representation to include the exception, because that is used in events, and
From 9dcbf77cc6bd236f4b8a67b276d70616f5dac9b1 Mon Sep 17 00:00:00 2001
From: Ryan Lamb <4955475+kinyoklion@users.noreply.github.com>
Date: Fri, 6 Nov 2026 11:08:44 -0800
Subject: [PATCH 2/9] feat: Count override-affected evaluations separately and
send no individual events for them (#219)
## Summary
The OVERRIDE specification marks an evaluation as override-affected when
any definition it read came from the SDK's override store. Such an
evaluation appears in summary events only: it produces no individual
feature event and no debug event, whatever the flag's configuration
requests, and it is counted in a separate summary counter that carries
an `overrideAffected` marker, so override-affected and ordinary
evaluations of the same flag, variation, and version are never collapsed
together.
- `Event.FeatureRequest` carries the marking as a boolean that the SDK
sets from its evaluation result. The existing constructors keep working
and leave it false; `toDebugEvent()` keeps the value.
- `DefaultEventProcessor` keys individual feature event and debug event
emission on the marking. Index events and summaries are unchanged.
- `EventSummarizer` keeps a second set of counters per flag for marked
evaluations, created on first use so unmarked flags pay nothing.
`EventOutputFormatter` writes `overrideAffected: true` only on those
counters, the same way the `unknown` marker is written.
- `EventSummarizerInterface` gains the marker parameter and keeps the
previous signature as a default method that delegates with false.
Flag overrides are currently experimental and subject to change. The
server SDK change that sets the marking depends on the release of this
package.
[SDK-3246](https://launchdarkly.atlassian.net/browse/SDK-3246)
[SDK-3246]:
https://launchdarkly.atlassian.net/browse/SDK-3246?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
---
> [!NOTE]
> **Overview**
> Adds **override-affected** handling for flag evaluations tied to the
experimental override store: `Event.FeatureRequest` carries an
`overrideAffected` flag (existing constructors default to false).
>
> **`DefaultEventProcessor`** still summarizes and emits index events,
but **suppresses individual feature and debug events** whenever
`isOverrideAffected()` is true, regardless of `trackEvents` or debug
configuration.
>
> **`EventSummarizer`** (and aggregated/per-context wrappers) buckets
those evaluations in a **separate counter map** per flag so they are not
merged with normal counts for the same version/variation;
**`EventOutputFormatter`** emits `overrideAffected: true` only on those
summary counters.
>
> Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0e7744f2770e644153c0b5f304161ab0a9682a77. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).
---
.../events/AggregatedEventSummarizer.java | 6 +-
.../events/DefaultEventProcessor.java | 9 ++-
.../sdk/internal/events/Event.java | 52 +++++++++++-
.../internal/events/EventOutputFormatter.java | 58 +++++++++-----
.../sdk/internal/events/EventSummarizer.java | 77 ++++++++++++++++--
.../events/EventSummarizerInterface.java | 32 +++++++-
.../events/PerContextEventSummarizer.java | 7 +-
.../sdk/internal/events/BaseEventTest.java | 22 ++++-
.../DefaultEventProcessorOutputTest.java | 80 +++++++++++++++++++
.../sdk/internal/events/EventOutputTest.java | 28 +++++++
.../internal/events/EventSummarizerTest.java | 50 ++++++++++++
11 files changed, 379 insertions(+), 42 deletions(-)
diff --git a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/AggregatedEventSummarizer.java b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/AggregatedEventSummarizer.java
index 710c8937..62ca1d6a 100644
--- a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/AggregatedEventSummarizer.java
+++ b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/AggregatedEventSummarizer.java
@@ -31,9 +31,11 @@ public void summarizeEvent(
int variation,
LDValue value,
LDValue defaultValue,
- LDContext context
+ LDContext context,
+ boolean overrideAffected
) {
- summarizer.summarizeEvent(timestamp, flagKey, flagVersion, variation, value, defaultValue, context);
+ summarizer.summarizeEvent(timestamp, flagKey, flagVersion, variation, value, defaultValue, context,
+ overrideAffected);
}
@Override
diff --git a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/DefaultEventProcessor.java b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/DefaultEventProcessor.java
index f258243b..a8974370 100644
--- a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/DefaultEventProcessor.java
+++ b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/DefaultEventProcessor.java
@@ -544,8 +544,10 @@ private void processEvent(Event e, EventBuffer outbox) {
if(!fe.isExcludeFromSummaries()) {
outbox.addToSummary(fe);
}
- addFullEvent = fe.isTrackEvents();
- if (shouldDebugEvent(fe)) {
+ // An override-affected evaluation appears only in the summary counters. It produces no
+ // individual feature event and no debug event, whatever the flag's configuration requests.
+ addFullEvent = fe.isTrackEvents() && !fe.isOverrideAffected();
+ if (!fe.isOverrideAffected() && shouldDebugEvent(fe)) {
debugEvent = fe.toDebugEvent();
}
} else {
@@ -702,7 +704,8 @@ void addToSummary(Event.FeatureRequest e) {
e.getVariation(),
e.getValue(),
e.getDefaultVal(),
- e.getContext()
+ e.getContext(),
+ e.isOverrideAffected()
);
}
diff --git a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/Event.java b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/Event.java
index 16c5b666..49abe8e2 100644
--- a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/Event.java
+++ b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/Event.java
@@ -155,6 +155,7 @@ public static final class FeatureRequest extends Event {
private final boolean debug;
private final long samplingRatio;
private final boolean excludeFromSummaries;
+ private final boolean overrideAffected;
/**
* Constructs a feature request event.
@@ -171,12 +172,14 @@ public static final class FeatureRequest extends Event {
* @param trackEvents true if full event tracking is turned on for this flag
* @param debugEventsUntilDate if non-null, the time until which event debugging should be enabled
* @param debug true if this is a debugging event
- * @param excludeFromSummaries true to exclude the event from summaries
* @param samplingRatio the sampling ratio for the event
+ * @param excludeFromSummaries true to exclude the event from summaries
+ * @param overrideAffected true if an override affected the evaluation; see {@link #isOverrideAffected()}
*/
public FeatureRequest(long timestamp, String key, LDContext context, int version, int variation, LDValue value,
LDValue defaultVal, EvaluationReason reason, String prereqOf, boolean trackEvents,
- Long debugEventsUntilDate, boolean debug, long samplingRatio, boolean excludeFromSummaries) {
+ Long debugEventsUntilDate, boolean debug, long samplingRatio, boolean excludeFromSummaries,
+ boolean overrideAffected) {
super(timestamp, context);
this.key = key;
this.version = version;
@@ -190,6 +193,32 @@ public FeatureRequest(long timestamp, String key, LDContext context, int version
this.debug = debug;
this.excludeFromSummaries = excludeFromSummaries;
this.samplingRatio = samplingRatio;
+ this.overrideAffected = overrideAffected;
+ }
+
+ /**
+ * Constructs a feature request event that no override affected.
+ *
+ * @param timestamp the timestamp in milliseconds
+ * @param key the flag key
+ * @param context the context associated with the event
+ * @param version the flag version, or -1 if the flag was not found
+ * @param variation the result variation, or -1 if there was an error
+ * @param value the result value
+ * @param defaultVal the default value passed by the application
+ * @param reason the evaluation reason, if it is to be included in the event
+ * @param prereqOf if this flag was evaluated as a prerequisite, this is the key of the flag that referenced it
+ * @param trackEvents true if full event tracking is turned on for this flag
+ * @param debugEventsUntilDate if non-null, the time until which event debugging should be enabled
+ * @param debug true if this is a debugging event
+ * @param samplingRatio the sampling ratio for the event
+ * @param excludeFromSummaries true to exclude the event from summaries
+ */
+ public FeatureRequest(long timestamp, String key, LDContext context, int version, int variation, LDValue value,
+ LDValue defaultVal, EvaluationReason reason, String prereqOf, boolean trackEvents,
+ Long debugEventsUntilDate, boolean debug, long samplingRatio, boolean excludeFromSummaries) {
+ this(timestamp, key, context, version, variation, value, defaultVal, reason, prereqOf, trackEvents,
+ debugEventsUntilDate, debug, samplingRatio, excludeFromSummaries, false);
}
/**
@@ -311,6 +340,23 @@ public boolean isExcludeFromSummaries() {
return excludeFromSummaries;
}
+ /**
+ * True if an override affected this evaluation. The override can be direct or transitive. It is
+ * direct when the evaluated flag came from the SDK's override store. It is transitive when a
+ * prerequisite flag at any depth, or a segment read during the evaluation, came from that store.
+ *
+ * The event processor keys on this value alone. It produces no individual feature event and no
+ * debug event for such an evaluation, and it counts the evaluation in a separate summary counter
+ * that carries the override-affected marker.
+ *
+ * Flag overrides are currently experimental and subject to change.
+ *
+ * @return true if an override affected the evaluation
+ */
+ public boolean isOverrideAffected() {
+ return overrideAffected;
+ }
+
@Override
public long getSamplingRatio() {
return samplingRatio;
@@ -324,7 +370,7 @@ public long getSamplingRatio() {
public FeatureRequest toDebugEvent() {
return new FeatureRequest(getCreationDate(), getKey(), getContext(), getVersion(),
getVariation(), getValue(), getDefaultVal(), getReason(), getPrereqOf(),
- false, null, true, samplingRatio, excludeFromSummaries);
+ false, null, true, samplingRatio, excludeFromSummaries, overrideAffected);
}
}
diff --git a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventOutputFormatter.java b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventOutputFormatter.java
index 6815812d..71f98ea3 100644
--- a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventOutputFormatter.java
+++ b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventOutputFormatter.java
@@ -280,28 +280,11 @@ private void writeSummaryEvent(EventSummarizer.EventSummary summary, JsonWriter
jw.name("counters");
jw.beginArray();
- for (int i = 0; i < flagInfo.versionsAndVariations.size(); i++) {
- int version = flagInfo.versionsAndVariations.keyAt(i);
- SimpleIntKeyedMap variations = flagInfo.versionsAndVariations.valueAt(i);
- for (int j = 0; j < variations.size(); j++) {
- int variation = variations.keyAt(j);
- CounterValue counter = variations.valueAt(j);
-
- jw.beginObject();
-
- if (variation >= 0) {
- jw.name("variation").value(variation);
- }
- if (version >= 0) {
- jw.name("version").value(version);
- } else {
- jw.name("unknown").value(true);
- }
- writeLDValue("value", counter.flagValue, jw);
- jw.name("count").value(counter.count);
-
- jw.endObject();
- }
+ writeCounters(jw, flagInfo.versionsAndVariations, false);
+ SimpleIntKeyedMap> overrideAffectedCounters =
+ flagInfo.overrideAffectedVersionsAndVariationsIfAny();
+ if (overrideAffectedCounters != null) {
+ writeCounters(jw, overrideAffectedCounters, true);
}
jw.endArray(); // end of "counters" array
@@ -312,6 +295,37 @@ private void writeSummaryEvent(EventSummarizer.EventSummary summary, JsonWriter
jw.endObject(); // end of summary event object
}
+ private void writeCounters(JsonWriter jw, SimpleIntKeyedMap> versionsAndVariations,
+ boolean overrideAffected) throws IOException {
+ for (int i = 0; i < versionsAndVariations.size(); i++) {
+ int version = versionsAndVariations.keyAt(i);
+ SimpleIntKeyedMap variations = versionsAndVariations.valueAt(i);
+ for (int j = 0; j < variations.size(); j++) {
+ int variation = variations.keyAt(j);
+ CounterValue counter = variations.valueAt(j);
+
+ jw.beginObject();
+
+ if (variation >= 0) {
+ jw.name("variation").value(variation);
+ }
+ if (version >= 0) {
+ jw.name("version").value(version);
+ } else {
+ jw.name("unknown").value(true);
+ }
+ // The override-affected marker is present only when true, like the unknown marker.
+ if (overrideAffected) {
+ jw.name("overrideAffected").value(true);
+ }
+ writeLDValue("value", counter.flagValue, jw);
+ jw.name("count").value(counter.count);
+
+ jw.endObject();
+ }
+ }
+ }
+
private void writeKindAndCreationDate(JsonWriter jw, String kind, long creationDate) throws IOException {
jw.name("kind").value(kind);
jw.name("creationDate").value(creationDate);
diff --git a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventSummarizer.java b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventSummarizer.java
index e4a87daf..c1d795e2 100644
--- a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventSummarizer.java
+++ b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventSummarizer.java
@@ -47,7 +47,33 @@ void summarizeEvent(
LDValue defaultValue,
LDContext context
) {
- eventsState.incrementCounter(flagKey, flagVersion, variation, value, defaultValue, context);
+ summarizeEvent(timestamp, flagKey, flagVersion, variation, value, defaultValue, context, false);
+ }
+
+ /**
+ * Adds information about an evaluation to our counters. An override-affected evaluation is
+ * counted in a separate counter from other evaluations of the same flag, version, and variation.
+ *
+ * @param timestamp the millisecond timestamp
+ * @param flagKey the flag key
+ * @param flagVersion the flag version, or -1 if the flag is unknown
+ * @param variation the result variation, or -1 if none
+ * @param value the result value
+ * @param defaultValue the application default value
+ * @param context the evaluation context
+ * @param overrideAffected true if an override affected the evaluation
+ */
+ void summarizeEvent(
+ long timestamp,
+ String flagKey,
+ int flagVersion,
+ int variation,
+ LDValue value,
+ LDValue defaultValue,
+ LDContext context,
+ boolean overrideAffected
+ ) {
+ eventsState.incrementCounter(flagKey, flagVersion, variation, value, defaultValue, context, overrideAffected);
eventsState.noteTimestamp(timestamp);
}
@@ -120,7 +146,8 @@ void incrementCounter(
int variation,
LDValue flagValue,
LDValue defaultVal,
- LDContext context
+ LDContext context,
+ boolean overrideAffected
) {
FlagInfo flagInfo = counters.get(flagKey);
if (flagInfo == null) {
@@ -131,10 +158,12 @@ void incrementCounter(
flagInfo.contextKinds.add(context.getIndividualContext(i).getKind().toString());
}
- SimpleIntKeyedMap variations = flagInfo.versionsAndVariations.get(flagVersion);
+ SimpleIntKeyedMap> versionsAndVariations =
+ overrideAffected ? flagInfo.overrideAffectedVersionsAndVariations() : flagInfo.versionsAndVariations;
+ SimpleIntKeyedMap variations = versionsAndVariations.get(flagVersion);
if (variations == null) {
variations = new SimpleIntKeyedMap<>();
- flagInfo.versionsAndVariations.put(flagVersion, variations);
+ versionsAndVariations.put(flagVersion, variations);
}
CounterValue value = variations.get(variation);
@@ -175,21 +204,55 @@ public int hashCode() {
static final class FlagInfo {
final LDValue defaultVal;
+ // Counters for evaluations that no override affected, keyed by version and then by variation.
final SimpleIntKeyedMap> versionsAndVariations;
+ // Counters for override-affected evaluations, with the same shape. Most flags never have any,
+ // so the map is created on first use.
+ private SimpleIntKeyedMap> overrideAffectedVersionsAndVariations;
final Set contextKinds;
FlagInfo(LDValue defaultVal, SimpleIntKeyedMap> versionsAndVariations,
Set contextKinds) {
+ this(defaultVal, versionsAndVariations, null, contextKinds);
+ }
+
+ FlagInfo(LDValue defaultVal, SimpleIntKeyedMap> versionsAndVariations,
+ SimpleIntKeyedMap> overrideAffectedVersionsAndVariations,
+ Set contextKinds) {
this.defaultVal = defaultVal;
this.versionsAndVariations = versionsAndVariations;
+ this.overrideAffectedVersionsAndVariations = overrideAffectedVersionsAndVariations;
this.contextKinds = contextKinds;
}
+
+ /**
+ * Returns the counters for override-affected evaluations, creating the map on first use.
+ *
+ * @return the counters, never null
+ */
+ SimpleIntKeyedMap> overrideAffectedVersionsAndVariations() {
+ if (overrideAffectedVersionsAndVariations == null) {
+ overrideAffectedVersionsAndVariations = new SimpleIntKeyedMap<>();
+ }
+ return overrideAffectedVersionsAndVariations;
+ }
+
+ /**
+ * Returns the counters for override-affected evaluations, or null if there are none.
+ *
+ * @return the counters or null
+ */
+ SimpleIntKeyedMap> overrideAffectedVersionsAndVariationsIfAny() {
+ return overrideAffectedVersionsAndVariations == null || overrideAffectedVersionsAndVariations.size() == 0
+ ? null : overrideAffectedVersionsAndVariations;
+ }
@Override
public boolean equals(Object other) { // used only in tests
if (other instanceof FlagInfo) {
FlagInfo o = (FlagInfo)other;
return o.defaultVal.equals(this.defaultVal) && o.versionsAndVariations.equals(this.versionsAndVariations) &&
+ Objects.equals(o.overrideAffectedVersionsAndVariationsIfAny(), this.overrideAffectedVersionsAndVariationsIfAny()) &&
o.contextKinds.equals(this.contextKinds);
}
return false;
@@ -202,8 +265,10 @@ public int hashCode() { // used only in tests
@Override
public String toString() { // used only in tests
- return "(default=" + defaultVal + ", counters=" + versionsAndVariations + ", contextKinds=" +
- String.join(",", contextKinds) + ")";
+ return "(default=" + defaultVal + ", counters=" + versionsAndVariations +
+ (overrideAffectedVersionsAndVariationsIfAny() == null ? "" :
+ ", overrideAffectedCounters=" + overrideAffectedVersionsAndVariations) +
+ ", contextKinds=" + String.join(",", contextKinds) + ")";
}
}
diff --git a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventSummarizerInterface.java b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventSummarizerInterface.java
index 87a352f0..e138a89d 100644
--- a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventSummarizerInterface.java
+++ b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/EventSummarizerInterface.java
@@ -15,7 +15,7 @@
*/
public interface EventSummarizerInterface {
/**
- * Adds information about an evaluation to the summary.
+ * Adds information about an evaluation that no override affected to the summary.
*
* @param timestamp the millisecond timestamp
* @param flagKey the flag key
@@ -25,7 +25,7 @@ public interface EventSummarizerInterface {
* @param defaultValue the application default value
* @param context the evaluation context
*/
- void summarizeEvent(
+ default void summarizeEvent(
long timestamp,
String flagKey,
int flagVersion,
@@ -33,6 +33,34 @@ void summarizeEvent(
LDValue value,
LDValue defaultValue,
LDContext context
+ ) {
+ summarizeEvent(timestamp, flagKey, flagVersion, variation, value, defaultValue, context, false);
+ }
+
+ /**
+ * Adds information about an evaluation to the summary.
+ *
+ * Override-affected evaluations are counted separately from other evaluations of the same flag,
+ * version, and variation, so the marker takes part in the counter key.
+ *
+ * @param timestamp the millisecond timestamp
+ * @param flagKey the flag key
+ * @param flagVersion the flag version, or -1 if the flag is unknown
+ * @param variation the result variation, or -1 if none
+ * @param value the result value
+ * @param defaultValue the application default value
+ * @param context the evaluation context
+ * @param overrideAffected true if an override affected the evaluation
+ */
+ void summarizeEvent(
+ long timestamp,
+ String flagKey,
+ int flagVersion,
+ int variation,
+ LDValue value,
+ LDValue defaultValue,
+ LDContext context,
+ boolean overrideAffected
);
/**
diff --git a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/PerContextEventSummarizer.java b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/PerContextEventSummarizer.java
index d621378c..3158d642 100644
--- a/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/PerContextEventSummarizer.java
+++ b/lib/shared/internal/src/main/java/com/launchdarkly/sdk/internal/events/PerContextEventSummarizer.java
@@ -36,6 +36,7 @@ public PerContextEventSummarizer() {
* @param value the result value
* @param defaultValue the application default value
* @param context the evaluation context
+ * @param overrideAffected true if an override affected the evaluation
*/
@Override
public void summarizeEvent(
@@ -45,13 +46,15 @@ public void summarizeEvent(
int variation,
LDValue value,
LDValue defaultValue,
- LDContext context
+ LDContext context,
+ boolean overrideAffected
) {
// Get or create summarizer for this context
EventSummarizer summarizer = summarizersByContext.computeIfAbsent(context, EventSummarizer::new);
// Delegate to the per-context summarizer
- summarizer.summarizeEvent(timestamp, flagKey, flagVersion, variation, value, defaultValue, context);
+ summarizer.summarizeEvent(timestamp, flagKey, flagVersion, variation, value, defaultValue, context,
+ overrideAffected);
}
/**
diff --git a/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/BaseEventTest.java b/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/BaseEventTest.java
index 776185cc..eb29e812 100644
--- a/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/BaseEventTest.java
+++ b/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/BaseEventTest.java
@@ -292,7 +292,19 @@ public static Matcher isSummaryEventCounter(int flagVersion, Inte
jsonProperty("variation", variation),
jsonProperty("version", (double)flagVersion),
jsonProperty("value", jsonFromValue(value)),
- jsonProperty("count", (double)count)
+ jsonProperty("count", (double)count),
+ jsonProperty("overrideAffected", jsonUndefined())
+ );
+ }
+
+ public static Matcher isOverrideAffectedSummaryEventCounter(int flagVersion, Integer variation,
+ LDValue value, int count) {
+ return allOf(
+ jsonProperty("variation", variation),
+ jsonProperty("version", (double)flagVersion),
+ jsonProperty("value", jsonFromValue(value)),
+ jsonProperty("count", (double)count),
+ jsonProperty("overrideAffected", true)
);
}
@@ -477,6 +489,7 @@ public static final class FeatureRequestEventBuilder {
private Long debugEventsUntilDate = null;
private long samplingRatio = 1;
private boolean excludeFromSummaries = false;
+ private boolean overrideAffected = false;
public FeatureRequestEventBuilder(LDContext context, String flagKey) {
this.context = context;
@@ -486,7 +499,12 @@ public FeatureRequestEventBuilder(LDContext context, String flagKey) {
public Event.FeatureRequest build() {
return new Event.FeatureRequest(timestamp, flagKey, context, flagVersion, variation, value,
defaultValue, reason, prereqOf, trackEvents, debugEventsUntilDate, false, samplingRatio,
- excludeFromSummaries);
+ excludeFromSummaries, overrideAffected);
+ }
+
+ public FeatureRequestEventBuilder overrideAffected(boolean overrideAffected) {
+ this.overrideAffected = overrideAffected;
+ return this;
}
public FeatureRequestEventBuilder flagVersion(int flagVersion) {
diff --git a/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/DefaultEventProcessorOutputTest.java b/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/DefaultEventProcessorOutputTest.java
index 78c4a19e..d5aaee58 100644
--- a/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/DefaultEventProcessorOutputTest.java
+++ b/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/DefaultEventProcessorOutputTest.java
@@ -351,6 +351,86 @@ public void identifyEventMakesIndexEventUnnecessary() throws Exception {
}
+ @SuppressWarnings("unchecked")
+ @Test
+ public void overrideAffectedEvaluationProducesNoFeatureEventAndNoDebugEvent() throws Exception {
+ // The flag requests both an individual feature event and a debug event. An override affected
+ // the evaluation, so neither is produced. The evaluation still produces an index event and a
+ // summary counter, and the counter carries the override-affected marker.
+ MockEventSender es = new MockEventSender();
+ long futureTime = System.currentTimeMillis() + 1000000;
+ Event.FeatureRequest fe = featureEvent(user, FLAG_KEY).flagVersion(FLAG_VERSION).variation(1)
+ .value(LDValue.of("value")).defaultValue(LDValue.of("default"))
+ .trackEvents(true).debugEventsUntilDate(futureTime).overrideAffected(true).build();
+
+ EventContextDeduplicator contextDeduplicator = contextDeduplicatorThatAlwaysSaysKeysAreNew();
+
+ try (DefaultEventProcessor ep = makeEventProcessor(baseConfig(es).contextDeduplicator(contextDeduplicator))) {
+ ep.sendEvent(fe);
+ }
+
+ assertThat(es.getEventsFromLastRequest(), contains(
+ isIndexEvent(fe, userJson),
+ allOf(
+ isSummaryEvent(),
+ hasSummaryFlag(FLAG_KEY, LDValue.of("default"),
+ contains(isOverrideAffectedSummaryEventCounter(FLAG_VERSION, 1, LDValue.of("value"), 1)))
+ )
+ ));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void overrideAffectedPrerequisiteEvaluationProducesNoFeatureEvent() throws Exception {
+ MockEventSender es = new MockEventSender();
+ Event.FeatureRequest fe = featureEvent(user, FLAG_KEY).prereqOf("parent")
+ .trackEvents(true).overrideAffected(true).build();
+
+ try (DefaultEventProcessor ep = makeEventProcessor(baseConfig(es))) {
+ ep.sendEvent(fe);
+ }
+
+ assertThat(es.getEventsFromLastRequest(), contains(
+ isSummaryEvent()
+ ));
+ }
+
+ @SuppressWarnings("unchecked")
+ @Test
+ public void overrideAffectedAndUnaffectedEvaluationsOfSameFlagGetSeparateCounters() throws Exception {
+ MockEventSender es = new MockEventSender();
+ LDValue value = LDValue.of("value"), defaultValue = LDValue.of("default");
+ Event.FeatureRequest plain = featureEvent(user, FLAG_KEY).flagVersion(FLAG_VERSION).variation(1)
+ .value(value).defaultValue(defaultValue).build();
+ Event.FeatureRequest marked = featureEvent(user, FLAG_KEY).flagVersion(FLAG_VERSION).variation(1)
+ .value(value).defaultValue(defaultValue).overrideAffected(true).build();
+
+ try (DefaultEventProcessor ep = makeEventProcessor(baseConfig(es))) {
+ ep.sendEvent(plain);
+ ep.sendEvent(marked);
+ ep.sendEvent(marked);
+ }
+
+ assertThat(es.getEventsFromLastRequest(), contains(
+ allOf(
+ isSummaryEvent(),
+ hasSummaryFlag(FLAG_KEY, defaultValue,
+ Matchers.containsInAnyOrder(
+ isSummaryEventCounter(FLAG_VERSION, 1, value, 1),
+ isOverrideAffectedSummaryEventCounter(FLAG_VERSION, 1, value, 2)
+ ))
+ )
+ ));
+ }
+
+ @Test
+ public void debugEventKeepsOverrideAffectedMarker() {
+ Event.FeatureRequest fe = featureEvent(user, FLAG_KEY).overrideAffected(true).build();
+ Assert.assertTrue(fe.toDebugEvent().isOverrideAffected());
+ Assert.assertTrue(fe.toDebugEvent().isDebug());
+ Assert.assertFalse(featureEvent(user, FLAG_KEY).build().isOverrideAffected());
+ }
+
@SuppressWarnings("unchecked")
@Test
public void nonTrackedEventsAreSummarized() throws Exception {
diff --git a/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/EventOutputTest.java b/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/EventOutputTest.java
index 27ed2d15..e3582203 100644
--- a/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/EventOutputTest.java
+++ b/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/EventOutputTest.java
@@ -461,6 +461,34 @@ public void summaryEventIsSerialized() throws Exception {
));
}
+ @Test
+ public void summaryEventMarksOverrideAffectedCounters() throws Exception {
+ LDValue value = LDValue.of("value"), defaultValue = LDValue.of("default");
+ LDContext context = LDContext.create("key1");
+
+ EventSummarizer es = new EventSummarizer();
+ es.summarizeEvent(1000, "flag", 11, 1, value, defaultValue, context, false);
+ es.summarizeEvent(1001, "flag", 11, 1, value, defaultValue, context, true);
+ es.summarizeEvent(1002, "flag", 11, 1, value, defaultValue, context, true);
+ es.summarizeEvent(1003, "unknown", -1, -1, defaultValue, defaultValue, context, true);
+ EventSummary summary = es.getSummaryAndReset();
+
+ EventOutputFormatter f = new EventOutputFormatter(defaultEventsConfig());
+ StringWriter w = new StringWriter();
+ f.writeOutputEvents(new Event[0], Collections.singletonList(summary), w);
+ LDValue featuresJson = parseValue(w.toString()).get(0).get("features");
+
+ // The marked and unmarked evaluations of the same flag, version, and variation are separate
+ // counters. The marker appears only on the marked counter.
+ assertThat(featuresJson.get("flag").get("counters").values(), containsInAnyOrder(
+ parseValue("{\"value\":\"value\",\"variation\":1,\"version\":11,\"count\":1}"),
+ parseValue("{\"value\":\"value\",\"variation\":1,\"version\":11,\"overrideAffected\":true,\"count\":2}")
+ ));
+ assertThat(featuresJson.get("unknown").get("counters").values(), contains(
+ parseValue("{\"unknown\":true,\"overrideAffected\":true,\"value\":\"default\",\"count\":1}")
+ ));
+ }
+
@Test
public void migrationOpEventIsSerialized() throws IOException {
LDContext context = LDContext.builder("user-key").name("me").build();
diff --git a/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/EventSummarizerTest.java b/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/EventSummarizerTest.java
index 8426512f..d636e615 100644
--- a/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/EventSummarizerTest.java
+++ b/lib/shared/internal/src/test/java/com/launchdarkly/sdk/internal/events/EventSummarizerTest.java
@@ -95,6 +95,56 @@ public void summarizeEventIncrementsCounters() {
.build()));
}
+ @Test
+ public void overrideAffectedEvaluationsAreCountedSeparately() {
+ EventSummarizer es = new EventSummarizer();
+ String flagKey = "key1";
+ int flagVersion = 11;
+ LDValue value1 = LDValue.of("value1"), default1 = LDValue.of("default1");
+ long timestamp = 1000;
+
+ // Same flag, version, variation, and value. Only the marker differs.
+ es.summarizeEvent(timestamp, flagKey, flagVersion, 1, value1, default1, context, false);
+ es.summarizeEvent(timestamp, flagKey, flagVersion, 1, value1, default1, context, true);
+ es.summarizeEvent(timestamp, flagKey, flagVersion, 1, value1, default1, context, true);
+
+ EventSummarizer.EventSummary data = es.getSummaryAndReset();
+
+ assertThat(data.counters, equalTo(ImmutableMap.builder()
+ .put(flagKey, new FlagInfo(default1,
+ new SimpleIntKeyedMap>()
+ .put(flagVersion, new SimpleIntKeyedMap()
+ .put(1, new CounterValue(1, value1))
+ ),
+ new SimpleIntKeyedMap>()
+ .put(flagVersion, new SimpleIntKeyedMap()
+ .put(1, new CounterValue(2, value1))
+ ),
+ ImmutableSet.of("user")))
+ .build()));
+ }
+
+ @Test
+ public void flagWithoutOverrideAffectedEvaluationsHasNoOverrideAffectedCounters() {
+ EventSummarizer es = new EventSummarizer();
+ es.summarizeEvent(1000, "key1", 11, 1, LDValue.of("v"), LDValue.of("d"), context);
+ EventSummarizer.EventSummary data = es.getSummaryAndReset();
+ assertNull(data.counters.get("key1").overrideAffectedVersionsAndVariationsIfAny());
+ }
+
+ @Test
+ public void flagInfoEqualityIncludesOverrideAffectedCounters() {
+ SimpleIntKeyedMap> plain = new SimpleIntKeyedMap>()
+ .put(1, new SimpleIntKeyedMap().put(0, new CounterValue(1, LDValue.of("a"))));
+ SimpleIntKeyedMap> marked = new SimpleIntKeyedMap>()
+ .put(1, new SimpleIntKeyedMap().put(0, new CounterValue(1, LDValue.of("a"))));
+ FlagInfo withMarked = new FlagInfo(LDValue.of("d"), plain, marked, ImmutableSet.of("user"));
+ FlagInfo withoutMarked = new FlagInfo(LDValue.of("d"), plain, ImmutableSet.of("user"));
+ assertNotEquals(withMarked, withoutMarked);
+ assertEquals(withMarked, new FlagInfo(LDValue.of("d"), plain, marked, ImmutableSet.of("user")));
+ assertThat(withMarked.toString(), org.hamcrest.Matchers.containsString("overrideAffectedCounters"));
+ }
+
// The following implementations are used only in debug/test code, but may as well test them
@Test
From 43b7e74d0cb9212e566c8d3bd49d0cd58faef3d8 Mon Sep 17 00:00:00 2001
From: Ryan Lamb <4955475+kinyoklion@users.noreply.github.com>
Date: Thu, 3 Dec 2026 09:40:33 -0800
Subject: [PATCH 3/9] feat: Add reload infrastructure for file-based flag
overrides (#220)
## Update, 2026-12-01
- Rebased onto `feat/overrides`, which has `main` merged into it again.
From `main` it gets the 7.19.0 to 7.19.2 releases, `java-sdk-internal`
1.14.0, and the FDv2 fix that leaves out an empty selector (#261). The
v3.2.0-alpha.21 contract tests check that fix, so CI failed three FDv2
streaming tests without it.
Changes from the review:
- The reloader and the poller run on one executor that the caller owns,
at the SDK's thread priority. The watcher keeps its own thread.
- An unexpected exception from a load is a failed load, and it is
retried. An `Error` is logged like any failure but arms no timed retry;
the next change reloads. A stack overflow while parsing a file is a
parse failure of that file, and a path that is not a regular file fails
before it is read.
- Every load sets the retry that it asks for, so the retry and its log
message always come from the latest load.
- The reloader's handler has only the apply callback. The error callback
had one implementation, an empty one in #224, because the reloader logs
every failure itself. Options that no caller used are gone too: skipping
unchanged content is always on, the retry delay must be positive, and
every load has a content digest.
- The poller Javadoc says to create it before the initial load, and the
`reloadNow` Javadoc says that loads run one at a time. #224 now starts
change detection before the initial load.
- Failure messages no longer quote file content, for the override source
and the existing file data source, in the log and in the data source
status. Neither keeps the parser's exception as the cause.
- A YAML syntax error gives SnakeYAML's problem and position, without
the quoted lines.
- A JSON syntax error gives Gson's problem and position, without the
JSON path, which can hold a value. A malformed `\u` escape also leaves
out the characters after `\u`.
- A YAML value that cannot be converted to the type that its tag names
fails without the value. For the file data source this is now a parse
failure, where the exception escaped the loader before.
- A string in a number property of an override entry fails without the
string, and every data model failure of an override entry names the flag
or segment.
- YAML files parsed at the same time no longer return each other's
documents: each parse has its own `Yaml` instance. The file data source
shared the same static instance.
- The watcher keeps watching after an unexpected exception. On macOS it
removes the overrides of a file whose directory is deleted (tested with
a scripted watch service, not run on macOS). It stops watching a
directory that no configured link leads into any more.
- The watcher Javadoc names what watching does not follow: a configured
directory replaced by rename, and a configured link whose target does
not exist yet.
- The empty JSON file message says how to remove the file's overrides:
delete the file or write `{}`.
- Verified with the v3.2.0-alpha.21 harness that CI runs, with `common`
2.6.0 and `internal` 1.15.0 published locally from `feat/overrides`:
- #220 itself builds against the released libraries, as CI builds it:
the server unit tests pass (2180, with the 72 existing skips), and the
full v3 contract tests pass (6369 tests ran), including the three FDv2
tests that failed in CI;
- every PR in the stack compiles, with Javadoc, at its own head;
- the server unit tests pass at the top (2348, with the 72 existing
skips);
- the full v3 contract tests pass at the top (6457 tests ran). That
includes the flag overrides suite and both flag listener suites.
## Update, 2026-11-13
- Rebased onto `feat/overrides`, which now includes #218 and #219 and
has `main` merged into it. From `main` it gets the 7.18.0 release, CI on
the latest v3 contract tests, flag change listener support in the
contract test service, and the `java-sdk-internal` 1.12.1 and 1.12.2
fixes. A common 2.6.0 and internal 1.13.0 release from this branch needs
those fixes.
- New commit, "fix: Follow symbolic links when watching the override
files". In watching mode, the watcher counted only events that named a
configured file. A mounted Kubernetes ConfigMap updates its files by
swapping a `..data` link, so no event named the file and the update was
never picked up. A configured link to a file in another directory wasn't
followed either. Polling picked up both, and the Node, .NET, Python and
Ruby watchers follow these links.
- An event for another entry in a watched directory now counts when a
configured file, read through any symbolic link, leads to another file,
or its file's modification time or size changed. A busy sibling file
still costs no reload.
- The directory of each link's final target is watched too, and is found
again after every event. One that is deleted, like a ConfigMap's
previous version, is dropped instead of being retried with a warning.
- New `FileDataWatcherTest` cases cover a ConfigMap update, a change to
a link target in another directory, and a link pointed at a file in a
third directory. Three mutants each fail at least one of them: other
entries never count, target directories aren't watched, and a deleted
target directory is retried.
- Verified at the top of the stack, with `common` and `internal`
published locally from `feat/overrides`:
- every PR in the stack compiles, with Javadoc, at its own head;
- the server unit tests pass (2285, with the 72 existing skips);
- the full v3 contract tests pass (6321 tests). That includes the flag
overrides suite, with the deleted-entry tests of
launchdarkly/sdk-test-harness#599, and both flag listener suites.
## Summary
The flag overrides feature defined by the OVERRIDE specification needs a
file source that reloads reliably: coalesced change notifications, retry
after a failed read, retention of the last good data, sequential
reloads, support for files that do not exist yet, and files that are
rewritten in place. This change adds that infrastructure to the
integrations package for the file-based override source that follows.
The existing file data source keeps its current behavior, apart from the
parsing fixes in the 2026-12-01 update.
- `FileDataReloader` serializes reloads, debounces change signals with a
100 ms settle window, keeps the last good data on failure by not
applying, retries a failed load after one second, reports an identical
repeated failure once, and skips a reload whose content did not change.
Close never waits for an in-flight read. An exception from the apply
callback is reported like any other load failure and retried, and
nothing from that load is remembered. A load that holds an emptied file
back (below) applies nothing, reports no failure, and arms its retry for
the time the loader asks for; a failure still arms the normal retry. The
loader is told of every result that becomes the data in effect, applied
or skipped as unchanged, through `Loader.accepted`.
- `FileDataPoller` detects changes by examining each file's modification
time and size on a fixed interval, including a file that appears or
disappears. A change callback that throws is logged and polling
continues. Its `observe` is package-private, so that the loader reads a
file's state the same way, through symbolic links.
- `FileDataWatcher` watches parent directories through the file system
watch service and signals once after start so a change made between an
initial load and the start of watching is not missed. A directory that
is missing at start or deleted later is registered again on a one-second
schedule once it exists, and one change is signaled so the reload picks
up what was written meanwhile.
- `OverrideFileLoader` reads a list of files with the override source's
rules: a file that does not exist contributes no entries, entries keep
the versions that the documents specify, a value-only entry becomes a
flag that is on and serves the value by fallthrough, a document that
parses but holds a flag the model rejects is reported as a file data
error, and the result carries a per-file summary and a content digest of
each file's path, whether it exists, and its content.
### Format, encoding and empty files
The override loader chooses the parser by the file name: `.yaml` and
`.yml`, in any case, are YAML, and any other file, including one with no
extension, is JSON. The OVERRIDE spec (requirement 1.3.3, sdk-specs
#272) recommends the extension and lets an SDK whose file data source
inspects the content keep doing so; the override source is unreleased,
so it follows the extension, which lets the format decide whether an
empty file is valid.
- The text encoding is detected from a byte order mark (UTF-8 or UTF-16)
and is UTF-8 otherwise, for both formats, through SnakeYAML's
`UnicodeReader`. A UTF-32 file fails to parse, and the last good
overrides stay.
- An empty or white-space JSON file fails with `the file has no content,
which is not a JSON document`, and the last good overrides stay. An
empty JSON placeholder therefore fails the whole reload. A JSON document
that is not an object, such as `null` or `[]`, fails with `the JSON
document is not an object`.
- An empty YAML file, or YAML with only a comment or a `---` marker, is
a document with no entries.
- Compatibility with choosing by content: a JSON file in UTF-16, or in
UTF-8 with a byte order mark, still loads. JSON indented with tabs, or
with the escape `\/`, loads from a `.json` file; SnakeYAML, which reads
YAML 1.1, rejects it in a `.yaml` file.
### In-place rewrites
Applications and editors rewrite a file in place: they truncate it and
then write the new content. A load in between finds the file empty. A
YAML file can legitimately be empty, so its parser cannot tell an
emptied file from one in the middle of a rewrite. The loader keeps, for
each file, whether it contributed content to the data in effect (updated
by `accepted`), and, for a file whose content is in effect and that
loads have found empty, since when it has been empty without being
written, its state then (modification time and size, read through any
symbolic link, compared only for equality), and when a load first held
it back.
- A file whose content is not in effect, such as a placeholder or a file
whose empty state was applied, is parsed right away.
- Otherwise a new state restarts the file's delay, and the file is held
back while it has stayed empty for less than the retry delay R, and for
at most 5 R from the first load that held it back. The clock is read
after the file's own read, so a slow read of another file does not
shorten its delay. The hold asks for its retry when the first held
file's delay or bound is over, plus R/10, so that a timer that fires a
little early still finds the time over.
- A file's bound starts over only at a load that holds nothing back, for
every file that load read, whether the load is applied, skipped as
unchanged, or fails. A read with content, even content that fails to
parse, or a missing file ends the file's empty state, so its next
emptying starts a new delay even where a coarse modification time makes
it look the same.
- A load reads and classifies every configured file, also after a read
or parse failure, so files emptied together start their delays in the
same load. It then fails with the first failure; then holds files back;
and only then merges the entries, so a duplicate key or an entry that
the data model rejects cannot keep a later file from being read. A
holding load keeps the data in effect, including changes to the other
files, because a reload applies all the files or none.
- Elapsed times are differences of `System.nanoTime()` readings, which
do not overflow.
A rewrite is covered when the gap between truncating and writing is
shorter than the retry delay. Not changed: a read that sees YAML cut off
between two entries, after `flagValues:`, or inside an unquoted value
parses as valid YAML and is applied until the next reload; JSON cut off
anywhere fails to parse. Go still detects the format from the content;
Node chooses by extension case-sensitively, while this change, like
.NET, ignores case.
### The existing file data source
`FileDataSourceImpl`, `FileSynchronizer` and `FileInitializer` are
unchanged from `feat/overrides`. `FileDataSourceBase` changes only a
comment, and `FileDataException.getDescription` no longer throws when
there is no cause. `FileDataSourceParsing` gains, for the override
source: two `FlagFactory` methods that keep document versions;
`selectForPath` and `parseForPath` (extension and encoding); the
`NO_DOCUMENT` result that the YAML parser returns for content with no
document, which has all-null maps as before;
`JsonFlagFileParser.parse(Reader)`; and the two JSON rules above, which
the file data source cannot reach because it parses a file as JSON only
when it starts with `{`. `parse(InputStream)` keeps reading JSON in the
platform's default encoding for the file data source. The file data
source still requires every configured file to exist, assigns a load
version to every entry, expands a value-only entry to an on flag with a
single fallthrough variation, reloads on every watch event with no
debounce, no retry timer, and no skip, and reports every failure. Two
new test classes pin that behavior: `FileSynchronizerReloadBehaviorTest`
(identical rewrite emits another change set, every failed reload is
reported and logged as the plain description at error level, no retry
without a file change, missing file logged with the path) and
`FileDataLoadingBehaviorTest` (a model-rejected document escapes as a
`SerializationException`, and `FileDataException.getDescription` shows
the cause when there is one). The existing tests pass unmodified.
## Testing
- `OverrideFileLoaderTest`, on real files rewritten in place
(`InPlaceWrites`), with a test clock that crosses the `long` overflow:
the format by extension, empty and non-object JSON, YAML with no
document, the encoding (UTF-8 with and without a byte order mark,
UTF-16LE and UTF-16BE with one, a non-ASCII value), the hold at 0.95 R
and its end at exactly R, the requested retries, a new write restarting
the delay (also through a symbolic link), the per-file bound with one
file kept written and with files rewritten in turn or emptied in
staggered turns, the bound starting over at a load that holds nothing
back and not otherwise, a file read during another file's failure, the
fix of a file saved with a mistake or a duplicate key, the first failure
reported, the digest covering paths and presence.
- `FileDataReloaderTest` (scripted loader): a hold applies nothing,
reports nothing, and is retried after the time the loader asks for; a
failure arms the normal retry delay; `accepted` is called for applied
and unchanged results only.
- `FileDataReloaderEmptiedFileTest` (the reloader with the real loader
on real files): with a test clock and an hour-long retry delay, the
hold's end and the requested retry delays on both arming paths; with the
real clock, an emptied file held back and the rewrite applied with no
empty application in between, a file that stays empty applied by the
retry, two quick rewrites, a change to another file while one is empty,
a retry finding a second truncation, a file moved between configured
paths, the same bytes moved from `.yaml` to `.json`.
- The in-place rewrite handling was reviewed in eight rounds as #248
(general and adversarial reviews, Bugbot). Mutation check with a clean
build per mutant: 57 mutants, each failing at least one test. The
override test classes ran 12 times in a row with no failure.
[SDK-3246](https://launchdarkly.atlassian.net/browse/SDK-3246)
Opened from termag
[SDK-3246]:
https://launchdarkly.atlassian.net/browse/SDK-3246?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
---
> [!NOTE]
> **Overview**
> Adds **reload infrastructure** for the upcoming file-based flag
override source: **`FileDataReloader`** (serialized loads, 100ms
debounce, 1s retry, content-hash skip, empty-file deferral via
`EmptiedFileException`), **`FileDataPoller`** (interval mtime/size
polling), **`FileDataWatcher`** (directory watches with
symlink/ConfigMap-style updates, missing-directory retry), and
**`OverrideFileLoader`** (multi-file merge, extension-based JSON/YAML,
UTF BOM detection, in-place rewrite hold-back).
>
> **Parsing changes** in `FileDataSourceParsing` support overrides:
parser selection by `.yaml`/`.yml`, safer error text (no quoted file
content in logs), per-parse YAML instances, `NO_DOCUMENT` for
comment-only YAML, and `FileDataException.getDescription()` fixed when
cause is null. The existing **file data source** behavior is largely
unchanged aside from those shared parsing fixes; new tests pin
synchronizer reload and loader error semantics.
>
> Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9e9909b52627c8f87364521a89346f6aa8f1bf3a. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).
---
.../server/integrations/FileDataPoller.java | 153 ++
.../server/integrations/FileDataReloader.java | 418 +++++
.../integrations/FileDataSourceBase.java | 3 +-
.../integrations/FileDataSourceParsing.java | 208 ++-
.../server/integrations/FileDataWatcher.java | 475 +++++
.../integrations/OverrideFileLoader.java | 604 +++++++
.../FileDataLoadingBehaviorTest.java | 73 +
.../integrations/FileDataPollerTest.java | 276 +++
.../FileDataReloaderEmptiedFileTest.java | 681 +++++++
.../integrations/FileDataReloaderTest.java | 881 +++++++++
.../integrations/FileDataWatcherTest.java | 696 +++++++
.../FileSynchronizerReloadBehaviorTest.java | 198 ++
.../integrations/FlagFileParserJsonTest.java | 56 +
.../integrations/FlagFileParserYamlTest.java | 117 ++
.../server/integrations/InPlaceWrites.java | 49 +
.../integrations/OverrideFileLoaderTest.java | 1594 +++++++++++++++++
16 files changed, 6465 insertions(+), 17 deletions(-)
create mode 100644 lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataPoller.java
create mode 100644 lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataReloader.java
create mode 100644 lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataWatcher.java
create mode 100644 lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/OverrideFileLoader.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataLoadingBehaviorTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataPollerTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataReloaderEmptiedFileTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataReloaderTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataWatcherTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileSynchronizerReloadBehaviorTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/InPlaceWrites.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/OverrideFileLoaderTest.java
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataPoller.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataPoller.java
new file mode 100644
index 00000000..44d53256
--- /dev/null
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataPoller.java
@@ -0,0 +1,153 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.logging.LogValues;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Detects changes to a set of files by examining them on a fixed interval. Use it where file
+ * system change notifications are not available or not reliable, alone or together with them.
+ * A change to the modification time or the size of any file invokes the change callback. A file
+ * that appears or disappears is also a change. A file whose attributes cannot be read counts as
+ * absent.
+ *
+ * The poller samples the files once per interval and compares only the modification time and the
+ * size. A rewrite that keeps both values is not detected.
+ *
+ * Detection is generous. The callback can run for a change that does not alter the effective
+ * data. Feed it into a {@link FileDataReloader}, whose debouncing and skip-unchanged handling
+ * absorb the excess.
+ */
+final class FileDataPoller implements Closeable {
+ private final List paths;
+ private final Runnable onChange;
+ private final LDLogger logger;
+ private final ScheduledFuture> task;
+ private final AtomicBoolean closed = new AtomicBoolean(false);
+ private List last;
+
+ /**
+ * Creates a started poller. It examines the files once before it returns, so only later changes
+ * invoke the callback. Create it before the caller's initial load of the files. Otherwise a change
+ * made between that load and this first examination is part of the starting state and is never
+ * reported. Call {@link #close()} to stop it.
+ *
+ * @param paths the files to examine
+ * @param interval the time between examinations
+ * @param onChange called when any file changed since the previous examination
+ * @param logger receives log output about a callback that fails
+ * @param executor runs the examinations and the callback. The caller owns it and shuts it down after
+ * closing the poller. It can be the executor of the {@link FileDataReloader} that the callback
+ * triggers.
+ */
+ FileDataPoller(List paths, Duration interval, Runnable onChange, LDLogger logger,
+ ScheduledExecutorService executor) {
+ this.paths = new ArrayList<>(paths);
+ this.onChange = onChange;
+ this.logger = logger;
+ this.last = observeAll(this.paths);
+ long millis = interval.toMillis();
+ this.task = executor.scheduleWithFixedDelay(this::examine, millis, millis, TimeUnit.MILLISECONDS);
+ }
+
+ /**
+ * Stops the poller by cancelling its examinations. The executor keeps running: its owner shuts it
+ * down. Close does not wait for an examination or a callback that is in progress. A
+ * file system that does not respond must not block shutdown. As a result, the callback can run
+ * one more time shortly after close returns. Consumers tolerate a late call, as they do for a
+ * late reload.
+ */
+ @Override
+ public void close() {
+ if (closed.getAndSet(true)) {
+ return;
+ }
+ task.cancel(false);
+ }
+
+ private void examine() {
+ if (closed.get()) {
+ return;
+ }
+ try {
+ List current = observeAll(paths);
+ boolean changed = !current.equals(last);
+ last = current;
+ if (changed && !closed.get()) {
+ onChange.run();
+ }
+ } catch (RuntimeException | Error e) {
+ // The executor would otherwise cancel the repeating task and the poller would go quiet.
+ logger.error("Unexpected error while examining files for changes: {}", LogValues.exceptionSummary(e));
+ logger.debug(LogValues.exceptionTrace(e));
+ }
+ }
+
+ static List observeAll(List paths) {
+ List states = new ArrayList<>(paths.size());
+ for (Path path : paths) {
+ states.add(observe(path));
+ }
+ return states;
+ }
+
+ /**
+ * Observes one file. The attributes are read through any symbolic link, so they describe the file
+ * that the link points to.
+ *
+ * @param path the file
+ * @return its state, or {@link FileState#ABSENT} if its attributes cannot be read
+ */
+ static FileState observe(Path path) {
+ try {
+ BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
+ return new FileState(true, attributes.lastModifiedTime().toMillis(), attributes.size());
+ } catch (IOException | RuntimeException e) {
+ return FileState.ABSENT;
+ }
+ }
+
+ /**
+ * The observed state of one file, or its absence.
+ */
+ static final class FileState {
+ static final FileState ABSENT = new FileState(false, 0, 0);
+
+ final boolean exists;
+ final long modifiedTimeMillis;
+ final long size;
+
+ FileState(boolean exists, long modifiedTimeMillis, long size) {
+ this.exists = exists;
+ this.modifiedTimeMillis = modifiedTimeMillis;
+ this.size = size;
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other instanceof FileState) {
+ FileState o = (FileState) other;
+ return exists == o.exists && modifiedTimeMillis == o.modifiedTimeMillis && size == o.size;
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(exists, modifiedTimeMillis, size);
+ }
+ }
+}
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataReloader.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataReloader.java
new file mode 100644
index 00000000..3ea9158a
--- /dev/null
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataReloader.java
@@ -0,0 +1,418 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.logging.LogValues;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FileDataException;
+import com.launchdarkly.sdk.server.integrations.OverrideFileLoader.LoadResult;
+
+import java.io.Closeable;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * Owns the reload cycle for the files of an override source. It serializes reloads, debounces
+ * change signals, retains the last good result on failure by not calling the apply callback,
+ * retries after failures, and skips applications whose content did not change.
+ *
+ * The reload work itself is delegated to a {@link Loader}. The loader reads every configured file
+ * and returns the merged result, or throws {@link FileDataException} when a file cannot be read or
+ * parsed or when the files cannot be merged. Any other exception from the loader is a failed load
+ * too. An {@link Error}, such as {@link OutOfMemoryError}, is logged like any failure, but arms no
+ * automatic retry, because it would most likely happen again on every retry. The next change signal
+ * loads the files again.
+ *
+ * A file whose content is in effect and is found empty may be in the middle of an in-place rewrite.
+ * The loader can hold such a file back with {@link EmptiedFileException}: the reloader keeps the
+ * current data, logs no failure, and reads the files again when the exception says.
+ *
+ * Debounced and retried reloads run on an executor that the caller owns. The {@link FileDataPoller}
+ * of the same source can share it; {@link #newExecutor(int)} creates one for both.
+ *
+ * The file data source does not use this class. It keeps its own reload behavior.
+ */
+final class FileDataReloader implements Closeable {
+ /**
+ * A settle window long enough to coalesce the burst of change notifications produced by a
+ * single file edit, and short enough to stay responsive.
+ */
+ static final Duration DEFAULT_DEBOUNCE_DELAY = Duration.ofMillis(100);
+
+ /**
+ * Bounds how long a failed reload can go uncorrected when no further change notification
+ * arrives, for example when the failure came from reading a file mid-write. Reading a local
+ * file is cheap, so this can be short.
+ */
+ static final Duration DEFAULT_RETRY_DELAY = Duration.ofSeconds(1);
+
+ /**
+ * Performs one full load of all configured files.
+ */
+ interface Loader {
+ /**
+ * Reads every configured file and merges the entries.
+ *
+ * @param retryDelay the reloader's retry delay. A loader may hold an empty file back for a time
+ * based on it, because a retry reads the files again.
+ * @return the merged result
+ * @throws FileDataException if a file cannot be read or parsed, or the files cannot be merged
+ * @throws EmptiedFileException if a file was found empty and is held back
+ */
+ LoadResult load(Duration retryDelay) throws FileDataException, EmptiedFileException;
+
+ /**
+ * Called with the result of a load that is now the data in effect: it was applied, or it was
+ * skipped because it is unchanged. It is called with the reload lock held.
+ *
+ * @param result the result
+ */
+ void accepted(LoadResult result);
+ }
+
+ /**
+ * Thrown by a {@link Loader} that holds back files it found empty. A file may be in the middle of an
+ * in-place rewrite: a writer that truncates the file and then writes the new content.
+ */
+ @SuppressWarnings("serial")
+ static final class EmptiedFileException extends Exception {
+ private final List paths;
+ private final long retryAfterNanos;
+
+ EmptiedFileException(List paths, long retryAfterNanos) {
+ super("files " + paths + " are empty");
+ this.paths = Collections.unmodifiableList(new ArrayList<>(paths));
+ this.retryAfterNanos = retryAfterNanos;
+ }
+
+ /**
+ * The files held back, in configuration order.
+ */
+ List getPaths() {
+ return paths;
+ }
+
+ /**
+ * How long to wait before loading again, in nanoseconds.
+ */
+ long getRetryAfterNanos() {
+ return retryAfterNanos;
+ }
+ }
+
+ /**
+ * Receives the results to apply.
+ *
+ * It is called with the reload lock held, so calls never overlap with each other or with another
+ * reload. It may not call back into {@link FileDataReloader#close()}.
+ */
+ interface Handler {
+ /**
+ * Called with each successfully merged result. An exception thrown here fails the reload: it is
+ * logged, nothing from the load is remembered as the last good result, and the reload is
+ * retried. An {@link Error} fails it the same way but arms no retry.
+ *
+ * @param result the merged data
+ */
+ void apply(LoadResult result);
+ }
+
+ private final Loader loader;
+ private final Handler handler;
+ private final ScheduledExecutorService executor;
+ private final LDLogger logger;
+ private final Duration debounceDelay;
+ private final Duration retryDelay;
+ // What load() returns when no retry is needed.
+ private static final long NO_RETRY = -1;
+
+ // Serializes the load work between reloadNow and the executor.
+ private final Object reloadLock = new Object();
+ private byte[] lastGoodHash = null;
+ private String lastErrorMessage = null;
+ // True from a load that found an emptied file until the next load starts. Written inside the
+ // reload lock. It only chooses the log message of the retry that such a load arms.
+ private volatile boolean readAgainPending = false;
+
+ // Guards the two timers.
+ private final Object timerLock = new Object();
+ private ScheduledFuture> debounceFuture = null;
+ private ScheduledFuture> retryFuture = null;
+ // The delay of the latest retry that a load asked for while the reloader was open, in nanoseconds, or
+ // -1 before the first. Visible for tests through getLastRequestedRetryNanos.
+ private volatile long lastRequestedRetryNanos = -1;
+
+ private final AtomicBoolean closed = new AtomicBoolean(false);
+
+ /**
+ * Creates a reloader. The caller performs the initial load with {@link #reloadNow()}, routes
+ * change signals to {@link #trigger()}, and calls {@link #close()} when finished.
+ *
+ * @param loader performs each full load
+ * @param handler receives the results to apply
+ * @param executor runs the debounced and retried reloads. The caller owns it and shuts it down after
+ * closing the reloader. Nothing is scheduled on it before the first {@link #trigger()} call or the
+ * first load that arms a retry.
+ * @param logger receives log output about reloads and failures
+ * @param debounceDelay how long to wait after a trigger for further triggers to settle before
+ * reloading
+ * @param retryDelay how long to wait after a failed reload before retrying without a trigger. It
+ * must be positive. A load that holds back an empty file says itself when to load again.
+ */
+ FileDataReloader(
+ Loader loader,
+ Handler handler,
+ ScheduledExecutorService executor,
+ LDLogger logger,
+ Duration debounceDelay,
+ Duration retryDelay
+ ) {
+ this.loader = loader;
+ this.handler = handler;
+ this.executor = executor;
+ this.logger = logger;
+ this.debounceDelay = debounceDelay;
+ this.retryDelay = retryDelay;
+ }
+
+ /**
+ * Creates the executor for the reloader of one source and the {@link FileDataPoller} of the same
+ * source. It has one daemon thread, started by the first task, so their work runs one task at a
+ * time. A cancelled task is removed at once, and a delayed task does not run after shutdown.
+ *
+ * The SDK's shared executor is not used: it runs event delivery and other SDK tasks on one thread,
+ * and a file read that does not return would hold all of them up.
+ *
+ * @param threadPriority the priority of the thread
+ * @return the executor. The caller shuts it down.
+ */
+ static ScheduledThreadPoolExecutor newExecutor(int threadPriority) {
+ ThreadFactory threadFactory = runnable -> {
+ Thread t = new Thread(runnable, "LaunchDarkly-FileDataReloader");
+ t.setDaemon(true);
+ t.setPriority(threadPriority);
+ return t;
+ };
+ ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1, threadFactory);
+ executor.setRemoveOnCancelPolicy(true);
+ executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
+ return executor;
+ }
+
+ /**
+ * Synchronously loads the files and applies the result or logs the failure. Use it for the
+ * initial load. A failure here arms the same automatic retry as a failed triggered reload.
+ *
+ * Change detection can start before this call, so that it detects a change made while the files
+ * are read. Loads run one at a time: a reload that a change signal starts during this call waits
+ * for it, and this call waits for a reload that is already in progress.
+ */
+ void reloadNow() {
+ reload();
+ }
+
+ /**
+ * Signals that the files may have changed and a reload should happen after the debounce delay.
+ * It never blocks. Signals that arrive while a reload is already pending extend the settle
+ * window, so a burst of signals produces one reload after the burst ends.
+ */
+ void trigger() {
+ synchronized (timerLock) {
+ if (closed.get()) {
+ return;
+ }
+ if (debounceFuture != null) {
+ debounceFuture.cancel(false);
+ }
+ debounceFuture = schedule(() -> runReload(false), debounceDelay.toNanos());
+ }
+ }
+
+ /**
+ * Stops the reloader and cancels the reloads it has scheduled. The executor keeps running: its owner
+ * shuts it down. Close does not wait for a reload that is already in progress. A reload
+ * wedged in a blocking file read must not be able to wedge shutdown. Such a reload may still
+ * deliver its result shortly after close returns, and consumers tolerate that. A reload that
+ * has not yet reached its callbacks when close is called does not invoke them.
+ */
+ @Override
+ public void close() {
+ if (closed.getAndSet(true)) {
+ return;
+ }
+ synchronized (timerLock) {
+ if (debounceFuture != null) {
+ debounceFuture.cancel(false);
+ debounceFuture = null;
+ }
+ if (retryFuture != null) {
+ retryFuture.cancel(false);
+ retryFuture = null;
+ }
+ }
+ }
+
+ /**
+ * Returns the delay of the latest retry that a load asked for while the reloader was open. Each such
+ * request arms a retry. Visible for tests.
+ *
+ * @return the delay in nanoseconds, or -1 if no retry was requested
+ */
+ long getLastRequestedRetryNanos() {
+ return lastRequestedRetryNanos;
+ }
+
+ // Called inside the reload lock after every load, so that the retry is the one that the latest load
+ // asks for. It replaces a retry that an earlier load armed, sooner or later. A load that asks for
+ // none cancels it, because that load read every file again.
+ private void setRetry(long delayNanos) {
+ synchronized (timerLock) {
+ if (retryFuture != null) {
+ retryFuture.cancel(false);
+ retryFuture = null;
+ }
+ if (delayNanos == NO_RETRY || closed.get()) {
+ return;
+ }
+ lastRequestedRetryNanos = delayNanos;
+ retryFuture = schedule(() -> runReload(true), delayNanos);
+ }
+ }
+
+ // Called with the timer lock held. Returns null if the executor no longer accepts tasks, which happens
+ // only after its owner has shut it down.
+ private ScheduledFuture> schedule(Runnable task, long delayNanos) {
+ try {
+ return executor.schedule(task, delayNanos, TimeUnit.NANOSECONDS);
+ } catch (RejectedExecutionException e) {
+ return null;
+ }
+ }
+
+ // Runs on the executor for a debounced or a retried reload.
+ private void runReload(boolean isRetry) {
+ try {
+ if (isRetry) {
+ logger.debug(readAgainPending ? "Reading flag data again after a file was found empty"
+ : "Retrying flag data load after earlier failure");
+ } else {
+ logger.info("Reloading flag data after detecting a change");
+ }
+ reload();
+ } catch (RuntimeException | Error e) {
+ // The executor would otherwise swallow the exception and the worker would go quiet.
+ logger.error("Unexpected error while reloading flag data: {}", LogValues.exceptionSummary(e));
+ logger.debug(LogValues.exceptionTrace(e));
+ }
+ }
+
+ // Loads the files and sets the retry that the load asks for. Loads run one at a time.
+ private void reload() {
+ synchronized (reloadLock) {
+ setRetry(load());
+ }
+ }
+
+ // Called inside the reload lock. Performs one full load of all configured files. It returns when to
+ // load again: NO_RETRY after a success, including a skipped no-op application, the retry delay after
+ // a failure, or the time that a load that holds back an empty file asks for. The whole set is re-read
+ // on every reload because entries are combined across files in order, so a change to one file can
+ // alter which file wins for a key.
+ private long load() {
+ // A trigger already queued when close was called can still reach here.
+ if (closed.get()) {
+ return NO_RETRY;
+ }
+ readAgainPending = false;
+
+ LoadResult result;
+ try {
+ result = loader.load(retryDelay);
+ } catch (EmptiedFileException e) {
+ return readAgainLater(e);
+ } catch (FileDataException e) {
+ return fail(e);
+ } catch (RuntimeException e) {
+ return fail(new FileDataException("unexpected error while loading flag data", e));
+ } catch (Error e) {
+ return failWithoutRetry(new FileDataException("unexpected error while loading flag data", e));
+ }
+
+ // Close may have happened while the files were being read. Deliver nothing in that case.
+ if (closed.get()) {
+ return NO_RETRY;
+ }
+
+ // A success right after a failure is applied even when the content is unchanged since the last
+ // success, so that the consumer can log the data in effect after the logged failure.
+ boolean recovering = lastErrorMessage != null;
+ byte[] hash = result.getContentHash();
+ if (!recovering && Arrays.equals(hash, lastGoodHash)) {
+ loader.accepted(result);
+ return NO_RETRY;
+ }
+ // Nothing is remembered until the consumer has accepted the result. A result that the
+ // consumer rejects must not become the baseline that unchanged content is compared against,
+ // and must not count as a recovery.
+ try {
+ handler.apply(result);
+ } catch (RuntimeException e) {
+ return fail(new FileDataException("unable to apply flag data", e));
+ } catch (Error e) {
+ return failWithoutRetry(new FileDataException("unable to apply flag data", e));
+ }
+ lastErrorMessage = null;
+ lastGoodHash = hash;
+ loader.accepted(result);
+ return NO_RETRY;
+ }
+
+ // Called inside the reload lock. The loader held back files that it found empty: a file whose
+ // content is in effect may be in the middle of an in-place rewrite, a writer that truncates the file
+ // and then writes the new content. Whatever the files' format, the load keeps the current data and
+ // arms the retry without reporting a failure, for the time that the loader asks for. The change
+ // signal for the write starts a load sooner. The loader decides how long a file can be held back. A
+ // closed reloader arms no retry.
+ private long readAgainLater(EmptiedFileException e) {
+ for (Path path : e.getPaths()) {
+ logger.debug("File {} is empty, possibly while it is being rewritten; reading it again before applying it", path);
+ }
+ readAgainPending = true;
+ return e.getRetryAfterNanos();
+ }
+
+ // Logs a failure that an Error caused, such as OutOfMemoryError, and arms no retry. It would most
+ // likely happen again on every retry, and each attempt could take memory from the application. The
+ // next change signal loads the files again.
+ private long failWithoutRetry(FileDataException e) {
+ fail(e);
+ return NO_RETRY;
+ }
+
+ // Logs a failure and returns when to retry.
+ private long fail(FileDataException e) {
+ // Close may have happened while the files were being read. Log nothing and arm no retry.
+ if (closed.get()) {
+ return NO_RETRY;
+ }
+ // A persistent failure would repeat the same log entry on every retry. Repeats of an identical
+ // failure are logged at debug level.
+ String description = e.getDescription();
+ if (description.equals(lastErrorMessage)) {
+ logger.debug("Unable to load flags: {}", description);
+ } else {
+ lastErrorMessage = description;
+ logger.error("Unable to load flags: {}", description);
+ }
+ return retryDelay.toNanos();
+ }
+}
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataSourceBase.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataSourceBase.java
index 2f0eec97..a06df777 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataSourceBase.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataSourceBase.java
@@ -108,8 +108,7 @@ Iterable getSources() {
* where the cause may be null.
*/
private String getErrorDescription(FileDataException e) {
- // FileDataException.getDescription() has a bug where it calls getCause().toString()
- // without null checking. We work around this by building our own description.
+ // Unlike FileDataException.getDescription(), this leaves out the source.
StringBuilder s = new StringBuilder();
if (e.getMessage() != null) {
s.append(e.getMessage());
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataSourceParsing.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataSourceParsing.java
index 81ff8cdc..eacbc158 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataSourceParsing.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataSourceParsing.java
@@ -2,7 +2,7 @@
import com.google.gson.Gson;
import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
+import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.launchdarkly.sdk.LDValue;
import com.launchdarkly.sdk.ObjectBuilder;
@@ -11,7 +11,11 @@
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
+import org.yaml.snakeyaml.error.Mark;
+import org.yaml.snakeyaml.error.MarkedYAMLException;
import org.yaml.snakeyaml.error.YAMLException;
+import org.yaml.snakeyaml.reader.ReaderException;
+import org.yaml.snakeyaml.reader.UnicodeReader;
import org.yaml.snakeyaml.representer.Representer;
import java.io.ByteArrayInputStream;
@@ -19,7 +23,11 @@
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
+import java.nio.file.Path;
+import java.util.Locale;
import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import static com.launchdarkly.sdk.server.DataModel.FEATURES;
import static com.launchdarkly.sdk.server.DataModel.SEGMENTS;
@@ -49,9 +57,13 @@ public String getDescription() {
StringBuilder s = new StringBuilder();
if (getMessage() != null) {
s.append(getMessage());
- s.append(" ");
}
- s.append("[").append(getCause().toString()).append("]");
+ if (getCause() != null) {
+ if (s.length() > 0) {
+ s.append(" ");
+ }
+ s.append("[").append(getCause().toString()).append("]");
+ }
if (source != null) {
s.append(": ").append(source.toString());
}
@@ -64,6 +76,13 @@ public String getDescription() {
* parse the flags or segments at this level; that will be done by {@link FlagFactory}.
*/
static final class FlagFileRep {
+ /**
+ * What a parser returns for content that holds no document, such as YAML with only a comment or a
+ * document marker. It has no entries. The override source compares a result with it by identity,
+ * so it must not be modified.
+ */
+ static final FlagFileRep NO_DOCUMENT = new FlagFileRep();
+
Map flags;
Map flagValues;
Map segments;
@@ -91,7 +110,43 @@ public static FlagFileParser selectForContent(byte[] data) {
Reader r = new InputStreamReader(new ByteArrayInputStream(data));
return detectJson(r) ? JsonParserHolder.getInstance() : YamlParserHolder.getInstance();
}
-
+
+ /**
+ * Chooses the parser by the extension of the file name: a file whose name ends in {@code .yaml}
+ * or {@code .yml}, in any case, is parsed as YAML, and any other file is parsed as JSON. The
+ * override source uses this. The file data source keeps choosing by content, with
+ * {@link #selectForContent(byte[])}.
+ *
+ * @param path the file
+ * @return the parser for the file
+ */
+ static FlagFileParser selectForPath(Path path) {
+ Path fileName = path.getFileName();
+ String name = fileName == null ? "" : fileName.toString().toLowerCase(Locale.ROOT);
+ return name.endsWith(".yaml") || name.endsWith(".yml")
+ ? YamlParserHolder.getInstance() : JsonParserHolder.getInstance();
+ }
+
+ /**
+ * Parses the content of a file with the parser that {@link #selectForPath(Path)} chooses. The
+ * text encoding is detected from a byte order mark, UTF-8 or UTF-16, and is UTF-8 otherwise, for
+ * both formats; the YAML parser does that itself. The override source uses this.
+ * The file data source keeps reading JSON in the platform's default encoding.
+ *
+ * @param path the file
+ * @param data its content
+ * @return the parsed content
+ * @throws FileDataException if the content cannot be decoded or parsed
+ * @throws IOException if the content cannot be read
+ */
+ static FlagFileRep parseForPath(Path path, byte[] data) throws FileDataException, IOException {
+ FlagFileParser parser = selectForPath(path);
+ if (parser instanceof JsonFlagFileParser) {
+ return ((JsonFlagFileParser) parser).parse(new UnicodeReader(new ByteArrayInputStream(data)));
+ }
+ return parser.parse(new ByteArrayInputStream(data));
+ }
+
private static boolean detectJson(Reader r) {
// A valid JSON file for our purposes must be an object, i.e. it must start with '{'
while (true) {
@@ -116,16 +171,68 @@ private static boolean detectJson(Reader r) {
static final class JsonFlagFileParser extends FlagFileParser {
private static final Gson gson = new Gson();
+
+ // Gson ends the message of a syntax error with the position and the JSON path of the error. The
+ // path holds the member name that was read last. In a malformed document that can be a value from
+ // the file, so the message keeps only the problem and the position.
+ private static final Pattern GSON_LOCATION = Pattern.compile("^(.*?) at line (\\d+) column (\\d+) path ");
+
+ // For a malformed Unicode escape, the problem text also holds the four characters of the escape.
+ // These characters come from the file, so the message keeps only this start of the problem text.
+ private static final String MALFORMED_ESCAPE = "Malformed Unicode escape";
@Override
public FlagFileRep parse(InputStream input) throws FileDataException, IOException {
+ return parse(new InputStreamReader(input));
+ }
+
+ /**
+ * Parses JSON from text that is already decoded.
+ *
+ * @param reader the text
+ * @return the parsed content
+ * @throws FileDataException if the text is not a JSON object, or cannot be decoded
+ * @throws IOException if the text cannot be read
+ */
+ FlagFileRep parse(Reader reader) throws FileDataException, IOException {
+ JsonElement tree;
try {
- return parseJson(gson.fromJson(new InputStreamReader(input), JsonElement.class));
+ tree = gson.fromJson(reader, JsonElement.class);
} catch (JsonSyntaxException e) {
- throw new FileDataException("cannot parse JSON", e);
- }
+ throw new FileDataException(describe(e), null);
+ } catch (JsonIOException e) {
+ // For example, bytes that are not valid in the detected encoding.
+ throw new FileDataException("cannot read JSON", e);
+ }
+ if (tree == null) {
+ // Gson finds no value in a file that is empty or white space only, or, since it reads
+ // leniently, one that holds only comments. That is not a JSON document. A file that is being
+ // rewritten in place can be empty for a moment, and the failure keeps its last good data
+ // until it is complete. The failure is logged once, so the message says how to clear the
+ // overrides. The file data source never gets here: it parses a file as JSON only when the file
+ // starts with '{'.
+ throw new FileDataException("the file has no content, which is not a JSON document;"
+ + " to remove its overrides, delete the file or write {}", null);
+ }
+ if (!tree.isJsonObject()) {
+ // A document such as null or [] holds no flags. The file data source never gets here either.
+ throw new FileDataException("the JSON document is not an object", null);
+ }
+ return parseJson(tree);
}
+ // Describes a syntax error by Gson's problem text and position, without the path. A message in
+ // another form gives no detail.
+ static String describe(JsonSyntaxException e) {
+ Throwable problem = e.getCause() == null ? e : e.getCause();
+ Matcher m = GSON_LOCATION.matcher(String.valueOf(problem.getMessage()));
+ if (!m.find()) {
+ return "cannot parse JSON";
+ }
+ String text = m.group(1).startsWith(MALFORMED_ESCAPE) ? MALFORMED_ESCAPE : m.group(1);
+ return "cannot parse JSON: " + text + " (line " + m.group(2) + ", column " + m.group(3) + ")";
+ }
+
public FlagFileRep parseJson(JsonElement tree) throws FileDataException, IOException {
try {
return gson.fromJson(tree, FlagFileRep.class);
@@ -161,21 +268,74 @@ public FlagFileRep parseJson(JsonElement tree) throws FileDataException, IOExcep
*
*/
static final class YamlFlagFileParser extends FlagFileParser {
- private static final Yaml yaml = new Yaml();
- // Using SafeConstructor disables instantiation of arbitrary classes - https://github.com/launchdarkly/java-server-sdk/issues/288
private static final Gson gson = new Gson();
private static final JsonFlagFileParser jsonFileParser = new JsonFlagFileParser();
+ private static final String TAG_MISMATCH =
+ "unable to parse YAML: a value cannot be converted to the type that its tag names";
@Override
public FlagFileRep parse(InputStream input) throws FileDataException, IOException {
Object root;
try {
- root = yaml.load(input);
+ // A Yaml instance keeps the state of the document that it is loading, so concurrent loads
+ // through one instance corrupt each other. Different files can be parsed at the same time,
+ // for example by two clients, or by a file data source and an override source, so each parse
+ // uses its own instance. SnakeYAML 2 rejects global tags by default, so a document cannot
+ // name a class to instantiate (https://github.com/launchdarkly/java-server-sdk/issues/288).
+ root = new Yaml().load(input);
} catch (YAMLException e) {
- throw new FileDataException("unable to parse YAML", e);
+ // The message of a SnakeYAML exception quotes the lines of the file around the error. Those lines
+ // can hold context keys or other data from the file. The failure is logged, and the file data
+ // source also reports it in its status. So the message names only the problem and its position,
+ // and the SnakeYAML exception is not kept as the cause.
+ throw new FileDataException(describe(e), null);
+ } catch (IllegalArgumentException | ClassCastException e) {
+ // A value with an explicit tag, such as "!!int", that SnakeYAML cannot convert to that type. The
+ // exception has no position, and its message can quote the value. Implicit types do not cause it.
+ throw new FileDataException(TAG_MISMATCH, null);
+ }
+ if (root == null) {
+ // Empty content, or content with only comments or document markers, holds no document. It has
+ // no entries.
+ return FlagFileRep.NO_DOCUMENT;
+ }
+ return jsonFileParser.parseJson(gson.toJsonTree(root));
+ }
+
+ private static String describe(YAMLException e) {
+ StringBuilder s = new StringBuilder("unable to parse YAML");
+ if (e instanceof MarkedYAMLException) {
+ MarkedYAMLException m = (MarkedYAMLException) e;
+ // SnakeYAML gives the context first, for example "while parsing a flow sequence", and then the
+ // problem, for example "expected ',' or ']'".
+ appendPart(s, m.getContext(), m.getContextMark());
+ appendPart(s, m.getProblem(), m.getProblemMark());
+ } else if (e instanceof ReaderException) {
+ // The document holds a character that YAML does not allow, such as a control character. The code
+ // point identifies the character without the text around it.
+ ReaderException r = (ReaderException) e;
+ appendPart(s, r.getMessage() + " (code point 0x"
+ + Integer.toHexString(r.getCodePoint()).toUpperCase(Locale.ROOT)
+ + " at position " + r.getPosition() + ")", null);
+ } else if (e.getMessage() != null && e.getMessage().startsWith("Unexpected timestamp")) {
+ // A value with the tag "!!timestamp" that is not a timestamp. The message quotes the value.
+ return TAG_MISMATCH;
+ } else {
+ // An error without a position, such as a document that nests too deeply.
+ appendPart(s, e.getMessage(), null);
+ }
+ return s.toString();
+ }
+
+ private static void appendPart(StringBuilder s, String text, Mark mark) {
+ if (text == null) {
+ return;
+ }
+ s.append(": ").append(text);
+ if (mark != null) {
+ // A mark counts lines and columns from zero.
+ s.append(" (line ").append(mark.getLine() + 1).append(", column ").append(mark.getColumn() + 1).append(")");
}
- JsonElement jsonRoot = root == null ? new JsonObject() : gson.toJsonTree(root);
- return jsonFileParser.parseJson(jsonRoot);
}
}
@@ -193,10 +353,20 @@ private FlagFactory() {}
static ItemDescriptor flagFromJson(LDValue jsonTree, int version) {
return FEATURES.deserialize(replaceVersion(jsonTree, version).toJsonString());
}
-
+
+ /**
+ * Constructs a flag from raw JSON and keeps the version that the document specifies. The
+ * override source uses this. The file data source keeps assigning its load version.
+ */
+ static ItemDescriptor flagFromJson(LDValue jsonTree) {
+ return FEATURES.deserialize(jsonTree.toJsonString());
+ }
+
/**
* Constructs a flag that always returns the same value. This is done by giving it a single
- * variation and setting the fallthrough variation to that.
+ * variation and setting the fallthrough variation to that. The file data source passes its
+ * load version. The override source passes version zero, because its documents supply no
+ * version for a value-only entry.
*/
static ItemDescriptor flagWithValue(String key, LDValue jsonValue, int version) {
LDValue o = LDValue.buildObject()
@@ -214,6 +384,14 @@ static ItemDescriptor flagWithValue(String key, LDValue jsonValue, int version)
static ItemDescriptor segmentFromJson(LDValue jsonTree, int version) {
return SEGMENTS.deserialize(replaceVersion(jsonTree, version).toJsonString());
}
+
+ /**
+ * Constructs a segment from raw JSON and keeps the version that the document specifies. The
+ * override source uses this.
+ */
+ static ItemDescriptor segmentFromJson(LDValue jsonTree) {
+ return SEGMENTS.deserialize(jsonTree.toJsonString());
+ }
private static LDValue replaceVersion(LDValue objectValue, int version) {
ObjectBuilder b = LDValue.buildObject();
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataWatcher.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataWatcher.java
new file mode 100644
index 00000000..742292a8
--- /dev/null
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/FileDataWatcher.java
@@ -0,0 +1,475 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.logging.LogValues;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.nio.file.ClosedWatchServiceException;
+import java.nio.file.FileSystems;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.WatchEvent;
+import java.nio.file.WatchKey;
+import java.nio.file.WatchService;
+import java.nio.file.Watchable;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
+import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
+import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
+import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
+
+/**
+ * Watches a set of files for changes on a worker thread and invokes a callback when one of them
+ * is created, modified, or deleted.
+ *
+ * The Java file system API reports changes at the directory level, so the watcher registers the
+ * parent directory of every file. A file that does not exist yet is reported when it appears. A
+ * directory that does not exist, or that is deleted while it is watched, is not an error. The
+ * watcher tries to register it again on a fixed schedule until it exists, and then signals one
+ * change so that a file written to it in the meantime is picked up. A directory that is replaced
+ * while it is watched, for example by renaming another directory to its name, is neither missing nor
+ * deleted. On Linux the watch stays with the directory that was renamed away, so the replacement is
+ * not followed; polling covers that deployment.
+ *
+ * A configured file can be a symbolic link. A mounted Kubernetes ConfigMap, for example, links each
+ * file through a {@code ..data} link that is swapped to a new directory on every update, so the
+ * update changes no entry that is named after a configured file. An event for any other entry in a
+ * watched directory therefore counts when a configured file, read through any symbolic link, now
+ * leads to another file, or its file's modification time or size changed. A busy sibling file costs
+ * no reload. The directory of each configured file's final target is watched as well, so that a
+ * change to a file that a configured link names in another directory is reported. That directory is
+ * found again after every event. A directory that no configured link leads into any more, such as the
+ * previous version of a ConfigMap or a directory that a link was pointed away from, is no longer
+ * watched. A configured link whose target does not exist is observed again only after an event in a
+ * watched directory. A target that appears later, such as a file on a volume that is mounted after
+ * watching starts, is therefore not followed until such an event. A configured directory that is
+ * itself a symbolic link and is pointed elsewhere, or a link further along the path that is pointed
+ * elsewhere while its old target stays, is not followed either; polling covers those deployments.
+ *
+ * The callback is invoked for every relevant notification, including the burst of notifications
+ * that a single edit can produce, and once more right after the watcher starts so that a change
+ * made between an initial load and the start of watching is not missed. Feed it into a
+ * {@link FileDataReloader}, which coalesces the burst and skips no-op reloads.
+ *
+ * An unexpected exception while the worker thread handles a change is logged, and the thread keeps
+ * watching.
+ */
+final class FileDataWatcher implements Closeable, Runnable {
+ /**
+ * The time between attempts to register a directory that cannot be watched because it does not
+ * exist.
+ */
+ static final Duration DEFAULT_DIRECTORY_RETRY_DELAY = Duration.ofSeconds(1);
+
+ /**
+ * Registers a directory with a watch service and returns its key. Visible for tests, which make
+ * registration fail or register with a watch service of their own.
+ */
+ interface Registrar {
+ WatchKey register(Path directory, WatchService watchService) throws IOException;
+ }
+
+ private static final Registrar DEFAULT_REGISTRAR =
+ (directory, watchService) -> directory.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
+
+ private final WatchService watchService;
+ private final Registrar registrar;
+ private final Set watchedFilePaths;
+ private final Set configuredDirectories;
+ private final long directoryRetryDelayNanos;
+ private final LDLogger logger;
+ private final Thread thread;
+ private final AtomicBoolean stopped = new AtomicBoolean(false);
+ private volatile Runnable onChange;
+
+ // The directories that are not registered because they do not exist, and the time of the next
+ // attempt to register them. The time comes from the monotonic clock, so a change to the system
+ // clock does not move the schedule. Both are written during creation and then only by the
+ // worker thread.
+ private final Set missingDirectories = new HashSet<>();
+ private long nextRetryAtNanos;
+
+ // What the watcher last observed of each configured file, through any symbolic link: the file
+ // that it finally leads to, and that file's state. The final targets that are not the configured
+ // files themselves, and the directories holding them that are watched in addition to the
+ // configured directories, with their keys. All are written during creation and then only by the
+ // worker thread.
+ private final Map observations = new HashMap<>();
+ private final Set targetPaths = new HashSet<>();
+ private final Map targetDirectories = new HashMap<>();
+
+ /**
+ * Creates a watcher for the given files. Nothing is watched until {@link #start(Runnable)}.
+ *
+ * @param filePaths the files to watch, absolute or relative to the working directory
+ * @param threadPriority the priority of the worker thread
+ * @param logger the logger
+ * @return the watcher
+ * @throws IOException if the watch service cannot be created
+ */
+ static FileDataWatcher create(Iterable filePaths, int threadPriority, LDLogger logger) throws IOException {
+ return create(filePaths, DEFAULT_DIRECTORY_RETRY_DELAY, threadPriority, FileSystems.getDefault().newWatchService(),
+ DEFAULT_REGISTRAR, logger);
+ }
+
+ /**
+ * Creates a watcher with a specific delay between attempts to register a directory that does not
+ * exist. Visible for tests.
+ *
+ * @param filePaths the files to watch, absolute or relative to the working directory
+ * @param directoryRetryDelay the time between registration attempts for a missing directory
+ * @param logger the logger
+ * @return the watcher
+ * @throws IOException if the watch service cannot be created
+ */
+ static FileDataWatcher create(Iterable filePaths, Duration directoryRetryDelay, LDLogger logger)
+ throws IOException {
+ return create(filePaths, directoryRetryDelay, Thread.NORM_PRIORITY, FileSystems.getDefault().newWatchService(),
+ DEFAULT_REGISTRAR, logger);
+ }
+
+ /**
+ * Creates a watcher that takes changes from the given watch service and registers directories
+ * through the given registrar. Visible for tests.
+ *
+ * @param filePaths the files to watch, absolute or relative to the working directory
+ * @param directoryRetryDelay the time between registration attempts for a missing directory
+ * @param watchService the watch service, which the watcher closes
+ * @param registrar registers each directory with the watch service
+ * @param logger the logger
+ * @return the watcher
+ * @throws IOException if creation fails and the watch service then fails to close
+ */
+ static FileDataWatcher create(Iterable filePaths, Duration directoryRetryDelay, WatchService watchService,
+ Registrar registrar, LDLogger logger) throws IOException {
+ return create(filePaths, directoryRetryDelay, Thread.NORM_PRIORITY, watchService, registrar, logger);
+ }
+
+ private static FileDataWatcher create(Iterable filePaths, Duration directoryRetryDelay, int threadPriority,
+ WatchService ws, Registrar registrar, LDLogger logger) throws IOException {
+ Set directoryPaths = new HashSet<>();
+ Set absoluteFilePaths = new HashSet<>();
+ for (Path p : filePaths) {
+ Path absolutePath = p.toAbsolutePath().normalize();
+ absoluteFilePaths.add(absolutePath);
+ directoryPaths.add(absolutePath.getParent());
+ }
+ FileDataWatcher watcher = new FileDataWatcher(ws, registrar, absoluteFilePaths, directoryPaths,
+ directoryRetryDelay, threadPriority, logger);
+ try {
+ for (Path d : directoryPaths) {
+ watcher.registerOrRememberAsMissing(d);
+ }
+ watcher.observeConfiguredFiles();
+ } catch (RuntimeException e) {
+ ws.close();
+ throw e;
+ }
+ return watcher;
+ }
+
+ private FileDataWatcher(
+ WatchService watchService,
+ Registrar registrar,
+ Set watchedFilePaths,
+ Set configuredDirectories,
+ Duration directoryRetryDelay,
+ int threadPriority,
+ LDLogger logger
+ ) {
+ this.watchService = watchService;
+ this.registrar = registrar;
+ this.watchedFilePaths = watchedFilePaths;
+ this.configuredDirectories = configuredDirectories;
+ this.directoryRetryDelayNanos = directoryRetryDelay.toNanos();
+ this.logger = logger;
+ this.thread = new Thread(this, "LaunchDarkly-FileDataWatcher");
+ this.thread.setDaemon(true);
+ this.thread.setPriority(threadPriority);
+ }
+
+ /**
+ * Starts the worker thread and then signals one change, because a file may have changed between
+ * the caller's initial load and the registration of the watches.
+ *
+ * @param onChange called when a watched file changed
+ */
+ void start(Runnable onChange) {
+ this.onChange = onChange;
+ thread.start();
+ signal();
+ }
+
+ @Override
+ public void run() {
+ while (!stopped.get()) {
+ WatchKey key;
+ try {
+ if (missingDirectories.isEmpty()) {
+ key = watchService.take(); // blocks until a change is available or the thread is interrupted
+ } else {
+ // Wake up for the next registration attempt even when no change arrives.
+ long waitNanos = nextRetryAtNanos - System.nanoTime();
+ key = waitNanos > 0 ? watchService.poll(waitNanos, TimeUnit.NANOSECONDS) : null;
+ }
+ } catch (InterruptedException e) {
+ continue; // if stopped, the loop condition ends the thread
+ } catch (ClosedWatchServiceException e) {
+ return;
+ }
+ try {
+ if (key != null) {
+ processKey(key);
+ }
+ if (!missingDirectories.isEmpty() && System.nanoTime() - nextRetryAtNanos >= 0) {
+ retryMissingDirectories();
+ }
+ } catch (RuntimeException | Error e) {
+ // This thread is the only one that watches the files, so it keeps running. The failure can
+ // repeat, but each one waits for the next change or the next registration attempt.
+ if (!stopped.get()) {
+ logger.error("Unexpected error while watching files for changes: {}", LogValues.exceptionSummary(e));
+ logger.debug(LogValues.exceptionTrace(e));
+ }
+ }
+ }
+ }
+
+ private void processKey(WatchKey key) {
+ boolean watchedFileWasChanged = false;
+ boolean otherEntryChanged = false;
+ for (WatchEvent> event : key.pollEvents()) {
+ if (event.kind() == OVERFLOW) {
+ // Notifications were dropped, so a watched file may have changed.
+ watchedFileWasChanged = true;
+ break;
+ }
+ Watchable w = key.watchable();
+ Object context = event.context();
+ if (w instanceof Path && context instanceof Path) {
+ Path absolutePath = ((Path) w).resolve((Path) context);
+ if (watchedFilePaths.contains(absolutePath) || targetPaths.contains(absolutePath)) {
+ watchedFileWasChanged = true;
+ break;
+ }
+ otherEntryChanged = true;
+ } else {
+ otherEntryChanged = true;
+ }
+ }
+ // Without the reset, the watch on this key stops working. The reset fails when the key is no
+ // longer valid, which means that the directory was deleted. The watch on a configured directory
+ // is gone, so the directory is registered again once it exists. The directory of a link's target
+ // is not registered again: it is watched only while a configured link leads into it. Either way
+ // the configured files are compared with what was last observed, because the key can come with
+ // no events. On macOS the JDK's watch service examines each directory on an interval. When a
+ // directory is gone, it cancels the key and signals it without an event for the files that were
+ // in the directory.
+ if (!key.reset() && !stopped.get() && key.watchable() instanceof Path) {
+ Path directory = (Path) key.watchable();
+ if (configuredDirectories.contains(directory)) {
+ logger.warn("Directory {} no longer exists. It is watched again once it appears.", directory);
+ rememberAsMissing(directory);
+ } else {
+ targetDirectories.remove(directory, key);
+ }
+ otherEntryChanged = true;
+ }
+ // Observe the configured files after every event, so that what a later event is compared with
+ // is current, and so that a link that now leads into another directory has it watched.
+ boolean observedChange = observeConfiguredFiles();
+ if ((watchedFileWasChanged || (otherEntryChanged && observedChange)) && !stopped.get()) {
+ signal();
+ }
+ }
+
+ // Observes every configured file through any symbolic link, watches the directory of each final
+ // target that is not watched yet, and stops watching each directory that no target is in any
+ // more. Returns true if a configured file now leads to another file, or its file's state changed,
+ // since the last observation. Called during creation and then only by the worker thread.
+ private boolean observeConfiguredFiles() {
+ boolean changed = false;
+ Set targets = new HashSet<>();
+ Set directories = new HashSet<>();
+ for (Path path : watchedFilePaths) {
+ Observation observation = Observation.of(path);
+ if (!observation.equals(observations.put(path, observation))) {
+ changed = true;
+ }
+ if (observation.target == null || observation.target.equals(observation.unlinked)) {
+ continue;
+ }
+ targets.add(observation.target);
+ Path directory = observation.target.getParent();
+ if (directory == null || configuredDirectories.contains(directory)) {
+ continue;
+ }
+ directories.add(directory);
+ if (targetDirectories.containsKey(directory)) {
+ continue;
+ }
+ try {
+ targetDirectories.put(directory, registrar.register(directory, watchService));
+ } catch (IOException | RuntimeException e) {
+ // The directory cannot be watched, for example because access to it is denied. The link is
+ // still followed through the events in its own directory, and polling covers the rest.
+ // Another observation tries again.
+ logger.debug("Unable to watch directory {} of a link target: {}", directory, LogValues.exceptionSummary(e));
+ }
+ }
+ targetPaths.clear();
+ targetPaths.addAll(targets);
+ // The watch service has one key for each directory. A directory that is also registered under
+ // another path, such as a configured directory that is reached through a symbolic link, gets the
+ // key of that registration. Such a key is not cancelled here.
+ targetDirectories.entrySet().removeIf(entry -> {
+ if (directories.contains(entry.getKey())) {
+ return false;
+ }
+ if (entry.getValue().watchable().equals(entry.getKey())) {
+ entry.getValue().cancel();
+ }
+ return true;
+ });
+ return changed;
+ }
+
+ // Registers a directory with the watch service. A directory that cannot be registered is
+ // remembered as missing, so that the worker thread tries again on the retry schedule.
+ private void registerOrRememberAsMissing(Path directory) {
+ try {
+ registrar.register(directory, watchService);
+ } catch (NoSuchFileException e) {
+ logger.warn("Directory {} does not exist. It is watched once it appears.", directory);
+ rememberAsMissing(directory);
+ } catch (IOException e) {
+ logger.warn("Unable to watch directory {}: {}. The attempt is repeated until it succeeds.", directory,
+ LogValues.exceptionSummary(e));
+ rememberAsMissing(directory);
+ }
+ }
+
+ private void rememberAsMissing(Path directory) {
+ if (missingDirectories.isEmpty()) {
+ nextRetryAtNanos = System.nanoTime() + directoryRetryDelayNanos;
+ }
+ missingDirectories.add(directory);
+ }
+
+ // Tries to register every missing directory. A directory that is registered leaves the missing
+ // set, and one change is signalled so that files written to it while it was not watched are
+ // picked up. A directory that still cannot be registered stays in the set without a new log
+ // entry, because its absence was logged when it was first found missing. The next attempt is
+ // scheduled first, so that an attempt that fails unexpectedly is not repeated at once.
+ private void retryMissingDirectories() {
+ nextRetryAtNanos = System.nanoTime() + directoryRetryDelayNanos;
+ boolean registered = false;
+ for (Iterator it = missingDirectories.iterator(); it.hasNext();) {
+ Path directory = it.next();
+ try {
+ registrar.register(directory, watchService);
+ } catch (IOException | RuntimeException e) {
+ continue;
+ }
+ logger.info("Directory {} exists. Watching it for changes.", directory);
+ it.remove();
+ registered = true;
+ }
+ if (registered && !stopped.get()) {
+ observeConfiguredFiles();
+ signal();
+ }
+ }
+
+ private void signal() {
+ try {
+ onChange.run();
+ } catch (RuntimeException e) {
+ // COVERAGE: there is no way to simulate this condition in a unit test
+ logger.warn("Unexpected exception when reloading file data: {}", LogValues.exceptionSummary(e));
+ }
+ }
+
+ /**
+ * Waits for the worker thread to end after {@link #close()}. Visible for tests.
+ *
+ * @param timeoutMillis how long to wait
+ * @return true if the worker thread has ended
+ * @throws InterruptedException if the wait is interrupted
+ */
+ boolean awaitStop(long timeoutMillis) throws InterruptedException {
+ thread.join(timeoutMillis);
+ return !thread.isAlive();
+ }
+
+ /**
+ * Stops watching and releases the watch service. It does not wait for the worker thread.
+ */
+ @Override
+ public void close() {
+ if (stopped.getAndSet(true)) {
+ return;
+ }
+ thread.interrupt();
+ try {
+ watchService.close();
+ } catch (IOException e) {
+ // COVERAGE: there is no way to simulate this condition in a unit test
+ logger.debug("Error closing file watch service: {}", LogValues.exceptionSummary(e));
+ }
+ }
+
+ // One observation of a configured file. The target is the file that the path finally leads to
+ // through any symbolic links, or null if it does not exist or cannot be resolved. The unlinked
+ // path is the configured file in its directory's real location: a target equal to it means that
+ // the file itself is not a link, even when a directory above it is. The state is that of the
+ // target file.
+ private static final class Observation {
+ final Path target;
+ final Path unlinked;
+ final FileDataPoller.FileState state;
+
+ private Observation(Path target, Path unlinked, FileDataPoller.FileState state) {
+ this.target = target;
+ this.unlinked = unlinked;
+ this.state = state;
+ }
+
+ static Observation of(Path path) {
+ Path target = null;
+ Path unlinked = null;
+ try {
+ target = path.toRealPath();
+ Path parent = path.getParent();
+ unlinked = parent == null ? path : parent.toRealPath().resolve(path.getFileName());
+ } catch (IOException | RuntimeException e) {
+ // A file that does not exist, or a link that cannot be resolved, leads to no file.
+ }
+ return new Observation(target, unlinked, FileDataPoller.observe(path));
+ }
+
+ @Override
+ public boolean equals(Object other) {
+ if (other instanceof Observation) {
+ Observation o = (Observation) other;
+ return Objects.equals(target, o.target) && Objects.equals(state, o.state);
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(target, state);
+ }
+ }
+}
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/OverrideFileLoader.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/OverrideFileLoader.java
new file mode 100644
index 00000000..150df136
--- /dev/null
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/OverrideFileLoader.java
@@ -0,0 +1,604 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.google.common.collect.ImmutableList;
+import com.launchdarkly.sdk.LDValue;
+import com.launchdarkly.sdk.server.integrations.FileDataReloader.EmptiedFileException;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FileDataException;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FlagFactory;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FlagFileParser;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FlagFileRep;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.DataKind;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.ItemDescriptor;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.KeyedItems;
+
+import org.yaml.snakeyaml.reader.UnicodeReader;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.Reader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.time.Duration;
+import java.util.AbstractMap;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.LongSupplier;
+
+import static com.launchdarkly.sdk.server.DataModel.FEATURES;
+import static com.launchdarkly.sdk.server.DataModel.SEGMENTS;
+
+/**
+ * Reads the files of the file-based override source and merges them into one snapshot.
+ *
+ * This loader is separate from the file data source's loader because the override source has
+ * different rules: a configured file that does not exist contributes no entries, entries keep the
+ * versions that the documents specify, a value-only entry becomes a flag that is on and serves the
+ * value by fallthrough, the format of a file is chosen by its extension, and every failure to read or
+ * parse a file is reported as a file data error. The file data source keeps its own behavior.
+ *
+ * Whether a file with no content is valid depends on its format, like the rest of its content. A JSON
+ * file with no content is not a JSON document, so it fails to parse. A YAML file with no content is a
+ * document with no entries.
+ *
+ * A file that is rewritten in place is empty for a moment, and a load can find it so. A file counts
+ * as empty when it holds only white space, or when its parser reads its content as no document, as the
+ * YAML parser does for a part of a file that holds only a comment or a document marker. The loader
+ * remembers, for each file, whether it contributed content to the data in effect, and since when it
+ * has been found empty without being written. A file whose content is in effect and that is found
+ * empty is held back, not parsed: {@link #load(Duration)} still reads the other files, so that files
+ * emptied together are held back from the same load, and then throws {@link EmptiedFileException}.
+ * The data in effect stays, and the reloader reads the files again when the exception says. A file is
+ * held back until it has stayed empty, without being written, for one retry delay, and for at most
+ * five retry delays from the first load that held it back, so that a file that keeps being rewritten
+ * cannot hold the changes back for longer. The bound is per file, and it starts over at a load that
+ * holds nothing back. A file that never contributed content, such as a placeholder, and a file whose empty state
+ * is in effect are parsed right away. The reloader calls {@link #load(Duration)} and
+ * {@link #accepted(LoadResult)} one call at a time, so this state needs no synchronization.
+ */
+final class OverrideFileLoader implements FileDataReloader.Loader {
+ /**
+ * How many retry delays a file can be held back for, from the first load that held it back.
+ */
+ static final int MAX_HOLD_RETRY_DELAYS = 5;
+
+ /**
+ * Reads a file. Tests substitute one that takes time.
+ */
+ interface FileReader {
+ byte[] read(Path path) throws IOException;
+ }
+
+ /**
+ * Describes one configured file after a load.
+ */
+ static final class FileSummary {
+ private final Path path;
+ private final boolean present;
+ private final boolean hasContent;
+ private final int flags;
+ private final int segments;
+
+ FileSummary(Path path, boolean present, boolean hasContent, int flags, int segments) {
+ this.path = path;
+ this.present = present;
+ this.hasContent = hasContent;
+ this.flags = flags;
+ this.segments = segments;
+ }
+
+ Path getPath() {
+ return path;
+ }
+
+ /**
+ * False when the file does not exist.
+ */
+ boolean isPresent() {
+ return present;
+ }
+
+ /**
+ * False when the file does not exist, is empty, holds only white space or a byte order mark, or
+ * holds content that its parser reads as no document, such as YAML with only a comment.
+ */
+ boolean hasContent() {
+ return hasContent;
+ }
+
+ /**
+ * The number of flag entries the merge kept from this file. An entry dropped by the duplicate keys
+ * handling is not counted.
+ */
+ int getFlags() {
+ return flags;
+ }
+
+ /**
+ * The number of segment entries the merge kept from this file.
+ */
+ int getSegments() {
+ return segments;
+ }
+ }
+
+ /**
+ * The merged result of one full load.
+ */
+ static final class LoadResult {
+ private final Iterable>> data;
+ private final List files;
+ private final int flagCount;
+ private final int segmentCount;
+ private final byte[] contentHash;
+
+ LoadResult(
+ Iterable>> data,
+ List files,
+ int flagCount,
+ int segmentCount,
+ byte[] contentHash
+ ) {
+ this.data = data;
+ this.files = Collections.unmodifiableList(new ArrayList<>(files));
+ this.flagCount = flagCount;
+ this.segmentCount = segmentCount;
+ this.contentHash = contentHash;
+ }
+
+ Iterable>> getData() {
+ return data;
+ }
+
+ /**
+ * One summary per configured file, in configuration order.
+ */
+ List getFiles() {
+ return files;
+ }
+
+ int getFlagCount() {
+ return flagCount;
+ }
+
+ int getSegmentCount() {
+ return segmentCount;
+ }
+
+ /**
+ * A digest of the raw content of every file that was read. Two loads with an equal digest produced
+ * the same data.
+ */
+ byte[] getContentHash() {
+ return contentHash;
+ }
+ }
+
+ /**
+ * A file whose content is in effect and that loads have found empty.
+ * Times are from the monotonic clock.
+ */
+ private static final class EmptyFile {
+ // Since when the file has been empty without being written, or null after a load read it with
+ // content, even content that fails to parse, or found it missing.
+ Long sinceNanos;
+ // The state of the file then: its modification time and size, read through any symbolic link. It
+ // is only compared for equality.
+ FileDataPoller.FileState state;
+ // When a load first held the file back, or null if no load has since the last load that got to the
+ // file and held nothing back. Loads that hold another file back keep it, so that a file that keeps
+ // being rewritten stays bounded.
+ Long firstHeldNanos;
+ }
+
+ private final List paths;
+ private final FileData.DuplicateKeysHandling duplicateKeysHandling;
+ private final LongSupplier nanoClock;
+ // Whether each configured file contributed content to the data in effect. Updated only by
+ // accepted(LoadResult). A file that is not listed did not.
+ private final Map appliedHadContent = new HashMap<>();
+ private final FileReader reader;
+ // The files whose content is in effect and that loads have found empty.
+ private final Map emptyFiles = new HashMap<>();
+
+ /**
+ * Creates a loader.
+ *
+ * @param paths the files to read, in precedence order
+ * @param duplicateKeysHandling what to do when the same key appears in more than one file
+ */
+ OverrideFileLoader(List paths, FileData.DuplicateKeysHandling duplicateKeysHandling) {
+ this(paths, duplicateKeysHandling, System::nanoTime);
+ }
+
+ /**
+ * Creates a loader with a specific monotonic clock. Visible for tests.
+ */
+ OverrideFileLoader(List paths, FileData.DuplicateKeysHandling duplicateKeysHandling,
+ LongSupplier nanoClock) {
+ this(paths, duplicateKeysHandling, nanoClock, OverrideFileLoader::readRegularFile);
+ }
+
+ /**
+ * Creates a loader with a specific monotonic clock and file reader. Visible for tests.
+ */
+ OverrideFileLoader(List paths, FileData.DuplicateKeysHandling duplicateKeysHandling,
+ LongSupplier nanoClock, FileReader reader) {
+ this.paths = new ArrayList<>(paths);
+ this.duplicateKeysHandling = duplicateKeysHandling;
+ this.nanoClock = nanoClock;
+ this.reader = reader;
+ }
+
+ /**
+ * Reads every configured file in order and merges the entries.
+ *
+ * @param retryDelay the reloader's retry delay. A file whose content is in effect and that is found
+ * empty is held back until it has stayed empty, without being written, for this long, and for at
+ * most {@link #MAX_HOLD_RETRY_DELAYS} times this from the first load that held it back.
+ * @return the merged result with a summary of each file
+ * @throws FileDataException if a file that exists cannot be read or parsed, or the files cannot be
+ * merged, also when another file is held back
+ * @throws EmptiedFileException if a file is held back and every other file loads
+ */
+ @Override
+ public LoadResult load(Duration retryDelay) throws FileDataException, EmptiedFileException {
+ MessageDigest digest = newDigest();
+ List heldBack = new ArrayList<>();
+ // The files that this load got to and did not hold back: read with content, parsed empty, found
+ // missing, or failing to read or parse. A load reads every configured file, also after a failure,
+ // so every file that is not held back is here.
+ List reached = new ArrayList<>();
+ // The parsed documents of the files that are not held back, in configuration order.
+ List documents = new ArrayList<>(paths.size());
+ // The first failure to read or parse a file. The other files are still read, so that each file
+ // is classified, and the load fails with this one after them.
+ FileDataException failure = null;
+ try {
+ for (Path path : paths) {
+ byte[] raw;
+ try {
+ raw = reader.read(path);
+ } catch (NoSuchFileException e) {
+ // Absence is a valid state, not a failure.
+ noteNotEmpty(path, reached);
+ updateDigest(digest, path, null);
+ documents.add(new ReadFile(path, null, false));
+ continue;
+ } catch (IOException e) {
+ reached.add(path);
+ failure = first(failure, new FileDataException("file " + path + ": unable to read file", e));
+ continue;
+ }
+ // Content that the parser reads as no document, such as YAML with only a comment, has no
+ // entries, and a read can see that much of a file that is being written. Content with only
+ // white space is invalid JSON, so it is parsed only when the file is not held back.
+ FlagFileRep document = null;
+ boolean hasContent = hasContent(raw);
+ if (hasContent) {
+ try {
+ document = parse(path, raw);
+ } catch (FileDataException e) {
+ noteNotEmpty(path, reached);
+ failure = first(failure, e);
+ continue;
+ }
+ hasContent = document != FlagFileRep.NO_DOCUMENT;
+ }
+ if (hasContent) {
+ noteNotEmpty(path, reached);
+ } else if (shouldHoldBack(path, retryDelay, nanoClock.getAsLong())) {
+ // The clock is read after this file's own read, so a slow read of another file does not
+ // shorten its delay. The other files are still read, so that each emptied file starts its
+ // delay in this load, and a failure of another file still fails the load.
+ heldBack.add(path);
+ continue;
+ } else {
+ reached.add(path);
+ }
+ // One read feeds both the digest and the parse, so the content digest can never disagree
+ // with the content that was applied.
+ updateDigest(digest, path, raw);
+ if (document == null) {
+ try {
+ document = parse(path, raw);
+ } catch (FileDataException e) {
+ failure = first(failure, e);
+ continue;
+ }
+ }
+ documents.add(new ReadFile(path, document, hasContent));
+ }
+
+ // A failure fails the load before a hold, and a hold comes before the merge.
+ if (failure != null) {
+ throw failure;
+ }
+ if (!heldBack.isEmpty()) {
+ throw new EmptiedFileException(heldBack, holdBack(heldBack, retryDelay, nanoClock.getAsLong()));
+ }
+
+ // The entries are merged only after every file is read, so that a duplicate key or an entry
+ // that the data model rejects cannot keep a later file from being read.
+ Map> data = new HashMap<>();
+ List files = new ArrayList<>(documents.size());
+ for (ReadFile file : documents) {
+ if (file.document == null) {
+ files.add(new FileSummary(file.path, false, false, 0, 0));
+ continue;
+ }
+ int[] added = addEntries(data, file.path, file.document);
+ files.add(new FileSummary(file.path, true, file.hasContent, added[0], added[1]));
+ }
+ ImmutableList.Builder>> all = ImmutableList.builder();
+ for (Map.Entry> e : data.entrySet()) {
+ all.add(new AbstractMap.SimpleEntry<>(e.getKey(), new KeyedItems<>(ImmutableList.copyOf(e.getValue().entrySet()))));
+ }
+ Map flags = data.get(FEATURES);
+ Map segments = data.get(SEGMENTS);
+ return new LoadResult(all.build(), files, flags == null ? 0 : flags.size(),
+ segments == null ? 0 : segments.size(), digest.digest());
+ } finally {
+ if (heldBack.isEmpty()) {
+ // A load that holds nothing back, whether it is applied, skipped as unchanged, or fails,
+ // starts the bound over for every file that it got to, including one that failed: such a
+ // file is no longer held, so its next rewrite is a new one.
+ for (Path path : reached) {
+ EmptyFile empty = emptyFiles.get(path);
+ if (empty != null) {
+ empty.firstHeldNanos = null;
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * A file that a load read and did not hold back.
+ */
+ private static final class ReadFile {
+ final Path path;
+ // The parsed content, or null if the file does not exist.
+ final FlagFileRep document;
+ final boolean hasContent;
+
+ ReadFile(Path path, FlagFileRep document, boolean hasContent) {
+ this.path = path;
+ this.document = document;
+ this.hasContent = hasContent;
+ }
+ }
+
+ private static FileDataException first(FileDataException earlier, FileDataException e) {
+ return earlier != null ? earlier : e;
+ }
+
+ // Adds a file to the content digest: its path, whether it exists, and its content. The format
+ // depends on the path, so the same bytes at another path can be different data.
+ private static void updateDigest(MessageDigest digest, Path path, byte[] raw) {
+ digest.update(path.toString().getBytes(StandardCharsets.UTF_8));
+ digest.update((byte) 0);
+ digest.update((byte) (raw == null ? 0 : 1));
+ if (raw != null) {
+ digest.update(raw);
+ digest.update((byte) 0);
+ }
+ }
+
+ // For a file that a load read with content, including content that fails to parse, or found
+ // missing: if it was empty before, its empty state has ended, so its next emptying starts a new delay
+ // even where a coarse modification time makes it look the same.
+ private void noteNotEmpty(Path path, List reached) {
+ reached.add(path);
+ EmptyFile empty = emptyFiles.get(path);
+ if (empty != null) {
+ empty.sinceNanos = null;
+ }
+ }
+
+ /**
+ * Reads a configured file. A path that exists but is not a regular file, such as a directory, a named
+ * pipe, or a device, fails before it is read: a read of a pipe can wait forever, and a device such as
+ * {@code /dev/zero} has no end. The check follows symbolic links.
+ *
+ * @param path the file
+ * @return its content
+ * @throws NoSuchFileException if nothing exists at the path
+ * @throws IOException if the path is not a regular file or cannot be read
+ */
+ static byte[] readRegularFile(Path path) throws IOException {
+ if (!Files.readAttributes(path, BasicFileAttributes.class).isRegularFile()) {
+ throw new IOException("not a regular file");
+ }
+ return Files.readAllBytes(path);
+ }
+
+ private static FlagFileRep parse(Path path, byte[] raw) throws FileDataException {
+ try {
+ return FlagFileParser.parseForPath(path, raw);
+ } catch (FileDataException e) {
+ throw new FileDataException("file " + path + ": " + e.getMessage(), e.getCause());
+ } catch (IOException e) {
+ throw new FileDataException("file " + path + ": cannot read document", e);
+ } catch (RuntimeException e) {
+ throw new FileDataException("file " + path + ": cannot parse flag or segment data", e);
+ } catch (StackOverflowError e) {
+ // A YAML alias can make a document contain itself, as in "f: &a {self: *a}". Converting that
+ // document recurses until the stack overflows. The stack is unwound when this runs, so the
+ // failure is reported like any other document that cannot be parsed.
+ throw new FileDataException("file " + path
+ + ": cannot parse flag or segment data: the document refers to itself or is nested too deeply", null);
+ }
+ }
+
+ // Adds the entries of one file and returns how many flags and segments the merge kept from it.
+ private int[] addEntries(Map> data, Path path, FlagFileRep document)
+ throws FileDataException {
+ int flagsAdded = 0;
+ int segmentsAdded = 0;
+ try {
+ if (document.flags != null) {
+ for (Map.Entry e : document.flags.entrySet()) {
+ if (add(data, FEATURES, e.getKey(), parseEntry(FEATURES, e.getKey(), e.getValue()))) {
+ flagsAdded++;
+ }
+ }
+ }
+ if (document.flagValues != null) {
+ for (Map.Entry e : document.flagValues.entrySet()) {
+ if (add(data, FEATURES, e.getKey(), FlagFactory.flagWithValue(e.getKey(), e.getValue(), 0))) {
+ flagsAdded++;
+ }
+ }
+ }
+ if (document.segments != null) {
+ for (Map.Entry e : document.segments.entrySet()) {
+ if (add(data, SEGMENTS, e.getKey(), parseEntry(SEGMENTS, e.getKey(), e.getValue()))) {
+ segmentsAdded++;
+ }
+ }
+ }
+ } catch (FileDataException e) {
+ throw new FileDataException("file " + path + ": " + e.getMessage(), e.getCause());
+ }
+ return new int[] { flagsAdded, segmentsAdded };
+ }
+
+ // A document can be valid JSON or YAML and still hold a flag or segment that the data model cannot
+ // accept. For the override source that is a parse failure of the file, so the last good overrides
+ // stay in effect.
+ private static ItemDescriptor parseEntry(DataKind kind, String key, LDValue entry) throws FileDataException {
+ try {
+ return kind == FEATURES ? FlagFactory.flagFromJson(entry) : FlagFactory.segmentFromJson(entry);
+ } catch (RuntimeException e) {
+ String name = (kind == FEATURES ? "flag" : "segment") + " \"" + key + "\"";
+ for (Throwable c = e; c != null; c = c.getCause()) {
+ if (c instanceof NumberFormatException) {
+ // A number property holds another value. The message of the exception quotes that value,
+ // which can be a context key or other data, so the failure does not keep it.
+ throw new FileDataException("cannot parse " + name + ": a property that must be a number is not a number",
+ null);
+ }
+ }
+ // The messages of the other failures hold no values from the entry.
+ throw new FileDataException("cannot parse " + name, e);
+ }
+ }
+
+ /**
+ * Records that the result of a load is now the data in effect: it was applied, or it was skipped
+ * because it is unchanged. Whether each file contributed content to the data in effect decides
+ * whether finding it empty later defers it.
+ *
+ * @param result the result of a load by this loader
+ */
+ @Override
+ public void accepted(LoadResult result) {
+ for (FileSummary file : result.getFiles()) {
+ appliedHadContent.put(file.getPath(), file.hasContent());
+ }
+ }
+
+ // Decides whether a file that a load found empty is held back. A file whose content is in effect
+ // and that is empty now may be in the middle of an in-place rewrite: a writer that truncates the file
+ // and then writes the new content. Such a file is held back until it has stayed empty, without being
+ // written, for the retry delay. A change of its state means that it was written since a load last
+ // found it empty, for example rewritten and truncated again between two loads, so the delay starts
+ // over. A file that keeps being written while loads find it empty would be held back without end, so
+ // each file is held back for at most MAX_HOLD_RETRY_DELAYS retry delays from the first load that held
+ // it back. The bound is the file's own, so one file reaching it does not cut short another file's
+ // rewrite. It starts over only at a load that holds nothing back, for every file that load got to,
+ // including one that fails to read or parse, whatever the load's outcome. Loads that hold another file back keep it, which bounds files
+ // rewritten in turn or emptied in staggered turns, and a file that was read during a long failure
+ // of another file has a fresh bound when that failure ends. A file whose content is not in effect,
+ // such as a placeholder that has always been empty, or a file whose empty state was applied, is
+ // parsed right away. Elapsed times are differences of monotonic clock readings, which do not
+ // overflow.
+ private boolean shouldHoldBack(Path path, Duration retryDelay, long now) {
+ if (!Boolean.TRUE.equals(appliedHadContent.get(path))) {
+ return false;
+ }
+ FileDataPoller.FileState state = FileDataPoller.observe(path);
+ EmptyFile empty = emptyFiles.computeIfAbsent(path, p -> new EmptyFile());
+ if (empty.sinceNanos == null || !state.equals(empty.state)) {
+ empty.sinceNanos = now;
+ empty.state = state;
+ }
+ long delay = retryDelay.toNanos();
+ if (now - empty.sinceNanos >= delay) {
+ // The file has stayed empty for the whole delay, so it is parsed as it is. Its bound starts over
+ // only at a load that holds nothing back, so that files that stay empty in staggered turns, each
+ // keeping the loads holding while the other settles, cannot hold the changes back without end.
+ return false;
+ }
+ if (empty.firstHeldNanos != null && now - empty.firstHeldNanos >= MAX_HOLD_RETRY_DELAYS * delay) {
+ return false;
+ }
+ if (empty.firstHeldNanos == null) {
+ empty.firstHeldNanos = now;
+ }
+ return true;
+ }
+
+ // Returns how long the reloader waits before it loads again: until the first of the held files has
+ // stayed empty for the retry delay or reaches its bound, plus a tenth of the retry delay, so that a
+ // timer that fires a little early still finds the time over. A change signal for a write starts a
+ // load sooner.
+ private long holdBack(List heldBack, Duration retryDelay, long now) {
+ long delay = retryDelay.toNanos();
+ long remaining = Long.MAX_VALUE;
+ for (Path path : heldBack) {
+ EmptyFile empty = emptyFiles.get(path);
+ long delayLeft = delay - (now - empty.sinceNanos);
+ long boundLeft = MAX_HOLD_RETRY_DELAYS * delay - (now - empty.firstHeldNanos);
+ remaining = Math.min(remaining, Math.min(delayLeft, boundLeft));
+ }
+ return Math.max(remaining, 0) + delay / 10;
+ }
+
+ // A file with only white space, after a byte order mark if it has one, has no content. The text is
+ // decoded as the parsers decode it. Content that cannot be decoded is left to the parser to report.
+ private static boolean hasContent(byte[] raw) {
+ try (Reader text = new UnicodeReader(new ByteArrayInputStream(raw))) {
+ int c;
+ while ((c = text.read()) >= 0) {
+ if (!Character.isWhitespace(c)) {
+ return true;
+ }
+ }
+ return false;
+ } catch (IOException e) {
+ return true;
+ }
+ }
+
+ // Adds an entry unless the key was already added. Reports whether it added the entry.
+ private boolean add(Map> data, DataKind kind, String key, ItemDescriptor item)
+ throws FileDataException {
+ Map items = data.computeIfAbsent(kind, k -> new HashMap<>());
+ if (items.containsKey(key)) {
+ if (duplicateKeysHandling == FileData.DuplicateKeysHandling.IGNORE) {
+ return false;
+ }
+ throw new FileDataException("in " + kind.getName() + ", key \"" + key + "\" was already defined", null);
+ }
+ items.put(key, item);
+ return true;
+ }
+
+ private static MessageDigest newDigest() {
+ try {
+ return MessageDigest.getInstance("SHA-256");
+ } catch (NoSuchAlgorithmException e) {
+ // COVERAGE: every Java runtime provides SHA-256
+ throw new IllegalStateException(e);
+ }
+ }
+}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataLoadingBehaviorTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataLoadingBehaviorTest.java
new file mode 100644
index 00000000..5a31d032
--- /dev/null
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataLoadingBehaviorTest.java
@@ -0,0 +1,73 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.sdk.server.datasources.Synchronizer;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceBase.DataBuilder;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceBase.DataLoader;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FileDataException;
+import com.launchdarkly.sdk.server.subsystems.SerializationException;
+import com.launchdarkly.testhelpers.TempDir;
+import com.launchdarkly.testhelpers.TempFile;
+
+import org.junit.Test;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.junit.Assert.fail;
+
+/**
+ * Pins the error behavior of the file data source's loader. A document that parses but holds a flag
+ * that the data model rejects is not a file data error: the deserialization exception escapes as it
+ * always has. The override source has its own loader with different rules.
+ */
+@SuppressWarnings("javadoc")
+public class FileDataLoadingBehaviorTest {
+ private static final String MODEL_REJECTED_DOCUMENT = "{\"flags\":{\"f1\":{\"key\":\"f1\",\"rules\":5}}}";
+
+ @Test
+ public void modelRejectedDocumentEscapesTheLoaderAsARuntimeException() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ try (TempFile file = dir.tempFile(".json")) {
+ file.setContents(MODEL_REJECTED_DOCUMENT);
+ DataLoader loader = new DataLoader(FileData.dataSource().filePaths(file.getPath()).sources);
+ try {
+ loader.load(new DataBuilder(FileData.DuplicateKeysHandling.FAIL));
+ fail("expected exception");
+ } catch (FileDataException e) {
+ fail("the loader must not convert a model rejection into a file data error");
+ } catch (RuntimeException e) {
+ assertThat(e, instanceOf(SerializationException.class));
+ }
+ }
+ }
+ }
+
+ @Test
+ public void modelRejectedDocumentEscapesTheSynchronizerAsARuntimeException() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ try (TempFile file = dir.tempFile(".json")) {
+ file.setContents(MODEL_REJECTED_DOCUMENT);
+ try (Synchronizer synchronizer = FileData.synchronizer().filePaths(file.getPath())
+ .build(TestDataSourceBuildInputs.create(LDLogger.none()))) {
+ try {
+ synchronizer.next();
+ fail("expected exception");
+ } catch (RuntimeException e) {
+ assertThat(e, instanceOf(SerializationException.class));
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void exceptionDescriptionShowsTheCauseWhenThereIsOne() {
+ FileDataException withCause = new FileDataException("message", new RuntimeException("boom"), null);
+ assertThat(withCause.getDescription(), equalTo("message [java.lang.RuntimeException: boom]"));
+
+ // A duplicate key failure or a YAML parse failure carries no cause.
+ FileDataException withoutCause = new FileDataException("message", null, null);
+ assertThat(withoutCause.getDescription(), equalTo("message"));
+ }
+}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataPollerTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataPollerTest.java
new file mode 100644
index 00000000..97fd78d9
--- /dev/null
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataPollerTest.java
@@ -0,0 +1,276 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.launchdarkly.logging.LDLogLevel;
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.logging.LogCapture;
+import com.launchdarkly.logging.Logs;
+import com.launchdarkly.testhelpers.TempDir;
+
+import org.junit.After;
+import org.junit.Test;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.attribute.FileTime;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.lessThan;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+@SuppressWarnings("javadoc")
+public class FileDataPollerTest {
+ private static final LDLogger testLogger = LDLogger.none();
+ private static final Duration INTERVAL = Duration.ofMillis(20);
+ private static final long WAIT_MILLIS = 5000;
+ private static final long QUIET_MILLIS = 250;
+ // Long enough for a rewrite that the poller observed in several steps to be fully reported.
+ private static final long SETTLE_MILLIS = 100;
+
+ private final ScheduledThreadPoolExecutor executor = FileDataReloader.newExecutor(Thread.NORM_PRIORITY);
+
+ @After
+ public void shutDownExecutor() {
+ executor.shutdownNow();
+ }
+
+ private static void awaitCount(AtomicInteger counter, int expected) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + WAIT_MILLIS;
+ while (counter.get() < expected) {
+ if (System.currentTimeMillis() > deadline) {
+ throw new AssertionError("timed out waiting for " + expected + " change signals, got " + counter.get());
+ }
+ Thread.sleep(5);
+ }
+ }
+
+ private static Path createFile(TempDir dir, String name, String contents, long modifiedMillis) throws Exception {
+ Path path = dir.getPath().resolve(name);
+ Files.write(path, contents.getBytes());
+ Files.setLastModifiedTime(path, FileTime.fromMillis(modifiedMillis));
+ return path;
+ }
+
+ private static void rewrite(Path path, String contents, long modifiedMillis) throws Exception {
+ Files.write(path, contents.getBytes());
+ Files.setLastModifiedTime(path, FileTime.fromMillis(modifiedMillis));
+ }
+
+ @Test
+ public void detectsModifiedTimeChange() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = createFile(dir, "a.json", "{}", 1000_000);
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataPoller poller = new FileDataPoller(Collections.singletonList(file), INTERVAL, changes::incrementAndGet, testLogger,
+ executor)) {
+ Thread.sleep(QUIET_MILLIS);
+ assertEquals(0, changes.get());
+
+ rewrite(file, "{}", 2000_000); // same size, new modified time
+ awaitCount(changes, 1);
+ }
+ }
+ }
+
+ @Test
+ public void detectsSizeChangeWithSameModifiedTime() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = createFile(dir, "a.json", "{}", 1000_000);
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataPoller poller = new FileDataPoller(Collections.singletonList(file), INTERVAL, changes::incrementAndGet, testLogger,
+ executor)) {
+ rewrite(file, "{\"flagValues\":{}}", 1000_000);
+ awaitCount(changes, 1);
+ }
+ }
+ }
+
+ // The poller updates its baseline after a change, so it goes quiet once the file is stable. It
+ // does not promise one callback per logical change: a rewrite is not atomic, and a poll that
+ // lands between its steps legitimately reports an extra change, which the reloader absorbs.
+ @Test
+ public void stopsFiringWhenFileIsStable() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = createFile(dir, "a.json", "{}", 1000_000);
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataPoller poller = new FileDataPoller(Collections.singletonList(file), INTERVAL, changes::incrementAndGet, testLogger,
+ executor)) {
+ rewrite(file, "{}", 2000_000);
+ awaitCount(changes, 1);
+ Thread.sleep(SETTLE_MILLIS);
+ int settled = changes.get();
+ Thread.sleep(QUIET_MILLIS);
+ assertEquals(settled, changes.get());
+ }
+ }
+ }
+
+ @Test
+ public void detectsFileAppearing() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = dir.getPath().resolve("later.json");
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataPoller poller = new FileDataPoller(Collections.singletonList(file), INTERVAL, changes::incrementAndGet, testLogger,
+ executor)) {
+ Thread.sleep(QUIET_MILLIS);
+ assertEquals(0, changes.get());
+
+ Files.write(file, "{}".getBytes());
+ awaitCount(changes, 1);
+ }
+ }
+ }
+
+ @Test
+ public void detectsFileDisappearing() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = createFile(dir, "a.json", "{}", 1000_000);
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataPoller poller = new FileDataPoller(Collections.singletonList(file), INTERVAL, changes::incrementAndGet, testLogger,
+ executor)) {
+ Files.delete(file);
+ awaitCount(changes, 1);
+ }
+ }
+ }
+
+ @Test
+ public void watchesEveryConfiguredFile() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path first = createFile(dir, "a.json", "{}", 1000_000);
+ Path second = createFile(dir, "b.json", "{}", 1000_000);
+ List paths = Arrays.asList(first, second);
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataPoller poller = new FileDataPoller(paths, INTERVAL, changes::incrementAndGet, testLogger,
+ executor)) {
+ rewrite(second, "{}", 2000_000);
+ awaitCount(changes, 1);
+ rewrite(first, "{}", 2000_000);
+ awaitCount(changes, 2);
+ }
+ }
+ }
+
+ @Test
+ public void stopsOnClose() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = createFile(dir, "a.json", "{}", 1000_000);
+ AtomicInteger changes = new AtomicInteger();
+ FileDataPoller poller = new FileDataPoller(Collections.singletonList(file), INTERVAL, changes::incrementAndGet, testLogger,
+ executor);
+ poller.close();
+ poller.close(); // idempotent
+
+ rewrite(file, "{}", 2000_000);
+ Thread.sleep(QUIET_MILLIS);
+ assertEquals(0, changes.get());
+ }
+ }
+
+ @Test
+ public void closeLeavesTheExecutorRunningForOtherTasks() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = createFile(dir, "a.json", "{}", 1000_000);
+ AtomicInteger changes = new AtomicInteger();
+ FileDataPoller poller = new FileDataPoller(Collections.singletonList(file), INTERVAL, changes::incrementAndGet,
+ testLogger, executor);
+ poller.close();
+
+ CountDownLatch ran = new CountDownLatch(1);
+ executor.execute(ran::countDown);
+ assertTrue(ran.await(WAIT_MILLIS, TimeUnit.MILLISECONDS));
+ rewrite(file, "{}", 2000_000);
+ Thread.sleep(QUIET_MILLIS);
+ assertEquals(0, changes.get());
+ }
+ }
+
+ @Test
+ public void closeReturnsWhileCallbackBlocks() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = createFile(dir, "a.json", "{}", 1000_000);
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ FileDataPoller poller = new FileDataPoller(Collections.singletonList(file), INTERVAL, () -> {
+ entered.countDown();
+ try {
+ release.await(WAIT_MILLIS, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }, testLogger, executor);
+ rewrite(file, "{}", 2000_000);
+ assertTrue(entered.await(WAIT_MILLIS, TimeUnit.MILLISECONDS));
+
+ long start = System.currentTimeMillis();
+ poller.close();
+ assertThat(System.currentTimeMillis() - start, lessThan(1000L));
+ release.countDown();
+ }
+ }
+
+ @Test
+ public void pollingContinuesAfterTheCallbackThrows() throws Exception {
+ LogCapture logCapture = Logs.capture();
+ LDLogger logger = LDLogger.withAdapter(logCapture, "");
+ try (TempDir dir = TempDir.create()) {
+ Path file = createFile(dir, "a.json", "{}", 1000_000);
+ AtomicInteger changes = new AtomicInteger();
+ Runnable onChange = () -> {
+ if (changes.incrementAndGet() == 1) {
+ throw new IllegalStateException("consumer failed");
+ }
+ };
+ try (FileDataPoller poller = new FileDataPoller(Collections.singletonList(file), INTERVAL, onChange, logger, executor)) {
+ // The first change makes the callback throw.
+ rewrite(file, "{}", 2000_000);
+ awaitCount(changes, 1);
+
+ // The next change must still be detected and delivered, and the failure logged as an error.
+ rewrite(file, "{}", 3000_000);
+ awaitCount(changes, 2);
+ assertTrue(logCapture.getMessages().stream().anyMatch(m -> m.getLevel() == LDLogLevel.ERROR));
+ }
+ }
+ }
+
+ @Test
+ public void examinationsContinueAfterTheCallbackThrowsAnError() throws Exception {
+ LogCapture logCapture = Logs.capture();
+ LDLogger logger = LDLogger.withAdapter(logCapture, "");
+ try (TempDir dir = TempDir.create()) {
+ Path file = createFile(dir, "a.json", "{}", 1000_000);
+ AtomicInteger changes = new AtomicInteger();
+ Runnable onChange = () -> {
+ if (changes.incrementAndGet() == 1) {
+ throw new Error("simulated");
+ }
+ };
+ try (FileDataPoller poller = new FileDataPoller(Collections.singletonList(file), INTERVAL, onChange, logger, executor)) {
+ rewrite(file, "{}", 2000_000);
+ awaitCount(changes, 1);
+
+ rewrite(file, "{}", 3000_000);
+ awaitCount(changes, 2);
+ assertTrue(logCapture.getMessages().stream().anyMatch(m -> m.getLevel() == LDLogLevel.ERROR));
+ }
+ }
+ }
+
+ @Test
+ public void unreadableAttributesCountAsAbsent() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path missing = dir.getPath().resolve("nope").resolve("missing.json");
+ List states = FileDataPoller.observeAll(Collections.singletonList(missing));
+ assertEquals(FileDataPoller.FileState.ABSENT, states.get(0));
+ }
+ }
+}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataReloaderEmptiedFileTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataReloaderEmptiedFileTest.java
new file mode 100644
index 00000000..a14efa59
--- /dev/null
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataReloaderEmptiedFileTest.java
@@ -0,0 +1,681 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.launchdarkly.logging.LDLogLevel;
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.logging.LogCapture;
+import com.launchdarkly.logging.Logs;
+import com.launchdarkly.sdk.LDValue;
+import com.launchdarkly.sdk.server.integrations.FileDataReloader.EmptiedFileException;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FileDataException;
+import com.launchdarkly.sdk.server.integrations.OverrideFileLoader.LoadResult;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.DataKind;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.ItemDescriptor;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.KeyedItems;
+import com.launchdarkly.testhelpers.TempDir;
+
+import org.junit.After;
+import org.junit.Test;
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+import java.util.function.LongSupplier;
+
+import static com.launchdarkly.sdk.server.DataModel.FEATURES;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.not;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * The reloader with the override files loader, on real files that are rewritten in place: a file
+ * whose content is in effect and is found empty is deferred until it has stayed empty for the retry
+ * delay.
+ */
+@SuppressWarnings("javadoc")
+public class FileDataReloaderEmptiedFileTest {
+ // Long enough that a test finishes what it does while a file is empty before the retry reads the
+ // file again, also on a loaded machine.
+ private static final Duration LONG_RETRY = Duration.ofMillis(1500);
+ private static final long WAIT_MILLIS = 10000;
+ private static final String REREAD_LOG = "DEBUG:Reading flag data again after a file was found empty";
+ private static final String FAILURE_PREFIX = "Unable to load flags: ";
+
+ private final LogCapture logCapture = Logs.capture();
+ private final LDLogger logger = LDLogger.withAdapter(logCapture, "");
+ private final List reloaders = new ArrayList<>();
+ private final ScheduledThreadPoolExecutor executor = FileDataReloader.newExecutor(Thread.NORM_PRIORITY);
+
+ @After
+ public void closeReloaders() {
+ for (FileDataReloader r : reloaders) {
+ r.close();
+ }
+ executor.shutdownNow();
+ }
+
+ /**
+ * Records the value of the flag "flag" in each applied snapshot, or "none" when a snapshot does
+ * not have it.
+ */
+ private static final class Recorder implements FileDataReloader.Handler {
+ final List applied = Collections.synchronizedList(new ArrayList<>());
+
+ @Override
+ public void apply(LoadResult result) {
+ String value = "none";
+ for (Map.Entry> kind : result.getData()) {
+ if (kind.getKey() != FEATURES) {
+ continue;
+ }
+ for (Map.Entry item : kind.getValue().getItems()) {
+ if (item.getKey().equals("flag")) {
+ LDValue v = LDValue.parse(FEATURES.serialize(item.getValue())).get("variations").get(0);
+ value = v.isString() ? v.stringValue() : v.toJsonString();
+ }
+ }
+ }
+ applied.add(value);
+ }
+ }
+
+ /**
+ * The override files loader, counting the loads that have finished.
+ */
+ private static final class CountingLoader implements FileDataReloader.Loader {
+ final OverrideFileLoader loader;
+ final AtomicInteger finished = new AtomicInteger();
+
+ CountingLoader(Path... paths) {
+ loader = new OverrideFileLoader(Arrays.asList(paths), FileData.DuplicateKeysHandling.FAIL);
+ }
+
+ CountingLoader(LongSupplier clock, Path... paths) {
+ loader = new OverrideFileLoader(Arrays.asList(paths), FileData.DuplicateKeysHandling.FAIL, clock);
+ }
+
+ @Override
+ public LoadResult load(Duration retryDelay) throws FileDataException, EmptiedFileException {
+ try {
+ return loader.load(retryDelay);
+ } finally {
+ finished.incrementAndGet();
+ }
+ }
+
+ @Override
+ public void accepted(LoadResult result) {
+ loader.accepted(result);
+ }
+
+ void awaitFinished(int expected) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + WAIT_MILLIS;
+ while (finished.get() < expected) {
+ if (System.currentTimeMillis() > deadline) {
+ throw new AssertionError("timed out waiting for load " + expected + ", got " + finished.get());
+ }
+ Thread.sleep(5);
+ }
+ }
+ }
+
+ private FileDataReloader reloader(CountingLoader loader, Recorder recorder, Duration retryDelay) {
+ FileDataReloader r = new FileDataReloader(loader, recorder, executor, logger, Duration.ZERO, retryDelay);
+ reloaders.add(r);
+ return r;
+ }
+
+ // The failures logged at error level, without the prefix of the log message.
+ private List failures() {
+ List failures = new ArrayList<>();
+ for (LogCapture.Message m : logCapture.getMessages()) {
+ if (m.getLevel() == LDLogLevel.ERROR && m.getText().startsWith(FAILURE_PREFIX)) {
+ failures.add(m.getText().substring(FAILURE_PREFIX.length()));
+ }
+ }
+ return failures;
+ }
+
+ private void awaitFailures(int expected) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + WAIT_MILLIS;
+ while (failures().size() < expected) {
+ if (System.currentTimeMillis() > deadline) {
+ throw new AssertionError("timed out waiting for " + expected + " failures, got " + failures());
+ }
+ Thread.sleep(5);
+ }
+ }
+
+ private static void awaitSize(List> list, int expected) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + WAIT_MILLIS;
+ while (list.size() < expected) {
+ if (System.currentTimeMillis() > deadline) {
+ throw new AssertionError("timed out waiting for size " + expected + ", got " + list);
+ }
+ Thread.sleep(5);
+ }
+ }
+
+ private static Path write(TempDir dir, String name, String contents) throws Exception {
+ Path p = dir.getPath().resolve(name);
+ Files.write(p, contents.getBytes());
+ return p;
+ }
+
+ private static String yaml(String value) {
+ return "flagValues:\n flag: \"" + value + "\"\n";
+ }
+
+ private static String json(String value) {
+ return "{\"flagValues\":{\"flag\":\"" + value + "\"}}";
+ }
+
+ private static String readAgainLog(Path file) {
+ return "DEBUG:File " + file + " is empty, possibly while it is being rewritten; reading it again before applying it";
+ }
+
+ // For the tests that move a clock themselves: a retry delay so long that no retry fires during the
+ // test, so every load is one the test starts with reloadNow.
+ private static final Duration HOUR = Duration.ofHours(1);
+
+ private static final long TENTH = HOUR.toNanos() / 10;
+
+ // Writes the file again, in place, with a later modification time than the previous write. File
+ // system timestamps can be coarse, so it waits until the time differs.
+ private static void writeAgain(Path file, String contents) throws Exception {
+ long before = Files.getLastModifiedTime(file).toMillis();
+ long deadline = System.currentTimeMillis() + 5000;
+ do {
+ Thread.sleep(20);
+ InPlaceWrites.rewrite(file, "x", () -> { });
+ InPlaceWrites.rewrite(file, contents, () -> { });
+ } while (Files.getLastModifiedTime(file).toMillis() == before && System.currentTimeMillis() < deadline);
+ }
+
+ @Test
+ public void holdAsksForTheRetryWhenTheDelayIsOver() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ AtomicLong clock = new AtomicLong();
+ FileDataReloader r = reloader(new CountingLoader(clock::get, file), new Recorder(), HOUR);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(file);
+ r.reloadNow();
+ assertEquals(HOUR.toNanos() + TENTH, r.getLastRequestedRetryNanos());
+
+ // A later load asks for the rest of the delay, not a whole one.
+ clock.addAndGet(Duration.ofMinutes(30).toNanos());
+ r.reloadNow();
+ assertEquals(Duration.ofMinutes(30).toNanos() + TENTH, r.getLastRequestedRetryNanos());
+ }
+ }
+
+ @Test
+ public void holdAsksForTheRetryWhenTheBoundIsOver() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ AtomicLong clock = new AtomicLong();
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(new CountingLoader(clock::get, file), recorder, HOUR);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(file);
+ r.reloadNow();
+ for (int i = 0; i < 4; i++) {
+ clock.addAndGet(Duration.ofMinutes(60).toNanos());
+ writeAgain(file, i % 2 == 0 ? " " : " ");
+ r.reloadNow();
+ }
+ clock.addAndGet(Duration.ofMinutes(48).toNanos());
+ writeAgain(file, " ");
+ r.reloadNow();
+
+ // The file's delay would be over in an hour, but its bound is over in 12 minutes.
+ assertEquals(Collections.singletonList("a"), recorder.applied);
+ assertEquals(Duration.ofMinutes(12).toNanos() + TENTH, r.getLastRequestedRetryNanos());
+ }
+ }
+
+ @Test
+ public void holdOfSeveralFilesAsksForTheRetryWhenTheFirstIsDue() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", yaml("a"));
+ Path b = write(dir, "b.yaml", "flagValues:\n other: \"b\"\n");
+ AtomicLong clock = new AtomicLong();
+ FileDataReloader r = reloader(new CountingLoader(clock::get, a, b), new Recorder(), HOUR);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(a);
+ r.reloadNow();
+ clock.addAndGet(Duration.ofMinutes(20).toNanos());
+ InPlaceWrites.truncate(b);
+ r.reloadNow();
+ assertEquals(Duration.ofMinutes(40).toNanos() + TENTH, r.getLastRequestedRetryNanos());
+ }
+ }
+
+ @Test
+ public void holdStartedByAChangeSignalAsksForTheRetryWhenTheDelayIsOver() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ AtomicLong clock = new AtomicLong();
+ CountingLoader loader = new CountingLoader(clock::get, file);
+ FileDataReloader r = reloader(loader, new Recorder(), HOUR);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(file);
+ r.trigger();
+ loader.awaitFinished(2);
+ long deadline = System.currentTimeMillis() + WAIT_MILLIS;
+ while (r.getLastRequestedRetryNanos() != HOUR.toNanos() + TENTH && System.currentTimeMillis() < deadline) {
+ Thread.sleep(5);
+ }
+ assertEquals(HOUR.toNanos() + TENTH, r.getLastRequestedRetryNanos());
+ assertThat(logCapture.getMessageStrings(), hasItem(readAgainLog(file)));
+ }
+ }
+
+ @Test
+ public void failedLoadAsksForTheRetryDelay() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ AtomicLong clock = new AtomicLong();
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(new CountingLoader(clock::get, file), recorder, HOUR);
+ r.reloadNow();
+
+ InPlaceWrites.rewrite(file, "flagValues: [", () -> { });
+ r.reloadNow();
+ assertEquals(1, failures().size());
+ assertEquals(HOUR.toNanos(), r.getLastRequestedRetryNanos());
+ }
+ }
+
+ @Test
+ public void holdEndsExactlyAfterTheRetryDelay() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ AtomicLong clock = new AtomicLong();
+ CountingLoader loader = new CountingLoader(clock::get, file);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, HOUR);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(file);
+ r.reloadNow();
+ clock.addAndGet(HOUR.toNanos() * 95 / 100);
+ r.reloadNow();
+ assertEquals(Collections.singletonList("a"), recorder.applied);
+ clock.addAndGet(HOUR.toNanos() * 5 / 100);
+ r.reloadNow();
+ assertEquals(Arrays.asList("a", "none"), recorder.applied);
+ assertTrue(failures().isEmpty());
+ }
+ }
+
+ @Test
+ public void fileRewrittenWithTheSameContentIsHeldBackAgainLater() throws Exception {
+ // A tool rewrites the file in place now and then with the same content. The load after a rewrite
+ // is skipped as unchanged, and that must start the file's bound over as an application does, or
+ // a rewrite five retry delays later would be applied while the file is empty.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ AtomicLong clock = new AtomicLong();
+ CountingLoader loader = new CountingLoader(clock::get, file);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, HOUR);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(file);
+ r.reloadNow();
+ InPlaceWrites.rewrite(file, yaml("a"), () -> { });
+ r.reloadNow();
+ assertEquals(3, loader.finished.get());
+ assertEquals(Collections.singletonList("a"), recorder.applied);
+
+ clock.addAndGet(HOUR.toNanos() * 6);
+ InPlaceWrites.truncate(file);
+ r.reloadNow();
+ assertEquals(Collections.singletonList("a"), recorder.applied);
+ assertTrue(failures().isEmpty());
+ }
+ }
+
+ @Test
+ public void sameBytesMovedToAFileOfAnotherFormatAreApplied() throws Exception {
+ // The format depends on the path, so the load after the move is not skipped as unchanged: YAML
+ // reads on as true, and JSON reads it as a string.
+ try (TempDir dir = TempDir.create()) {
+ Path yaml = write(dir, "overrides.yaml", "{\"flagValues\": {\"flag\": on}}");
+ Path json = dir.getPath().resolve("overrides.json");
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(new CountingLoader(yaml, json), recorder, HOUR);
+ r.reloadNow();
+ Files.move(yaml, json);
+ r.reloadNow();
+ assertEquals(Arrays.asList("true", "on"), recorder.applied);
+ }
+ }
+
+ @Test
+ public void changesToOtherFilesWaitWhileAFileIsHeld() throws Exception {
+ // A reload applies all the files or none.
+ try (TempDir dir = TempDir.create()) {
+ Path emptied = write(dir, "emptied.yaml", "flagValues:\n other: \"x\"\n");
+ Path changed = write(dir, "changed.yaml", yaml("b1"));
+ AtomicLong clock = new AtomicLong();
+ CountingLoader loader = new CountingLoader(clock::get, emptied, changed);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, HOUR);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(emptied);
+ InPlaceWrites.rewrite(changed, yaml("b2"), () -> { });
+ r.reloadNow();
+ assertEquals(Collections.singletonList("b1"), recorder.applied);
+ clock.addAndGet(HOUR.toNanos());
+ r.reloadNow();
+ assertEquals(Arrays.asList("b1", "b2"), recorder.applied);
+ }
+ }
+
+ @Test
+ public void emptiedYamlFileIsReadAgainAndTheRewrittenContentIsApplied() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ CountingLoader loader = new CountingLoader(file);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ InPlaceWrites.rewrite(file, yaml("b"), () -> {
+ // The change signal of the truncation starts a load that finds the file empty.
+ r.trigger();
+ loader.awaitFinished(2);
+ });
+ r.trigger();
+ awaitSize(recorder.applied, 2);
+
+ assertEquals(Arrays.asList("a", "b"), recorder.applied);
+ assertTrue(failures().isEmpty());
+ assertThat(logCapture.getMessageStrings(), hasItem(readAgainLog(file)));
+ }
+ }
+
+ @Test
+ public void yamlFileThatStaysEmptyIsAppliedByTheRetry() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ CountingLoader loader = new CountingLoader(file);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(file);
+ r.trigger();
+ loader.awaitFinished(2);
+ assertEquals(Collections.singletonList("a"), recorder.applied);
+
+ // No further signal arrives. The retry reads the file again and applies it.
+ awaitSize(recorder.applied, 2);
+ assertEquals(Arrays.asList("a", "none"), recorder.applied);
+ assertEquals(3, loader.finished.get());
+ assertTrue(failures().isEmpty());
+ assertThat(logCapture.getMessageStrings(), hasItem(REREAD_LOG));
+ }
+ }
+
+ @Test
+ public void emptiedJsonFileIsReportedOnlyByTheLoadAfterTheOneThatFindsItEmpty() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.json", json("a"));
+ CountingLoader loader = new CountingLoader(file);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(file);
+ r.trigger();
+ loader.awaitFinished(2);
+ assertTrue(failures().isEmpty());
+
+ awaitFailures(1);
+ assertThat(failures().get(0),
+ containsString("the file has no content, which is not a JSON document"));
+ assertEquals(Collections.singletonList("a"), recorder.applied);
+ }
+ }
+
+ @Test
+ public void furtherChangeSignalWithinTheGraceDoesNotApplyTheEmptyFile() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ CountingLoader loader = new CountingLoader(file);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(file);
+ r.trigger();
+ loader.awaitFinished(2);
+ r.trigger();
+ loader.awaitFinished(3);
+ assertEquals(Collections.singletonList("a"), recorder.applied);
+
+ // The retry armed by the second load finds that the file has stayed empty for the retry delay.
+ awaitSize(recorder.applied, 2);
+ assertEquals(Arrays.asList("a", "none"), recorder.applied);
+ assertEquals(4, loader.finished.get());
+ assertThat(logCapture.getMessageStrings(), hasItem(REREAD_LOG));
+ }
+ }
+
+ @Test
+ public void secondRewriteWithinOneDebounceWindowIsDeferredToo() throws Exception {
+ // F1: the write of b and the next truncation happen before any load reads b. The next load
+ // finds the file empty again; the file is in a new rewrite, not one that stayed empty.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ CountingLoader loader = new CountingLoader(file);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ InPlaceWrites.rewrite(file, yaml("b"), () -> {
+ r.trigger();
+ loader.awaitFinished(2);
+ });
+ Thread.sleep(50);
+ InPlaceWrites.rewrite(file, yaml("c"), () -> {
+ r.trigger();
+ loader.awaitFinished(3);
+ });
+ r.trigger();
+ awaitSize(recorder.applied, 2);
+
+ assertEquals(Arrays.asList("a", "c"), recorder.applied);
+ }
+ }
+
+ @Test
+ public void changeToAnotherFileWhileAFileIsEmptyDoesNotApplyTheEmptyFile() throws Exception {
+ // F2: a change to b starts a load while a is still in the middle of its rewrite.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", yaml("a"));
+ Path b = write(dir, "b.yaml", "flagValues:\n other: \"b1\"\n");
+ CountingLoader loader = new CountingLoader(a, b);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ InPlaceWrites.rewrite(a, yaml("a2"), () -> {
+ r.trigger();
+ loader.awaitFinished(2);
+ InPlaceWrites.rewrite(b, "flagValues:\n other: \"b2\"\n", () -> { });
+ r.trigger();
+ loader.awaitFinished(3);
+ });
+ r.trigger();
+ awaitSize(recorder.applied, 2);
+
+ assertEquals(Arrays.asList("a", "a2"), recorder.applied);
+ }
+ }
+
+ @Test
+ public void retryThatFindsANewTruncationIsDeferredToo() throws Exception {
+ // F3: the file is rewritten, and rewritten again before any load reads the first new content.
+ // The retry armed by the first deferral finds the second truncation.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ CountingLoader loader = new CountingLoader(file);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ InPlaceWrites.rewrite(file, yaml("b"), () -> {
+ r.trigger();
+ loader.awaitFinished(2);
+ });
+ Thread.sleep(50);
+ InPlaceWrites.rewrite(file, yaml("c"), () -> loader.awaitFinished(3));
+ r.trigger();
+ awaitSize(recorder.applied, 2);
+
+ assertEquals(Arrays.asList("a", "c"), recorder.applied);
+ assertThat(logCapture.getMessageStrings(), hasItem(REREAD_LOG));
+ }
+ }
+
+ @Test
+ public void filesEmptiedTogetherAreAppliedByTheFirstRetry() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", yaml("a"));
+ Path b = write(dir, "b.yaml", "flagValues:\n other: \"b\"\n");
+ CountingLoader loader = new CountingLoader(a, b);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ InPlaceWrites.truncate(a);
+ InPlaceWrites.truncate(b);
+ r.trigger();
+ loader.awaitFinished(2);
+ awaitSize(recorder.applied, 2);
+
+ assertEquals(Arrays.asList("a", "none"), recorder.applied);
+ assertEquals(3, loader.finished.get());
+ assertThat(logCapture.getMessageStrings(), hasItem(readAgainLog(a)));
+ assertThat(logCapture.getMessageStrings(), hasItem(readAgainLog(b)));
+ }
+ }
+
+ @Test
+ public void fileMovedToAnotherConfiguredPathIsDeferredWhenItIsRewritten() throws Exception {
+ // Moving a file from one configured path to another leaves the same flags in effect. The load
+ // after the move records that the content now comes from the new path, or an in-place rewrite
+ // of that path would be applied while it is empty. The content digest covers the paths,
+ // so that load is applied rather than skipped.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", yaml("a"));
+ Path b = dir.getPath().resolve("b.yaml");
+ CountingLoader loader = new CountingLoader(a, b);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ Files.move(a, b);
+ r.trigger();
+ awaitSize(recorder.applied, 2);
+ assertEquals(Arrays.asList("a", "a"), recorder.applied);
+
+ InPlaceWrites.rewrite(b, yaml("b"), () -> {
+ r.trigger();
+ loader.awaitFinished(3);
+ });
+ r.trigger();
+ awaitSize(recorder.applied, 3);
+
+ assertEquals(Arrays.asList("a", "a", "b"), recorder.applied);
+ assertThat(logCapture.getMessageStrings(), hasItem(readAgainLog(b)));
+ }
+ }
+
+ @Test
+ public void emptyPlaceholderFileDoesNotDelayAChangeToAnotherFile() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path placeholder = write(dir, "placeholder.yaml", "");
+ Path data = write(dir, "data.json", json("a"));
+ CountingLoader loader = new CountingLoader(placeholder, data);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ InPlaceWrites.rewrite(data, json("b"), () -> { });
+ r.trigger();
+ awaitSize(recorder.applied, 2);
+
+ // The load of the signal applied the change, without waiting for a retry.
+ assertEquals(Arrays.asList("a", "b"), recorder.applied);
+ assertEquals(2, loader.finished.get());
+ assertThat(logCapture.getMessageStrings(), not(hasItem(readAgainLog(placeholder))));
+ }
+ }
+
+ @Test
+ public void fileThatIsDeletedAndCreatedEmptyIsAppliedRightAway() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ CountingLoader loader = new CountingLoader(file);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ Files.delete(file);
+ r.trigger();
+ loader.awaitFinished(2);
+ Files.write(file, new byte[0]);
+ r.trigger();
+ awaitSize(recorder.applied, 3);
+
+ assertEquals(Arrays.asList("a", "none", "none"), recorder.applied);
+ assertEquals(3, loader.finished.get());
+ assertThat(logCapture.getMessageStrings(), not(hasItem(readAgainLog(file))));
+ }
+ }
+
+ @Test
+ public void retryLeftOverFromAFailureThatFindsTheFileEmptiedReadsItAgain() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", yaml("a"));
+ CountingLoader loader = new CountingLoader(file);
+ Recorder recorder = new Recorder();
+ FileDataReloader r = reloader(loader, recorder, LONG_RETRY);
+ r.reloadNow();
+
+ // A load fails and arms the retry.
+ InPlaceWrites.rewrite(file, "flagValues: [", () -> { });
+ r.trigger();
+ awaitFailures(1);
+
+ // The file is rewritten again, and only the retry reads it while it is empty.
+ InPlaceWrites.rewrite(file, yaml("b"), () -> loader.awaitFinished(3));
+ r.trigger();
+ awaitSize(recorder.applied, 2);
+
+ assertEquals(Arrays.asList("a", "b"), recorder.applied);
+ assertThat(logCapture.getMessageStrings(), hasItem(readAgainLog(file)));
+ }
+ }
+}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataReloaderTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataReloaderTest.java
new file mode 100644
index 00000000..7dd719d9
--- /dev/null
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataReloaderTest.java
@@ -0,0 +1,881 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.launchdarkly.logging.LDLogLevel;
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.logging.LogCapture;
+import com.launchdarkly.logging.Logs;
+import com.launchdarkly.sdk.server.integrations.FileDataReloader.EmptiedFileException;
+import com.launchdarkly.sdk.server.integrations.OverrideFileLoader.LoadResult;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FileDataException;
+
+import org.junit.After;
+import org.junit.Test;
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.lessThan;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.startsWith;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+@SuppressWarnings("javadoc")
+public class FileDataReloaderTest {
+ private static final Duration SHORT = Duration.ofMillis(50);
+ // A retry delay that does not come during a test.
+ private static final Duration HOUR = Duration.ofHours(1);
+ private static final String FAILURE_PREFIX = "Unable to load flags: ";
+ private static final long WAIT_MILLIS = 5000;
+
+ private final LogCapture logCapture = Logs.capture();
+ private final LDLogger logger = LDLogger.withAdapter(logCapture, "");
+ private final List reloaders = new ArrayList<>();
+ private final ScheduledThreadPoolExecutor executor = FileDataReloader.newExecutor(Thread.NORM_PRIORITY);
+
+ @After
+ public void closeReloaders() {
+ for (FileDataReloader r : reloaders) {
+ r.close();
+ }
+ executor.shutdownNow();
+ }
+
+ private static LoadResult resultWithHash(int... values) {
+ byte[] hash = new byte[values.length];
+ for (int i = 0; i < values.length; i++) {
+ hash[i] = (byte) values[i];
+ }
+ return new LoadResult(Collections.emptyList(), Collections.emptyList(), 0, 0, hash);
+ }
+
+ private static FileDataException failure(String message) {
+ return new FileDataException(message, null, null);
+ }
+
+ /**
+ * One step of a scripted loader: it returns a result or throws.
+ */
+ private interface Step {
+ LoadResult run() throws FileDataException, EmptiedFileException;
+ }
+
+ /**
+ * A scripted loader: each call takes the next step from the queue. A step either returns a result
+ * or throws. When the queue is empty the last step repeats. It records the argument of each call
+ * and every accepted result. A throwable set in throwOnAccepted is thrown by the next accepted call.
+ */
+ private static final class ScriptedLoader implements FileDataReloader.Loader {
+ final AtomicInteger calls = new AtomicInteger();
+ final List retryDelayArguments = Collections.synchronizedList(new ArrayList<>());
+ final List accepted = Collections.synchronizedList(new ArrayList<>());
+ final LinkedBlockingQueue steps = new LinkedBlockingQueue<>();
+ volatile Step last;
+ volatile CountDownLatch entered;
+ volatile CountDownLatch release;
+ volatile Throwable throwOnAccepted;
+
+ ScriptedLoader then(LoadResult result) {
+ steps.add(() -> result);
+ return this;
+ }
+
+ ScriptedLoader thenFail(String message) {
+ steps.add(() -> {
+ throw failure(message);
+ });
+ return this;
+ }
+
+ ScriptedLoader thenThrow(RuntimeException e) {
+ steps.add(() -> {
+ throw e;
+ });
+ return this;
+ }
+
+ ScriptedLoader thenThrow(Error e) {
+ steps.add(() -> {
+ throw e;
+ });
+ return this;
+ }
+
+ ScriptedLoader thenEmptied(Path path) {
+ return thenEmptied(path, SHORT);
+ }
+
+ ScriptedLoader thenEmptied(Path path, Duration retryAfter) {
+ steps.add(() -> {
+ throw new EmptiedFileException(Collections.singletonList(path), retryAfter.toNanos());
+ });
+ return this;
+ }
+
+ @Override
+ public LoadResult load(Duration retryDelay) throws FileDataException, EmptiedFileException {
+ // Both latches are read before the entered signal, so a test that clears them after the
+ // signal cannot change what this call does.
+ CountDownLatch enteredLatch = entered;
+ CountDownLatch releaseLatch = release;
+ retryDelayArguments.add(retryDelay);
+ calls.incrementAndGet();
+ if (enteredLatch != null) {
+ enteredLatch.countDown();
+ }
+ if (releaseLatch != null) {
+ try {
+ releaseLatch.await(WAIT_MILLIS, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ Step step = steps.poll();
+ if (step == null) {
+ step = last;
+ } else {
+ last = step;
+ }
+ return step.run();
+ }
+
+ @Override
+ public void accepted(LoadResult result) {
+ accepted.add(result);
+ Throwable thrown = throwOnAccepted;
+ if (thrown != null) {
+ throwOnAccepted = null;
+ if (thrown instanceof Error) {
+ throw (Error) thrown;
+ }
+ throw (RuntimeException) thrown;
+ }
+ }
+ }
+
+ private static class RecordingHandler implements FileDataReloader.Handler {
+ final List applied = Collections.synchronizedList(new ArrayList<>());
+
+ @Override
+ public void apply(LoadResult result) {
+ applied.add(result);
+ }
+ }
+
+ private FileDataReloader reloader(ScriptedLoader loader, RecordingHandler handler,
+ Duration debounce, Duration retry) {
+ FileDataReloader r = new FileDataReloader(loader, handler, executor, logger, debounce, retry);
+ reloaders.add(r);
+ return r;
+ }
+
+ private static void awaitAtLeast(AtomicInteger counter, int expected) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + WAIT_MILLIS;
+ while (counter.get() < expected) {
+ if (System.currentTimeMillis() > deadline) {
+ throw new AssertionError("timed out waiting for count " + expected + ", got " + counter.get());
+ }
+ Thread.sleep(5);
+ }
+ }
+
+ // The failures logged at error level, without the prefix of the log message.
+ private List failures() {
+ List failures = new ArrayList<>();
+ for (LogCapture.Message m : logCapture.getMessages()) {
+ if (m.getLevel() == LDLogLevel.ERROR && m.getText().startsWith(FAILURE_PREFIX)) {
+ failures.add(m.getText().substring(FAILURE_PREFIX.length()));
+ }
+ }
+ return failures;
+ }
+
+ private void awaitFailures(int expected) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + WAIT_MILLIS;
+ while (failures().size() < expected) {
+ if (System.currentTimeMillis() > deadline) {
+ throw new AssertionError("timed out waiting for " + expected + " failures, got " + failures());
+ }
+ Thread.sleep(5);
+ }
+ }
+
+ private static void awaitSize(List> list, int expected) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + WAIT_MILLIS;
+ while (list.size() < expected) {
+ if (System.currentTimeMillis() > deadline) {
+ throw new AssertionError("timed out waiting for size " + expected + ", got " + list.size());
+ }
+ Thread.sleep(5);
+ }
+ }
+
+ @Test
+ public void initialLoadAppliesResultSynchronously() {
+ LoadResult result = resultWithHash(1);
+ ScriptedLoader loader = new ScriptedLoader().then(result);
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+
+ r.reloadNow();
+
+ assertEquals(1, loader.calls.get());
+ assertEquals(1, handler.applied.size());
+ assertEquals(result, handler.applied.get(0));
+ assertTrue(failures().isEmpty());
+ }
+
+ @Test
+ public void failedLoadIsLoggedAndAppliesNothing() {
+ ScriptedLoader loader = new ScriptedLoader().thenFail("bad file");
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+
+ r.reloadNow();
+
+ assertTrue(handler.applied.isEmpty());
+ assertEquals(Collections.singletonList("bad file"), failures());
+ }
+
+ @Test
+ public void reloaderThatIsNeverTriggeredSchedulesNothing() {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, SHORT, SHORT);
+
+ r.reloadNow();
+
+ assertEquals(0, executor.getTaskCount());
+ }
+
+ @Test
+ public void newExecutorRunsTasksOnADaemonThreadWithThePriority() throws Exception {
+ ScheduledThreadPoolExecutor e = FileDataReloader.newExecutor(Thread.MIN_PRIORITY);
+ try {
+ AtomicReference thread = new AtomicReference<>();
+ e.submit(() -> thread.set(Thread.currentThread())).get(WAIT_MILLIS, TimeUnit.MILLISECONDS);
+ assertTrue(thread.get().isDaemon());
+ assertEquals(Thread.MIN_PRIORITY, thread.get().getPriority());
+ assertThat(thread.get().getName(), equalTo("LaunchDarkly-FileDataReloader"));
+ } finally {
+ e.shutdownNow();
+ }
+ }
+
+ @Test
+ public void closeCancelsAPendingReloadAndLeavesTheExecutorRunning() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).then(resultWithHash(2));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ofMillis(200), HOUR);
+ r.reloadNow();
+ r.trigger();
+
+ r.close();
+
+ CountDownLatch ran = new CountDownLatch(1);
+ executor.schedule(ran::countDown, 400, TimeUnit.MILLISECONDS);
+ assertTrue(ran.await(WAIT_MILLIS, TimeUnit.MILLISECONDS));
+ assertEquals(1, loader.calls.get());
+ }
+
+ @Test
+ public void triggerAfterTheExecutorIsShutDownDoesNotThrow() {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, SHORT, SHORT);
+ r.reloadNow();
+ executor.shutdownNow();
+
+ r.trigger();
+
+ assertEquals(1, loader.calls.get());
+ }
+
+ @Test
+ public void triggerReloadsAfterDebounceDelay() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).then(resultWithHash(2));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, SHORT, HOUR);
+ r.reloadNow();
+
+ r.trigger();
+
+ awaitSize(handler.applied, 2);
+ assertThat(logCapture.getMessageStrings(), hasItem("INFO:Reloading flag data after detecting a change"));
+ }
+
+ @Test
+ public void debounceCoalescesBurstOfTriggersIntoOneReload() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).then(resultWithHash(2));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ofMillis(150), HOUR);
+ r.reloadNow();
+
+ for (int i = 0; i < 10; i++) {
+ r.trigger();
+ }
+
+ awaitSize(handler.applied, 2);
+ Thread.sleep(400);
+ assertEquals(2, loader.calls.get());
+ assertEquals(2, handler.applied.size());
+ }
+
+ @Test
+ public void debounceWindowIsExtendedByEachTrigger() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).then(resultWithHash(2));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ofMillis(200), HOUR);
+ r.reloadNow();
+
+ // Triggers arrive every 50ms for 400ms. The window is 200ms, so no reload happens while they
+ // keep arriving.
+ for (int i = 0; i < 8; i++) {
+ r.trigger();
+ Thread.sleep(50);
+ }
+ assertEquals(1, loader.calls.get());
+
+ awaitSize(handler.applied, 2);
+ Thread.sleep(300);
+ assertEquals(2, loader.calls.get());
+ }
+
+ @Test
+ public void zeroDebounceReloadsOnEveryTrigger() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).then(resultWithHash(2)).then(resultWithHash(3));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+ r.reloadNow();
+
+ r.trigger();
+ awaitAtLeast(loader.calls, 2);
+ r.trigger();
+ awaitAtLeast(loader.calls, 3);
+
+ awaitSize(handler.applied, 3);
+ }
+
+ @Test
+ public void failedInitialLoadRetriesWithoutFurtherTriggers() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().thenFail("first").thenFail("first").then(resultWithHash(1));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+
+ r.reloadNow();
+
+ awaitSize(handler.applied, 1);
+ assertThat(loader.calls.get(), greaterThanOrEqualTo(3));
+ assertThat(logCapture.getMessageStrings(), hasItem("DEBUG:Retrying flag data load after earlier failure"));
+ }
+
+ @Test
+ public void identicalRepeatedFailureIsReportedOnceUntilItChanges() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().thenFail("same").thenFail("same").thenFail("same")
+ .thenFail("different").then(resultWithHash(1));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+
+ r.reloadNow();
+
+ awaitSize(handler.applied, 1);
+ assertEquals(Arrays.asList("same", "different"), failures());
+ assertThat(logCapture.getMessageStrings(), hasItem("DEBUG:Unable to load flags: same"));
+ }
+
+ @Test
+ public void successReArmsFailureReporting() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().thenFail("same").then(resultWithHash(1)).thenFail("same")
+ .then(resultWithHash(2));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+
+ r.reloadNow(); // fails, retry applies result 1
+ awaitSize(handler.applied, 1);
+ r.trigger(); // fails again with the same message, retry applies result 2
+ awaitSize(handler.applied, 2);
+
+ assertEquals(Arrays.asList("same", "same"), failures());
+ }
+
+ @Test
+ public void retryStopsAfterSuccess() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().thenFail("first").then(resultWithHash(1));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+
+ r.reloadNow();
+ awaitSize(handler.applied, 1);
+ int callsAfterSuccess = loader.calls.get();
+
+ Thread.sleep(300);
+ assertEquals(callsAfterSuccess, loader.calls.get());
+ }
+
+ @Test
+ public void reloadWithUnchangedContentIsSkipped() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).then(resultWithHash(1)).then(resultWithHash(2));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+
+ r.reloadNow();
+ r.trigger();
+ awaitAtLeast(loader.calls, 2);
+ r.trigger();
+ awaitAtLeast(loader.calls, 3);
+
+ awaitSize(handler.applied, 2);
+ assertEquals(2, handler.applied.size());
+ }
+
+ @Test
+ public void recoveryAppliesEvenWhenContentIsUnchanged() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).thenFail("broken").then(resultWithHash(1));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+
+ r.reloadNow();
+ r.trigger();
+ awaitFailures(1);
+ r.trigger();
+
+ awaitSize(handler.applied, 2);
+ }
+
+ @Test
+ public void closeStopsFurtherReloads() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+ r.reloadNow();
+
+ r.close();
+ r.trigger();
+ r.reloadNow();
+ Thread.sleep(100);
+
+ assertEquals(1, loader.calls.get());
+ assertEquals(1, handler.applied.size());
+ }
+
+ @Test
+ public void closeCancelsPendingRetry() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().thenFail("broken");
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, Duration.ofMillis(100));
+ r.reloadNow();
+
+ r.close();
+ Thread.sleep(300);
+
+ assertEquals(1, loader.calls.get());
+ }
+
+ @Test
+ public void closeIsIdempotent() {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1));
+ FileDataReloader r = reloader(loader, new RecordingHandler(), SHORT, SHORT);
+ r.trigger();
+ r.close();
+ r.close();
+ }
+
+ @Test
+ public void closeDoesNotWaitForInFlightReloadAndDropsItsResult() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1));
+ loader.entered = new CountDownLatch(1);
+ loader.release = new CountDownLatch(1);
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+
+ r.trigger();
+ assertTrue(loader.entered.await(WAIT_MILLIS, TimeUnit.MILLISECONDS));
+
+ long start = System.currentTimeMillis();
+ r.close();
+ assertThat(System.currentTimeMillis() - start, lessThan(1000L));
+
+ loader.release.countDown();
+ Thread.sleep(200);
+ assertTrue(handler.applied.isEmpty());
+ }
+
+ @Test
+ public void reloadTriggeredDuringReloadNowRunsAfterIt() throws Exception {
+ // Change detection can start before the initial load. A reload that it triggers while the
+ // initial load blocks in the loader must wait, and must apply after the initial load.
+ LoadResult initial = resultWithHash(1);
+ LoadResult changed = resultWithHash(2);
+ ScriptedLoader loader = new ScriptedLoader().then(initial).then(changed);
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ loader.entered = entered;
+ loader.release = release;
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+
+ Thread caller = new Thread(r::reloadNow);
+ caller.start();
+ assertTrue(entered.await(WAIT_MILLIS, TimeUnit.MILLISECONDS));
+ // The triggered load must not block.
+ loader.entered = null;
+ loader.release = null;
+
+ r.trigger();
+ Thread.sleep(150);
+ assertEquals(1, loader.calls.get());
+ assertTrue(handler.applied.isEmpty());
+
+ release.countDown();
+ caller.join(WAIT_MILLIS);
+ assertFalse(caller.isAlive());
+ awaitSize(handler.applied, 2);
+ assertEquals(Arrays.asList(initial, changed), handler.applied);
+ }
+
+ @Test
+ public void reloadsAreSerializedBetweenCallerAndWorker() throws Exception {
+ // The loader blocks on the worker thread. A synchronous reload from the caller must wait for
+ // it rather than run concurrently.
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).then(resultWithHash(2));
+ CountDownLatch entered = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ loader.entered = entered;
+ loader.release = release;
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+
+ r.trigger();
+ assertTrue(entered.await(WAIT_MILLIS, TimeUnit.MILLISECONDS));
+ // Later calls must not block.
+ loader.entered = null;
+ loader.release = null;
+
+ AtomicReference syncReloadFinished = new AtomicReference<>(false);
+ Thread caller = new Thread(() -> {
+ r.reloadNow();
+ syncReloadFinished.set(true);
+ });
+ caller.start();
+ Thread.sleep(150);
+ assertFalse(syncReloadFinished.get());
+ assertEquals(1, loader.calls.get());
+
+ release.countDown();
+ caller.join(WAIT_MILLIS);
+ assertTrue(syncReloadFinished.get());
+ assertEquals(2, loader.calls.get());
+ assertEquals(2, handler.applied.size());
+ }
+
+ @Test
+ public void applyThatThrowsIsReportedAsAFailureAndRetried() throws Exception {
+ LoadResult result = resultWithHash(1);
+ ScriptedLoader loader = new ScriptedLoader().then(result);
+ AtomicInteger applies = new AtomicInteger();
+ RecordingHandler handler = new RecordingHandler() {
+ @Override
+ public void apply(LoadResult r) {
+ if (applies.incrementAndGet() == 1) {
+ throw new IllegalStateException("consumer failed");
+ }
+ super.apply(r);
+ }
+ };
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+
+ // The initial load's apply throws. The reload returns normally and logs the failure.
+ r.reloadNow();
+ assertTrue(handler.applied.isEmpty());
+ assertEquals(Collections.singletonList("unable to apply flag data"
+ + " [java.lang.IllegalStateException: consumer failed]"), failures());
+
+ // The retry applies the same content without a further trigger.
+ awaitSize(handler.applied, 1);
+ assertEquals(result, handler.applied.get(0));
+
+ // Only now is the content remembered: a further reload of it is skipped.
+ r.trigger();
+ awaitAtLeast(loader.calls, 3);
+ assertEquals(1, handler.applied.size());
+ }
+
+ @Test
+ public void unexpectedRuntimeExceptionFromLoaderIsAFailureThatIsRetried() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().thenThrow(new IllegalStateException("loader failed"))
+ .then(resultWithHash(1));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+
+ r.reloadNow();
+
+ assertEquals(Collections.singletonList("unexpected error while loading flag data"
+ + " [java.lang.IllegalStateException: loader failed]"), failures());
+ assertEquals(SHORT.toNanos(), r.getLastRequestedRetryNanos());
+ // The retry loads again without a further trigger.
+ awaitSize(handler.applied, 1);
+ }
+
+ @Test
+ public void errorFromLoaderIsReportedAndArmsNoRetry() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().thenThrow(new OutOfMemoryError("simulated"))
+ .then(resultWithHash(1));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+
+ // The initial load does not throw the Error into the caller.
+ r.reloadNow();
+
+ assertEquals(Collections.singletonList("unexpected error while loading flag data"
+ + " [java.lang.OutOfMemoryError: simulated]"), failures());
+ assertEquals(-1, r.getLastRequestedRetryNanos());
+ Thread.sleep(SHORT.toMillis() * 4);
+ assertEquals(1, loader.calls.get());
+
+ // The next change signal loads the files again.
+ r.trigger();
+ awaitSize(handler.applied, 1);
+ }
+
+ @Test
+ public void errorFromHandlerIsReportedAndArmsNoRetry() throws Exception {
+ LoadResult result = resultWithHash(1);
+ ScriptedLoader loader = new ScriptedLoader().then(result);
+ AtomicInteger applies = new AtomicInteger();
+ RecordingHandler handler = new RecordingHandler() {
+ @Override
+ public void apply(LoadResult r) {
+ if (applies.incrementAndGet() == 1) {
+ throw new OutOfMemoryError("simulated");
+ }
+ super.apply(r);
+ }
+ };
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+
+ // A triggered reload runs on the executor, where an Error would otherwise end in a future that
+ // nothing reads.
+ r.trigger();
+ awaitFailures(1);
+ assertEquals(Collections.singletonList("unable to apply flag data"
+ + " [java.lang.OutOfMemoryError: simulated]"), failures());
+ Thread.sleep(SHORT.toMillis() * 4);
+ assertEquals(1, loader.calls.get());
+ assertEquals(-1, r.getLastRequestedRetryNanos());
+
+ r.trigger();
+ awaitSize(handler.applied, 1);
+ assertEquals(result, handler.applied.get(0));
+ }
+
+ @Test
+ public void runtimeExceptionThatEscapesAReloadIsLoggedAndTheWorkerSurvives() throws Exception {
+ escapingThrowableIsLoggedAndTheWorkerSurvives(new IllegalStateException("accepted failed"));
+ }
+
+ @Test
+ public void errorThatEscapesAReloadIsLoggedAndTheWorkerSurvives() throws Exception {
+ escapingThrowableIsLoggedAndTheWorkerSurvives(new LinkageError("accepted failed"));
+ }
+
+ // The loader's accepted callback throws, so the throwable leaves the reload itself.
+ private void escapingThrowableIsLoggedAndTheWorkerSurvives(Throwable thrown) throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).then(resultWithHash(2));
+ loader.throwOnAccepted = thrown;
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+
+ r.trigger();
+ awaitSize(handler.applied, 1);
+ // The worker still runs the next reload, and the throwable was logged.
+ r.trigger();
+ awaitSize(handler.applied, 2);
+ assertThat(logCapture.getMessageStrings(),
+ hasItem(startsWith("ERROR:Unexpected error while reloading flag data:")));
+ }
+
+ private static final Path EMPTIED = Paths.get("/overrides/emptied.yaml");
+ private static final String READ_AGAIN_MESSAGE = "DEBUG:File " + EMPTIED
+ + " is empty, possibly while it is being rewritten; reading it again before applying it";
+
+ @Test
+ public void emptiedFileIsReadAgainAfterTheRetryDelayWithoutReportingAFailure() throws Exception {
+ LoadResult first = resultWithHash(1);
+ LoadResult rewritten = resultWithHash(2);
+ ScriptedLoader loader = new ScriptedLoader().then(first).thenEmptied(EMPTIED).then(rewritten);
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+ r.reloadNow();
+
+ // The load that finds the file emptied applies nothing. Only the retry, with no further
+ // trigger, loads again.
+ r.trigger();
+ awaitSize(handler.applied, 2);
+
+ assertEquals(first, handler.applied.get(0));
+ assertEquals(rewritten, handler.applied.get(1));
+ assertEquals(3, loader.calls.get());
+ List messages = logCapture.getMessageStrings();
+ assertThat(messages, hasItem(READ_AGAIN_MESSAGE));
+ assertThat(messages, hasItem("DEBUG:Reading flag data again after a file was found empty"));
+ assertThat(messages, not(hasItem("DEBUG:Retrying flag data load after earlier failure")));
+ for (String message : messages) {
+ assertFalse(message, message.startsWith("ERROR:"));
+ }
+ }
+
+ @Test
+ public void retryIsTheOneThatTheLatestLoadAsksFor() throws Exception {
+ // The first load fails and arms a retry after the retry delay, which does not come in this test.
+ // The next load holds back an emptied file and asks for a retry much sooner, and gets it.
+ LoadResult rewritten = resultWithHash(1);
+ ScriptedLoader loader = new ScriptedLoader().thenFail("broken").thenEmptied(EMPTIED, Duration.ofMillis(30))
+ .then(rewritten);
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+ r.reloadNow();
+ r.reloadNow();
+
+ awaitSize(handler.applied, 1);
+ assertEquals(rewritten, handler.applied.get(0));
+ assertEquals(3, loader.calls.get());
+ }
+
+ @Test
+ public void loadThatSucceedsCancelsTheRetryThatAnEarlierLoadArmed() throws Exception {
+ // That load read every file again, so the retry has nothing left to do.
+ Duration retryDelay = Duration.ofMillis(200);
+ ScriptedLoader loader = new ScriptedLoader().thenFail("broken").then(resultWithHash(1));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, retryDelay);
+ r.reloadNow();
+ r.reloadNow();
+ assertEquals(1, handler.applied.size());
+
+ Thread.sleep(retryDelay.toMillis() * 3);
+ assertEquals(2, loader.calls.get());
+ }
+
+ @Test
+ public void holdIsRetriedAfterTheTimeTheLoaderAsksFor() throws Exception {
+ // The loader asks for a retry sooner than the retry delay, which would not come in this test.
+ LoadResult rewritten = resultWithHash(2);
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).thenEmptied(EMPTIED, Duration.ofMillis(30))
+ .then(rewritten);
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+ r.reloadNow();
+
+ r.trigger();
+ awaitSize(handler.applied, 2);
+ assertEquals(rewritten, handler.applied.get(1));
+ assertEquals(3, loader.calls.get());
+ assertEquals(Duration.ofMillis(30).toNanos(), r.getLastRequestedRetryNanos());
+ }
+
+ @Test
+ public void failureAfterAHoldIsRetriedAfterTheRetryDelay() throws Exception {
+ // A hold asks for a retry soon. The failure that follows arms the normal retry delay, which does
+ // not come in this test.
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).thenEmptied(EMPTIED, Duration.ofMillis(30))
+ .thenFail("broken").then(resultWithHash(2));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+ r.reloadNow();
+
+ r.trigger();
+ awaitFailures(1);
+ Thread.sleep(300);
+ assertEquals(3, loader.calls.get());
+ assertEquals(1, handler.applied.size());
+ assertEquals(HOUR.toNanos(), r.getLastRequestedRetryNanos());
+ }
+
+ @Test
+ public void loaderIsGivenTheRetryDelay() {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1));
+ reloader(loader, new RecordingHandler(), Duration.ZERO, SHORT).reloadNow();
+ assertEquals(Collections.singletonList(SHORT), loader.retryDelayArguments);
+ }
+
+ @Test
+ public void loaderIsToldOfEveryResultThatBecomesTheDataInEffect() throws Exception {
+ // An applied result and a result skipped as unchanged are the data in effect. A failure, a
+ // deferral and a result that the consumer rejects are not.
+ LoadResult first = resultWithHash(1);
+ LoadResult unchanged = resultWithHash(1);
+ LoadResult rejected = resultWithHash(2);
+ LoadResult last = resultWithHash(3);
+ ScriptedLoader loader = new ScriptedLoader().then(first).then(unchanged).thenFail("broken")
+ .thenEmptied(EMPTIED).then(rejected).then(last);
+ RecordingHandler handler = new RecordingHandler() {
+ @Override
+ public void apply(LoadResult r) {
+ if (r == rejected) {
+ throw new IllegalStateException("consumer failed");
+ }
+ super.apply(r);
+ }
+ };
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, HOUR);
+ r.reloadNow();
+ for (int i = 2; i <= 6; i++) {
+ r.trigger();
+ awaitAtLeast(loader.calls, i);
+ }
+ awaitSize(loader.accepted, 3);
+
+ assertEquals(Arrays.asList(first, unchanged, last), loader.accepted);
+ assertEquals(Arrays.asList(first, last), handler.applied);
+ }
+
+ @Test
+ public void failureAfterAReadAgainIsRetriedAsAFailure() throws Exception {
+ ScriptedLoader loader = new ScriptedLoader().then(resultWithHash(1)).thenEmptied(EMPTIED).thenFail("broken")
+ .then(resultWithHash(2));
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+ r.reloadNow();
+
+ r.trigger();
+ awaitSize(handler.applied, 2);
+ assertEquals(4, loader.calls.get());
+ assertEquals(1, failures().size());
+ List messages = logCapture.getMessageStrings();
+ assertThat(messages, hasItem("DEBUG:Reading flag data again after a file was found empty"));
+ assertThat(messages, hasItem("DEBUG:Retrying flag data load after earlier failure"));
+ }
+
+ @Test
+ public void readingAnEmptiedFileAgainDoesNotEndARecovery() throws Exception {
+ // After a failure, the next success applies even when its content is unchanged. A read again
+ // in between is not that success.
+ LoadResult result = resultWithHash(1);
+ ScriptedLoader loader = new ScriptedLoader().then(result).thenFail("broken").thenEmptied(EMPTIED).then(result);
+ RecordingHandler handler = new RecordingHandler();
+ FileDataReloader r = reloader(loader, handler, Duration.ZERO, SHORT);
+ r.reloadNow();
+
+ r.trigger();
+ awaitSize(handler.applied, 2);
+ assertEquals(4, loader.calls.get());
+ assertEquals(1, failures().size());
+ assertThat(logCapture.getMessageStrings(), hasItem(READ_AGAIN_MESSAGE));
+ }
+}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataWatcherTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataWatcherTest.java
new file mode 100644
index 00000000..d940bd30
--- /dev/null
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileDataWatcherTest.java
@@ -0,0 +1,696 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.launchdarkly.logging.LDLogLevel;
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.logging.LogCapture;
+import com.launchdarkly.logging.Logs;
+import com.launchdarkly.testhelpers.TempDir;
+
+import org.junit.Test;
+
+import java.io.IOException;
+import java.nio.file.ClosedWatchServiceException;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.WatchEvent;
+import java.nio.file.WatchKey;
+import java.nio.file.WatchService;
+import java.nio.file.Watchable;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Supplier;
+
+import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
+import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
+import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assume.assumeTrue;
+
+@SuppressWarnings("javadoc")
+public class FileDataWatcherTest {
+ private static final LDLogger testLogger = LDLogger.none();
+ private static final long WAIT_MILLIS = 10000;
+ private static final long QUIET_MILLIS = 300;
+ private static final Duration DIRECTORY_RETRY = Duration.ofMillis(50);
+
+ private static void awaitAtLeast(AtomicInteger counter, int expected) throws InterruptedException {
+ awaitAtLeast(counter, expected, "change signals");
+ }
+
+ private static void awaitAtLeast(AtomicInteger counter, int expected, String what) throws InterruptedException {
+ long deadline = System.currentTimeMillis() + WAIT_MILLIS;
+ while (counter.get() < expected) {
+ if (System.currentTimeMillis() > deadline) {
+ throw new AssertionError("timed out waiting for " + expected + " " + what + ", got " + counter.get());
+ }
+ Thread.sleep(10);
+ }
+ }
+
+ private static WatchKey register(Path directory, WatchService watchService) throws IOException {
+ return directory.register(watchService, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
+ }
+
+ // Creates a symbolic link, or skips the test where the platform or the account cannot create one,
+ // as on Windows without the privilege.
+ private static void link(Path link, Path target) {
+ try {
+ Files.createSymbolicLink(link, target);
+ } catch (IOException | UnsupportedOperationException | SecurityException e) {
+ assumeTrue("symbolic links are not available: " + e, false);
+ }
+ }
+
+ // Points a link at a new target in one operation, as a ConfigMap update swaps its ..data link.
+ private static void swapLink(Path link, Path newTarget) throws IOException {
+ Path temporary = link.resolveSibling(link.getFileName() + "_tmp");
+ Files.createSymbolicLink(temporary, newTarget);
+ Files.move(temporary, link, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
+ }
+
+ private static void deleteTree(Path directory) throws IOException {
+ try (java.util.stream.Stream paths = Files.walk(directory)) {
+ for (Path p : (Iterable) paths.sorted(java.util.Comparator.reverseOrder())::iterator) {
+ Files.delete(p);
+ }
+ }
+ }
+
+ @Test
+ public void startSignalsOnceSoThatAChangeBeforeWatchingIsNotMissed() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = dir.getPath().resolve("a.json");
+ Files.write(file, "{}".getBytes());
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.NORM_PRIORITY, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+ assertEquals(1, changes.get());
+ }
+ }
+ }
+
+ @Test
+ public void workerThreadHasTheConfiguredPriority() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = dir.getPath().resolve("a.json");
+ Files.write(file, "{}".getBytes());
+ AtomicInteger changes = new AtomicInteger();
+ AtomicReference signalled = new AtomicReference<>();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.MIN_PRIORITY,
+ testLogger)) {
+ watcher.start(() -> {
+ signalled.set(Thread.currentThread());
+ changes.incrementAndGet();
+ });
+ // Start signals once on the calling thread; a change is signalled on the worker thread.
+ awaitAtLeast(changes, 1);
+ Files.write(file, "{\"flags\":{}}".getBytes());
+ awaitAtLeast(changes, 2);
+ assertEquals(Thread.MIN_PRIORITY, signalled.get().getPriority());
+ }
+ }
+ }
+
+ @Test
+ public void modifiedFileSignalsChange() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = dir.getPath().resolve("a.json");
+ Files.write(file, "{}".getBytes());
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.NORM_PRIORITY, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ Files.write(file, "{\"flagValues\":{}}".getBytes());
+ awaitAtLeast(changes, 2);
+ }
+ }
+ }
+
+ @Test
+ public void fileThatDoesNotExistYetSignalsChangeWhenItAppears() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = dir.getPath().resolve("later.json");
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.NORM_PRIORITY, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ Files.write(file, "{}".getBytes());
+ awaitAtLeast(changes, 2);
+ }
+ }
+ }
+
+ @Test
+ public void deletedFileSignalsChange() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = dir.getPath().resolve("a.json");
+ Files.write(file, "{}".getBytes());
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.NORM_PRIORITY, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ Files.delete(file);
+ awaitAtLeast(changes, 2);
+ }
+ }
+ }
+
+ @Test
+ public void unrelatedFileInSameDirectoryDoesNotSignal() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = dir.getPath().resolve("a.json");
+ Files.write(file, "{}".getBytes());
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.NORM_PRIORITY, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ Files.write(dir.getPath().resolve("other.json"), "{}".getBytes());
+ Thread.sleep(QUIET_MILLIS);
+ assertEquals(1, changes.get());
+ }
+ }
+ }
+
+ @Test
+ public void configMapUpdateThatSwapsTheDataLinkSignalsChange() throws Exception {
+ // The layout of a mounted ConfigMap: the file is a link through ..data, which links to a
+ // versioned directory. An update writes a new directory, swaps ..data to it, and deletes the
+ // old one, so no event names the configured file.
+ LogCapture logCapture = Logs.capture();
+ LDLogger logger = LDLogger.withAdapter(logCapture, "");
+ try (TempDir dir = TempDir.create()) {
+ Path mount = dir.getPath();
+ Path v1 = Files.createDirectory(mount.resolve("..v1"));
+ Files.write(v1.resolve("a.json"), "{}".getBytes());
+ link(mount.resolve("..data"), mount.resolve("..v1").getFileName());
+ Path file = mount.resolve("a.json");
+ link(file, mount.resolve("..data").getFileName().resolve("a.json"));
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), DIRECTORY_RETRY, logger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ Path v2 = Files.createDirectory(mount.resolve("..v2"));
+ Files.write(v2.resolve("a.json"), "{\"flagValues\":{}}".getBytes());
+ swapLink(mount.resolve("..data"), v2.getFileName());
+ deleteTree(v1);
+ awaitAtLeast(changes, 2);
+ Thread.sleep(QUIET_MILLIS);
+
+ // The deleted version directory is not reported as a lost directory.
+ long warnings = logCapture.getMessages().stream().filter(m -> m.getLevel() == LDLogLevel.WARN).count();
+ assertEquals(0, warnings);
+ }
+ }
+ }
+
+ @Test
+ public void changeToALinkTargetInAnotherDirectorySignalsChange() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path configured = Files.createDirectory(dir.getPath().resolve("configured"));
+ Path other = Files.createDirectory(dir.getPath().resolve("other"));
+ Path target = other.resolve("a.json");
+ Files.write(target, "{}".getBytes());
+ Path file = configured.resolve("a.json");
+ link(file, target);
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.NORM_PRIORITY, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ Files.write(target, "{\"flagValues\":{}}".getBytes());
+ awaitAtLeast(changes, 2);
+ Thread.sleep(QUIET_MILLIS);
+ int afterEdit = changes.get();
+
+ // An unrelated file next to the target costs no reload.
+ Files.write(other.resolve("unrelated.json"), "{}".getBytes());
+ Thread.sleep(QUIET_MILLIS);
+ assertEquals(afterEdit, changes.get());
+ }
+ }
+ }
+
+ @Test
+ public void linkPointedAtAFileInAnotherDirectoryIsFollowedThere() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path configured = Files.createDirectory(dir.getPath().resolve("configured"));
+ Path first = Files.createDirectory(dir.getPath().resolve("first"));
+ Path second = Files.createDirectory(dir.getPath().resolve("second"));
+ Files.write(first.resolve("a.json"), "{}".getBytes());
+ Files.write(second.resolve("a.json"), "{\"flagValues\":{}}".getBytes());
+ Path file = configured.resolve("a.json");
+ link(file, first.resolve("a.json"));
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.NORM_PRIORITY, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ swapLink(file, second.resolve("a.json"));
+ awaitAtLeast(changes, 2);
+ Thread.sleep(QUIET_MILLIS);
+ int afterSwap = changes.get();
+
+ // The new target's directory is watched now.
+ Files.write(second.resolve("a.json"), "{\"flagValues\":{\"f\":true}}".getBytes());
+ awaitAtLeast(changes, afterSwap + 1);
+ }
+ }
+ }
+
+ @Test
+ public void directoryThatALinkWasPointedAwayFromIsNoLongerWatched() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path configured = Files.createDirectory(dir.getPath().resolve("configured"));
+ Path first = Files.createDirectory(dir.getPath().resolve("first"));
+ Path second = Files.createDirectory(dir.getPath().resolve("second"));
+ Files.write(first.resolve("a.json"), "{}".getBytes());
+ Files.write(second.resolve("a.json"), "{}".getBytes());
+ Path file = configured.resolve("a.json");
+ link(file, first.resolve("a.json"));
+ Map keys = new ConcurrentHashMap<>();
+ FileDataWatcher.Registrar registrar = (directory, watchService) -> {
+ WatchKey key = register(directory, watchService);
+ keys.put(directory, key);
+ return key;
+ };
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), DIRECTORY_RETRY,
+ FileSystems.getDefault().newWatchService(), registrar, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+ WatchKey firstKey = keys.get(first.toRealPath());
+ assertTrue(firstKey.isValid());
+
+ swapLink(file, second.resolve("a.json"));
+ awaitAtLeast(changes, 2);
+
+ // The first directory holds no target now, so its watch is cancelled. The second one is watched.
+ assertFalse(firstKey.isValid());
+ assertTrue(keys.get(second.toRealPath()).isValid());
+ }
+ }
+ }
+
+ @Test
+ public void configuredDirectoryThatALinkLeadsIntoThroughAnotherPathStaysWatched() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path real = Files.createDirectory(dir.getPath().resolve("real"));
+ Path other = Files.createDirectory(dir.getPath().resolve("other"));
+ Files.write(real.resolve("b.json"), "{}".getBytes());
+ Files.write(other.resolve("c.json"), "{}".getBytes());
+ Files.write(other.resolve("d.json"), "{}".getBytes());
+ Path configured = dir.getPath().resolve("configured");
+ link(configured, real);
+ // The configured directory is reached through a link, and the configured file leads to a file
+ // next to it. The watch service returns the configured directory's key for the target's directory.
+ Path file = configured.resolve("a.json");
+ link(file, real.resolve("b.json"));
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.NORM_PRIORITY,
+ testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ // Pointing the link away from that directory must not cancel the watch on the configured directory.
+ swapLink(file, other.resolve("c.json"));
+ awaitAtLeast(changes, 2);
+ Thread.sleep(QUIET_MILLIS);
+ int afterSwap = changes.get();
+
+ swapLink(file, other.resolve("d.json"));
+ awaitAtLeast(changes, afterSwap + 1);
+ }
+ }
+ }
+
+ @Test
+ public void relativePathIsWatchedByItsAbsoluteLocation() throws Exception {
+ // The watcher must compare the directory-relative event name against the same absolute form
+ // it registered, whatever form the caller used.
+ try (TempDir dir = TempDir.create()) {
+ Path file = dir.getPath().resolve("sub").resolve("..").resolve("a.json");
+ Files.createDirectories(dir.getPath().resolve("sub"));
+ Files.write(file, "{}".getBytes());
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.NORM_PRIORITY, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ Files.write(file, "{\"flagValues\":{}}".getBytes());
+ awaitAtLeast(changes, 2);
+ }
+ }
+ }
+
+ @Test
+ public void deletedAndRecreatedDirectoryIsWatchedAgain() throws Exception {
+ LogCapture logCapture = Logs.capture();
+ LDLogger logger = LDLogger.withAdapter(logCapture, "");
+ try (TempDir dir = TempDir.create()) {
+ Path sub = dir.getPath().resolve("sub");
+ Files.createDirectory(sub);
+ Path file = sub.resolve("a.json");
+ Files.write(file, "{}".getBytes());
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), DIRECTORY_RETRY, logger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ // Delete the file and then its directory, and let the deletion notifications settle.
+ Files.delete(file);
+ Files.delete(sub);
+ awaitAtLeast(changes, 2);
+ Thread.sleep(QUIET_MILLIS);
+ int afterDeletion = changes.get();
+
+ // A file written into the recreated directory must be reported.
+ Files.createDirectory(sub);
+ Files.write(file, "{\"flagValues\":{}}".getBytes());
+ awaitAtLeast(changes, afterDeletion + 1);
+
+ // The lost directory is reported once, not on every registration attempt.
+ long warnings = logCapture.getMessages().stream().filter(m -> m.getLevel() == LDLogLevel.WARN).count();
+ assertEquals(1, warnings);
+ }
+ }
+ }
+
+ // On macOS the JDK's watch service examines each directory on an interval. When a directory is
+ // gone, it cancels the key and signals it with no events, also for the files that were in it. The
+ // scripted watch service delivers such a key, so these tests run the same way on every platform.
+
+ @Test
+ public void configuredDirectoryGoneWithItsFileSignalsChangeWhenItsKeyHasNoEvents() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path sub = Files.createDirectory(dir.getPath().resolve("sub"));
+ Path file = sub.resolve("a.json");
+ Files.write(file, "{}".getBytes());
+ ScriptedWatchService watchService = new ScriptedWatchService();
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), DIRECTORY_RETRY,
+ watchService, watchService.registrar(), testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+
+ Files.delete(file);
+ Files.delete(sub);
+ watchService.signalGone(sub);
+ // The file is gone, so a reload must remove its overrides.
+ awaitAtLeast(changes, 2);
+
+ // The directory is registered again once it exists.
+ Files.createDirectory(sub);
+ Files.write(file, "{}".getBytes());
+ awaitAtLeast(changes, 3);
+ }
+ }
+ }
+
+ @Test
+ public void configuredDirectoryGoneWithoutTheFileDoesNotSignal() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path sub = Files.createDirectory(dir.getPath().resolve("sub"));
+ Path file = sub.resolve("a.json");
+ ScriptedWatchService watchService = new ScriptedWatchService();
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), DIRECTORY_RETRY,
+ watchService, watchService.registrar(), testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+
+ Files.delete(sub);
+ watchService.signalGone(sub);
+ // The worker handled the key once it tries to register the directory again.
+ int attemptsBefore = watchService.registrationAttempts.get();
+ awaitAtLeast(watchService.registrationAttempts, attemptsBefore + 1, "registration attempts");
+ // The file did not exist before, so nothing changed that needs a reload.
+ assertEquals(1, changes.get());
+ }
+ }
+ }
+
+ // A watch service that signals a key only when the test says that its directory is gone.
+ private static final class ScriptedWatchService implements WatchService {
+ final AtomicInteger registrationAttempts = new AtomicInteger();
+ private final Map keys = new ConcurrentHashMap<>();
+ private final LinkedBlockingQueue signalled = new LinkedBlockingQueue<>();
+ private volatile boolean closed;
+
+ // Registers like the real watch service: a directory that does not exist cannot be registered.
+ FileDataWatcher.Registrar registrar() {
+ return (directory, watchService) -> {
+ registrationAttempts.incrementAndGet();
+ if (!Files.isDirectory(directory)) {
+ throw new NoSuchFileException(directory.toString());
+ }
+ ScriptedKey key = new ScriptedKey(directory);
+ keys.put(directory, key);
+ return key;
+ };
+ }
+
+ void signalGone(Path directory) {
+ ScriptedKey key = keys.get(directory.toAbsolutePath().normalize());
+ assertNotNull("directory is not registered: " + directory, key);
+ key.cancel();
+ signalled.add(key);
+ }
+
+ @Override
+ public void close() {
+ closed = true;
+ }
+
+ @Override
+ public WatchKey poll() {
+ checkOpen();
+ return signalled.poll();
+ }
+
+ @Override
+ public WatchKey poll(long timeout, TimeUnit unit) throws InterruptedException {
+ checkOpen();
+ return signalled.poll(timeout, unit);
+ }
+
+ @Override
+ public WatchKey take() throws InterruptedException {
+ checkOpen();
+ return signalled.take();
+ }
+
+ private void checkOpen() {
+ if (closed) {
+ throw new ClosedWatchServiceException();
+ }
+ }
+ }
+
+ private static final class ScriptedKey implements WatchKey {
+ private final Path directory;
+ private volatile boolean valid = true;
+
+ ScriptedKey(Path directory) {
+ this.directory = directory;
+ }
+
+ @Override
+ public boolean isValid() {
+ return valid;
+ }
+
+ @Override
+ public List> pollEvents() {
+ return Collections.emptyList();
+ }
+
+ @Override
+ public boolean reset() {
+ return valid;
+ }
+
+ @Override
+ public void cancel() {
+ valid = false;
+ }
+
+ @Override
+ public Watchable watchable() {
+ return directory;
+ }
+ }
+
+ @Test
+ public void directoryMissingAtStartIsWatchedOnceItExists() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path sub = dir.getPath().resolve("later");
+ Path file = sub.resolve("a.json");
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), DIRECTORY_RETRY, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ // Create the directory and write the file into it.
+ Files.createDirectory(sub);
+ Files.write(file, "{}".getBytes());
+ // The file is reported even though its directory did not exist when watching began.
+ awaitAtLeast(changes, 2);
+ }
+ }
+ }
+
+ @Test
+ public void exceptionFromARegistrationAttemptIsRetriedOnTheSchedule() throws Exception {
+ // A directory that cannot be registered is not watched yet, as when it does not exist. That is
+ // not an unexpected error, and each attempt is not logged again.
+ LogCapture logCapture = Logs.capture();
+ retryOfAMissingDirectorySurvives(() -> new SecurityException("access denied"), LDLogger.withAdapter(logCapture, ""));
+ assertFalse(logCapture.getMessages().stream().anyMatch(m -> m.getLevel() == LDLogLevel.ERROR));
+ }
+
+ @Test
+ public void errorFromARegistrationAttemptIsLoggedAndRetriedOnTheSchedule() throws Exception {
+ // An Error passes every handler for a failed registration and reaches the worker's last guard.
+ LogCapture logCapture = Logs.capture();
+ retryOfAMissingDirectorySurvives(() -> new Error("simulated"), LDLogger.withAdapter(logCapture, ""));
+ assertTrue(logCapture.getMessages().stream().anyMatch(m -> m.getLevel() == LDLogLevel.ERROR
+ && m.getText().contains("Unexpected error while watching files for changes")));
+ }
+
+ // A missing directory is created, but registering it fails until the test allows it. The worker
+ // must keep trying on its schedule, not stop and not try again at once, and then watch it.
+ private static void retryOfAMissingDirectorySurvives(Supplier failure, LDLogger logger)
+ throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path sub = dir.getPath().resolve("later");
+ Path file = sub.resolve("a.json");
+ AtomicBoolean denied = new AtomicBoolean(true);
+ AtomicInteger deniedAttempts = new AtomicInteger();
+ FileDataWatcher.Registrar registrar = (directory, watchService) -> {
+ if (Files.isDirectory(directory) && denied.get()) {
+ deniedAttempts.incrementAndGet();
+ Throwable t = failure.get();
+ if (t instanceof Error) {
+ throw (Error) t;
+ }
+ throw (RuntimeException) t;
+ }
+ return register(directory, watchService);
+ };
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), DIRECTORY_RETRY,
+ FileSystems.getDefault().newWatchService(), registrar, logger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+
+ Files.createDirectory(sub);
+ awaitAtLeast(deniedAttempts, 3, "registration attempts");
+ Thread.sleep(QUIET_MILLIS);
+ // About one attempt for each retry delay. An attempt repeated at once would make thousands.
+ int attempts = deniedAttempts.get();
+ assertTrue("attempts: " + attempts, attempts < 50);
+
+ denied.set(false);
+ Files.write(file, "{}".getBytes());
+ awaitAtLeast(changes, 2);
+ }
+ }
+ }
+
+ @Test
+ public void linkTargetDirectoryThatCannotBeWatchedDoesNotStopWatching() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path conf = Files.createDirectory(dir.getPath().resolve("conf"));
+ Path data = Files.createDirectory(dir.getPath().resolve("data"));
+ Files.write(data.resolve("a.json"), "{}".getBytes());
+ Files.write(data.resolve("b.json"), "{}".getBytes());
+ Path file = conf.resolve("a.json");
+ link(file, data.resolve("a.json"));
+ Path deniedDirectory = data.toRealPath();
+ FileDataWatcher.Registrar registrar = (directory, watchService) -> {
+ if (directory.equals(deniedDirectory)) {
+ throw new SecurityException("access denied");
+ }
+ return register(directory, watchService);
+ };
+ AtomicInteger changes = new AtomicInteger();
+ try (FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), DIRECTORY_RETRY,
+ FileSystems.getDefault().newWatchService(), registrar, testLogger)) {
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ Thread.sleep(QUIET_MILLIS);
+
+ // The configured directory is still watched, so pointing the link at another file is reported.
+ swapLink(file, data.resolve("b.json"));
+ awaitAtLeast(changes, 2);
+ }
+ }
+ }
+
+ @Test
+ public void closeEndsTheWorkerWhileADirectoryIsMissing() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = dir.getPath().resolve("later").resolve("a.json");
+ AtomicInteger changes = new AtomicInteger();
+ FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), DIRECTORY_RETRY, testLogger);
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+
+ // Close while the worker is waiting for its next registration attempt.
+ watcher.close();
+ // The worker must end instead of continuing to retry.
+ assertTrue(watcher.awaitStop(WAIT_MILLIS));
+ }
+ }
+
+ @Test
+ public void closeStopsSignalsAndIsIdempotent() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = dir.getPath().resolve("a.json");
+ Files.write(file, "{}".getBytes());
+ AtomicInteger changes = new AtomicInteger();
+ FileDataWatcher watcher = FileDataWatcher.create(Collections.singletonList(file), Thread.NORM_PRIORITY, testLogger);
+ watcher.start(changes::incrementAndGet);
+ awaitAtLeast(changes, 1);
+ watcher.close();
+ watcher.close();
+
+ Files.write(file, "{\"flagValues\":{}}".getBytes());
+ Thread.sleep(QUIET_MILLIS);
+ assertEquals(1, changes.get());
+ }
+ }
+}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileSynchronizerReloadBehaviorTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileSynchronizerReloadBehaviorTest.java
new file mode 100644
index 00000000..a1c7d2ad
--- /dev/null
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FileSynchronizerReloadBehaviorTest.java
@@ -0,0 +1,198 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.launchdarkly.logging.LDLogLevel;
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.logging.LogCapture;
+import com.launchdarkly.logging.Logs;
+import com.launchdarkly.sdk.fdv2.SourceResultType;
+import com.launchdarkly.sdk.fdv2.SourceSignal;
+import com.launchdarkly.sdk.server.datasources.FDv2SourceResult;
+import com.launchdarkly.sdk.server.datasources.Synchronizer;
+import com.launchdarkly.sdk.server.interfaces.DataSourceStatusProvider.ErrorKind;
+import com.launchdarkly.testhelpers.TempDir;
+import com.launchdarkly.testhelpers.TempFile;
+
+import org.junit.Test;
+
+import java.util.List;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import static com.launchdarkly.sdk.server.integrations.FileDataSourceTestData.getResourceContents;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.greaterThanOrEqualTo;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.fail;
+
+/**
+ * Pins the reload behavior of the file data source's synchronizer: it reloads on every file system
+ * event, reports every failed load, does not retry on its own, and logs a failure as the plain
+ * description at error level. The override source has different rules and its own tests.
+ */
+@SuppressWarnings("javadoc")
+public class FileSynchronizerReloadBehaviorTest {
+ private static final long CHANGE_TIMEOUT_SECONDS = 15;
+ private static final String MALFORMED = "{\"flags\"";
+
+ private final LogCapture logCapture = Logs.capture();
+ private final LDLogger logger = LDLogger.withAdapter(logCapture, "");
+
+ private Synchronizer autoUpdatingSynchronizer(TempFile file) {
+ return FileData.synchronizer()
+ .filePaths(file.getPath())
+ .autoUpdate(true)
+ .build(TestDataSourceBuildInputs.create(logger));
+ }
+
+ private static FDv2SourceResult await(CompletableFuture future) throws Exception {
+ return future.get(CHANGE_TIMEOUT_SECONDS, TimeUnit.SECONDS);
+ }
+
+ // Consumes results until none arrives for a short quiet period, then returns the one future that is
+ // still outstanding. A single edit can produce more than one file system event, and the synchronizer
+ // reloads on each of them. Only one next() future is ever left outstanding, because the queue
+ // delivers each result to the oldest waiting future, and a forgotten one would swallow a result.
+ private static CompletableFuture settle(Synchronizer synchronizer) throws Exception {
+ CompletableFuture pending = synchronizer.next();
+ while (true) {
+ try {
+ pending.get(500, TimeUnit.MILLISECONDS);
+ pending = synchronizer.next();
+ } catch (TimeoutException e) {
+ return pending;
+ }
+ }
+ }
+
+ private void awaitErrorMessages(int atLeast) throws Exception {
+ long deadline = System.currentTimeMillis() + CHANGE_TIMEOUT_SECONDS * 1000;
+ while (errorMessages().size() < atLeast) {
+ if (System.currentTimeMillis() > deadline) {
+ fail("expected at least " + atLeast + " error logs but saw " + errorMessages());
+ }
+ Thread.sleep(50);
+ }
+ }
+
+ private List errorMessages() {
+ List out = new java.util.ArrayList<>();
+ for (LogCapture.Message m : logCapture.getMessages()) {
+ if (m.getLevel() == LDLogLevel.ERROR) {
+ out.add(m.getText());
+ }
+ }
+ return out;
+ }
+
+ @Test
+ public void rewriteWithIdenticalContentEmitsAnotherChangeSet() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ try (TempFile file = dir.tempFile(".json")) {
+ String contents = getResourceContents("flag-only.json");
+ file.setContents(contents);
+ try (Synchronizer synchronizer = autoUpdatingSynchronizer(file)) {
+ assertThat(await(synchronizer.next()).getResultType(), equalTo(SourceResultType.CHANGE_SET));
+
+ CompletableFuture next = synchronizer.next();
+ Thread.sleep(200); // let the watcher register before the change
+ file.setContents(contents); // same bytes, new modification time
+
+ // The content did not change, and the synchronizer still delivers a new change set.
+ assertThat(await(next).getResultType(), equalTo(SourceResultType.CHANGE_SET));
+ }
+ }
+ }
+ }
+
+ @Test
+ public void everyFailedReloadIsReportedAndLoggedAsThePlainDescription() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ try (TempFile file = dir.tempFile(".json")) {
+ file.setContents(getResourceContents("flag-only.json"));
+ try (Synchronizer synchronizer = autoUpdatingSynchronizer(file)) {
+ assertThat(await(synchronizer.next()).getResultType(), equalTo(SourceResultType.CHANGE_SET));
+
+ CompletableFuture next = synchronizer.next();
+ Thread.sleep(200);
+ file.setContents(MALFORMED);
+ FDv2SourceResult first = await(next);
+ assertThat(first.getResultType(), equalTo(SourceResultType.STATUS));
+ assertThat(first.getStatus().getState(), equalTo(SourceSignal.INTERRUPTED));
+ assertThat(first.getStatus().getErrorInfo().getKind(), equalTo(ErrorKind.INVALID_DATA));
+ CompletableFuture pending = settle(synchronizer);
+ int errorsAfterFirstFailure = errorMessages().size();
+
+ // The same malformed content again is the same failure. It is reported again, not deduplicated.
+ file.setContents(MALFORMED);
+ FDv2SourceResult second = await(pending);
+ assertThat(second.getResultType(), equalTo(SourceResultType.STATUS));
+ assertThat(second.getStatus().getState(), equalTo(SourceSignal.INTERRUPTED));
+ assertEquals(first.getStatus().getErrorInfo().getMessage(), second.getStatus().getErrorInfo().getMessage());
+ awaitErrorMessages(errorsAfterFirstFailure + 1);
+
+ // Each failure is logged at error level as the plain description: the parser's problem and
+ // its position. There is no prefix, and the description does not name the file.
+ List errors = errorMessages();
+ assertThat(errors.size(), greaterThanOrEqualTo(2));
+ for (String message : errors) {
+ assertEquals("cannot parse JSON: End of input (line 1, column 9)", message);
+ }
+ assertEquals(errors.get(0), first.getStatus().getErrorInfo().getMessage());
+ }
+ }
+ }
+ }
+
+ @Test
+ public void failedReloadIsNotRetriedWithoutAFileChange() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ try (TempFile file = dir.tempFile(".json")) {
+ file.setContents(getResourceContents("flag-only.json"));
+ try (Synchronizer synchronizer = autoUpdatingSynchronizer(file)) {
+ assertThat(await(synchronizer.next()).getResultType(), equalTo(SourceResultType.CHANGE_SET));
+
+ CompletableFuture next = synchronizer.next();
+ Thread.sleep(200);
+ file.setContents(MALFORMED);
+ assertThat(await(next).getStatus().getState(), equalTo(SourceSignal.INTERRUPTED));
+ CompletableFuture later = settle(synchronizer);
+ int errorsAfterFailure = errorMessages().size();
+
+ // With the file untouched, nothing reloads: no result, no further error log, no retry log.
+ try {
+ FDv2SourceResult unexpected = later.get(2, TimeUnit.SECONDS);
+ fail("unexpected reload result: " + unexpected.getResultType());
+ } catch (TimeoutException e) {
+ // expected
+ }
+ assertEquals(errorsAfterFailure, errorMessages().size());
+ for (LogCapture.Message m : logCapture.getMessages()) {
+ assertFalse(m.getText(), m.getText().contains("Retrying"));
+ }
+ assertFalse(later.isDone());
+ }
+ }
+ }
+ }
+
+ @Test
+ public void missingFileAtStartupIsAnErrorLoggedWithThePath() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ java.nio.file.Path missing = dir.getPath().resolve("missing.json");
+ try (Synchronizer synchronizer = FileData.synchronizer().filePaths(missing)
+ .build(TestDataSourceBuildInputs.create(logger))) {
+ FDv2SourceResult result = await(synchronizer.next());
+ assertThat(result.getResultType(), equalTo(SourceResultType.STATUS));
+ assertThat(result.getStatus().getState(), equalTo(SourceSignal.INTERRUPTED));
+ // The description is the cause in brackets. The path appears only inside the cause text.
+ List errors = errorMessages();
+ assertEquals(1, errors.size());
+ assertEquals("[java.nio.file.NoSuchFileException: " + missing + "]", errors.get(0));
+ assertEquals(errors.get(0), result.getStatus().getErrorInfo().getMessage());
+ }
+ }
+ }
+}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FlagFileParserJsonTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FlagFileParserJsonTest.java
index 45fe4cdf..83d8455b 100644
--- a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FlagFileParserJsonTest.java
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FlagFileParserJsonTest.java
@@ -1,10 +1,66 @@
package com.launchdarkly.sdk.server.integrations;
+import com.google.gson.JsonSyntaxException;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FileDataException;
import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.JsonFlagFileParser;
+import org.junit.Test;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+
@SuppressWarnings("javadoc")
public class FlagFileParserJsonTest extends FlagFileParserTestBase {
public FlagFileParserJsonTest() {
super(new JsonFlagFileParser(), ".json");
}
+
+ // The message of a parse failure is logged, and the file data source also reports it in its status.
+ // It names the problem and its position. Gson's JSON path is left out, because in a malformed
+ // document the path can hold a value from the file.
+
+ @Test
+ public void syntaxErrorIsDescribedByItsProblemAndPositionWithoutThePath() throws Exception {
+ // Braces in place of brackets make the first target a member name, which Gson puts in its path.
+ String doc = "{\n"
+ + " \"segments\": {\n"
+ + " \"s1\": {\n"
+ + " \"key\": \"s1\",\n"
+ + " \"included\": {\"alice@example.com\", \"bob@example.com\"}\n"
+ + " }\n"
+ + " }\n"
+ + "}\n";
+ assertParseFails(doc, "cannot parse JSON: Expected ':' (line 5, column 40)");
+ }
+
+ @Test
+ public void endOfInputIsDescribedByItsPositionWithoutThePath() throws Exception {
+ assertParseFails("{\"flagValues\": {\"alice@example.com\": ",
+ "cannot parse JSON: End of input (line 1, column 38)");
+ }
+
+ @Test
+ public void malformedUnicodeEscapeIsDescribedWithoutTheCharactersAfterIt() throws Exception {
+ assertParseFails("{\"flagValues\": {\"f1\": \"\\user@example.com\"}}",
+ "cannot parse JSON: Malformed Unicode escape (line 1, column 26)");
+ }
+
+ @Test
+ public void errorInAnotherFormIsDescribedWithoutItsMessage() {
+ assertEquals("cannot parse JSON", JsonFlagFileParser.describe(new JsonSyntaxException("alice@example.com")));
+ }
+
+ private void assertParseFails(String doc, String expectedMessage) throws Exception {
+ try {
+ new JsonFlagFileParser().parse(new ByteArrayInputStream(doc.getBytes(StandardCharsets.UTF_8)));
+ fail("expected a parse failure");
+ } catch (FileDataException e) {
+ assertEquals(expectedMessage, e.getMessage());
+ assertNull(e.getCause());
+ }
+ }
}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FlagFileParserYamlTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FlagFileParserYamlTest.java
index ce9100c4..1c0be184 100644
--- a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FlagFileParserYamlTest.java
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/FlagFileParserYamlTest.java
@@ -1,10 +1,127 @@
package com.launchdarkly.sdk.server.integrations;
+import com.launchdarkly.sdk.LDValue;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FileDataException;
import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.YamlFlagFileParser;
+import org.junit.Test;
+
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+
@SuppressWarnings("javadoc")
public class FlagFileParserYamlTest extends FlagFileParserTestBase {
public FlagFileParserYamlTest() {
super(new YamlFlagFileParser(), ".yml");
}
+
+ // The message of a parse failure is logged, and the file data source also reports it in its status.
+ // It names the problem and its position, and quotes no content of the file.
+
+ @Test
+ public void syntaxErrorIsDescribedByItsProblemAndPosition() throws Exception {
+ String doc = "flags:\n"
+ + " flag:\n"
+ + " targets:\n"
+ + " - values: [alice@example.com, bob@example.com\n"
+ + " variation: 0\n";
+ assertParseFails(doc, "unable to parse YAML: while parsing a flow sequence (line 4, column 17):"
+ + " expected ',' or ']', but got : (line 5, column 18)");
+ }
+
+ @Test
+ public void disallowedCharacterIsDescribedByItsCodePointAndPosition() throws Exception {
+ assertParseFails("flagValues:\n flag: \"alice@example.com\u0001\"\n",
+ "unable to parse YAML: special characters are not allowed (code point 0x1 at position 38)");
+ }
+
+ @Test
+ public void errorWithoutAPositionIsDescribedByItsMessage() throws Exception {
+ StringBuilder doc = new StringBuilder("flagValues:\n flag: ");
+ for (int i = 0; i < 60; i++) {
+ doc.append('[');
+ }
+ assertParseFails(doc.toString(), "unable to parse YAML: Nesting Depth exceeded max 50");
+ }
+
+ @Test
+ public void valueThatDoesNotMatchItsTagIsDescribedWithoutTheValue() throws Exception {
+ for (String value : new String[] { "!!int alice@example.com", "!!float alice@example.com",
+ "!!timestamp alice@example.com", "!!binary alice@example.com", "!!set [alice@example.com]" }) {
+ assertParseFails("flagValues:\n flag: " + value + "\n",
+ "unable to parse YAML: a value cannot be converted to the type that its tag names");
+ }
+ }
+
+ private void assertParseFails(String doc, String expectedMessage) throws Exception {
+ try {
+ new YamlFlagFileParser().parse(new ByteArrayInputStream(doc.getBytes(StandardCharsets.UTF_8)));
+ fail("expected a parse failure");
+ } catch (FileDataException e) {
+ assertEquals(expectedMessage, e.getMessage());
+ assertNull(e.getCause());
+ }
+ }
+
+ @Test(timeout = 60000)
+ public void concurrentParsesEachReturnTheirOwnDocument() throws Exception {
+ // Different files can be parsed at the same time, for example by two clients in one JVM, or by a
+ // file data source and an override source. The SDK shares one parser between them.
+ YamlFlagFileParser parser = new YamlFlagFileParser();
+ int threads = 8;
+ int parsesPerThread = 2000;
+ ExecutorService pool = Executors.newFixedThreadPool(threads, runnable -> {
+ Thread t = new Thread(runnable);
+ t.setDaemon(true);
+ return t;
+ });
+ try {
+ CountDownLatch go = new CountDownLatch(1);
+ List> outcomes = new ArrayList<>();
+ for (int t = 0; t < threads; t++) {
+ Map expected = new HashMap<>();
+ StringBuilder doc = new StringBuilder("flagValues:\n");
+ for (int i = 0; i < 20; i++) {
+ String key = "thread" + t + "-flag" + i;
+ expected.put(key, LDValue.of("value" + i));
+ doc.append(" ").append(key).append(": value").append(i).append('\n');
+ }
+ byte[] bytes = doc.toString().getBytes(StandardCharsets.UTF_8);
+ int thread = t;
+ outcomes.add(pool.submit(() -> {
+ go.await();
+ for (int i = 0; i < parsesPerThread; i++) {
+ Map values;
+ try {
+ values = parser.parse(new ByteArrayInputStream(bytes)).flagValues;
+ } catch (Exception e) {
+ return "parse " + i + " on thread " + thread + " threw " + e;
+ }
+ if (!expected.equals(values)) {
+ return "parse " + i + " on thread " + thread + " returned " + values;
+ }
+ }
+ return null;
+ }));
+ }
+ go.countDown();
+ for (Future outcome : outcomes) {
+ assertNull(outcome.get());
+ }
+ } finally {
+ pool.shutdownNow();
+ }
+ }
}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/InPlaceWrites.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/InPlaceWrites.java
new file mode 100644
index 00000000..69273d79
--- /dev/null
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/InPlaceWrites.java
@@ -0,0 +1,49 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.time.Duration;
+
+/**
+ * Rewrites files in place the way many applications and editors save them: the file is truncated
+ * when it is opened for writing, and the new content is written through the same open stream. A
+ * reader in between finds the file empty. The tests use these writes, not an atomic replacement, so
+ * that the code under test must handle a file that is being rewritten.
+ */
+@SuppressWarnings("javadoc")
+final class InPlaceWrites {
+ /**
+ * Work done while the file is empty, between the truncation and the write.
+ */
+ interface WhileEmpty {
+ void run() throws Exception;
+ }
+
+ private InPlaceWrites() {}
+
+ /**
+ * Truncates the file, pauses, and then writes the new content.
+ */
+ static void rewrite(Path path, String content, Duration pause) throws Exception {
+ rewrite(path, content, () -> Thread.sleep(pause.toMillis()));
+ }
+
+ /**
+ * Truncates the file, runs the given work while the file is empty, and then writes the new content.
+ */
+ static void rewrite(Path path, String content, WhileEmpty whileEmpty) throws Exception {
+ try (OutputStream out = Files.newOutputStream(path)) {
+ whileEmpty.run();
+ out.write(content.getBytes(StandardCharsets.UTF_8));
+ }
+ }
+
+ /**
+ * Truncates the file and leaves it empty.
+ */
+ static void truncate(Path path) throws Exception {
+ rewrite(path, "", () -> { });
+ }
+}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/OverrideFileLoaderTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/OverrideFileLoaderTest.java
new file mode 100644
index 00000000..bb5a7ea1
--- /dev/null
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/integrations/OverrideFileLoaderTest.java
@@ -0,0 +1,1594 @@
+package com.launchdarkly.sdk.server.integrations;
+
+import com.launchdarkly.sdk.LDValue;
+import com.launchdarkly.sdk.server.integrations.FileDataReloader.EmptiedFileException;
+import com.launchdarkly.sdk.server.integrations.FileDataSourceParsing.FileDataException;
+import com.launchdarkly.sdk.server.integrations.OverrideFileLoader.FileSummary;
+import com.launchdarkly.sdk.server.integrations.OverrideFileLoader.LoadResult;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.DataKind;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.ItemDescriptor;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.KeyedItems;
+import com.launchdarkly.sdk.server.subsystems.SerializationException;
+import com.launchdarkly.testhelpers.TempDir;
+
+import org.junit.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static com.launchdarkly.sdk.server.DataModel.FEATURES;
+import static com.launchdarkly.sdk.server.DataModel.SEGMENTS;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.instanceOf;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+import static org.junit.Assume.assumeTrue;
+
+@SuppressWarnings("javadoc")
+public class OverrideFileLoaderTest {
+ private static Map> toMap(LoadResult result) {
+ Map> out = new HashMap<>();
+ for (Map.Entry> kind : result.getData()) {
+ Map items = new HashMap<>();
+ for (Map.Entry item : kind.getValue().getItems()) {
+ items.put(item.getKey(), item.getValue());
+ }
+ out.put(kind.getKey(), items);
+ }
+ return out;
+ }
+
+ private static LDValue json(DataKind kind, ItemDescriptor item) {
+ return LDValue.parse(kind.serialize(item));
+ }
+
+ private static Path write(TempDir dir, String name, String contents) throws Exception {
+ Path p = dir.getPath().resolve(name);
+ Files.write(p, contents.getBytes());
+ return p;
+ }
+
+ private static OverrideFileLoader loader(Path... paths) {
+ return new OverrideFileLoader(Arrays.asList(paths), FileData.DuplicateKeysHandling.FAIL);
+ }
+
+ @Test
+ public void loadsFlagsFlagValuesAndSegmentsKeepingDocumentVersions() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.json",
+ "{\"flags\":{\"f1\":{\"key\":\"f1\",\"version\":7,\"on\":true,\"variations\":[true],\"fallthrough\":{\"variation\":0}}},"
+ + "\"flagValues\":{\"f2\":\"x\"},"
+ + "\"segments\":{\"s1\":{\"key\":\"s1\",\"version\":9}}}");
+ LoadResult result = loader(file).load(Duration.ZERO);
+
+ Map> data = toMap(result);
+ assertEquals(7, data.get(FEATURES).get("f1").getVersion());
+ assertEquals(LDValue.of(7), json(FEATURES, data.get(FEATURES).get("f1")).get("version"));
+ assertEquals(9, data.get(SEGMENTS).get("s1").getVersion());
+ assertEquals(LDValue.of(9), json(SEGMENTS, data.get(SEGMENTS).get("s1")).get("version"));
+ assertEquals(2, result.getFlagCount());
+ assertEquals(1, result.getSegmentCount());
+ assertEquals(1, result.getFiles().size());
+ assertTrue(result.getFiles().get(0).isPresent());
+ assertEquals(2, result.getFiles().get(0).getFlags());
+ assertEquals(1, result.getFiles().get(0).getSegments());
+ assertEquals(file, result.getFiles().get(0).getPath());
+ }
+ }
+
+ @Test
+ public void valueOnlyEntryBecomesFallthroughFlagServingTheValue() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.json", "{\"flagValues\":{\"f2\":\"x\"}}");
+ LoadResult result = loader(file).load(Duration.ZERO);
+ ItemDescriptor f2 = toMap(result).get(FEATURES).get("f2");
+ assertEquals(0, f2.getVersion());
+ LDValue flag = json(FEATURES, f2);
+ assertEquals(LDValue.of("f2"), flag.get("key"));
+ assertEquals(LDValue.of(0), flag.get("version"));
+ assertEquals(LDValue.of(true), flag.get("on"));
+ assertEquals(LDValue.ofNull(), flag.get("offVariation"));
+ assertEquals(LDValue.of(0), flag.get("fallthrough").get("variation"));
+ assertEquals(LDValue.buildArray().add("x").build(), flag.get("variations"));
+ }
+ }
+
+ @Test
+ public void yamlFileIsParsedAsYaml() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", "flagValues:\n yaml-flag: \"override-value\"\n");
+ LoadResult result = loader(file).load(Duration.ZERO);
+ assertEquals(LDValue.buildArray().add("override-value").build(),
+ json(FEATURES, toMap(result).get(FEATURES).get("yaml-flag")).get("variations"));
+ }
+ }
+
+ @Test
+ public void missingFileContributesNothing() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path present = write(dir, "present.json", "{\"flagValues\":{\"flag\":\"value\"}}");
+ Path missing = dir.getPath().resolve("missing.json");
+ Path segments = write(dir, "segments.json", "{\"segments\":{\"s1\":{\"key\":\"s1\"}}}");
+ LoadResult result = loader(present, missing, segments).load(Duration.ZERO);
+
+ Map> data = toMap(result);
+ assertEquals(1, data.get(FEATURES).size());
+ assertEquals(1, data.get(SEGMENTS).size());
+ List files = result.getFiles();
+ assertEquals(3, files.size());
+ assertTrue(files.get(0).isPresent());
+ assertEquals(1, files.get(0).getFlags());
+ assertFalse(files.get(1).isPresent());
+ assertEquals(missing, files.get(1).getPath());
+ assertEquals(0, files.get(1).getFlags());
+ assertTrue(files.get(2).isPresent());
+ assertEquals(1, files.get(2).getSegments());
+ }
+ }
+
+ @Test
+ public void allFilesMissingProducesEmptyResult() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ LoadResult result = loader(dir.getPath().resolve("a.json"), dir.getPath().resolve("b.json")).load(Duration.ZERO);
+ assertEquals(0, result.getFlagCount());
+ assertEquals(0, result.getSegmentCount());
+ assertFalse(result.getData().iterator().hasNext());
+ assertEquals(2, result.getFiles().size());
+ }
+ }
+
+ @Test
+ public void directoryAtAConfiguredPathFailsTheLoad() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path directory = dir.getPath().resolve("dir.json");
+ Files.createDirectory(directory);
+ assertNotARegularFile(directory);
+ }
+ }
+
+ @Test(timeout = 10000)
+ public void namedPipeAtAConfiguredPathFailsTheLoadWithoutWaitingForAWriter() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path pipe = dir.getPath().resolve("pipe.json");
+ int exit;
+ try {
+ exit = new ProcessBuilder("mkfifo", pipe.toString()).inheritIO().start().waitFor();
+ } catch (java.io.IOException e) {
+ exit = -1;
+ }
+ assumeTrue("mkfifo is not available", exit == 0);
+ // Opening a named pipe for reading waits until something opens it for writing.
+ assertNotARegularFile(pipe);
+ }
+ }
+
+ private static void assertNotARegularFile(Path path) throws Exception {
+ try {
+ loader(path).load(Duration.ZERO);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), equalTo("file " + path + ": unable to read file"));
+ assertThat(e.getCause(), instanceOf(java.io.IOException.class));
+ assertThat(e.getCause().getMessage(), equalTo("not a regular file"));
+ }
+ }
+
+ @Test
+ public void linkToARegularFileIsRead() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path target = write(dir, "target.json", "{\"flagValues\":{\"flag\":\"value\"}}");
+ Path link = dir.getPath().resolve("link.json");
+ try {
+ Files.createSymbolicLink(link, target);
+ } catch (UnsupportedOperationException | java.io.IOException e) {
+ org.junit.Assume.assumeNoException("symbolic links are not available", e);
+ }
+ // The regular file check applies to the file that the link points to.
+ assertEquals(1, loader(link).load(Duration.ZERO).getFlagCount());
+ }
+ }
+
+ @Test
+ public void selfReferringYamlDocumentFailsTheLoad() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ // The alias makes the flag contain itself, so converting the document never ends.
+ Path file = write(dir, "overrides.yaml", "flags:\n f: &a {self: *a}\n");
+ try {
+ loader(file).load(Duration.ZERO);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), equalTo("file " + file
+ + ": cannot parse flag or segment data: the document refers to itself or is nested too deeply"));
+ }
+ }
+ }
+
+ @Test
+ public void malformedDocumentFailsTheLoadWithFileAttribution() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path good = write(dir, "good.json", "{\"flagValues\":{\"a\":1}}");
+ Path bad = write(dir, "bad.json", "{\"flagValues\"");
+ try {
+ loader(good, bad).load(Duration.ZERO);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString(bad + ": cannot parse JSON: End of input (line 1, column 14)"));
+ assertNull(e.getCause());
+ }
+ }
+ }
+
+ @Test
+ public void modelRejectedDocumentIsAFileDataError() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "bad-model.json", "{\"flags\":{\"f1\":{\"key\":\"f1\",\"rules\":5}}}");
+ try {
+ loader(file).load(Duration.ZERO);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), equalTo("file " + file + ": cannot parse flag \"f1\""));
+ assertThat(e.getCause(), instanceOf(SerializationException.class));
+ }
+ }
+ }
+
+ @Test
+ public void numberPropertyThatHoldsAnotherValueFailsTheLoadWithoutQuotingTheValue() throws Exception {
+ // The data model's own message would quote the value, which can be a context key.
+ try (TempDir dir = TempDir.create()) {
+ Path flagFile = write(dir, "flag.json",
+ "{\"flags\":{\"f1\":{\"key\":\"f1\",\"offVariation\":\"alice@example.com\"}}}");
+ Path segmentFile = write(dir, "segment.yaml",
+ "segments:\n s1:\n key: s1\n rules:\n - weight: alice@example.com\n clauses: []\n");
+ String[][] cases = {
+ { flagFile.toString(), "flag \"f1\"" },
+ { segmentFile.toString(), "segment \"s1\"" } };
+ for (String[] c : cases) {
+ try {
+ loader(Paths.get(c[0])).load(Duration.ZERO);
+ fail("expected exception for " + c[0]);
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), equalTo("file " + c[0] + ": cannot parse " + c[1]
+ + ": a property that must be a number is not a number"));
+ assertNull(e.getCause());
+ }
+ }
+ }
+ }
+
+ @Test
+ public void duplicateKeysFailByDefaultAcrossFilesAndWithinAFile() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.json", "{\"flagValues\":{\"flag\":\"a\"}}");
+ Path b = write(dir, "b.json", "{\"flagValues\":{\"flag\":\"b\"}}");
+ try {
+ loader(a, b).load(Duration.ZERO);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString("in features, key \"flag\" was already defined"));
+ assertThat(e.getMessage(), containsString(b.toString()));
+ assertNull(e.getCause());
+ }
+
+ Path both = write(dir, "both.json", "{\"flags\":{\"x\":{\"key\":\"x\"}},\"flagValues\":{\"x\":true}}");
+ try {
+ loader(both).load(Duration.ZERO);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString("key \"x\" was already defined"));
+ }
+
+ Path seg1 = write(dir, "seg1.json", "{\"segments\":{\"s\":{\"key\":\"s\"}}}");
+ Path seg2 = write(dir, "seg2.json", "{\"segments\":{\"s\":{\"key\":\"s\"}}}");
+ try {
+ loader(seg1, seg2).load(Duration.ZERO);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString("in segments, key \"s\" was already defined"));
+ }
+ }
+ }
+
+ @Test
+ public void ignoreHandlingKeepsFirstFileAndCountsOnlyKeptEntries() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path first = write(dir, "first.json", "{\"flagValues\":{\"shared\":\"first\"}}");
+ Path second = write(dir, "second.json", "{\"flagValues\":{\"shared\":\"second\",\"only-second\":\"x\"}}");
+ OverrideFileLoader loader = new OverrideFileLoader(Arrays.asList(first, second), FileData.DuplicateKeysHandling.IGNORE);
+ LoadResult result = loader.load(Duration.ZERO);
+
+ Map flags = toMap(result).get(FEATURES);
+ assertEquals(LDValue.buildArray().add("first").build(), json(FEATURES, flags.get("shared")).get("variations"));
+ assertEquals(2, flags.size());
+ assertEquals(1, result.getFiles().get(0).getFlags());
+ assertEquals(1, result.getFiles().get(1).getFlags()); // the dropped duplicate is not counted
+ assertEquals(2, result.getFlagCount());
+ }
+ }
+
+ @Test
+ public void contentHashReflectsRawContentOfPresentFiles() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.json", "{\"flagValues\":{\"a\":1}}");
+ Path missing = dir.getPath().resolve("missing.json");
+ OverrideFileLoader loader = loader(file, missing);
+ byte[] first = loader.load(Duration.ZERO).getContentHash();
+ byte[] second = loader.load(Duration.ZERO).getContentHash();
+ assertArrayEquals(first, second);
+
+ Files.write(file, "{\"flagValues\":{\"a\":2}}".getBytes());
+ byte[] third = loader.load(Duration.ZERO).getContentHash();
+ assertThat(Arrays.equals(first, third), is(false));
+
+ // A file that appears changes the digest.
+ Files.write(missing, "{}".getBytes());
+ byte[] fourth = loader.load(Duration.ZERO).getContentHash();
+ assertThat(Arrays.equals(third, fourth), is(false));
+ }
+ }
+
+ @Test
+ public void emptyDocumentContributesNothing() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "empty.json", "{}");
+ LoadResult result = loader(file).load(Duration.ZERO);
+ assertEquals(0, result.getFlagCount());
+ assertTrue(result.getFiles().get(0).isPresent());
+ assertThat(result.getFiles().get(0).getFlags(), equalTo(0));
+ }
+ }
+
+ @Test
+ public void loaderReadsFilesInConfiguredOrder() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.json", "{\"flagValues\":{\"k\":\"a\"}}");
+ Path b = write(dir, "b.json", "{\"flagValues\":{\"k\":\"b\"}}");
+ OverrideFileLoader loader = new OverrideFileLoader(Arrays.asList(b, a), FileData.DuplicateKeysHandling.IGNORE);
+ assertEquals(LDValue.buildArray().add("b").build(),
+ json(FEATURES, toMap(loader.load(Duration.ZERO)).get(FEATURES).get("k")).get("variations"));
+ assertEquals(Collections.singletonList(b).get(0), loader.load(Duration.ZERO).getFiles().get(0).getPath());
+ }
+ }
+
+ private static final String YAML_DOC = "flagValues:\n flag: \"value\"\n";
+ private static final String JSON_DOC = "{\"flagValues\":{\"flag\":\"value\"}}";
+ private static final Duration RETRY = Duration.ofSeconds(1);
+
+ /**
+ * A monotonic clock that the test moves. It starts near the largest value, so that elapsed times
+ * cross the overflow of the clock's readings.
+ */
+ private static final class TestClock {
+ final AtomicLong nanos = new AtomicLong(Long.MAX_VALUE - RETRY.toNanos() / 2);
+
+ void advance(double retryDelays) {
+ nanos.addAndGet((long) (retryDelays * RETRY.toNanos()));
+ }
+ }
+
+ private static OverrideFileLoader loader(TestClock clock, Path... paths) {
+ return new OverrideFileLoader(Arrays.asList(paths), FileData.DuplicateKeysHandling.FAIL, clock.nanos::get);
+ }
+
+ // Loads and applies the result, as the reloader does with a result it applies.
+ private static LoadResult loadAndAccept(OverrideFileLoader loader) throws Exception {
+ LoadResult result = loader.load(RETRY);
+ loader.accepted(result);
+ return result;
+ }
+
+ private static void assertNoContentFailure(OverrideFileLoader loader, Path file) throws Exception {
+ try {
+ loader.load(RETRY);
+ fail("expected exception for " + file);
+ } catch (FileDataException e) {
+ assertEquals("file " + file + ": the file has no content, which is not a JSON document; to remove its overrides,"
+ + " delete the file or write {}", e.getMessage());
+ assertNull(e.getCause());
+ }
+ }
+
+ // Asserts that a load holds back the given files and returns how long it asks the reloader to
+ // wait, in retry delays.
+ private static double assertHeld(OverrideFileLoader loader, Path... files) throws Exception {
+ try {
+ loader.load(RETRY);
+ fail("expected the empty files " + Arrays.asList(files) + " to be held back");
+ return 0;
+ } catch (EmptiedFileException e) {
+ assertEquals(Arrays.asList(files), e.getPaths());
+ return (double) e.getRetryAfterNanos() / RETRY.toNanos();
+ }
+ }
+
+ // Writes the file again, in place, with a later modification time than the previous write. File
+ // system timestamps can be coarse, so it waits until the time differs. It writes other content first,
+ // so that the file is modified even when the new content is what it already holds.
+ private static void writeAgain(Path file, String contents) throws Exception {
+ long before = Files.getLastModifiedTime(file).toMillis();
+ long deadline = System.currentTimeMillis() + 5000;
+ do {
+ Thread.sleep(20);
+ InPlaceWrites.rewrite(file, "x", () -> { });
+ InPlaceWrites.rewrite(file, contents, () -> { });
+ } while (Files.getLastModifiedTime(file).toMillis() == before && System.currentTimeMillis() < deadline);
+ assertThat(Files.getLastModifiedTime(file).toMillis(), not(equalTo(before)));
+ }
+
+ private static void truncateAgain(Path file) throws Exception {
+ writeAgain(file, "");
+ }
+
+ @Test
+ public void formatIsChosenByTheFileNameExtension() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ for (String name : new String[] { "a.yaml", "a.yml", "a.YAML", "a.Yml" }) {
+ assertEquals(name, 1, loader(write(dir, name, YAML_DOC)).load(Duration.ZERO).getFlagCount());
+ }
+ // A YAML file can hold most JSON documents. The YAML parser reads YAML 1.1, which rejects some
+ // JSON, such as indentation with tabs or the escape \/.
+ assertEquals(1, loader(write(dir, "json.yaml", JSON_DOC)).load(Duration.ZERO).getFlagCount());
+ for (String json : new String[] { "{\n\t\"flagValues\": {\"flag\": \"v\"}\n}", "{\"flagValues\":{\"flag\":\"a\\/b\"}}" }) {
+ Path file = write(dir, "strict.yaml", json);
+ try {
+ loader(file).load(Duration.ZERO);
+ fail("expected the YAML parser to reject " + json);
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString(file + ": unable to parse YAML"));
+ }
+ }
+ // Any other file is JSON, whatever its content.
+ for (String name : new String[] { "b.json", "b.txt", "b", "b.yaml.bak" }) {
+ Path file = write(dir, name, YAML_DOC);
+ try {
+ loader(file).load(Duration.ZERO);
+ fail("expected exception for " + name);
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString(file + ": cannot parse JSON"));
+ }
+ }
+ }
+ }
+
+ @Test
+ public void yamlParseFailureIsLoggedWithoutTheContentOfTheFile() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "a.yaml", "flagValues:\n flag: [alice@example.com\n other: 1\n");
+ try {
+ loader(file).load(Duration.ZERO);
+ fail("expected a parse failure");
+ } catch (FileDataException e) {
+ assertEquals("file " + file + ": unable to parse YAML: while parsing a flow sequence (line 2, column 9):"
+ + " expected ',' or ']', but got : (line 3, column 8)", e.getDescription());
+ }
+ }
+ }
+
+ @Test
+ public void emptyOrWhiteSpaceJsonFileFailsToParse() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ // A file with no extension or another extension is JSON, so it gets the same rule.
+ for (String name : new String[] { "empty.json", "empty", "empty.txt" }) {
+ for (String contents : new String[] { "", " \n\t\r\n" }) {
+ Path file = write(dir, name, contents);
+ assertNoContentFailure(loader(file), file);
+ }
+ }
+ }
+ }
+
+ @Test
+ public void yamlFileWithNoDocumentHasNoEntries() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ for (String name : new String[] { "empty.yaml", "empty.yml" }) {
+ for (String contents : new String[] { "", " \n\n", "# only a comment\n", "---\n" }) {
+ LoadResult result = loader(write(dir, name, contents)).load(RETRY);
+ assertEquals(0, result.getFlagCount());
+ assertTrue(result.getFiles().get(0).isPresent());
+ assertFalse(contents, result.getFiles().get(0).hasContent());
+ }
+ }
+ }
+ }
+
+ @Test
+ public void documentWithNoEntriesHasContent() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ for (String name : new String[] { "empty.yaml", "empty.json" }) {
+ LoadResult result = loader(write(dir, name, "{}")).load(RETRY);
+ assertEquals(0, result.getFlagCount());
+ assertTrue(name, result.getFiles().get(0).hasContent());
+ }
+ }
+ }
+
+ @Test
+ public void emptiedYamlFileIsHeldForExactlyTheRetryDelayAndThenHasNoEntries() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ assertTrue(loadAndAccept(loader).getFiles().get(0).hasContent());
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ clock.advance(0.95);
+ assertHeld(loader, file);
+ // The file has stayed empty without being written for the retry delay.
+ clock.advance(0.05);
+ assertEquals(0, loader.load(RETRY).getFlagCount());
+ // It is not held back again until it changes.
+ assertEquals(0, loader.load(RETRY).getFlagCount());
+ }
+ }
+
+ @Test
+ public void emptiedJsonFileIsHeldForTheRetryDelayAndThenFailsToParse() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.json", JSON_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ clock.advance(1);
+ assertNoContentFailure(loader, file);
+ assertNoContentFailure(loader, file);
+ }
+ }
+
+ @Test
+ public void holdAsksForARetryWhenTheFirstDelayEnds() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path first = write(dir, "first.yaml", YAML_DOC);
+ Path second = write(dir, "second.yaml", "flagValues:\n other: \"value\"\n");
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, first, second);
+ loadAndAccept(loader);
+
+ // The retry comes when the delay ends, plus a tenth of the retry delay for a timer that fires a
+ // little early.
+ InPlaceWrites.truncate(first);
+ assertEquals(1.1, assertHeld(loader, first), 1e-9);
+ clock.advance(0.4);
+ assertEquals(0.7, assertHeld(loader, first), 1e-9);
+ // A second file found empty later does not delay the retry for the first.
+ InPlaceWrites.truncate(second);
+ clock.advance(0.2);
+ assertEquals(0.5, assertHeld(loader, first, second), 1e-9);
+ }
+ }
+
+ @Test
+ public void holdAsksForARetryWhenTheBoundEnds() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ for (int i = 0; i < 4; i++) {
+ clock.advance(0.9);
+ writeAgain(file, " ");
+ assertHeld(loader, file);
+ }
+ // 4.6 retry delays after the first hold, the file is written again. Its delay would end at 5.6,
+ // its bound at 5.0.
+ clock.advance(1.0);
+ writeAgain(file, " ");
+ assertEquals(0.5, assertHeld(loader, file), 1e-9);
+ }
+ }
+
+ @Test
+ public void contentThatIsOnlyWhiteSpaceOrAByteOrderMarkCountsAsEmpty() throws Exception {
+ // A read can see only the byte order mark that an editor writes first. For JSON that is not a
+ // parse failure to report but an empty file to hold back.
+ for (String name : new String[] { "overrides.yaml", "overrides.json" }) {
+ try (TempDir dir = TempDir.create()) {
+ String doc = name.endsWith(".json") ? JSON_DOC : YAML_DOC;
+ Path file = write(dir, name, doc);
+ OverrideFileLoader loader = loader(new TestClock(), file);
+ for (String contents : new String[] { " \n\t\r\n", "\uFEFF", "\uFEFF\n" }) {
+ assertEquals(name, 1, loadAndAccept(loader).getFlagCount());
+ InPlaceWrites.rewrite(file, contents, () -> { });
+ assertHeld(loader, file);
+ InPlaceWrites.rewrite(file, doc, () -> { });
+ }
+ }
+ }
+ }
+
+ @Test
+ public void fileEmptiedAgainWithTheSameStateAfterContentStartsANewDelay() throws Exception {
+ // File system timestamps are coarse, so a file can be emptied again with the modification time
+ // and size that it had when it was last found empty. A load that read content in between shows
+ // that this is a new emptying, so its delay starts over. Nothing is applied in between: the test
+ // does not accept the result of the load that reads the content.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ java.nio.file.attribute.FileTime emptiedAt = Files.getLastModifiedTime(file);
+ assertHeld(loader, file);
+ clock.advance(0.8);
+ InPlaceWrites.rewrite(file, YAML_DOC, () -> { });
+ assertEquals(1, loader.load(RETRY).getFlagCount());
+
+ clock.advance(0.4);
+ InPlaceWrites.truncate(file);
+ Files.setLastModifiedTime(file, emptiedAt);
+ assertHeld(loader, file);
+ // The new delay is still running a little later.
+ clock.advance(0.2);
+ assertHeld(loader, file);
+ }
+ }
+
+ @Test
+ public void yamlWithOnlyACommentOrADocumentMarkerIsHeld() throws Exception {
+ // A read can see only the first line of a YAML file that is being written.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ OverrideFileLoader loader = loader(new TestClock(), file);
+ for (String contents : new String[] { "# overrides for the incident\n", "---\n" }) {
+ assertEquals(1, loadAndAccept(loader).getFlagCount());
+ InPlaceWrites.rewrite(file, contents, () -> { });
+ assertHeld(loader, file);
+ InPlaceWrites.rewrite(file, YAML_DOC, () -> { });
+ }
+ }
+ }
+
+ @Test
+ public void documentWithNoEntriesIsAppliedRightAway() throws Exception {
+ // {} is how to remove a file's overrides without deleting it.
+ try (TempDir dir = TempDir.create()) {
+ for (String name : new String[] { "overrides.yaml", "overrides.json" }) {
+ Path file = write(dir, name, name.endsWith(".json") ? JSON_DOC : YAML_DOC);
+ OverrideFileLoader loader = loader(new TestClock(), file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.rewrite(file, "{}", () -> { });
+ assertEquals(name, 0, loader.load(RETRY).getFlagCount());
+ }
+ }
+ }
+
+ @Test
+ public void contentThatWasReadButNotAppliedDoesNotHoldTheFile() throws Exception {
+ // Only the data in effect counts. A load whose result was not applied, for example because
+ // another file failed to parse, does not make the file's later emptiness a rewrite.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ OverrideFileLoader loader = loader(new TestClock(), file);
+ loader.load(RETRY);
+
+ InPlaceWrites.truncate(file);
+ assertEquals(0, loader.load(RETRY).getFlagCount());
+ }
+ }
+
+ @Test
+ public void fileThatHasNoContentFromTheStartIsNeverHeld() throws Exception {
+ for (String placeholderContents : new String[] { "", "# placeholder\n" }) {
+ try (TempDir dir = TempDir.create()) {
+ Path placeholder = write(dir, "placeholder.yaml", placeholderContents);
+ Path data = write(dir, "data.json", JSON_DOC);
+ OverrideFileLoader loader = loader(new TestClock(), placeholder, data);
+ for (int i = 0; i < 3; i++) {
+ assertEquals(1, loadAndAccept(loader).getFlagCount());
+ }
+ truncateAgain(placeholder);
+ assertEquals(1, loadAndAccept(loader).getFlagCount());
+ }
+ }
+ }
+
+ @Test
+ public void fileWhoseEmptyStateIsInEffectIsNotHeldAgain() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ clock.advance(1);
+ assertEquals(0, loadAndAccept(loader).getFlagCount());
+
+ // A new truncation of the file whose empty state is in effect is parsed right away.
+ writeAgain(file, " ");
+ assertEquals(0, loader.load(RETRY).getFlagCount());
+ }
+ }
+
+ @Test
+ public void fileThatIsDeletedAndCreatedEmptyIsParsed() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ OverrideFileLoader loader = loader(new TestClock(), file);
+ loadAndAccept(loader);
+
+ Files.delete(file);
+ assertFalse(loadAndAccept(loader).getFiles().get(0).isPresent());
+ Files.write(file, new byte[0]);
+ LoadResult result = loader.load(RETRY);
+ assertTrue(result.getFiles().get(0).isPresent());
+ assertEquals(0, result.getFlagCount());
+ }
+ }
+
+ @Test
+ public void newWriteStartsTheDelayAgain() throws Exception {
+ // A write and a new truncation that no load saw in between: the file is in a new rewrite, not one
+ // that has stayed empty.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ clock.advance(0.8);
+ writeAgain(file, YAML_DOC);
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ clock.advance(0.95);
+ assertHeld(loader, file);
+ clock.advance(0.05);
+ assertEquals(0, loader.load(RETRY).getFlagCount());
+ }
+ }
+
+ @Test
+ public void newWriteOfALinkedFileStartsTheDelayAgain() throws Exception {
+ // The state of a file that is configured through a symbolic link is that of the file it points
+ // to; the link itself does not change when the file is written.
+ try (TempDir dir = TempDir.create()) {
+ Path target = write(dir, "target.yaml", YAML_DOC);
+ Path link = dir.getPath().resolve("overrides.yaml");
+ try {
+ Files.createSymbolicLink(link, target);
+ } catch (UnsupportedOperationException | java.io.IOException e) {
+ org.junit.Assume.assumeNoException("symbolic links are not available", e);
+ }
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, link);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(target);
+ assertHeld(loader, link);
+ clock.advance(0.8);
+ truncateAgain(target);
+ assertHeld(loader, link);
+ clock.advance(0.95);
+ assertHeld(loader, link);
+ clock.advance(0.05);
+ assertEquals(0, loader.load(RETRY).getFlagCount());
+ }
+ }
+
+ @Test
+ public void fileThatKeepsBeingWrittenIsParsedAfterItsBound() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ // Every load finds a new write, so the delay keeps starting again, up to the bound of five retry
+ // delays from the first hold.
+ for (int i = 0; i < 5; i++) {
+ clock.advance(0.9);
+ truncateAgain(file);
+ assertHeld(loader, file);
+ }
+ clock.advance(0.5);
+ truncateAgain(file);
+ assertEquals(0, loader.load(RETRY).getFlagCount());
+ }
+ }
+
+ @Test
+ public void filesRewrittenInTurnAreParsedAfterTheirBound() throws Exception {
+ // Each load finds one of the files empty and the other with content, so each file's own delay
+ // starts again whenever it is found empty. A read with content keeps the file's bound, so it
+ // still ends.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ Path b = write(dir, "b.yaml", "flagValues:\n other: \"value\"\n");
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, a, b);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(a);
+ assertHeld(loader, a);
+ for (int i = 0; i < 9; i++) {
+ clock.advance(0.5);
+ Path emptied = i % 2 == 0 ? b : a;
+ Path written = i % 2 == 0 ? a : b;
+ writeAgain(written, written == a ? YAML_DOC : "flagValues:\n other: \"value\"\n");
+ truncateAgain(emptied);
+ assertHeld(loader, emptied);
+ }
+ clock.advance(0.5);
+ writeAgain(b, "flagValues:\n other: \"value\"\n");
+ truncateAgain(a);
+ assertEquals(1, loader.load(RETRY).getFlagCount());
+ }
+ }
+
+ @Test
+ public void loadThatHoldsNothingBackStartsTheBoundOver() throws Exception {
+ // A load that reads the file with content and holds nothing back starts the file's bound over,
+ // although nothing is applied here because the test does not accept the result.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ for (int i = 0; i < 5; i++) {
+ clock.advance(0.9);
+ truncateAgain(file);
+ assertHeld(loader, file);
+ }
+ writeAgain(file, YAML_DOC);
+ assertEquals(1, loader.load(RETRY).getFlagCount());
+ truncateAgain(file);
+ clock.advance(0.5);
+ assertHeld(loader, file);
+ clock.advance(0.4);
+ assertHeld(loader, file);
+ }
+ }
+
+ @Test
+ public void applyingDataStartsTheBoundOver() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ for (int i = 0; i < 5; i++) {
+ clock.advance(0.9);
+ truncateAgain(file);
+ assertHeld(loader, file);
+ }
+ writeAgain(file, YAML_DOC);
+ assertEquals(1, loadAndAccept(loader).getFlagCount());
+ truncateAgain(file);
+ clock.advance(0.5);
+ assertHeld(loader, file);
+ clock.advance(0.4);
+ assertHeld(loader, file);
+ }
+ }
+
+ @Test
+ public void jsonFileThatStaysEmptyIsHeldBackAgainWhenRewrittenLater() throws Exception {
+ // A JSON file that stays empty is parsed after the delay and fails. That load holds nothing back,
+ // so the file's bound starts over, and when it is later rewritten in place, the new truncation is
+ // held back again instead of reported.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.json", JSON_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ clock.advance(1);
+ assertNoContentFailure(loader, file);
+ clock.advance(10);
+ assertNoContentFailure(loader, file);
+
+ writeAgain(file, " ");
+ assertHeld(loader, file);
+ InPlaceWrites.rewrite(file, JSON_DOC, () -> { });
+ assertEquals(1, loader.load(RETRY).getFlagCount());
+ }
+ }
+
+ @Test
+ public void failingOtherFileDoesNotRestartTheBound() throws Exception {
+ // a.yaml keeps being written while empty. Another file fails to load now and then, which must not
+ // give a.yaml a fresh bound.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ String other = "{\"flagValues\":{\"other\":\"value\"}}";
+ Path c = write(dir, "c.json", other);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, a, c);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(a);
+ assertHeld(loader, a);
+ for (int i = 1; i < 10; i++) {
+ clock.advance(0.5);
+ writeAgain(a, " ");
+ if (i % 2 == 1) {
+ InPlaceWrites.rewrite(c, "{bad", () -> { });
+ try {
+ loader.load(RETRY);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString(c.toString()));
+ }
+ } else {
+ InPlaceWrites.rewrite(c, other, () -> { });
+ assertHeld(loader, a);
+ }
+ }
+ clock.advance(0.5);
+ writeAgain(a, " ");
+ InPlaceWrites.rewrite(c, other, () -> { });
+ LoadResult result = loader.load(RETRY);
+ assertEquals(1, result.getFlagCount());
+ assertFalse(result.getFiles().get(0).hasContent());
+ }
+ }
+
+ // Loads the files and applies the result, as the reloader does, or reports that the load held a
+ // file back.
+ private static boolean loadApplies(OverrideFileLoader loader) throws Exception {
+ try {
+ loader.accepted(loader.load(RETRY));
+ return true;
+ } catch (EmptiedFileException e) {
+ return false;
+ }
+ }
+
+ @Test
+ public void filesEmptiedInStaggeredTurnsAreAppliedAfterTheBound() throws Exception {
+ // Two files stay empty and are truncated again in turn, so that whenever one of them has stayed
+ // empty for the whole delay, the other is still within its delay and holds the load back. A file
+ // that settles so does not get a fresh bound while the other is held back.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ Path b = write(dir, "b.yaml", "flagValues:\n other: \"value\"\n");
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, a, b);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(a);
+ assertHeld(loader, a);
+ boolean applied = false;
+ for (int i = 1; i <= 14 && !applied; i++) {
+ clock.advance(0.9);
+ if (i == 1) {
+ InPlaceWrites.truncate(b);
+ } else {
+ truncateAgain(i % 2 == 1 ? b : a);
+ }
+ applied = loadApplies(loader);
+ if (!applied) {
+ // The retry that the hold arms, a little after the other file's delay is over.
+ clock.advance(0.2);
+ applied = loadApplies(loader);
+ clock.advance(-0.2);
+ }
+ }
+ assertTrue("the files were held back without end", applied);
+ }
+ }
+
+ @Test
+ public void boundOfAFileHeldBackDuringAFailureStartsOverOnceItIsReadAgain() throws Exception {
+ // While b.json fails to load, a.yaml is rewritten once and its gap is held back. Later, b.json is
+ // fixed while a.yaml is in the middle of another rewrite, which is held back with a bound of its own.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ String other = "{\"flagValues\":{\"other\":\"value\"}}";
+ Path b = write(dir, "b.json", other);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, a, b);
+ loadAndAccept(loader);
+
+ InPlaceWrites.rewrite(b, "{bad", () -> { });
+ InPlaceWrites.truncate(a);
+ assertLoadFailsFor(loader, b);
+ InPlaceWrites.rewrite(a, "flagValues:\n flag: \"other value\"\n", () -> { });
+ assertLoadFailsFor(loader, b);
+ clock.advance(6);
+ assertLoadFailsFor(loader, b);
+
+ InPlaceWrites.rewrite(b, other, () -> { });
+ InPlaceWrites.truncate(a);
+ assertHeld(loader, a);
+ }
+ }
+
+ @Test
+ public void fileFoundMissingStartsANewDelayWhenItIsCreatedEmptyAgain() throws Exception {
+ // While b.json fails, a.yaml is emptied, deleted, and created empty again with the state it had
+ // when it was first found empty, as within one tick of a coarse clock. Being missing ended its
+ // empty state, so it is held back with a new delay.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ String other = "{\"flagValues\":{\"other\":\"value\"}}";
+ Path b = write(dir, "b.json", other);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, a, b);
+ loadAndAccept(loader);
+
+ InPlaceWrites.rewrite(b, "{bad", () -> { });
+ InPlaceWrites.truncate(a);
+ java.nio.file.attribute.FileTime emptiedAt = Files.getLastModifiedTime(a);
+ assertLoadFailsFor(loader, b);
+ clock.advance(0.5);
+ Files.delete(a);
+ assertLoadFailsFor(loader, b);
+ clock.advance(0.67);
+ Files.write(a, new byte[0]);
+ Files.setLastModifiedTime(a, emptiedAt);
+ assertLoadFailsFor(loader, b);
+
+ InPlaceWrites.rewrite(b, other, () -> { });
+ assertHeld(loader, a);
+ }
+ }
+
+ @Test
+ public void fixOfAFileSavedInPlaceWithAnErrorIsHeldBack() throws Exception {
+ // An operator saves the file in place with a mistake, and saves the fix in place long after. The
+ // loads in between fail on the file, and the fix's own gap is held back.
+ for (String name : new String[] { "data.yaml", "data.json" }) {
+ try (TempDir dir = TempDir.create()) {
+ boolean yaml = name.endsWith(".yaml");
+ Path file = write(dir, name, yaml ? YAML_DOC : JSON_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ InPlaceWrites.rewrite(file, yaml ? "flagValues: [\n" : "{\"flagValues\": ", () -> { });
+ assertLoadFailsFor(loader, file);
+ for (int i = 0; i < 6; i++) {
+ clock.advance(1);
+ assertLoadFailsFor(loader, file);
+ }
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ InPlaceWrites.rewrite(file, yaml ? "flagValues:\n flag: \"fixed\"\n" : "{\"flagValues\":{\"flag\":\"fixed\"}}",
+ () -> { });
+ assertEquals(name, 1, loader.load(RETRY).getFlagCount());
+ }
+ }
+ }
+
+ @Test
+ public void fileThatFailedToParseStartsANewDelayWhenItIsEmptiedAgain() throws Exception {
+ // Content that fails to parse also ends the file's empty state, so an emptying after it starts a
+ // new delay, even when a coarse clock gives it the state of the earlier emptying.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, file);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ java.nio.file.attribute.FileTime emptiedAt = Files.getLastModifiedTime(file);
+ assertHeld(loader, file);
+ clock.advance(0.5);
+ InPlaceWrites.rewrite(file, "flagValues: [\n", () -> { });
+ assertLoadFailsFor(loader, file);
+ clock.advance(0.7);
+ InPlaceWrites.truncate(file);
+ Files.setLastModifiedTime(file, emptiedAt);
+ assertHeld(loader, file);
+ }
+ }
+
+ @Test
+ public void fileThatFailsToReadStartsItsBoundOver() throws Exception {
+ // A load that fails because a file cannot be read holds nothing back, so it starts that file's
+ // bound over too.
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ AtomicLong unreadable = new AtomicLong();
+ OverrideFileLoader loader = new OverrideFileLoader(Collections.singletonList(file),
+ FileData.DuplicateKeysHandling.FAIL, clock.nanos::get, path -> {
+ if (unreadable.get() != 0) {
+ throw new java.io.IOException("permission denied");
+ }
+ return Files.readAllBytes(path);
+ });
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(file);
+ assertHeld(loader, file);
+ unreadable.set(1);
+ for (int i = 0; i < 6; i++) {
+ clock.advance(1);
+ assertLoadFailsFor(loader, file);
+ }
+ unreadable.set(0);
+ writeAgain(file, " ");
+ assertHeld(loader, file);
+ }
+ }
+
+ @Test
+ public void boundOfAFileAfterAFailingFileStartsOverOnceItIsReadAgain() throws Exception {
+ // c.json comes first. While it fails, a.yaml, which was held back, gets its content; the failing
+ // loads still read a.yaml, so its bound starts over, and the in-place rewrite of a.yaml that comes
+ // with the fix of c.json is held back.
+ try (TempDir dir = TempDir.create()) {
+ String other = "{\"flagValues\":{\"other\":\"value\"}}";
+ Path c = write(dir, "c.json", other);
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, c, a);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(a);
+ assertHeld(loader, a);
+ InPlaceWrites.rewrite(c, "{bad", () -> { });
+ InPlaceWrites.rewrite(a, YAML_DOC, () -> { });
+ for (int i = 0; i < 6; i++) {
+ assertLoadFailsFor(loader, c);
+ clock.advance(1);
+ }
+ InPlaceWrites.rewrite(c, other, () -> { });
+ InPlaceWrites.truncate(a);
+ assertHeld(loader, a);
+ }
+ }
+
+ @Test
+ public void failingLoadReportsTheFirstFailure() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path first = write(dir, "first.json", "{bad");
+ Path second = write(dir, "second.yaml", "flagValues: [\n");
+ try {
+ loader(first, second).load(RETRY);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString(first + ": cannot parse JSON"));
+ }
+ }
+ }
+
+ @Test
+ public void fileAfterADuplicateKeyIsReadSoItsBoundStartsOver() throws Exception {
+ // The entries are merged only after every file is read, so a duplicate key between a.yaml and
+ // b.yaml does not keep the loads from reading c.yaml, whose bound starts over while they fail.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", "flagValues:\n k: \"a\"\n");
+ String bDoc = "flagValues:\n j: \"b\"\n";
+ Path b = write(dir, "b.yaml", bDoc);
+ Path c = write(dir, "c.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, a, b, c);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(c);
+ assertHeld(loader, c);
+ InPlaceWrites.rewrite(b, "flagValues:\n j: \"b\"\n k: \"dup\"\n", () -> { });
+ InPlaceWrites.rewrite(c, YAML_DOC, () -> { });
+ for (int i = 0; i < 8; i++) {
+ clock.advance(1);
+ try {
+ loader.load(RETRY);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString("key \"k\" was already defined"));
+ }
+ }
+ InPlaceWrites.rewrite(b, bDoc, () -> { });
+ truncateAgain(c);
+ assertHeld(loader, c);
+ }
+ }
+
+ @Test
+ public void fixOfAFileSavedInPlaceWithADuplicateKeyIsHeldBack() throws Exception {
+ // As with a parse error: b.yaml is saved in place with a key that a.yaml defines, then the fix is
+ // saved in place several retry delays later. The fix's gap is held back.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", "flagValues:\n k: \"a\"\n");
+ Path b = write(dir, "b.yaml", "flagValues:\n j: \"b\"\n");
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, a, b);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(b);
+ assertHeld(loader, b);
+ InPlaceWrites.rewrite(b, "flagValues:\n j: \"b\"\n k: \"dup\"\n", () -> { });
+ for (int i = 0; i < 7; i++) {
+ try {
+ loader.load(RETRY);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString("key \"k\" was already defined"));
+ }
+ clock.advance(1);
+ }
+ InPlaceWrites.truncate(b);
+ assertHeld(loader, b);
+ }
+ }
+
+ @Test
+ public void slowReadOfTheEmptiedFileItselfDoesNotShortenItsDelay() throws Exception {
+ // The emptied file's own read stalls for most of a retry delay, as on a network file system. Its
+ // delay counts from after its read.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ AtomicLong slowRead = new AtomicLong();
+ OverrideFileLoader loader = new OverrideFileLoader(Collections.singletonList(a),
+ FileData.DuplicateKeysHandling.FAIL, clock.nanos::get, path -> {
+ byte[] raw = Files.readAllBytes(path);
+ if (slowRead.getAndSet(0) != 0) {
+ clock.advance(0.9);
+ }
+ return raw;
+ });
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(a);
+ slowRead.set(1);
+ assertHeld(loader, a);
+ clock.advance(0.2);
+ assertHeld(loader, a);
+ }
+ }
+
+ @Test
+ public void jsonDocumentThatIsNotAnObjectFailsToParse() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ for (String doc : new String[] { "null", "[]", "5", "\"x\"" }) {
+ Path file = write(dir, "overrides.json", doc);
+ try {
+ loader(file).load(Duration.ZERO);
+ fail("expected exception for " + doc);
+ } catch (FileDataException e) {
+ assertEquals("file " + file + ": the JSON document is not an object", e.getMessage());
+ assertNull(e.getCause());
+ }
+ }
+ }
+ }
+
+ @Test
+ public void textEncodingIsDetectedFromAByteOrderMarkAndIsUtf8Otherwise() throws Exception {
+ // Applies to both formats. Without a byte order mark the text is UTF-8, whatever the platform's
+ // default encoding.
+ String[] names = { "overrides.json", "overrides.yaml" };
+ java.nio.charset.Charset[] charsets = { StandardCharsets.UTF_8, StandardCharsets.UTF_16LE,
+ StandardCharsets.UTF_16BE };
+ try (TempDir dir = TempDir.create()) {
+ for (String name : names) {
+ String doc = name.endsWith(".json") ? "{\"flagValues\":{\"flag\":\"caf\u00e9\"}}"
+ : "flagValues:\n flag: \"caf\u00e9\"\n";
+ for (java.nio.charset.Charset charset : charsets) {
+ for (boolean bom : new boolean[] { true, false }) {
+ if (!bom && charset != StandardCharsets.UTF_8) {
+ continue;
+ }
+ Path file = dir.getPath().resolve(name);
+ Files.write(file, ((bom ? "\uFEFF" : "") + doc).getBytes(charset));
+ LoadResult result = loader(file).load(Duration.ZERO);
+ String what = name + " " + charset + (bom ? " with a byte order mark" : "");
+ assertEquals(what, LDValue.buildArray().add("caf\u00e9").build(),
+ json(FEATURES, toMap(result).get(FEATURES).get("flag")).get("variations"));
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void utf16FileWithOnlyWhiteSpaceCountsAsEmpty() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ OverrideFileLoader loader = loader(new TestClock(), file);
+ loadAndAccept(loader);
+
+ Files.write(file, "\uFEFF \n".getBytes(StandardCharsets.UTF_16LE));
+ assertHeld(loader, file);
+ }
+ }
+
+ @Test
+ public void contentHashCoversPathsAndPresence() throws Exception {
+ // The format depends on the path, so the same bytes moved from one configured file to another
+ // can be different data.
+ try (TempDir dir = TempDir.create()) {
+ Path yaml = write(dir, "overrides.yaml", "{\"flagValues\": {\"flag\": on}}");
+ Path json = dir.getPath().resolve("overrides.json");
+ OverrideFileLoader loader = loader(yaml, json);
+ LoadResult before = loader.load(Duration.ZERO);
+ Files.move(yaml, json);
+ LoadResult after = loader.load(Duration.ZERO);
+ assertThat(Arrays.equals(before.getContentHash(), after.getContentHash()), is(false));
+ assertEquals(LDValue.of(true), json(FEATURES, toMap(before).get(FEATURES).get("flag")).get("variations").get(0));
+ assertEquals(LDValue.of("on"), json(FEATURES, toMap(after).get(FEATURES).get("flag")).get("variations").get(0));
+ }
+ }
+
+ // Loads the files and applies the result, as the reloader does, or reports that the load held a
+ // file back or failed.
+ private static boolean loadAppliesOrFails(OverrideFileLoader loader) throws Exception {
+ try {
+ loader.accepted(loader.load(RETRY));
+ return true;
+ } catch (EmptiedFileException | FileDataException e) {
+ return false;
+ }
+ }
+
+ @Test
+ public void loadThatHoldsAFileBackAndThenFailsDoesNotStartBoundsOver() throws Exception {
+ // a.yaml and b.yaml are rewritten in turn, so that every load holds one of them back, and c.json
+ // fails at every other load. Those loads hold a file back, so they start no bound over.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ String bDoc = "flagValues:\n other: \"value\"\n";
+ Path b = write(dir, "b.yaml", bDoc);
+ String cGood = "{\"flagValues\":{\"third\":\"value\"}}";
+ Path c = write(dir, "c.json", cGood);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, a, b, c);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(a);
+ assertHeld(loader, a);
+ boolean applied = false;
+ for (int i = 1; i <= 12 && !applied; i++) {
+ clock.advance(0.5);
+ boolean odd = i % 2 == 1;
+ InPlaceWrites.rewrite(odd ? a : b, odd ? YAML_DOC : bDoc, () -> { });
+ InPlaceWrites.truncate(odd ? b : a);
+ InPlaceWrites.rewrite(c, odd ? "{bad" : cGood, () -> { });
+ applied = loadAppliesOrFails(loader);
+ }
+ assertTrue("the files were held back without end", applied);
+ }
+ }
+
+ @Test
+ public void fileKeptWrittenWhileEmptyIsAppliedAfterItsBoundWhileAnEarlierFileFails() throws Exception {
+ // c.json comes first and fails now and then, while a.yaml keeps being written while empty. The
+ // failing loads still read a.yaml and hold it back, so they do not start its bound over.
+ try (TempDir dir = TempDir.create()) {
+ String other = "{\"flagValues\":{\"other\":\"value\"}}";
+ Path c = write(dir, "c.json", other);
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, c, a);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(a);
+ assertHeld(loader, a);
+ for (int i = 1; i <= 5; i++) {
+ clock.advance(0.9);
+ writeAgain(a, i % 2 == 0 ? " " : " ");
+ if (i % 2 == 1) {
+ InPlaceWrites.rewrite(c, "{bad", () -> { });
+ assertLoadFailsFor(loader, c);
+ } else {
+ InPlaceWrites.rewrite(c, other, () -> { });
+ assertHeld(loader, a);
+ }
+ }
+ clock.advance(0.9);
+ writeAgain(a, " ");
+ InPlaceWrites.rewrite(c, other, () -> { });
+ assertEquals(1, loader.load(RETRY).getFlagCount());
+ }
+ }
+
+ @Test
+ public void holdAsksForTheRetryFromTheEndOfTheLoad() throws Exception {
+ // The read of the file after the held one takes longer than what is left of the held file's
+ // delay, so the retry is due right away, after the margin.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ Path b = write(dir, "b.yaml", "flagValues:\n other: \"value\"\n");
+ TestClock clock = new TestClock();
+ AtomicLong slowReadOf = new AtomicLong();
+ OverrideFileLoader loader = new OverrideFileLoader(Arrays.asList(a, b), FileData.DuplicateKeysHandling.FAIL,
+ clock.nanos::get, path -> {
+ byte[] raw = Files.readAllBytes(path);
+ if (path.equals(b) && slowReadOf.getAndSet(0) != 0) {
+ clock.advance(0.1);
+ }
+ return raw;
+ });
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(a);
+ assertEquals(1.1, assertHeld(loader, a), 1e-9);
+ clock.advance(0.95);
+ slowReadOf.set(1);
+ assertEquals(0.1, assertHeld(loader, a), 1e-9);
+ }
+ }
+
+ private static void assertLoadFailsFor(OverrideFileLoader loader, Path file) throws Exception {
+ try {
+ loader.load(RETRY);
+ fail("expected the load to fail");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString(file.toString()));
+ }
+ }
+
+ @Test
+ public void anotherFilesBoundDoesNotCutShortARewrite() throws Exception {
+ // b.yaml keeps being written while empty, and reaches its bound while a.yaml is in the middle of an
+ // ordinary rewrite. a.yaml is still held back.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ Path b = write(dir, "b.yaml", "flagValues:\n other: \"value\"\n");
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, a, b);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(b);
+ assertHeld(loader, b);
+ for (int i = 1; i <= 9; i++) {
+ clock.advance(0.5);
+ writeAgain(b, " ");
+ if (i == 9) {
+ InPlaceWrites.truncate(a);
+ assertHeld(loader, a, b);
+ } else {
+ assertHeld(loader, b);
+ }
+ }
+ // b's bound is over now, but a has been empty for half a retry delay only.
+ clock.advance(0.5);
+ writeAgain(b, " ");
+ assertHeld(loader, a);
+
+ clock.advance(0.25);
+ InPlaceWrites.rewrite(a, YAML_DOC, () -> { });
+ LoadResult result = loader.load(RETRY);
+ assertEquals(1, result.getFlagCount());
+ assertTrue(result.getFiles().get(0).hasContent());
+ }
+ }
+
+ @Test
+ public void holdAsksForTheRestOfTheDelayAfterASlowReadOfAnotherFile() throws Exception {
+ // a.yaml is held back, and the read of b.yaml after it takes half a retry delay. The retry comes
+ // when a.yaml's delay is over, counted from when the load asks for it.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ Path b = write(dir, "b.yaml", "flagValues:\n other: \"value\"\n");
+ TestClock clock = new TestClock();
+ AtomicLong slowReadOf = new AtomicLong();
+ OverrideFileLoader loader = new OverrideFileLoader(Arrays.asList(a, b), FileData.DuplicateKeysHandling.FAIL,
+ clock.nanos::get, path -> {
+ byte[] raw = Files.readAllBytes(path);
+ if (path.equals(b) && slowReadOf.getAndSet(0) != 0) {
+ clock.advance(0.5);
+ }
+ return raw;
+ });
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(a);
+ slowReadOf.set(1);
+ assertEquals(0.6, assertHeld(loader, a), 1e-9);
+ }
+ }
+
+ @Test
+ public void slowReadOfAnotherFileDoesNotShortenTheDelay() throws Exception {
+ // The read of b.yaml, which comes first, takes most of a retry delay. a.yaml's delay counts from
+ // when a.yaml was read.
+ try (TempDir dir = TempDir.create()) {
+ Path a = write(dir, "a.yaml", YAML_DOC);
+ Path b = write(dir, "b.yaml", "flagValues:\n other: \"value\"\n");
+ TestClock clock = new TestClock();
+ AtomicLong slowReadOf = new AtomicLong();
+ OverrideFileLoader loader = new OverrideFileLoader(Arrays.asList(b, a), FileData.DuplicateKeysHandling.FAIL,
+ clock.nanos::get, path -> {
+ byte[] raw = Files.readAllBytes(path);
+ if (path.equals(b) && slowReadOf.getAndSet(0) != 0) {
+ clock.advance(0.94);
+ }
+ return raw;
+ });
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(a);
+ slowReadOf.set(1);
+ assertHeld(loader, a);
+ clock.advance(0.1);
+ assertHeld(loader, a);
+ }
+ }
+
+ @Test
+ public void withoutRetriesAnEmptiedFileIsParsedRightAway() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path file = write(dir, "overrides.yaml", YAML_DOC);
+ OverrideFileLoader loader = loader(new TestClock(), file);
+ loader.accepted(loader.load(Duration.ZERO));
+
+ InPlaceWrites.truncate(file);
+ assertEquals(0, loader.load(Duration.ZERO).getFlagCount());
+ }
+ }
+
+ @Test
+ public void filesEmptiedTogetherAreHeldFromTheSameLoad() throws Exception {
+ // A load that holds back one file still reads the others, so each emptied file starts its delay
+ // in that load and all of them are parsed after one retry delay, not one retry delay per file.
+ try (TempDir dir = TempDir.create()) {
+ Path first = write(dir, "first.yaml", YAML_DOC);
+ Path second = write(dir, "second.yaml", "flagValues:\n other: \"value\"\n");
+ TestClock clock = new TestClock();
+ OverrideFileLoader loader = loader(clock, first, second);
+ assertEquals(2, loadAndAccept(loader).getFlagCount());
+
+ InPlaceWrites.truncate(first);
+ InPlaceWrites.truncate(second);
+ assertHeld(loader, first, second);
+ clock.advance(1);
+ assertEquals(0, loader.load(RETRY).getFlagCount());
+ }
+ }
+
+ @Test
+ public void failureOfAnotherFileFailsALoadThatHoldsAFile() throws Exception {
+ try (TempDir dir = TempDir.create()) {
+ Path first = write(dir, "first.yaml", YAML_DOC);
+ Path second = write(dir, "second.json", JSON_DOC.replace("flag", "other"));
+ OverrideFileLoader loader = loader(new TestClock(), first, second);
+ loadAndAccept(loader);
+
+ InPlaceWrites.truncate(first);
+ InPlaceWrites.rewrite(second, "{\"flagValues\"", () -> { });
+ try {
+ loader.load(RETRY);
+ fail("expected exception");
+ } catch (FileDataException e) {
+ assertThat(e.getMessage(), containsString(second + ": cannot parse JSON"));
+ }
+ }
+ }
+}
From 939b451d048d5c6733491d0cae5a1e588bad5e31 Mon Sep 17 00:00:00 2001
From: Ryan Lamb <4955475+kinyoklion@users.noreply.github.com>
Date: Thu, 3 Dec 2026 09:59:06 -0800
Subject: [PATCH 4/9] feat: Add the override marker to the flag and segment
models and mark evaluations (#221)
## Update, 2026-12-03
- `launchdarkly-java-sdk-common` 2.6.0 is released from `main` (#298).
Its source is the same as on `feat/overrides`, and the pin is unchanged.
- Verified against the Maven Central artifact: this head builds, with
the contract test service, and CI passes.
## Update, 2026-12-01
- Rebased onto `feat/overrides`, which has `main` merged into it again.
From `main` it gets the 7.19.0 to 7.19.2 releases, `java-sdk-internal`
1.14.0, and the FDv2 fix that leaves out an empty selector (#261). The
v3.2.0-alpha.21 contract tests check that fix, so CI failed three FDv2
streaming tests without it.
- Rebase conflict in `build.gradle`: `main`'s internal 1.14.0, with this
PR's common 2.6.0.
- `main` added a `clientSideAvailability` argument to the `FeatureFlag`
constructor (#275). The marked copy of a flag now passes it on, so an
override keeps the flag's client-side availability. The change is in the
first commit, and its test checks it.
- Verified with the v3.2.0-alpha.21 harness that CI runs, with `common`
2.6.0 and `internal` 1.15.0 published locally from `feat/overrides`:
- every PR in the stack compiles, with Javadoc, at its own head;
- the server unit tests pass at the top (2348, with the 72 existing
skips);
- the full v3 contract tests pass at the top (6457 tests ran). That
includes the flag overrides suite and both flag listener suites.
## Update, 2026-11-13
- Rebased onto `feat/overrides`, which now includes #218 and #219 and
has `main` merged into it. From `main` it gets the 7.18.0 release, CI on
the latest v3 contract tests, flag change listener support in the
contract test service, and the `java-sdk-internal` 1.12.1 and 1.12.2
fixes. A common 2.6.0 and internal 1.13.0 release from this branch needs
those fixes.
- Rebase conflicts with `main`, both resolved by keeping both sides:
- `Evaluator.java`: `main`'s #258 keeps the big segments status on an
error reason, and this PR marks that result as override-affected.
- `build.gradle`: `main`'s `jsr305` and internal 1.12.2, with this PR's
common 2.6.0.
- Verified at the top of the stack, with `common` and `internal`
published locally from `feat/overrides`:
- every PR in the stack compiles, with Javadoc, at its own head;
- the server unit tests pass (2285, with the 72 existing skips);
- the full v3 contract tests pass (6321 tests). That includes the flag
overrides suite, with the deleted-entry tests of
launchdarkly/sdk-test-harness#599, and both flag listener suites.
## Summary
The OVERRIDE specification requires an evaluation to be marked as
override-affected when any definition it read carried the override
marker: the evaluated flag, a prerequisite at any depth, or a segment
consulted during matching, whether or not the segment matched. The
marking propagates upward only: a prerequisite's own record reflects
only the definitions that its own subtree read, while the evaluation
that requested it accumulates the result. An evaluation that fails is
still marked when it read a marked definition, and a requested-type
mismatch keeps the marking on its error reason, as does the WRONG_TYPE
error that `migrationVariation` returns for an unrecognized stage.
- `DataModel.FeatureFlag` and `DataModel.Segment` carry a transient
`isOverride` marker. It is never serialized and never read from JSON.
`markedAsOverride()` returns a shallow copy with the marker set, sharing
nested collections and preprocessing with the source and never modifying
it. The override layer will use it in the next change.
- The evaluator tracks the marking per evaluation scope. The scope
starts from its own flag's marker, each segment read can set it, and the
value is saved, reset to the prerequisite's own marker, and restored
around every prerequisite evaluation. Each result and each prerequisite
record carries the marking on its reason.
- `EvalResult.isOverrideAffected()` reads the reason's indicator, and
`withOverrideAffected(boolean)` returns a copy so that the shared
precomputed results are never mutated.
- An evaluation that throws returns an `EXCEPTION` result marked with
the evaluated flag's own marker, because that definition was read before
the failure.
- The server SDK now depends on launchdarkly-java-sdk-common 2.6.0,
which adds `EvaluationReason.isOverrideAffected()` and the
`overrideAffected` JSON property (written only when true).
Flag overrides are currently experimental and subject to change.
The existing file data source keeps its current behavior; this change
does not touch its code paths.
[SDK-3246](https://launchdarkly.atlassian.net/browse/SDK-3246)
[SDK-3246]:
https://launchdarkly.atlassian.net/browse/SDK-3246?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
---
> [!NOTE]
> **Overview**
> Adds **experimental flag-override tracking** so evaluations can report
when they were influenced by local override definitions rather than
LaunchDarkly data.
>
> **FeatureFlag** and **Segment** gain a transient `isOverride` marker
(never serialized) and `markedAsOverride()` shallow copies for the
override layer to use. The **Evaluator** tracks whether the current
scope read any marked flag, prerequisite subtree, or segment (match or
not), propagating upward while keeping each prerequisite record scoped
to its own subtree. **`EvalResult`** exposes `isOverrideAffected()` and
`withOverrideAffected()` via `EvaluationReason` so shared precomputed
results stay immutable.
>
> **InputValidatingEvaluator**, **MigrationStageEnforcingEvaluator**,
and `allFlagsState` preserve override marking across type errors,
exceptions, and malformed evaluations. Dependency
**`launchdarkly-java-sdk-common`** is bumped to **2.6.0** for
`EvaluationReason.isOverrideAffected()`.
>
> Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a2a5c8e4758c8cf342738552237fecb7c2c4fd78. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).
Opened from termag
---
lib/sdk/server/build.gradle | 2 +-
.../launchdarkly/sdk/server/DataModel.java | 60 +++
.../launchdarkly/sdk/server/EvalResult.java | 19 +
.../launchdarkly/sdk/server/Evaluator.java | 35 +-
.../sdk/server/InputValidatingEvaluator.java | 18 +-
.../MigrationStageEnforcingEvaluator.java | 5 +-
.../sdk/server/DataModelTest.java | 91 +++++
.../sdk/server/EvalResultTest.java | 47 +++
.../server/EvaluatorOverrideMarkingTest.java | 346 ++++++++++++++++++
.../InputValidatingEvaluatorOverrideTest.java | 183 +++++++++
10 files changed, 798 insertions(+), 8 deletions(-)
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/EvaluatorOverrideMarkingTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/InputValidatingEvaluatorOverrideTest.java
diff --git a/lib/sdk/server/build.gradle b/lib/sdk/server/build.gradle
index 07d418d5..c3278119 100644
--- a/lib/sdk/server/build.gradle
+++ b/lib/sdk/server/build.gradle
@@ -72,7 +72,7 @@ ext.versions = [
"guava": "33.8.0-jre",
"jackson": "2.11.2",
"jsr305": "3.0.2",
- "launchdarklyJavaSdkCommon": "2.3.0",
+ "launchdarklyJavaSdkCommon": "2.6.0",
"launchdarklyJavaSdkInternal": "1.14.0",
"launchdarklyLogging": "1.1.0",
"okhttp": "4.12.0", // specify this for the SDK build instead of relying on the transitive dependency from okhttp-eventsource
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataModel.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataModel.java
index e00b6e4d..7777e074 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataModel.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataModel.java
@@ -146,6 +146,15 @@ static final class FeatureFlag implements VersionedData, JsonHelpers.PostProcess
private Migration migration;
private boolean excludeFromSummaries;
+ // True if this definition came from the SDK's override store rather than from LaunchDarkly. The
+ // field is transient so that it never appears in the JSON form of the flag and never takes part
+ // in deserialization. Only the override layer sets it, on a copy that it owns. Evaluation reads
+ // it to mark the evaluation as override-affected. Other readers treat a marked flag the same as
+ // any other flag.
+ //
+ // Flag overrides are currently experimental and subject to change.
+ private transient boolean isOverride;
+
/**
* Tells which kinds of client-side SDK can use the flag. The flag has this object only if its JSON
* has a "clientSideAvailability" object.
@@ -300,6 +309,31 @@ boolean isExcludeFromSummaries() {
return excludeFromSummaries;
}
+ /**
+ * Returns true if this definition came from the override store.
+ *
+ * @return true for an override entry
+ */
+ boolean isOverride() {
+ return isOverride;
+ }
+
+ /**
+ * Returns a shallow copy of this flag that carries the override marker. The copy shares its
+ * nested lists and its preprocessing data with this flag and never writes to them. This flag is
+ * not modified.
+ *
+ * @return a marked copy
+ */
+ FeatureFlag markedAsOverride() {
+ FeatureFlag copy = new FeatureFlag(key, version, on, prerequisites, salt, targets, contextTargets, rules,
+ fallthrough, offVariation, variations, clientSide, clientSideAvailability, trackEvents,
+ trackEventsFallthrough, debugEventsUntilDate, deleted, samplingRatio, migration, excludeFromSummaries);
+ copy.preprocessed = preprocessed;
+ copy.isOverride = true;
+ return copy;
+ }
+
public void afterDeserialized() {
// The "clientSideAvailability" object is in the newer schema. If the flag has the object, set
// "clientSide" to the value of "usingEnvironmentId". The SDK then writes the two properties
@@ -546,6 +580,10 @@ static final class Segment implements VersionedData, JsonHelpers.PostProcessingD
private ContextKind unboundedContextKind;
private Integer generation;
+ // True if this definition came from the SDK's override store rather than from LaunchDarkly. See
+ // the note on the same field in FeatureFlag.
+ private transient boolean isOverride;
+
Segment() {}
Segment(String key,
@@ -627,6 +665,28 @@ public Integer getGeneration() {
return generation;
}
+ /**
+ * Returns true if this definition came from the override store.
+ *
+ * @return true for an override entry
+ */
+ boolean isOverride() {
+ return isOverride;
+ }
+
+ /**
+ * Returns a shallow copy of this segment that carries the override marker. The copy shares its
+ * nested collections with this segment and never writes to them. This segment is not modified.
+ *
+ * @return a marked copy
+ */
+ Segment markedAsOverride() {
+ Segment copy = new Segment(key, included, excluded, includedContexts, excludedContexts, salt, rules,
+ version, deleted, unbounded, unboundedContextKind, generation);
+ copy.isOverride = true;
+ return copy;
+ }
+
public void afterDeserialized() {
DataModelPreprocessing.preprocessSegment(this);
}
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/EvalResult.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/EvalResult.java
index 8611afbb..ac7a2b89 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/EvalResult.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/EvalResult.java
@@ -228,6 +228,14 @@ public EvaluationDetail getAsString() {
*/
public boolean isForceReasonTracking() { return forceReasonTracking; }
+ /**
+ * Returns true if an override affected this evaluation, directly or transitively. The value is
+ * the reason's indicator, so the result and the reason it returns to the caller always agree.
+ * Flag overrides are currently experimental and subject to change.
+ * @return true if an override affected the evaluation
+ */
+ public boolean isOverrideAffected() { return anyType.getReason().isOverrideAffected(); }
+
public List getPrerequisiteEvalRecords() { return prerequisiteEvalRecords; }
/**
@@ -251,6 +259,17 @@ public EvalResult withForceReasonTracking(boolean newValue) {
public EvalResult withPrerequisiteEvalRecords(List newValue) {
return this.prerequisiteEvalRecords == newValue ? this : new EvalResult(this, newValue);
}
+
+ /**
+ * Returns a transformed copy of this EvalResult whose reason carries the given override-affected
+ * indicator, or this same instance if the indicator is unchanged. Precomputed results are shared
+ * between evaluations, so a marked result is always a new instance.
+ * @param newValue the new value for the indicator
+ * @return a transformed copy
+ */
+ public EvalResult withOverrideAffected(boolean newValue) {
+ return withReason(anyType.getReason().withOverrideAffected(newValue));
+ }
@Override
public boolean equals(Object other) {
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/Evaluator.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/Evaluator.java
index 7590cb73..74609fb1 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/Evaluator.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/Evaluator.java
@@ -124,6 +124,12 @@ private static class EvaluatorState {
private List prerequisiteStack = null;
private List prerequisiteEvalRecords = new ArrayList<>(0); // 0 initial capacity uses a static instance for performance
private List segmentStack = null;
+ // True if the current evaluation scope has read a definition that carries the override marker.
+ // The scope starts from its own flag's marker. Each segment read can set it. Around a
+ // prerequisite evaluation the value is saved and reset, so the prerequisite's record reflects
+ // only the definitions that its own subtree read, and the parent scope accumulates that result
+ // afterwards. The marking therefore propagates upward only.
+ private boolean overrideAffected = false;
}
Evaluator(Getters getters, LDLogger logger) {
@@ -146,6 +152,8 @@ EvalResult evaluate(FeatureFlag flag, LDContext context, @Nonnull EvaluationReco
EvaluatorState state = new EvaluatorState();
state.originalFlag = flag;
+ // Reading the flag's own definition is the first read of this scope.
+ state.overrideAffected = flag.isOverride();
try {
EvalResult result = evaluateInternal(flag, context, recorder, state);
@@ -160,7 +168,7 @@ EvalResult evaluate(FeatureFlag flag, LDContext context, @Nonnull EvaluationReco
result = result.withPrerequisiteEvalRecords(state.prerequisiteEvalRecords);
}
- return result;
+ return result.withOverrideAffected(state.overrideAffected);
} catch (EvaluationException e) {
logger.error("Could not evaluate flag \"{}\": {}", flag.getKey(), e.getMessage());
EvalResult result = EvalResult.error(e.errorKind);
@@ -170,7 +178,9 @@ EvalResult evaluate(FeatureFlag flag, LDContext context, @Nonnull EvaluationReco
result.getReason().withBigSegmentsStatus(state.bigSegmentsStatus)
);
}
- return result;
+ // An error result is marked too. A malformed override definition yields the caller's default
+ // value with an error reason, and an override still affected that result.
+ return result.withOverrideAffected(state.overrideAffected);
}
}
@@ -253,7 +263,20 @@ private EvalResult checkPrerequisites(FeatureFlag flag, LDContext context, @Nonn
logger.error("Could not retrieve prerequisite flag \"{}\" when evaluating \"{}\"", prereq.getKey(), flag.getKey());
prereqOk = false;
} else {
- EvalResult prereqEvalResult = evaluateInternal(prereqFeatureFlag, context, recorder, state);
+ // The prerequisite evaluation is a scope of its own. Its marking starts from its own flag's
+ // marker, so its record reflects only the definitions that its subtree read. This scope
+ // accumulates that result afterwards, whether the nested evaluation returns or throws.
+ boolean parentOverrideAffected = state.overrideAffected;
+ state.overrideAffected = prereqFeatureFlag.isOverride();
+ EvalResult prereqEvalResult;
+ boolean prereqOverrideAffected;
+ try {
+ prereqEvalResult = evaluateInternal(prereqFeatureFlag, context, recorder, state);
+ } finally {
+ prereqOverrideAffected = state.overrideAffected;
+ state.overrideAffected = parentOverrideAffected || prereqOverrideAffected;
+ }
+ prereqEvalResult = prereqEvalResult.withOverrideAffected(prereqOverrideAffected);
// Note that if the prerequisite flag is off, we don't consider it a match no matter what its
// off variation was. But we still need to evaluate it in order to generate an event.
if (!prereqFeatureFlag.isOn() || prereqEvalResult.getVariationIndex() != prereq.getVariation()) {
@@ -468,6 +491,12 @@ private boolean matchAnySegment(List values, LDContext context, Evaluat
}
Segment segment = getters.getSegment(segmentKey);
if (segment != null) {
+ // The segment definition is read at this point, so an override segment marks the scope here.
+ // A match is not required. A negated clause turns a non-match into a match, so the definition
+ // shapes the result either way.
+ if (segment.isOverride()) {
+ state.overrideAffected = true;
+ }
if (segmentMatchesContext(segment, context, state)) {
return true;
}
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/InputValidatingEvaluator.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/InputValidatingEvaluator.java
index 8e7b61fd..e1ee6d05 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/InputValidatingEvaluator.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/InputValidatingEvaluator.java
@@ -135,7 +135,11 @@ EvalResultAndFlag evaluate(String flagKey, LDContext context, LDValue defaultVal
value.getType() != requireType) {
logger.error("Feature flag \"{}\"; evaluation expected result as {}, but got {}", flagKey, defaultValue.getType(), value.getType());
recorder.recordEvaluationError(featureFlag, context, defaultValue, ErrorKind.WRONG_TYPE);
- return new EvalResultAndFlag(EvalResult.error(ErrorKind.WRONG_TYPE, defaultValue), featureFlag);
+ // The type mismatch replaces the reason. The evaluation read the same definitions, so the
+ // new reason keeps the override-affected marking.
+ return new EvalResultAndFlag(
+ EvalResult.error(ErrorKind.WRONG_TYPE, defaultValue).withOverrideAffected(result.isOverrideAffected()),
+ featureFlag);
}
}
@@ -151,7 +155,12 @@ EvalResultAndFlag evaluate(String flagKey, LDContext context, LDValue defaultVal
} else {
recorder.recordEvaluationError(featureFlag, context, defaultValue, ErrorKind.EXCEPTION);
}
- return new EvalResultAndFlag(EvalResult.of(defaultValue, NO_VARIATION, EvaluationReason.exception(e)), null);
+ // The flag's definition was read before the failure, so its own marker decides the marking of
+ // the error result.
+ boolean overrideAffected = featureFlag != null && featureFlag.isOverride();
+ return new EvalResultAndFlag(
+ EvalResult.of(defaultValue, NO_VARIATION, EvaluationReason.exception(e)).withOverrideAffected(overrideAffected),
+ null);
}
}
@@ -199,7 +208,10 @@ public FeatureFlagsState allFlagsState(LDContext context, FlagsStateOption... op
logger.error("Exception caught for feature flag \"{}\" when evaluating all flags: {}", flag.getKey(),
LogValues.exceptionSummary(e));
logger.debug(e.toString(), LogValues.exceptionTrace(e));
- builder.addFlag(flag, EvalResult.of(LDValue.ofNull(), NO_VARIATION, EvaluationReason.exception(e)));
+ // The flag's definition was read before the failure, so its own marker decides the marking,
+ // and with it the state's event tracking fields for the flag.
+ builder.addFlag(flag, EvalResult.of(LDValue.ofNull(), NO_VARIATION, EvaluationReason.exception(e))
+ .withOverrideAffected(flag.isOverride()));
}
}
return builder.build();
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/MigrationStageEnforcingEvaluator.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/MigrationStageEnforcingEvaluator.java
index bdf2be3f..806a8bb2 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/MigrationStageEnforcingEvaluator.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/MigrationStageEnforcingEvaluator.java
@@ -28,7 +28,10 @@ public EvalResultAndFlag evalAndFlag(String method, String flagKey, LDContext co
String resStageString = resDetail.getValue();
if (!MigrationStage.isStage(resStageString)) {
logger.error("Unrecognized MigrationState for \"{}\"; returning default value.", flagKey);
- return new EvalResultAndFlag(EvalResult.error(EvaluationReason.ErrorKind.WRONG_TYPE, defaultValue), res.getFlag());
+ // The unrecognized stage replaces the result. The evaluation read the same definitions, so
+ // the new result keeps the override-affected marking.
+ return new EvalResultAndFlag(EvalResult.error(EvaluationReason.ErrorKind.WRONG_TYPE, defaultValue)
+ .withOverrideAffected(res.getResult().isOverrideAffected()), res.getFlag());
}
return res;
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/DataModelTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/DataModelTest.java
index 9cbbe9cd..142da821 100644
--- a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/DataModelTest.java
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/DataModelTest.java
@@ -11,9 +11,20 @@
import com.launchdarkly.sdk.server.DataModel.SegmentRule;
import com.launchdarkly.sdk.server.DataModel.Target;
+import com.launchdarkly.sdk.LDValue;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.ItemDescriptor;
+
import org.junit.Test;
+import static com.launchdarkly.sdk.server.ModelBuilders.flagBuilder;
+import static com.launchdarkly.sdk.server.ModelBuilders.prerequisite;
+import static com.launchdarkly.sdk.server.ModelBuilders.segmentBuilder;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
@SuppressWarnings("javadoc")
public class DataModelTest {
@@ -108,4 +119,84 @@ private Segment segmentWithAllZeroValuedFields() {
// and no preprocessing has happened.
return new Segment();
}
+
+ @Test
+ public void flagAndSegmentAreNotOverridesByDefault() {
+ assertFalse(flagBuilder("f").build().isOverride());
+ assertFalse(segmentBuilder("s").build().isOverride());
+ assertFalse(((FeatureFlag) DataModel.FEATURES.deserialize("{\"key\":\"f\",\"version\":1}").getItem()).isOverride());
+ assertFalse(((Segment) DataModel.SEGMENTS.deserialize("{\"key\":\"s\",\"version\":1}").getItem()).isOverride());
+ }
+
+ @Test
+ public void markedFlagCopyCarriesMarkerAndSharesDataWithoutMutatingSource() {
+ FeatureFlag source = flagBuilder("f").version(7).on(true).variations(LDValue.of("a"), LDValue.of("b"))
+ .fallthroughVariation(1).offVariation(0).prerequisites(prerequisite("p", 1)).trackEvents(true)
+ .debugEventsUntilDate(1000L).clientSideAvailability(true, false).build();
+
+ FeatureFlag marked = source.markedAsOverride();
+
+ assertTrue(marked.isOverride());
+ assertFalse(source.isOverride());
+ assertNotSame(source, marked);
+ assertEquals(source.getKey(), marked.getKey());
+ assertEquals(source.getVersion(), marked.getVersion());
+ assertEquals(source.isOn(), marked.isOn());
+ assertSame(source.getVariations(), marked.getVariations());
+ assertSame(source.getPrerequisites(), marked.getPrerequisites());
+ assertSame(source.getFallthrough(), marked.getFallthrough());
+ assertEquals(source.getOffVariation(), marked.getOffVariation());
+ assertEquals(source.isTrackEvents(), marked.isTrackEvents());
+ assertEquals(source.getDebugEventsUntilDate(), marked.getDebugEventsUntilDate());
+ assertSame(source.getClientSideAvailability(), marked.getClientSideAvailability());
+ assertEquals(source.isClientSide(), marked.isClientSide());
+ assertSame(source.preprocessed, marked.preprocessed);
+ }
+
+ @Test
+ public void markedFlagCopyOfUnpreprocessedFlagHasNoPreprocessing() {
+ FeatureFlag source = flagBuilder("f").disablePreprocessing(true).build();
+ FeatureFlag marked = source.markedAsOverride();
+ assertNull(marked.preprocessed);
+ assertNull(source.preprocessed);
+ assertTrue(marked.isOverride());
+ }
+
+ @Test
+ public void markedSegmentCopyCarriesMarkerAndSharesDataWithoutMutatingSource() {
+ Segment source = segmentBuilder("s").version(3).included("u1").excluded("u2").unbounded(false).build();
+
+ Segment marked = source.markedAsOverride();
+
+ assertTrue(marked.isOverride());
+ assertFalse(source.isOverride());
+ assertNotSame(source, marked);
+ assertEquals(source.getKey(), marked.getKey());
+ assertEquals(source.getVersion(), marked.getVersion());
+ assertSame(source.getIncluded(), marked.getIncluded());
+ assertSame(source.getExcluded(), marked.getExcluded());
+ assertSame(source.getRules(), marked.getRules());
+ }
+
+ @Test
+ public void overrideMarkerIsNeverSerialized() {
+ FeatureFlag flag = flagBuilder("f").version(7).build().markedAsOverride();
+ String flagJson = DataModel.FEATURES.serialize(new ItemDescriptor(flag.getVersion(), flag));
+ assertFalse(flagJson.toLowerCase().contains("override"));
+ assertEquals(LDValue.of("f"), LDValue.parse(flagJson).get("key"));
+
+ Segment segment = segmentBuilder("s").version(3).build().markedAsOverride();
+ String segmentJson = DataModel.SEGMENTS.serialize(new ItemDescriptor(segment.getVersion(), segment));
+ assertFalse(segmentJson.toLowerCase().contains("override"));
+ }
+
+ @Test
+ public void overrideMarkerInJsonIsIgnoredWhenDeserializing() {
+ FeatureFlag flag = (FeatureFlag) DataModel.FEATURES.deserialize(
+ "{\"key\":\"f\",\"version\":1,\"isOverride\":true}").getItem();
+ assertFalse(flag.isOverride());
+ Segment segment = (Segment) DataModel.SEGMENTS.deserialize(
+ "{\"key\":\"s\",\"version\":1,\"isOverride\":true}").getItem();
+ assertFalse(segment.isOverride());
+ }
}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/EvalResultTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/EvalResultTest.java
index 71ef5dec..59f1dfd0 100644
--- a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/EvalResultTest.java
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/EvalResultTest.java
@@ -13,6 +13,7 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.sameInstance;
@SuppressWarnings("javadoc")
@@ -134,6 +135,52 @@ public void withForceReasonTracking() {
assertThat(r1.getAnyType(), sameInstance(r.getAnyType()));
}
+ @Test
+ public void overrideAffectedFollowsTheReason() {
+ EvalResult r = EvalResult.of(SOME_VALUE, SOME_VARIATION, SOME_REASON);
+ assertThat(r.isOverrideAffected(), is(false));
+ assertThat(EvalResult.of(SOME_VALUE, SOME_VARIATION, SOME_REASON.withOverrideAffected(true)).isOverrideAffected(),
+ is(true));
+ assertThat(EvalResult.error(EvaluationReason.ErrorKind.MALFORMED_FLAG).isOverrideAffected(), is(false));
+ }
+
+ @Test
+ public void withOverrideAffected() {
+ EvalResult r = EvalResult.of(SOME_VALUE, SOME_VARIATION, SOME_REASON);
+
+ // Unchanged value keeps the same instance, so shared precomputed results stay shared.
+ assertThat(r.withOverrideAffected(false), sameInstance(r));
+
+ EvalResult marked = r.withOverrideAffected(true);
+ assertThat(marked, not(sameInstance(r)));
+ assertThat(marked.isOverrideAffected(), is(true));
+ assertThat(marked.getReason(), equalTo(SOME_REASON.withOverrideAffected(true)));
+ assertThat(marked.getValue(), equalTo(r.getValue()));
+ assertThat(marked.getVariationIndex(), equalTo(r.getVariationIndex()));
+ assertThat(marked.withOverrideAffected(true), sameInstance(marked));
+ assertThat(marked.withOverrideAffected(false), equalTo(r));
+
+ // Every typed view carries the marked reason.
+ assertThat(marked.getAsBoolean().getReason().isOverrideAffected(), is(true));
+ assertThat(marked.getAsInteger().getReason().isOverrideAffected(), is(true));
+ assertThat(marked.getAsDouble().getReason().isOverrideAffected(), is(true));
+ assertThat(marked.getAsString().getReason().isOverrideAffected(), is(true));
+ assertThat(marked.getAnyType().getReason().isOverrideAffected(), is(true));
+
+ // The original is untouched.
+ assertThat(r.isOverrideAffected(), is(false));
+ }
+
+ @Test
+ public void withOverrideAffectedKeepsPrerequisiteRecordsAndForceTracking() {
+ EvalResult r = EvalResult.of(SOME_VALUE, SOME_VARIATION, EvaluationReason.fallthrough(true))
+ .withPrerequisiteEvalRecords(java.util.Collections.singletonList(
+ new PrerequisiteEvalRecord(null, null, EvalResult.of(SOME_VALUE, SOME_VARIATION, SOME_REASON))));
+ EvalResult marked = r.withOverrideAffected(true);
+ assertThat(marked.isForceReasonTracking(), is(true));
+ assertThat(marked.getPrerequisiteEvalRecords(), sameInstance(r.getPrerequisiteEvalRecords()));
+ }
+
private void testForType(T value, LDValue ldValue, Function getter) {
assertThat(
getter.apply(EvalResult.of(EvaluationDetail.fromValue(ldValue, SOME_VARIATION, SOME_REASON))),
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/EvaluatorOverrideMarkingTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/EvaluatorOverrideMarkingTest.java
new file mode 100644
index 00000000..98affee2
--- /dev/null
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/EvaluatorOverrideMarkingTest.java
@@ -0,0 +1,346 @@
+package com.launchdarkly.sdk.server;
+
+import com.launchdarkly.sdk.EvaluationReason;
+import com.launchdarkly.sdk.EvaluationReason.ErrorKind;
+import com.launchdarkly.sdk.LDContext;
+import com.launchdarkly.sdk.LDValue;
+import com.launchdarkly.sdk.server.DataModel.FeatureFlag;
+import com.launchdarkly.sdk.server.DataModel.Segment;
+import com.launchdarkly.sdk.server.EvaluatorTestUtil.EvaluatorBuilder;
+
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.BASE_USER;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.FALLTHROUGH_VALUE;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.FALLTHROUGH_VARIATION;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.GREEN_VARIATION;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.MATCH_VALUE;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.MATCH_VARIATION;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.OFF_VALUE;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.OFF_VARIATION;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.buildRedGreenFlag;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.buildThreeWayFlag;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.evaluatorBuilder;
+import static com.launchdarkly.sdk.server.ModelBuilders.clause;
+import static com.launchdarkly.sdk.server.ModelBuilders.clauseMatchingSegment;
+import static com.launchdarkly.sdk.server.ModelBuilders.flagBuilder;
+import static com.launchdarkly.sdk.server.ModelBuilders.negateClause;
+import static com.launchdarkly.sdk.server.ModelBuilders.prerequisite;
+import static com.launchdarkly.sdk.server.ModelBuilders.ruleBuilder;
+import static com.launchdarkly.sdk.server.ModelBuilders.segmentBuilder;
+import static com.launchdarkly.sdk.server.ModelBuilders.segmentRuleBuilder;
+import static com.launchdarkly.sdk.server.ModelBuilders.target;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotSame;
+import static org.junit.Assert.assertSame;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * An evaluation is override-affected when any definition it read carries the override marker: the
+ * evaluated flag, a prerequisite at any depth, or a segment consulted during matching. The marking
+ * propagates upward only. A prerequisite's own record reflects only its own subtree.
+ */
+@SuppressWarnings("javadoc")
+public class EvaluatorOverrideMarkingTest {
+ private static final LDContext OTHER_USER = LDContext.create("other");
+
+ private static final class RecordingRecorder implements EvaluationRecorder {
+ final List prerequisites = new ArrayList<>();
+
+ @Override
+ public void recordPrerequisiteEvaluation(FeatureFlag flag, FeatureFlag prereqOfFlag, LDContext context, EvalResult result) {
+ prerequisites.add(new PrerequisiteEvalRecord(flag, prereqOfFlag, result));
+ }
+ }
+
+ private static PrerequisiteEvalRecord recordFor(List records, String flagKey) {
+ for (PrerequisiteEvalRecord r : records) {
+ if (r.flag.getKey().equals(flagKey)) {
+ return r;
+ }
+ }
+ throw new AssertionError("no prerequisite record for " + flagKey);
+ }
+
+ @Test
+ public void evaluationOfUnmarkedFlagIsNotOverrideAffected() {
+ FeatureFlag f = buildThreeWayFlag("feature").on(true).build();
+ EvalResult result = evaluatorBuilder().build().evaluate(f, BASE_USER, new EvaluationRecorder() {});
+
+ assertFalse(result.isOverrideAffected());
+ assertFalse(result.getReason().isOverrideAffected());
+ assertEquals(EvaluationReason.fallthrough(), result.getReason());
+ }
+
+ @Test
+ public void evaluationOfOverrideFlagIsMarkedForEveryReasonKind() {
+ Evaluator e = evaluatorBuilder().build();
+
+ FeatureFlag off = buildThreeWayFlag("off").on(false).build().markedAsOverride();
+ EvalResult offResult = e.evaluate(off, BASE_USER, new EvaluationRecorder() {});
+ assertEquals(EvalResult.of(OFF_VALUE, OFF_VARIATION, EvaluationReason.off().withOverrideAffected(true)), offResult);
+ assertTrue(offResult.isOverrideAffected());
+
+ FeatureFlag fallthrough = buildThreeWayFlag("fallthrough").on(true).build().markedAsOverride();
+ assertEquals(EvaluationReason.fallthrough().withOverrideAffected(true),
+ e.evaluate(fallthrough, BASE_USER, new EvaluationRecorder() {}).getReason());
+
+ FeatureFlag targeted = buildThreeWayFlag("target").on(true)
+ .targets(target(MATCH_VARIATION, BASE_USER.getKey())).build().markedAsOverride();
+ assertEquals(EvaluationReason.targetMatch().withOverrideAffected(true),
+ e.evaluate(targeted, BASE_USER, new EvaluationRecorder() {}).getReason());
+
+ FeatureFlag ruled = buildThreeWayFlag("rule").on(true)
+ .rules(ruleBuilder().id("r").variation(MATCH_VARIATION)
+ .clauses(clause("key", DataModel.Operator.in, LDValue.of(BASE_USER.getKey()))).build())
+ .build().markedAsOverride();
+ EvalResult ruleResult = e.evaluate(ruled, BASE_USER, new EvaluationRecorder() {});
+ assertEquals(EvaluationReason.ruleMatch(0, "r").withOverrideAffected(true), ruleResult.getReason());
+ assertEquals(MATCH_VALUE, ruleResult.getValue());
+ }
+
+ @Test
+ public void evaluationErrorOfOverrideFlagIsMarked() {
+ // The fallthrough points at a variation that does not exist, which is a malformed flag.
+ FeatureFlag malformed = flagBuilder("malformed").on(true).variations(LDValue.of("only"))
+ .fallthroughVariation(5).offVariation(0).build().markedAsOverride();
+ EvalResult result = evaluatorBuilder().build().evaluate(malformed, BASE_USER, new EvaluationRecorder() {});
+
+ assertEquals(EvaluationReason.error(ErrorKind.MALFORMED_FLAG).withOverrideAffected(true), result.getReason());
+ assertTrue(result.isNoVariation());
+ assertTrue(result.isOverrideAffected());
+ }
+
+ @Test
+ public void thrownEvaluationErrorOfOverrideFlagIsMarked() {
+ // A clause without an attribute makes the evaluator throw, which becomes an error result.
+ FeatureFlag broken = buildThreeWayFlag("broken").on(true)
+ .rules(ruleBuilder().id("r").variation(MATCH_VARIATION)
+ .clauses(clause(null, DataModel.Operator.in, LDValue.of("x"))).build())
+ .build().markedAsOverride();
+ EvalResult result = evaluatorBuilder().build().evaluate(broken, BASE_USER, new EvaluationRecorder() {});
+
+ assertEquals(EvaluationReason.error(ErrorKind.MALFORMED_FLAG).withOverrideAffected(true), result.getReason());
+ }
+
+ @Test
+ public void overridePrerequisiteMarksParentAndItsOwnRecord() {
+ FeatureFlag parent = buildThreeWayFlag("parent").on(true)
+ .prerequisites(prerequisite("prereq", GREEN_VARIATION)).build();
+ FeatureFlag prereq = buildRedGreenFlag("prereq").on(true).build().markedAsOverride();
+ RecordingRecorder recorder = new RecordingRecorder();
+
+ EvalResult result = evaluatorBuilder().withStoredFlags(prereq).build().evaluate(parent, BASE_USER, recorder);
+
+ assertEquals(FALLTHROUGH_VALUE, result.getValue());
+ assertEquals(EvaluationReason.fallthrough().withOverrideAffected(true), result.getReason());
+ assertTrue(result.isOverrideAffected());
+
+ PrerequisiteEvalRecord record = recordFor(recorder.prerequisites, "prereq");
+ assertTrue(record.result.isOverrideAffected());
+ assertEquals(EvaluationReason.fallthrough().withOverrideAffected(true), record.result.getReason());
+ // The same record is on the result.
+ assertTrue(recordFor(result.getPrerequisiteEvalRecords(), "prereq").result.isOverrideAffected());
+ }
+
+ @Test
+ public void failedOverridePrerequisiteStillMarksParent() {
+ FeatureFlag parent = buildThreeWayFlag("parent").on(true)
+ .prerequisites(prerequisite("prereq", GREEN_VARIATION)).build();
+ FeatureFlag prereq = buildRedGreenFlag("prereq").on(false).build().markedAsOverride();
+
+ EvalResult result = evaluatorBuilder().withStoredFlags(prereq).build()
+ .evaluate(parent, BASE_USER, new EvaluationRecorder() {});
+
+ assertEquals(OFF_VALUE, result.getValue());
+ assertEquals(EvaluationReason.prerequisiteFailed("prereq").withOverrideAffected(true), result.getReason());
+ }
+
+ @Test
+ public void unaffectedPrerequisiteRecordIsNotMarkedInsideMarkedEvaluation() {
+ FeatureFlag parent = buildThreeWayFlag("parent").on(true)
+ .prerequisites(prerequisite("overridden", GREEN_VARIATION), prerequisite("plain", GREEN_VARIATION)).build();
+ FeatureFlag overridden = buildRedGreenFlag("overridden").on(true).build().markedAsOverride();
+ FeatureFlag plain = buildRedGreenFlag("plain").on(true).build();
+ RecordingRecorder recorder = new RecordingRecorder();
+
+ EvalResult result = evaluatorBuilder().withStoredFlags(overridden, plain).build().evaluate(parent, BASE_USER, recorder);
+
+ assertTrue(result.isOverrideAffected());
+ assertTrue(recordFor(recorder.prerequisites, "overridden").result.isOverrideAffected());
+ assertFalse(recordFor(recorder.prerequisites, "plain").result.isOverrideAffected());
+ assertEquals(EvaluationReason.fallthrough(), recordFor(recorder.prerequisites, "plain").result.getReason());
+ }
+
+ @Test
+ public void markingPropagatesUpwardThroughEveryDepthButNotSideways() {
+ // A depends on B and C. B depends on D, which is the only override. A, B, and D are marked.
+ // C is not.
+ FeatureFlag a = buildThreeWayFlag("a").on(true)
+ .prerequisites(prerequisite("b", GREEN_VARIATION), prerequisite("c", GREEN_VARIATION)).build();
+ FeatureFlag b = buildRedGreenFlag("b").on(true).prerequisites(prerequisite("d", GREEN_VARIATION)).build();
+ FeatureFlag c = buildRedGreenFlag("c").on(true).build();
+ FeatureFlag d = buildRedGreenFlag("d").on(true).build().markedAsOverride();
+ RecordingRecorder recorder = new RecordingRecorder();
+
+ EvalResult result = evaluatorBuilder().withStoredFlags(b, c, d).build().evaluate(a, BASE_USER, recorder);
+
+ assertTrue(result.isOverrideAffected());
+ assertTrue(recordFor(recorder.prerequisites, "b").result.isOverrideAffected());
+ assertTrue(recordFor(recorder.prerequisites, "d").result.isOverrideAffected());
+ assertFalse(recordFor(recorder.prerequisites, "c").result.isOverrideAffected());
+ }
+
+ @Test
+ public void overrideFlagWithUnmarkedPrerequisiteMarksOnlyItself() {
+ FeatureFlag parent = buildThreeWayFlag("parent").on(true)
+ .prerequisites(prerequisite("prereq", GREEN_VARIATION)).build().markedAsOverride();
+ FeatureFlag prereq = buildRedGreenFlag("prereq").on(true).build();
+ RecordingRecorder recorder = new RecordingRecorder();
+
+ EvalResult result = evaluatorBuilder().withStoredFlags(prereq).build().evaluate(parent, BASE_USER, recorder);
+
+ assertTrue(result.isOverrideAffected());
+ // The parent's marking does not flow down into the prerequisite's record.
+ assertFalse(recordFor(recorder.prerequisites, "prereq").result.isOverrideAffected());
+ }
+
+ @Test
+ public void circularReferenceThroughOverridePrerequisiteIsMarkedError() {
+ FeatureFlag a = buildThreeWayFlag("a").on(true).prerequisites(prerequisite("b", GREEN_VARIATION)).build();
+ FeatureFlag b = buildRedGreenFlag("b").on(true).prerequisites(prerequisite("a", GREEN_VARIATION)).build()
+ .markedAsOverride();
+
+ EvalResult result = evaluatorBuilder().withStoredFlags(b).build().evaluate(a, BASE_USER, new EvaluationRecorder() {});
+
+ assertEquals(EvaluationReason.error(ErrorKind.MALFORMED_FLAG).withOverrideAffected(true), result.getReason());
+ }
+
+ @Test
+ public void matchingOverrideSegmentMarksEvaluation() {
+ Segment segment = segmentBuilder("seg").included(BASE_USER.getKey()).build().markedAsOverride();
+ FeatureFlag f = buildThreeWayFlag("feature").on(true)
+ .rules(ruleBuilder().id("r").variation(MATCH_VARIATION).clauses(clauseMatchingSegment("seg")).build())
+ .build();
+
+ EvalResult result = evaluatorBuilder().withStoredSegments(segment).build()
+ .evaluate(f, BASE_USER, new EvaluationRecorder() {});
+
+ assertEquals(MATCH_VALUE, result.getValue());
+ assertEquals(EvaluationReason.ruleMatch(0, "r").withOverrideAffected(true), result.getReason());
+ }
+
+ @Test
+ public void nonMatchingOverrideSegmentStillMarksEvaluation() {
+ Segment segment = segmentBuilder("seg").included(BASE_USER.getKey()).build().markedAsOverride();
+ FeatureFlag f = buildThreeWayFlag("feature").on(true)
+ .rules(ruleBuilder().id("r").variation(MATCH_VARIATION).clauses(clauseMatchingSegment("seg")).build())
+ .build();
+
+ EvalResult result = evaluatorBuilder().withStoredSegments(segment).build()
+ .evaluate(f, OTHER_USER, new EvaluationRecorder() {});
+
+ assertEquals(FALLTHROUGH_VALUE, result.getValue());
+ assertEquals(EvaluationReason.fallthrough().withOverrideAffected(true), result.getReason());
+ }
+
+ @Test
+ public void negatedClauseOnOverrideSegmentMarksEvaluation() {
+ Segment segment = segmentBuilder("seg").included(BASE_USER.getKey()).build().markedAsOverride();
+ FeatureFlag f = buildThreeWayFlag("feature").on(true)
+ .rules(ruleBuilder().id("r").variation(MATCH_VARIATION)
+ .clauses(negateClause(clauseMatchingSegment("seg"))).build())
+ .build();
+
+ EvalResult result = evaluatorBuilder().withStoredSegments(segment).build()
+ .evaluate(f, OTHER_USER, new EvaluationRecorder() {});
+
+ assertEquals(MATCH_VALUE, result.getValue());
+ assertTrue(result.isOverrideAffected());
+ }
+
+ @Test
+ public void unmarkedSegmentDoesNotMarkEvaluation() {
+ Segment segment = segmentBuilder("seg").included(BASE_USER.getKey()).build();
+ FeatureFlag f = buildThreeWayFlag("feature").on(true)
+ .rules(ruleBuilder().id("r").variation(MATCH_VARIATION).clauses(clauseMatchingSegment("seg")).build())
+ .build();
+
+ EvalResult result = evaluatorBuilder().withStoredSegments(segment).build()
+ .evaluate(f, BASE_USER, new EvaluationRecorder() {});
+
+ assertEquals(MATCH_VALUE, result.getValue());
+ assertFalse(result.isOverrideAffected());
+ }
+
+ @Test
+ public void overrideSegmentReferencedByAnotherSegmentMarksEvaluation() {
+ Segment inner = segmentBuilder("inner").included(BASE_USER.getKey()).build().markedAsOverride();
+ Segment outer = segmentBuilder("outer")
+ .rules(segmentRuleBuilder().clauses(clauseMatchingSegment("inner")).build()).build();
+ FeatureFlag f = buildThreeWayFlag("feature").on(true)
+ .rules(ruleBuilder().id("r").variation(MATCH_VARIATION).clauses(clauseMatchingSegment("outer")).build())
+ .build();
+
+ EvalResult result = evaluatorBuilder().withStoredSegments(inner, outer).build()
+ .evaluate(f, BASE_USER, new EvaluationRecorder() {});
+
+ assertEquals(MATCH_VALUE, result.getValue());
+ assertTrue(result.isOverrideAffected());
+ }
+
+ @Test
+ public void segmentReadByPrerequisiteMarksPrerequisiteAndParent() {
+ Segment segment = segmentBuilder("seg").included(BASE_USER.getKey()).build().markedAsOverride();
+ FeatureFlag parent = buildThreeWayFlag("parent").on(true)
+ .prerequisites(prerequisite("prereq", GREEN_VARIATION)).build();
+ FeatureFlag prereq = buildRedGreenFlag("prereq").on(true)
+ .rules(ruleBuilder().id("r").variation(GREEN_VARIATION).clauses(clauseMatchingSegment("seg")).build())
+ .build();
+ RecordingRecorder recorder = new RecordingRecorder();
+
+ EvalResult result = evaluatorBuilder().withStoredFlags(prereq).withStoredSegments(segment).build()
+ .evaluate(parent, BASE_USER, recorder);
+
+ assertTrue(result.isOverrideAffected());
+ assertTrue(recordFor(recorder.prerequisites, "prereq").result.isOverrideAffected());
+ }
+
+ @Test
+ public void markedEvaluationDoesNotAlterSharedPrecomputedResults() {
+ FeatureFlag source = buildThreeWayFlag("feature").on(false).build();
+ FeatureFlag marked = source.markedAsOverride();
+ Evaluator e = evaluatorBuilder().build();
+
+ EvalResult markedResult = e.evaluate(marked, BASE_USER, new EvaluationRecorder() {});
+ EvalResult sourceResult = e.evaluate(source, BASE_USER, new EvaluationRecorder() {});
+
+ assertTrue(markedResult.isOverrideAffected());
+ assertFalse(sourceResult.isOverrideAffected());
+ assertFalse(source.isOverride());
+ assertNotSame(markedResult, sourceResult);
+ // The unmarked evaluation still returns the shared precomputed instance.
+ assertSame(sourceResult, e.evaluate(source, BASE_USER, new EvaluationRecorder() {}));
+ }
+
+ @Test
+ public void bigSegmentsStatusAndOverrideMarkingAreBothKept() {
+ Segment bigSegment = segmentBuilder("big").unbounded(true).generation(1).build().markedAsOverride();
+ FeatureFlag f = buildThreeWayFlag("feature").on(true)
+ .rules(ruleBuilder().id("r").variation(MATCH_VARIATION).clauses(clauseMatchingSegment("big")).build())
+ .build();
+ // No big segment store is configured, so the status is NOT_CONFIGURED.
+ EvaluatorBuilder builder = evaluatorBuilder().withStoredSegments(bigSegment)
+ .withBigSegmentQueryResult(BASE_USER.getKey(), null);
+
+ EvalResult result = builder.build().evaluate(f, BASE_USER, new EvaluationRecorder() {});
+
+ assertEquals(FALLTHROUGH_VARIATION, result.getVariationIndex());
+ assertEquals(EvaluationReason.BigSegmentsStatus.NOT_CONFIGURED, result.getReason().getBigSegmentsStatus());
+ assertTrue(result.getReason().isOverrideAffected());
+ }
+}
diff --git a/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/InputValidatingEvaluatorOverrideTest.java b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/InputValidatingEvaluatorOverrideTest.java
new file mode 100644
index 00000000..5aa52b7e
--- /dev/null
+++ b/lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/InputValidatingEvaluatorOverrideTest.java
@@ -0,0 +1,183 @@
+package com.launchdarkly.sdk.server;
+
+import com.launchdarkly.sdk.EvaluationReason;
+import com.launchdarkly.sdk.EvaluationReason.ErrorKind;
+import com.launchdarkly.sdk.LDValue;
+import com.launchdarkly.sdk.LDValueType;
+import com.launchdarkly.sdk.server.DataModel.FeatureFlag;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.DataKind;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.ItemDescriptor;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.KeyedItems;
+
+import org.junit.Test;
+
+import java.util.AbstractMap;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import static com.launchdarkly.sdk.server.DataModel.FEATURES;
+import static com.launchdarkly.sdk.server.EvaluatorTestUtil.BASE_USER;
+import static com.launchdarkly.sdk.server.ModelBuilders.flagBuilder;
+import static com.launchdarkly.sdk.server.ModelBuilders.prerequisite;
+import static com.launchdarkly.sdk.server.TestComponents.nullLogger;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+@SuppressWarnings("javadoc")
+public class InputValidatingEvaluatorOverrideTest {
+ private static ReadOnlyStore storeWith(FeatureFlag... flags) {
+ Map items = new HashMap<>();
+ for (FeatureFlag f : flags) {
+ items.put(f.getKey(), new ItemDescriptor(f.getVersion(), f));
+ }
+ return new ReadOnlyStore() {
+ @Override
+ public ItemDescriptor get(DataKind kind, String key) {
+ return kind == FEATURES ? items.get(key) : null;
+ }
+
+ @Override
+ public KeyedItems getAll(DataKind kind) {
+ return kind == FEATURES ? new KeyedItems<>(items.entrySet()) : new KeyedItems<>(Collections.emptyList());
+ }
+
+ @Override
+ public boolean isInitialized() {
+ return true;
+ }
+ };
+ }
+
+ // A store that holds the given flags and fails when the given key is read, as a store does
+ // when its database is unreachable.
+ private static ReadOnlyStore storeFailingOn(String failingKey, FeatureFlag... flags) {
+ ReadOnlyStore base = storeWith(flags);
+ return new ReadOnlyStore() {
+ @Override
+ public ItemDescriptor get(DataKind kind, String key) {
+ if (key.equals(failingKey)) {
+ throw new RuntimeException("store failed");
+ }
+ return base.get(kind, key);
+ }
+
+ @Override
+ public KeyedItems getAll(DataKind kind) {
+ return base.getAll(kind);
+ }
+
+ @Override
+ public boolean isInitialized() {
+ return true;
+ }
+ };
+ }
+
+ // A flag whose evaluation reads the prerequisite "prereq".
+ private static FeatureFlag flagWithPrerequisite(String key) {
+ return flagBuilder(key).on(true).prerequisites(prerequisite("prereq", 0)).fallthroughVariation(0)
+ .offVariation(0).variations(LDValue.of("value")).trackEvents(true).build();
+ }
+
+ @Test
+ public void exceptionWhileEvaluatingOverrideFlagKeepsMarking() {
+ FeatureFlag flag = flagWithPrerequisite("flag").markedAsOverride();
+ EvalResultAndFlag result = evaluatorOver(storeFailingOn("prereq", flag)).evaluate("flag", BASE_USER,
+ LDValue.of("default"), null, InputValidatingEvaluator.NO_OP_EVALUATION_EVENT_RECORDER);
+
+ assertEquals(LDValue.of("default"), result.getResult().getValue());
+ assertEquals(EvaluationReason.ErrorKind.EXCEPTION, result.getResult().getReason().getErrorKind());
+ assertTrue(result.getResult().getReason().isOverrideAffected());
+ assertTrue(result.getResult().isOverrideAffected());
+ }
+
+ @Test
+ public void exceptionWhileEvaluatingPlainFlagIsNotMarked() {
+ FeatureFlag flag = flagWithPrerequisite("flag");
+ EvalResultAndFlag result = evaluatorOver(storeFailingOn("prereq", flag)).evaluate("flag", BASE_USER,
+ LDValue.of("default"), null, InputValidatingEvaluator.NO_OP_EVALUATION_EVENT_RECORDER);
+
+ assertEquals(EvaluationReason.ErrorKind.EXCEPTION, result.getResult().getReason().getErrorKind());
+ assertFalse(result.getResult().isOverrideAffected());
+ }
+
+ private static InputValidatingEvaluator evaluatorOver(ReadOnlyStore store) {
+ return new InputValidatingEvaluator(store, null, new NoOpEventProcessor(), nullLogger);
+ }
+
+ @Test
+ public void typeMismatchOnOverrideFlagKeepsMarking() {
+ FeatureFlag flag = flagBuilder("flag").on(false).offVariation(0).variations(LDValue.of("a string"))
+ .build().markedAsOverride();
+ EvalResultAndFlag result = evaluatorOver(storeWith(flag)).evaluate("flag", BASE_USER, LDValue.of(true),
+ LDValueType.BOOLEAN, InputValidatingEvaluator.NO_OP_EVALUATION_EVENT_RECORDER);
+
+ assertEquals(LDValue.of(true), result.getResult().getValue());
+ assertEquals(EvaluationReason.error(ErrorKind.WRONG_TYPE).withOverrideAffected(true), result.getResult().getReason());
+ assertTrue(result.getResult().isOverrideAffected());
+ }
+
+ @Test
+ public void unrecognizedMigrationStageFromOverrideFlagKeepsMarking() {
+ FeatureFlag flag = flagBuilder("flag").on(false).offVariation(0).variations(LDValue.of("potato"))
+ .build().markedAsOverride();
+ MigrationStageEnforcingEvaluator evaluator =
+ new MigrationStageEnforcingEvaluator(evaluatorOver(storeWith(flag)), nullLogger);
+ EvalResultAndFlag result = evaluator.evalAndFlag("LDClient.migrationVariation", "flag", BASE_USER,
+ LDValue.of("off"), LDValueType.STRING, EvaluationOptions.EVENTS_WITHOUT_REASONS);
+
+ assertEquals(LDValue.of("off"), result.getResult().getValue());
+ assertEquals(EvaluationReason.error(ErrorKind.WRONG_TYPE).withOverrideAffected(true), result.getResult().getReason());
+ }
+
+ @Test
+ public void typeMismatchOnOrdinaryFlagIsNotMarked() {
+ FeatureFlag flag = flagBuilder("flag").on(false).offVariation(0).variations(LDValue.of("a string")).build();
+ EvalResultAndFlag result = evaluatorOver(storeWith(flag)).evaluate("flag", BASE_USER, LDValue.of(true),
+ LDValueType.BOOLEAN, InputValidatingEvaluator.NO_OP_EVALUATION_EVENT_RECORDER);
+
+ assertEquals(EvaluationReason.error(ErrorKind.WRONG_TYPE), result.getResult().getReason());
+ assertFalse(result.getResult().isOverrideAffected());
+ }
+
+ @Test
+ public void errorResultOfOverrideFlagKeepsMarkingWithCallerDefault() {
+ FeatureFlag malformed = flagBuilder("flag").on(true).variations(LDValue.of("only"))
+ .fallthroughVariation(5).offVariation(0).build().markedAsOverride();
+ EvalResultAndFlag result = evaluatorOver(storeWith(malformed)).evaluate("flag", BASE_USER, LDValue.of("fallback"),
+ null, InputValidatingEvaluator.NO_OP_EVALUATION_EVENT_RECORDER);
+
+ assertEquals(LDValue.of("fallback"), result.getResult().getValue());
+ assertTrue(result.getResult().isNoVariation());
+ assertEquals(EvaluationReason.error(ErrorKind.MALFORMED_FLAG).withOverrideAffected(true), result.getResult().getReason());
+ }
+
+ @Test
+ public void allFlagsStateKeepsMarkedReason() {
+ FeatureFlag marked = flagBuilder("marked").on(false).offVariation(0).variations(LDValue.of("x")).build()
+ .markedAsOverride();
+ FeatureFlag plain = flagBuilder("plain").on(false).offVariation(0).variations(LDValue.of("y")).build();
+ FeatureFlagsState state = evaluatorOver(storeWith(marked, plain)).allFlagsState(BASE_USER, FlagsStateOption.WITH_REASONS);
+
+ assertTrue(state.isValid());
+ assertTrue(state.getFlagReason("marked").isOverrideAffected());
+ assertFalse(state.getFlagReason("plain").isOverrideAffected());
+ Map.Entry expected = new AbstractMap.SimpleEntry<>("marked", LDValue.of("x"));
+ assertEquals(expected.getValue(), state.getFlagValue("marked"));
+ }
+
+ @Test
+ public void allFlagsStateMarksTheExceptionOfAnOverrideFlag() {
+ FeatureFlag marked = flagWithPrerequisite("marked").markedAsOverride();
+ FeatureFlag plain = flagWithPrerequisite("plain");
+ FeatureFlagsState state = evaluatorOver(storeFailingOn("prereq", marked, plain))
+ .allFlagsState(BASE_USER, FlagsStateOption.WITH_REASONS);
+
+ assertEquals(ErrorKind.EXCEPTION, state.getFlagReason("marked").getErrorKind());
+ assertTrue(state.getFlagReason("marked").isOverrideAffected());
+ assertEquals(ErrorKind.EXCEPTION, state.getFlagReason("plain").getErrorKind());
+ assertFalse(state.getFlagReason("plain").isOverrideAffected());
+ }
+}
From eeac2a107e041b37d2c1c879c3ad7404717cba98 Mon Sep 17 00:00:00 2001
From: Ryan Lamb <4955475+kinyoklion@users.noreply.github.com>
Date: Thu, 3 Dec 2026 10:10:17 -0800
Subject: [PATCH 5/9] feat: Add the override layer, the store overlay, and the
override source configuration (#222)
## Update, 2026-12-01
- Rebased onto `feat/overrides`, which has `main` merged into it again.
From `main` it gets the 7.19.0 to 7.19.2 releases, `java-sdk-internal`
1.14.0, and the FDv2 fix that leaves out an empty selector (#261). The
v3.2.0-alpha.21 contract tests check that fix, so CI failed three FDv2
streaming tests without it.
- The `@since` tags this PR adds now say 7.20.0, because 7.19.0 to
7.19.2 shipped from `main` without flag overrides. The change is in the
existing commit "docs: Give the flag override API the version that will
ship it".
- `main` replaced the boolean FDv1 fallback argument of
`FDv2SourceResult.changeSet` with an `FDv1Fallback` (#278). The override
test data source passes `null`, as `main`'s own callers do. The change
is in the first commit.
- Verified with the v3.2.0-alpha.21 harness that CI runs, with `common`
2.6.0 and `internal` 1.15.0 published locally from `feat/overrides`:
- every PR in the stack compiles, with Javadoc, at its own head;
- the server unit tests pass at the top (2348, with the 72 existing
skips);
- the full v3 contract tests pass at the top (6457 tests ran). That
includes the flag overrides suite and both flag listener suites.
## Update, 2026-11-13
- Rebased onto `feat/overrides`, which now includes #218 and #219 and
has `main` merged into it. From `main` it gets the 7.18.0 release, CI on
the latest v3 contract tests, flag change listener support in the
contract test service, and the `java-sdk-internal` 1.12.1 and 1.12.2
fixes. A common 2.6.0 and internal 1.13.0 release from this branch needs
those fixes.
- New commit, "docs: Give the flag override API the version that will
ship it". Java 7.18.0 was released from `main` without flag overrides,
so the `@since` tags this PR adds now say 7.19.0, the next minor
release.
- Verified at the top of the stack, with `common` and `internal`
published locally from `feat/overrides`:
- every PR in the stack compiles, with Javadoc, at its own head;
- the server unit tests pass (2285, with the 72 existing skips);
- the full v3 contract tests pass (6321 tests). That includes the flag
overrides suite, with the deleted-entry tests of
launchdarkly/sdk-test-harness#599, and both flag listener suites.
## Summary
This adds the override layer that the OVERRIDE specification describes:
an override source supplies complete snapshots of flag and segment
definitions to an override store, and an overlay at the store read
boundary returns the store's entry for a key in preference to
LaunchDarkly data. Evaluation, prerequisite and segment resolution, and
the all-flags state all read through the overlay, so an override is a
full definition that evaluates like any other. Overrides do not take
part in the data system: they have no effect on initialization status,
data availability, or data source status, and they are never written to
a persistent store.
Public surface, all marked experimental and subject to change:
- `DataSystemBuilder.overrides(ComponentConfigurer)` and
`DataSystemConfiguration.getOverrideSource()`. The option lives on the
FDv2 data system builder only. An FDv1 data source configuration has no
place to supply one.
- `subsystems.OverrideSource` (start with a sink, close) and
`subsystems.OverrideSink` (replace the whole layer with one snapshot).
The SDK builds the source like any other component, starts it before the
data source so its initial load completes during client construction,
and closes it with the client; the sink stops accepting snapshots before
the source is closed, and an exception from the source's `close` is
logged while the rest of the shutdown proceeds. An offline client does
not build or start the override source, and logs a warning that it does
not. A source that cannot be built fails client construction the same
way other invalid component configuration does. An exception from the
source's `start` does not: the SDK logs it, closes the source, clears
anything the source supplied before failing, and the client runs without
overrides.
Internals:
- `OverrideLayer` holds marked shallow copies of the supplied entities
in an immutable map that is swapped on each update. The source's objects
are never modified.
- `OverrideOverlayStore` implements the read boundary: per-key reads
prefer the layer, enumeration is the union with override precedence, and
a failure of the base store propagates, as it does without the overlay.
- `OverrideSinkImpl` serializes snapshot application and fires the
normal flag change notifications for every flag whose merged-view
evaluation may have changed, using the dependency tracker over both the
old and the new merged views so prerequisite and segment dependents are
included.
- The not-initialized short-circuit consults the layer first: a flag
that the layer holds is served before the client has LaunchDarkly data,
and any other flag returns the client-not-ready default as before.
Before the store is initialized, the all-flags state contains only the
flags that the layer holds, read from the layer rather than the merged
store so that LaunchDarkly data in a store without an init marker stays
out, and it logs once that it returned only override entries; with no
override flags the state is invalid, as it is without a source. Without
a source this state is empty, because the SDK reports no flags before
the store is initialized, so the override flags only add to what it
reports; overrides never remove a flag from the state. When the store
fails to list its flags, the failure is logged as before; the state,
invalid and empty without a source, then holds the override layer's
flags and stays invalid (empty and invalid when the layer holds no
flags), because a client-side SDK bootstrapped from it uses its flags
whatever `$valid` says. The all-flags state presents an
override-affected flag with `trackEvents` and `trackReason` false and no
`debugEventsUntilDate`.
The OVERRIDE specification's test vectors run as a unit test through the
full client stack (value, variation index, and reason). The
per-evaluation summary marker in the vectors is asserted by the events
change that follows.
This PR depends on the model and evaluator marking change
(rlamb/overrides-java-model-marker) and is based on that branch;
retarget it to feat/overrides once that branch merges.
The existing file data source keeps its current behavior; this change
does not touch its code paths.
[SDK-3246](https://launchdarkly.atlassian.net/browse/SDK-3246)
[SDK-3246]:
https://launchdarkly.atlassian.net/browse/SDK-3246?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
## Follow-ups from review
- A LaunchDarkly change now notifies the flags whose overrides depend on
it. The override layer keeps the dependency edges of its own entries,
rebuilt on every replacement, and `DataSourceUpdatesImpl` expands each
changed LaunchDarkly item through both its own tracker and the layer's
until nothing new is reached, so an override that matches a LaunchDarkly
segment or has a LaunchDarkly prerequisite is notified like the
LaunchDarkly flags that depend on it.
- `isFlagKnown` consults the override layer before the not-initialized
short circuit, the same as evaluation does, so an override-only flag is
known while the client is uninitialized.
- When the evaluation of a flag throws during `allFlagsState`, the
`EXCEPTION` result carries that flag's own override marking, so an
overridden flag keeps its marked reason with event tracking off.
---
> [!NOTE]
> **Overview**
> Adds an **experimental flag/segment override** path for FDv2 clients
so operators can force known definitions without changing initialization
or data-source status.
>
> Configuration wires in `DataSystemBuilder.overrides()` with public
`OverrideSource` / `OverrideSink` APIs. When configured,
`FDv2DataSystem` builds an `OverrideLayer`, applies snapshots via
`OverrideSinkImpl`, and exposes evaluations through
`OverrideOverlayStore` (overrides win per key). The override source
starts before the main data source; start/close failures are logged and
the client can run without overrides. Offline mode skips the override
source.
>
> Evaluation and client behavior are updated so override-backed flags
work **before** the client is initialized (`isFlagKnown`, single-flag
eval, `allFlagsState` with override-only/bootstrap semantics).
Override-affected results carry marking in reasons and **disable**
per-flag analytics fields in `FeatureFlagsState`. Flag-change
notifications fan out across merged LaunchDarkly + override dependency
graphs via `ExternalDependencies` on `DataSourceUpdatesImpl`.
>
> Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
59f203e61c1d84b2a9459b3836b0550f6416e4d4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).
Opened from termag
---
.../sdk/server/DataModelDependencies.java | 8 +
.../sdk/server/DataSourceUpdatesImpl.java | 54 +-
.../launchdarkly/sdk/server/DataSystem.java | 9 +
.../sdk/server/FDv1DataSystem.java | 5 +
.../sdk/server/FDv2DataSystem.java | 100 ++-
.../sdk/server/FeatureFlagsState.java | 10 +-
.../sdk/server/InputValidatingEvaluator.java | 70 +-
.../com/launchdarkly/sdk/server/LDClient.java | 14 +-
.../sdk/server/OverrideLayer.java | 152 +++++
.../sdk/server/OverrideOverlayStore.java | 84 +++
.../sdk/server/OverrideSinkImpl.java | 223 +++++++
.../integrations/DataSystemBuilder.java | 42 +-
.../subsystems/DataSystemConfiguration.java | 46 +-
.../sdk/server/subsystems/OverrideSink.java | 36 +
.../sdk/server/subsystems/OverrideSource.java | 44 ++
.../sdk/server/DataSourceUpdatesImplTest.java | 30 +
.../InputValidatingEvaluatorOverrideTest.java | 21 +-
.../sdk/server/LDClientOverridesTest.java | 627 ++++++++++++++++++
.../sdk/server/OverrideLayerTest.java | 181 +++++
.../sdk/server/OverrideOverlayStoreTest.java | 187 ++++++
.../sdk/server/OverrideSinkImplTest.java | 229 +++++++
.../sdk/server/OverrideSpecVectorsTest.java | 154 +++++
.../sdk/server/OverrideTestDataSources.java | 76 +++
.../sdk/server/TestOverrideSource.java | 86 +++
.../resources/override-vectors/vectors.json | 316 +++++++++
25 files changed, 2776 insertions(+), 28 deletions(-)
create mode 100644 lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideLayer.java
create mode 100644 lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideOverlayStore.java
create mode 100644 lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideSinkImpl.java
create mode 100644 lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/subsystems/OverrideSink.java
create mode 100644 lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/subsystems/OverrideSource.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/LDClientOverridesTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/OverrideLayerTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/OverrideOverlayStoreTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/OverrideSinkImplTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/OverrideSpecVectorsTest.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/OverrideTestDataSources.java
create mode 100644 lib/sdk/server/src/test/java/com/launchdarkly/sdk/server/TestOverrideSource.java
create mode 100644 lib/sdk/server/src/test/resources/override-vectors/vectors.json
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataModelDependencies.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataModelDependencies.java
index 17ca660e..543755d5 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataModelDependencies.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataModelDependencies.java
@@ -218,6 +218,14 @@ public int compare(DataKind o1, DataKind o2) {
/**
* Maintains a bidirectional dependency graph that can be updated whenever an item has changed.
*/
+ /**
+ * Dependency edges that live outside the LaunchDarkly data, such as those of the override
+ * layer's entries. Given an item, adds it and everything that depends on it through those edges.
+ */
+ interface ExternalDependencies {
+ void addAffectedItems(Set itemsOut, KindAndKey item);
+ }
+
static final class DependencyTracker {
private final Map> dependenciesFrom = new HashMap<>();
private final Map> dependenciesTo = new HashMap<>();
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataSourceUpdatesImpl.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataSourceUpdatesImpl.java
index 55bb1061..0887808e 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataSourceUpdatesImpl.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataSourceUpdatesImpl.java
@@ -29,6 +29,9 @@
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
+import java.util.Deque;
+import java.util.Arrays;
+import java.util.ArrayDeque;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
@@ -56,6 +59,10 @@ final class DataSourceUpdatesImpl implements DataSourceUpdateSink, DataSourceUpd
private final EventBroadcasterImpl flagChangeEventNotifier;
private final EventBroadcasterImpl dataSourceStatusNotifier;
private final DataModelDependencies.DependencyTracker dependencyTracker = new DataModelDependencies.DependencyTracker();
+ // Dependencies of definitions the data system does not hold. The override layer supplies its
+ // entries' dependencies, so that a change to a LaunchDarkly item also notifies the overridden
+ // flags that reference it. Null when no override source is configured.
+ private volatile DataModelDependencies.ExternalDependencies externalDependencies = null;
private final DataStoreStatusProvider dataStoreStatusProvider;
private final OutageTracker outageTracker;
private final Object stateLock = new Object();
@@ -84,6 +91,47 @@ final class DataSourceUpdatesImpl implements DataSourceUpdateSink, DataSourceUpd
currentStatus = new Status(State.INITIALIZING, Instant.now(), null);
}
+ /**
+ * Registers dependency edges that live outside the LaunchDarkly data, such as the override
+ * layer's. Called once during construction of the data system.
+ */
+ void setExternalDependencies(DataModelDependencies.ExternalDependencies externalDependencies) {
+ this.externalDependencies = externalDependencies;
+ }
+
+ /**
+ * Adds the modified item and everything that depends on it to the set. The LaunchDarkly data and
+ * the external dependencies each know their own edges, and a chain can cross between them in
+ * either direction: an overridden flag can reference a LaunchDarkly segment, and a LaunchDarkly
+ * flag can have an overridden prerequisite. Each newly reached item is therefore expanded through
+ * both until nothing new is found.
+ */
+ private void addAffectedItems(Set itemsOut, KindAndKey item) {
+ DataModelDependencies.ExternalDependencies external = externalDependencies;
+ if (external == null) {
+ dependencyTracker.addAffectedItems(itemsOut, item);
+ return;
+ }
+ Deque pending = new ArrayDeque<>();
+ pending.push(item);
+ while (!pending.isEmpty()) {
+ KindAndKey next = pending.pop();
+ // Each tracker gets its own set: a tracker skips an item that is already in the set it is
+ // given, so sharing one set would stop the second tracker at the starting item.
+ Set viaData = new HashSet<>();
+ dependencyTracker.addAffectedItems(viaData, next);
+ Set viaExternal = new HashSet<>();
+ external.addAffectedItems(viaExternal, next);
+ for (Set reached : Arrays.asList(viaData, viaExternal)) {
+ for (KindAndKey reachedItem : reached) {
+ if (itemsOut.add(reachedItem)) {
+ pending.push(reachedItem);
+ }
+ }
+ }
+ }
+ }
+
@Override
public boolean init(FullDataSet allData) {
Map> oldData = null;
@@ -132,7 +180,7 @@ public boolean upsert(DataKind kind, String key, ItemDescriptor item) {
dependencyTracker.updateDependenciesFrom(kind, key, item);
if (hasFlagChangeEventListeners()) {
Set affectedItems = new HashSet<>();
- dependencyTracker.addAffectedItems(affectedItems, new KindAndKey(kind, key));
+ addAffectedItems(affectedItems, new KindAndKey(kind, key));
sendChangeEvents(affectedItems);
}
}
@@ -270,7 +318,7 @@ private Set computeChangedItemsForFullDataSet(Map handlePartialChangeset(
for (Map.Entry itemEntry: kindEntry.getValue().getItems()) {
String key = itemEntry.getKey();
dependencyTracker.updateDependenciesFrom(kind, key, itemEntry.getValue());
- dependencyTracker.addAffectedItems(affectedItems, new KindAndKey(kind, key));
+ addAffectedItems(affectedItems, new KindAndKey(kind, key));
}
}
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataSystem.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataSystem.java
index 6558cc45..1eb6f9bd 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataSystem.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/DataSystem.java
@@ -62,6 +62,15 @@ interface DataSystem {
* @return the environment ID, or null
*/
String getEnvironmentId();
+
+ /**
+ * Returns the override layer, or null if no override source is configured. The layer holds the
+ * entries that take precedence over LaunchDarkly data; {@link #getStore()} already applies them.
+ * The client consults the layer directly only for the not-initialized short-circuit.
+ *
+ * @return the override layer, or null
+ */
+ OverrideLayer getOverrideLayer();
}
/**
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FDv1DataSystem.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FDv1DataSystem.java
index a03da864..92020402 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FDv1DataSystem.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FDv1DataSystem.java
@@ -160,6 +160,11 @@ public String getEnvironmentId() {
return dataStore.getEnvironmentId();
}
+ @Override
+ public OverrideLayer getOverrideLayer() {
+ return null;
+ }
+
@Override
public void close() throws IOException {
if (disposed) {
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FDv2DataSystem.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FDv2DataSystem.java
index 2e44afba..129cc487 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FDv2DataSystem.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FDv2DataSystem.java
@@ -2,6 +2,7 @@
import com.google.common.collect.ImmutableList;
import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.logging.LogValues;
import com.launchdarkly.sdk.server.datasources.Initializer;
import com.launchdarkly.sdk.server.datasources.SelectorSource;
import com.launchdarkly.sdk.server.datasources.Synchronizer;
@@ -15,6 +16,7 @@
import com.launchdarkly.sdk.server.subsystems.DataStore;
import com.launchdarkly.sdk.server.subsystems.LoggingConfiguration;
import com.launchdarkly.sdk.server.subsystems.DataSystemConfiguration;
+import com.launchdarkly.sdk.server.subsystems.OverrideSource;
import java.io.Closeable;
import java.io.IOException;
@@ -34,6 +36,15 @@ final class FDv2DataSystem implements DataSystem, Closeable {
private final FlagChangeNotifier flagChanged;
private final DataSourceStatusProvider dataSourceStatusProvider;
private final DataStoreStatusProvider dataStoreStatusProvider;
+ private final LDLogger logger;
+ // The following are non-null only when an override source is configured. The layer holds the
+ // override entries. The overlay serves them in preference to the store's data at the store read
+ // boundary. The source populates the layer at runtime. None of them take part in
+ // initialization or data source status.
+ private final OverrideLayer overrideLayer;
+ private final OverrideSinkImpl overrideSink;
+ // Null after the source failed to start or was closed.
+ private volatile OverrideSource overrideSource;
private boolean disposed = false;
private FDv2DataSystem(
@@ -41,14 +52,29 @@ private FDv2DataSystem(
DataSource dataSource,
DataSourceStatusProvider dataSourceStatusProvider,
DataStoreStatusProvider dataStoreStatusProvider,
- FlagChangeNotifier flagChanged
+ FlagChangeNotifier flagChanged,
+ EventBroadcasterImpl flagChangeBroadcaster,
+ OverrideSource overrideSource,
+ LDLogger logger
) {
this.store = store;
this.dataSource = dataSource;
this.dataStoreStatusProvider = dataStoreStatusProvider;
this.dataSourceStatusProvider = dataSourceStatusProvider;
this.flagChanged = flagChanged;
- this.readOnlyStore = new ReadonlyStoreFacade(store);
+ this.logger = logger;
+ ReadOnlyStore baseStore = new ReadonlyStoreFacade(store);
+ this.overrideSource = overrideSource;
+ if (overrideSource == null) {
+ this.overrideLayer = null;
+ this.overrideSink = null;
+ this.readOnlyStore = baseStore;
+ } else {
+ this.overrideLayer = new OverrideLayer();
+ this.overrideSink = new OverrideSinkImpl(overrideLayer, baseStore, flagChangeBroadcaster,
+ logger.subLogger(Loggers.DATA_SOURCE_LOGGER_NAME));
+ this.readOnlyStore = new OverrideOverlayStore(baseStore, overrideLayer);
+ }
}
private static class FactoryWrapper implements FDv2DataSource.DataSourceFactory {
@@ -186,13 +212,33 @@ static FDv2DataSystem create(
FlagChangeNotifier flagChanged = new FlagChangedFacade(dataSourceUpdates);
- return new FDv2DataSystem(
+ // The override source is built like any other component. Invalid configuration fails here, the
+ // same way an invalid data source or data store configuration fails. An offline client starts
+ // no data sources and no override source.
+ OverrideSource overrideSource = null;
+ if (dataSystemConfiguration.getOverrideSource() != null) {
+ if (config.offline) {
+ logger.warn("Offline mode is enabled; the override source is not started and no overrides are served");
+ } else {
+ overrideSource = dataSystemConfiguration.getOverrideSource().build(clientContext);
+ }
+ }
+
+ FDv2DataSystem system = new FDv2DataSystem(
store,
dataSource,
dataSourceStatusProvider,
dataStoreStatusProvider,
- flagChanged
+ flagChanged,
+ flagChangeBroadcaster,
+ overrideSource,
+ logger
);
+ if (system.overrideLayer != null) {
+ // A LaunchDarkly change must also notify the flags whose overrides depend on it.
+ dataSourceUpdates.setExternalDependencies(system.overrideLayer);
+ }
+ return system;
}
@Override
@@ -202,6 +248,27 @@ public ReadOnlyStore getStore() {
@Override
public Future start() {
+ if (overrideSource != null) {
+ // The source starts before the data source, so a source that loads synchronously has its
+ // overrides in place before the client begins evaluating. Its initial load is part of
+ // starting the client. A source that fails to start does not prevent the client from
+ // operating: the failure is logged, the source is closed, and the client runs without
+ // overrides. The SDK's own file-based source does not throw from start; it logs a failed
+ // load and retries it. A custom source could throw, and an application in an incident is
+ // better served by a client that runs without its overrides than by one that does not start.
+ try {
+ overrideSource.start(overrideSink);
+ } catch (RuntimeException e) {
+ logger.error("Unable to start the override source; the client runs without overrides: {}",
+ LogValues.exceptionSummary(e));
+ logger.debug(LogValues.exceptionTrace(e));
+ closeOverrideSource("Unable to close the override source after it failed to start: {}");
+ // The source may have supplied a snapshot before it failed. Clearing the layer removes it,
+ // so the client runs without overrides as logged, and a late snapshot from the closed
+ // source is ignored.
+ overrideSink.closeAndClear();
+ }
+ }
return dataSource.start();
}
@@ -230,12 +297,37 @@ public String getEnvironmentId() {
return store.getEnvironmentId();
}
+ // A custom source can throw from close. That is logged and not thrown, so the rest of the client
+ // still shuts down, or still starts after a failed start.
+ private void closeOverrideSource(String failureMessage) {
+ OverrideSource source = overrideSource;
+ overrideSource = null;
+ try {
+ source.close();
+ } catch (IOException | RuntimeException e) {
+ logger.warn(failureMessage, LogValues.exceptionSummary(e));
+ logger.debug(LogValues.exceptionTrace(e));
+ }
+ }
+
+ @Override
+ public OverrideLayer getOverrideLayer() {
+ return overrideLayer;
+ }
+
@Override
public void close() throws IOException {
if (disposed) {
return;
}
try {
+ if (overrideSource != null) {
+ // The sink stops accepting snapshots first, so a snapshot that the source supplies while it
+ // shuts down cannot update the layer or notify listeners through components that are being
+ // closed.
+ overrideSink.close();
+ closeOverrideSource("Unable to close the override source: {}");
+ }
dataSource.close();
store.close();
} finally {
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FeatureFlagsState.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FeatureFlagsState.java
index beafaaea..c4cc3476 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FeatureFlagsState.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/FeatureFlagsState.java
@@ -276,15 +276,19 @@ public Builder add(
}
Builder addFlag(DataModel.FeatureFlag flag, EvalResult eval) {
+ // A consumer of this state sends individual events according to the tracking fields. An
+ // override-affected evaluation produces no individual events, so the state turns them off
+ // for this flag. The flag, its value, its version, and its reason stay.
+ boolean overrideAffected = eval.isOverrideAffected();
return add(
flag.getKey(),
eval.getValue(),
eval.isNoVariation() ? null : eval.getVariationIndex(),
eval.getReason(),
flag.getVersion(),
- flag.isTrackEvents() || eval.isForceReasonTracking(),
- eval.isForceReasonTracking(),
- flag.getDebugEventsUntilDate(),
+ !overrideAffected && (flag.isTrackEvents() || eval.isForceReasonTracking()),
+ !overrideAffected && eval.isForceReasonTracking(),
+ overrideAffected ? null : flag.getDebugEventsUntilDate(),
eval.getPrerequisiteEvalRecords().stream()
.filter(record -> record.prereqOfFlag.getKey() == flag.getKey()) // only include top level prereqs
.map(record -> record.flag.getKey()) // map from prereq record to prereq key
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/InputValidatingEvaluator.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/InputValidatingEvaluator.java
index e1ee6d05..811af12c 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/InputValidatingEvaluator.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/InputValidatingEvaluator.java
@@ -13,7 +13,9 @@
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
+import java.util.Collections;
import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
import static com.launchdarkly.sdk.EvaluationDetail.NO_VARIATION;
import static com.launchdarkly.sdk.server.DataModel.FEATURES;
@@ -28,7 +30,11 @@ class InputValidatingEvaluator implements EvaluatorInterface {
private final Evaluator evaluator;
private final ReadOnlyStore store;
+ // Null when no override source is configured. The store already applies the layer. The layer is
+ // consulted directly only for the not-initialized short-circuit.
+ private final OverrideLayer overrideLayer;
private final LDLogger logger;
+ private final AtomicBoolean allFlagsOverridesOnlyWarningLogged = new AtomicBoolean(false);
// these are created at construction to avoid recreation during each evaluation
private final EvaluationRecorder evaluationEventRecorderWithDetails;
@@ -40,11 +46,14 @@ class InputValidatingEvaluator implements EvaluatorInterface {
* Creates an {@link InputValidatingEvaluator}
*
* @param store will be used to get flag data
+ * @param overrideLayer the override layer, or null if no override source is configured
* @param segmentStore will be used to get segment data
* @param eventProcessor will be used to record events during evaluations as necessary
* @param logger for logging messages and errors during evaluations
*/
- InputValidatingEvaluator(ReadOnlyStore store, BigSegmentStoreWrapper segmentStore, @Nonnull EventProcessor eventProcessor, LDLogger logger) {
+ InputValidatingEvaluator(ReadOnlyStore store, @Nullable OverrideLayer overrideLayer, BigSegmentStoreWrapper segmentStore,
+ @Nonnull EventProcessor eventProcessor, LDLogger logger) {
+ this.overrideLayer = overrideLayer;
this.evaluator = new Evaluator(new Evaluator.Getters() {
public DataModel.FeatureFlag getFlag(String key) {
return InputValidatingEvaluator.getFlag(store, key);
@@ -101,7 +110,9 @@ public EvalResultAndFlag evalAndFlag(String method, String flagKey, LDContext co
*/
EvalResultAndFlag evaluate(String flagKey, LDContext context, LDValue defaultValue,
@Nullable LDValueType requireType, EvaluationRecorder recorder) {
- if (!store.isInitialized()) {
+ // The override layer is consulted before the not-initialized short-circuit. A flag that the
+ // layer holds is served from it. Any other flag returns the not-ready default as before.
+ if (!store.isInitialized() && !hasOverrideFor(flagKey)) {
logger.warn("Evaluation called before client initialized for feature flag \"{}\"; data store unavailable, returning default value", flagKey);
recorder.recordEvaluationUnknownFlagError(flagKey, context, defaultValue, ErrorKind.CLIENT_NOT_READY);
return new EvalResultAndFlag(EvalResult.error(ErrorKind.CLIENT_NOT_READY, defaultValue), null);
@@ -167,9 +178,23 @@ EvalResultAndFlag evaluate(String flagKey, LDContext context, LDValue defaultVal
public FeatureFlagsState allFlagsState(LDContext context, FlagsStateOption... options) {
FeatureFlagsState.Builder builder = FeatureFlagsState.builder(options);
+ DataStoreTypes.KeyedItems overrideFlags = null;
if (!store.isInitialized()) {
- logger.warn("allFlagsState() was called before client initialized; data store unavailable, returning no data");
- return builder.valid(false).build();
+ // No LaunchDarkly data is available. When the override layer holds flags, the state contains
+ // only those, read from the layer itself: a store that is not initialized can still hold
+ // LaunchDarkly data, which the state must not include. Without override flags the state is
+ // invalid, as it is without an override source.
+ Map layerFlags =
+ overrideLayer == null ? Collections.emptyMap() : overrideLayer.all(FEATURES);
+ if (layerFlags.isEmpty()) {
+ logger.warn("allFlagsState() was called before client initialized; data store unavailable, returning no data");
+ return builder.valid(false).build();
+ }
+ if (allFlagsOverridesOnlyWarningLogged.compareAndSet(false, true)) {
+ logger.warn("allFlagsState() was called before client initialized; returning only flags from the override layer."
+ + " This message is logged once.");
+ }
+ overrideFlags = new DataStoreTypes.KeyedItems<>(layerFlags.entrySet());
}
if (context == null) {
@@ -183,12 +208,27 @@ public FeatureFlagsState allFlagsState(LDContext context, FlagsStateOption... op
boolean clientSideOnly = FlagsStateOption.hasOption(options, FlagsStateOption.CLIENT_SIDE_ONLY);
DataStoreTypes.KeyedItems flags;
- try {
- flags = store.getAll(FEATURES);
- } catch (Exception e) {
- logger.error("Exception from data store when evaluating all flags: {}", LogValues.exceptionSummary(e));
- logger.debug(e.toString(), LogValues.exceptionTrace(e));
- return builder.valid(false).build();
+ boolean valid = true;
+ if (overrideFlags != null) {
+ flags = overrideFlags;
+ } else {
+ try {
+ flags = store.getAll(FEATURES);
+ } catch (Exception e) {
+ logger.error("Exception from data store when evaluating all flags: {}", LogValues.exceptionSummary(e));
+ logger.debug(e.toString(), LogValues.exceptionTrace(e));
+ // Overrides only add to the state. Without them the state is invalid and empty here, so it
+ // holds the override layer's flags and stays invalid. A client-side SDK bootstrapped from the
+ // state uses its flags whatever $valid says (js-client-sdk 3.x and the 4.x browser SDK only
+ // log a warning), so the overridden values still reach it.
+ Map layerFlags =
+ overrideLayer == null ? Collections.emptyMap() : overrideLayer.all(FEATURES);
+ if (layerFlags.isEmpty()) {
+ return builder.valid(false).build();
+ }
+ flags = new DataStoreTypes.KeyedItems<>(layerFlags.entrySet());
+ valid = false;
+ }
}
for (Map.Entry entry : flags.getItems()) {
@@ -214,7 +254,7 @@ public FeatureFlagsState allFlagsState(LDContext context, FlagsStateOption... op
.withOverrideAffected(flag.isOverride()));
}
}
- return builder.build();
+ return builder.valid(valid).build();
}
private static DataModel.FeatureFlag getFlag(ReadOnlyStore store, String key) {
@@ -222,6 +262,14 @@ private static DataModel.FeatureFlag getFlag(ReadOnlyStore store, String key) {
return item == null ? null : (DataModel.FeatureFlag) item.getItem();
}
+ private boolean hasOverrideFor(String flagKey) {
+ if (overrideLayer == null) {
+ return false;
+ }
+ DataStoreTypes.ItemDescriptor item = overrideLayer.get(FEATURES, flagKey);
+ return item != null && item.getItem() != null;
+ }
+
private static DataModel.Segment getSegment(ReadOnlyStore store, String key) {
DataStoreTypes.ItemDescriptor item = store.get(SEGMENTS, key);
return item == null ? null : (DataModel.Segment) item.getItem();
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/LDClient.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/LDClient.java
index 066b8332..88dbbb81 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/LDClient.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/LDClient.java
@@ -218,7 +218,8 @@ public LDClient(String sdkKey, LDConfig config) {
this.dataSystem = FDv1DataSystem.create(baseLogger, config, context, context.getLogging());
}
- EvaluatorInterface evaluator = new InputValidatingEvaluator(this.dataSystem.getStore(), bigSegmentStoreWrapper, eventProcessor, evaluationLogger);
+ EvaluatorInterface evaluator = new InputValidatingEvaluator(this.dataSystem.getStore(),
+ this.dataSystem.getOverrideLayer(), bigSegmentStoreWrapper, eventProcessor, evaluationLogger);
// build environment metadata for plugins
SdkMetadata sdkMetadata;
@@ -446,6 +447,17 @@ public MigrationVariation migrationVariation(String key, LDContext context, Migr
@Override
public boolean isFlagKnown(String featureKey) {
+ // An override makes a flag known whether or not the client is initialized, the same as
+ // evaluation serves an override before the not-initialized short circuit (spec 1.5.3). A
+ // caller that gates on isFlagKnown must not skip an override during an outage.
+ OverrideLayer overrideLayer = dataSystem.getOverrideLayer();
+ if (overrideLayer != null) {
+ ItemDescriptor overridden = overrideLayer.get(DataModel.FEATURES, featureKey);
+ if (overridden != null && overridden.getItem() != null) {
+ return true;
+ }
+ }
+
ReadOnlyStore store = dataSystem.getStore();
if (!isInitialized()) {
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideLayer.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideLayer.java
new file mode 100644
index 00000000..ce1f55ea
--- /dev/null
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideLayer.java
@@ -0,0 +1,152 @@
+package com.launchdarkly.sdk.server;
+
+import com.google.common.collect.ImmutableMap;
+import com.launchdarkly.sdk.server.DataModel.FeatureFlag;
+import com.launchdarkly.sdk.server.DataModel.Segment;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.DataKind;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.ItemDescriptor;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.KeyedItems;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * The override layer: a thread-safe store of override entries that an override source replaces
+ * wholesale on each update. Entries take precedence over LaunchDarkly data at the store read
+ * boundary; see {@link OverrideOverlayStore}.
+ *
+ * Each entry is a marked shallow copy of the entity that the source supplied. The copy shares its
+ * nested collections with the source's entity, and the layer never writes to them. The source's
+ * entity is never marked, so a source may retain the entities it supplied and supply them again.
+ *
+ * This class is package-private and should not be used by application code.
+ */
+final class OverrideLayer implements DataModelDependencies.ExternalDependencies {
+ /**
+ * The previous and current contents of the layer after a replacement. The maps must not be
+ * modified.
+ */
+ static final class Replacement {
+ final ImmutableMap> previous;
+ final ImmutableMap> current;
+
+ Replacement(
+ ImmutableMap> previous,
+ ImmutableMap> current
+ ) {
+ this.previous = previous;
+ this.current = current;
+ }
+ }
+
+ // The contents are an immutable map that is swapped on each update, so the layer holds exactly
+ // one snapshot at any instant and readers never take a lock.
+ private volatile ImmutableMap> contents = ImmutableMap.of();
+ // A single volatile read decides the common case of a configured but unpopulated layer.
+ private volatile boolean nonEmpty = false;
+ private final Object writeLock = new Object();
+ // The dependency edges of the layer's own entries: which entries reference which flags and
+ // segments. Rebuilt with the contents on every replacement and swapped with them.
+ private volatile DataModelDependencies.DependencyTracker dependencies = new DataModelDependencies.DependencyTracker();
+
+ /**
+ * Atomically replaces the entire layer contents. A null or empty collection clears the layer.
+ *
+ * @param data the complete set of entries, grouped by data kind
+ * @return the previous and the new contents
+ */
+ Replacement setAll(Iterable>> data) {
+ Map> collected = new HashMap<>();
+ DataModelDependencies.DependencyTracker tracker = new DataModelDependencies.DependencyTracker();
+ int count = 0;
+ if (data != null) {
+ for (Map.Entry> kindEntry : data) {
+ Map items = collected.computeIfAbsent(kindEntry.getKey(), k -> new HashMap<>());
+ Iterable> kindItems = kindEntry.getValue() == null
+ ? null : kindEntry.getValue().getItems();
+ if (kindItems == null) {
+ continue;
+ }
+ for (Map.Entry item : kindItems) {
+ ItemDescriptor copied = markedCopy(item.getValue());
+ items.put(item.getKey(), copied);
+ tracker.updateDependenciesFrom(kindEntry.getKey(), item.getKey(), copied);
+ count++;
+ }
+ }
+ }
+ ImmutableMap.Builder> builder = ImmutableMap.builder();
+ for (Map.Entry> e : collected.entrySet()) {
+ builder.put(e.getKey(), ImmutableMap.copyOf(e.getValue()));
+ }
+ ImmutableMap> replacement = builder.build();
+
+ synchronized (writeLock) {
+ ImmutableMap> previous = contents;
+ contents = replacement;
+ dependencies = tracker;
+ nonEmpty = count != 0;
+ return new Replacement(previous, replacement);
+ }
+ }
+
+ /**
+ * Adds the given item to the set together with every item whose override entry depends on it,
+ * directly or through other override entries. A LaunchDarkly update uses this so that a change to
+ * a LaunchDarkly segment or prerequisite notifies the overridden flags that reference it, which
+ * the data system's own dependency tracking cannot see.
+ */
+ @Override
+ public void addAffectedItems(Set itemsOut, DataModelDependencies.KindAndKey item) {
+ dependencies.addAffectedItems(itemsOut, item);
+ }
+
+ /**
+ * Returns the override entry for a key, or null if the layer has none.
+ *
+ * @param kind the data kind
+ * @param key the item key
+ * @return the marked entry or null
+ */
+ ItemDescriptor get(DataKind kind, String key) {
+ if (!nonEmpty) {
+ return null;
+ }
+ ImmutableMap items = contents.get(kind);
+ return items == null ? null : items.get(key);
+ }
+
+ /**
+ * Returns the entries of a kind. The map must not be modified.
+ *
+ * @param kind the data kind
+ * @return the entries, possibly empty
+ */
+ ImmutableMap all(DataKind kind) {
+ ImmutableMap items = contents.get(kind);
+ return items == null ? ImmutableMap.of() : items;
+ }
+
+ /**
+ * Reports whether the layer contains no entries.
+ *
+ * @return true if empty
+ */
+ boolean isEmpty() {
+ return !nonEmpty;
+ }
+
+ // Returns a copy of the descriptor whose item carries the override marker. An item of another
+ // type, or a deleted item placeholder, is returned as is.
+ static ItemDescriptor markedCopy(ItemDescriptor item) {
+ Object entity = item.getItem();
+ if (entity instanceof FeatureFlag) {
+ return new ItemDescriptor(item.getVersion(), ((FeatureFlag) entity).markedAsOverride());
+ }
+ if (entity instanceof Segment) {
+ return new ItemDescriptor(item.getVersion(), ((Segment) entity).markedAsOverride());
+ }
+ return item;
+ }
+}
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideOverlayStore.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideOverlayStore.java
new file mode 100644
index 00000000..5901145e
--- /dev/null
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideOverlayStore.java
@@ -0,0 +1,84 @@
+package com.launchdarkly.sdk.server;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.DataKind;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.ItemDescriptor;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.KeyedItems;
+
+import java.util.AbstractMap;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Merges an {@link OverrideLayer} over a base store. A read for a key returns the override entry
+ * when one exists, and the base entry otherwise. The overlay sits at the store read boundary, so
+ * targeting rules, prerequisites, and segment matches behave identically for overridden and
+ * ordinary data: they are the same reads through the same boundary.
+ *
+ * This class is package-private and should not be used by application code.
+ */
+final class OverrideOverlayStore implements ReadOnlyStore {
+ private final ReadOnlyStore base;
+ private final OverrideLayer layer;
+
+ OverrideOverlayStore(ReadOnlyStore base, OverrideLayer layer) {
+ this.base = base;
+ this.layer = layer;
+ }
+
+ /**
+ * Returns the override entry for the key if one exists, and otherwise delegates to the base
+ * store. This works even when the base store is uninitialized, because an uninitialized base
+ * reports not found rather than failing.
+ */
+ @Override
+ public ItemDescriptor get(DataKind kind, String key) {
+ ItemDescriptor override = layer.get(kind, key);
+ if (override != null) {
+ return override;
+ }
+ return base.get(kind, key);
+ }
+
+ /**
+ * Returns the union of the base store's items and the layer's items. The override entry wins for
+ * any key present in both, including keys that the base holds as deleted-item placeholders. A
+ * failure of the base store propagates, as it does without the overlay.
+ */
+ @Override
+ public KeyedItems getAll(DataKind kind) {
+ KeyedItems fromBase = base.getAll(kind);
+ ImmutableMap overrides = layer.all(kind);
+ if (overrides.isEmpty()) {
+ return fromBase;
+ }
+ Iterable> baseItems =
+ fromBase == null || fromBase.getItems() == null ? Collections.emptyList() : fromBase.getItems();
+
+ ImmutableList.Builder> result = ImmutableList.builder();
+ Set seen = new HashSet<>();
+ for (Map.Entry item : baseItems) {
+ ItemDescriptor override = overrides.get(item.getKey());
+ result.add(override == null ? item : new AbstractMap.SimpleEntry<>(item.getKey(), override));
+ seen.add(item.getKey());
+ }
+ for (Map.Entry override : overrides.entrySet()) {
+ if (!seen.contains(override.getKey())) {
+ result.add(override);
+ }
+ }
+ return new KeyedItems<>(result.build());
+ }
+
+ /**
+ * Delegates to the base store. The override layer never affects initialization status or data
+ * availability.
+ */
+ @Override
+ public boolean isInitialized() {
+ return base.isInitialized();
+ }
+}
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideSinkImpl.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideSinkImpl.java
new file mode 100644
index 00000000..280eed07
--- /dev/null
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/OverrideSinkImpl.java
@@ -0,0 +1,223 @@
+package com.launchdarkly.sdk.server;
+
+import com.google.common.collect.ImmutableMap;
+import com.launchdarkly.logging.LDLogger;
+import com.launchdarkly.sdk.server.DataModelDependencies.DependencyTracker;
+import com.launchdarkly.sdk.server.DataModelDependencies.KindAndKey;
+import com.launchdarkly.sdk.server.interfaces.FlagChangeEvent;
+import com.launchdarkly.sdk.server.interfaces.FlagChangeListener;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.DataKind;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.ItemDescriptor;
+import com.launchdarkly.sdk.server.subsystems.DataStoreTypes.KeyedItems;
+import com.launchdarkly.sdk.server.subsystems.OverrideSink;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashSet;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+import static com.launchdarkly.sdk.server.DataModel.FEATURES;
+import static com.launchdarkly.sdk.server.DataModel.SEGMENTS;
+
+/**
+ * Applies override layer replacements supplied by an override source, and notifies flag change
+ * listeners of the flags affected by each replacement.
+ *
+ * This class is package-private and should not be used by application code.
+ */
+final class OverrideSinkImpl implements OverrideSink {
+ private static final DataKind[] DIFF_KINDS = new DataKind[] { FEATURES, SEGMENTS };
+
+ private final OverrideLayer layer;
+ private final ReadOnlyStore base;
+ private final EventBroadcasterImpl flagChangeBroadcaster;
+ private final LDLogger logger;
+ private boolean closed; // guarded by this
+
+ /**
+ * Creates a sink that writes to the given layer.
+ *
+ * @param layer the override layer
+ * @param base the raw store that holds LaunchDarkly data, without the overlay. Merged-view
+ * snapshots for change computation are built from it plus the layer.
+ * @param flagChangeBroadcaster the client's flag change broadcaster
+ * @param logger the logger
+ */
+ OverrideSinkImpl(
+ OverrideLayer layer,
+ ReadOnlyStore base,
+ EventBroadcasterImpl flagChangeBroadcaster,
+ LDLogger logger
+ ) {
+ this.layer = layer;
+ this.base = base;
+ this.flagChangeBroadcaster = flagChangeBroadcaster;
+ this.logger = logger;
+ }
+
+ /**
+ * Atomically replaces the entire override layer, then notifies listeners of every flag whose
+ * merged-view evaluation may have changed. Calls are serialized, so overlapping updates from a
+ * source cannot interleave.
+ */
+ @Override
+ public synchronized void setOverrides(Iterable>> data) {
+ if (closed) {
+ logger.debug("Ignoring an override snapshot supplied after the override source was closed");
+ return;
+ }
+ apply(data);
+ }
+
+ /**
+ * Stops accepting snapshots. Used when the client is closed: a snapshot that the source supplies
+ * while it shuts down is ignored. The layer keeps its contents.
+ */
+ synchronized void close() {
+ closed = true;
+ }
+
+ /**
+ * Stops accepting snapshots and clears the layer. Used when the source failed to start: a snapshot
+ * the source supplied before failing is removed, so the client runs without overrides, and a late
+ * snapshot from the closed source is ignored.
+ */
+ synchronized void closeAndClear() {
+ closed = true;
+ apply(Collections.emptyList());
+ }
+
+ // Called while holding the lock on this.
+ private void apply(Iterable>> data) {
+ // Computing affected flags requires snapshots of the merged view before and after the
+ // replacement. Skip all of that work when nothing is listening.
+ if (!flagChangeBroadcaster.hasListeners()) {
+ layer.setAll(data);
+ return;
+ }
+
+ OverrideLayer.Replacement replacement = layer.setAll(data);
+ Map> oldMerged = snapshotMergedView(replacement.previous);
+ Map> newMerged = snapshotMergedView(replacement.current);
+
+ Set affected = computeAffectedFlags(replacement.previous, replacement.current, oldMerged, newMerged);
+ if (!affected.isEmpty()) {
+ logger.debug("Override update affected {} flag(s)", affected.size());
+ }
+ for (String key : affected) {
+ flagChangeBroadcaster.broadcast(new FlagChangeEvent(key));
+ }
+ }
+
+ // Returns the keys of all flags whose merged-view evaluation may have changed when the layer was
+ // replaced. The result includes the flags whose override entries were added, removed, or changed.
+ // Dependency fan-out adds every flag that depends, directly or transitively, on any added,
+ // removed, or changed entry of either kind.
+ static Set computeAffectedFlags(
+ ImmutableMap> oldOverrides,
+ ImmutableMap> newOverrides,
+ Map> oldMerged,
+ Map> newMerged
+ ) {
+ Set seeds = diffOverrides(oldOverrides, newOverrides);
+ Set flagKeys = new LinkedHashSet<>();
+ if (seeds.isEmpty()) {
+ return flagKeys;
+ }
+
+ // Dependency edges are computed over both the old and the new merged views, because a
+ // replacement can rewire dependencies. For example, removing a flag override restores the
+ // prerequisite edges of the LaunchDarkly definition. Flags that depended on the override's
+ // references exist as dependents only in the old view.
+ DependencyTracker oldTracker = trackerFromView(oldMerged);
+ DependencyTracker newTracker = trackerFromView(newMerged);
+ Set affected = new LinkedHashSet<>();
+ for (KindAndKey seed : seeds) {
+ oldTracker.addAffectedItems(affected, seed);
+ newTracker.addAffectedItems(affected, seed);
+ }
+ for (KindAndKey item : affected) {
+ if (item.kind == FEATURES) {
+ flagKeys.add(item.key);
+ }
+ }
+ return flagKeys;
+ }
+
+ // Returns each key whose override entry differs between the two layer snapshots. An added or
+ // removed entry is always a change, even when its content matches the underlying LaunchDarkly
+ // data: the override marker alone changes the served entry. Entries present in both snapshots
+ // are compared by version and serialized form, because the layer is rebuilt wholesale on every
+ // update and identity comparison would report every retained entry as changed.
+ private static Set diffOverrides(
+ ImmutableMap> oldOverrides,
+ ImmutableMap> newOverrides
+ ) {
+ Set seeds = new LinkedHashSet<>();
+ for (DataKind kind : DIFF_KINDS) {
+ Map oldItems = oldOverrides.getOrDefault(kind, ImmutableMap.of());
+ Map newItems = newOverrides.getOrDefault(kind, ImmutableMap.of());
+ for (Map.Entry e : oldItems.entrySet()) {
+ ItemDescriptor newItem = newItems.get(e.getKey());
+ if (newItem == null || !itemsEqual(kind, e.getValue(), newItem)) {
+ seeds.add(new KindAndKey(kind, e.getKey()));
+ }
+ }
+ for (String key : newItems.keySet()) {
+ if (!oldItems.containsKey(key)) {
+ seeds.add(new KindAndKey(kind, key));
+ }
+ }
+ }
+ return seeds;
+ }
+
+ private static boolean itemsEqual(DataKind kind, ItemDescriptor a, ItemDescriptor b) {
+ if (a.getVersion() != b.getVersion()) {
+ return false;
+ }
+ return Objects.equals(kind.serialize(a), kind.serialize(b));
+ }
+
+ // Captures the data visible at the store read boundary: base data with the given override entries
+ // overlaid. A base read failure for a kind yields just the overrides for that kind. This degrades
+ // the dependency fan-out but never loses the directly changed keys.
+ private Map> snapshotMergedView(
+ ImmutableMap> overrides
+ ) {
+ Map> view = new HashMap<>();
+ for (DataKind kind : DIFF_KINDS) {
+ Map items = new HashMap<>();
+ try {
+ KeyedItems baseItems = base.getAll(kind);
+ if (baseItems != null && baseItems.getItems() != null) {
+ for (Map.Entry item : baseItems.getItems()) {
+ items.put(item.getKey(), item.getValue());
+ }
+ }
+ } catch (RuntimeException e) {
+ logger.debug("Unable to read {} from the data store while computing override changes: {}",
+ kind.getName(), e.toString());
+ }
+ items.putAll(overrides.getOrDefault(kind, ImmutableMap.of()));
+ view.put(kind, items);
+ }
+ return view;
+ }
+
+ private static DependencyTracker trackerFromView(Map> view) {
+ DependencyTracker tracker = new DependencyTracker();
+ for (DataKind kind : DIFF_KINDS) {
+ Map items = view.get(kind);
+ if (items == null) {
+ continue;
+ }
+ for (Map.Entry e : items.entrySet()) {
+ tracker.updateDependenciesFrom(kind, e.getKey(), e.getValue());
+ }
+ }
+ return tracker;
+ }
+}
diff --git a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/DataSystemBuilder.java b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/DataSystemBuilder.java
index 73d1f3b3..d86539e5 100644
--- a/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/DataSystemBuilder.java
+++ b/lib/sdk/server/src/main/java/com/launchdarkly/sdk/server/integrations/DataSystemBuilder.java
@@ -19,6 +19,7 @@ public final class DataSystemBuilder {
private ComponentConfigurer fDv1FallbackSynchronizer;
private ComponentConfigurer persistentStore;
private DataSystemConfiguration.DataStoreMode persistentDataStoreMode;
+ private ComponentConfigurer